blob: 5b6fe91b9c1a5e171b8fd78d18e360b89f41eaac [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;
Xiao Ma06c8ba02020-04-06 11:24:48 +000044import android.net.dhcp.IDhcpEventCallbacks;
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
Xiao Ma06c8ba02020-04-06 11:24:48 +0000465 private class DhcpLeaseCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900466 @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
Xiao Ma06c8ba02020-04-06 11:24:48 +0000499 public void onNewPrefixRequest(IpPrefix currentPrefix) {
500 //TODO: add specific implementation.
501 }
502
503 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900504 public int getInterfaceVersion() {
505 return this.VERSION;
506 }
507
508 @Override
509 public String getInterfaceHash() throws RemoteException {
510 return this.HASH;
511 }
512 }
513
markchien74a4fa92019-09-09 20:50:49 +0800514 private boolean startDhcp(Inet4Address addr, int prefixLen) {
515 if (mUsingLegacyDhcp) {
516 return true;
517 }
518 final DhcpServingParamsParcel params;
519 params = new DhcpServingParamsParcelExt()
520 .setDefaultRouters(addr)
521 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
522 .setDnsServers(addr)
523 .setServerAddr(new LinkAddress(addr, prefixLen))
524 .setMetered(true);
525 // TODO: also advertise link MTU
526
527 mDhcpServerStartIndex++;
528 mDeps.makeDhcpServer(
529 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
530 return true;
531 }
532
533 private void stopDhcp() {
534 // Make all previous start requests obsolete so servers are not started later
535 mDhcpServerStartIndex++;
536
537 if (mDhcpServer != null) {
538 try {
539 mDhcpServer.stop(new OnHandlerStatusCallback() {
540 @Override
541 public void callback(int statusCode) {
542 if (statusCode != STATUS_SUCCESS) {
543 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800544 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800545 // Not much more we can do here
546 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900547 mDhcpLeases.clear();
548 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800549 }
550 });
551 mDhcpServer = null;
552 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800553 mLog.e("Error stopping DHCP", e);
554 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800555 }
556 }
557 }
558
559 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
560 if (enable) {
561 return startDhcp(addr, prefixLen);
562 } else {
563 stopDhcp();
564 return true;
565 }
566 }
567
568 private void stopIPv4() {
569 configureIPv4(false);
570 // NOTE: All of configureIPv4() will be refactored out of existence
571 // into calls to InterfaceController, shared with startIPv4().
572 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800573 mIpv4Address = null;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000574 mStaticIpv4ServerAddr = null;
575 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800576 }
577
markchien74a4fa92019-09-09 20:50:49 +0800578 private boolean configureIPv4(boolean enabled) {
579 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
580
581 // TODO: Replace this hard-coded information with dynamically selected
582 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800583 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800584 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800585 try {
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000586 if (mStaticIpv4ServerAddr != null) {
587 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
588 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
589 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900590 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800591 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
592 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800593 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800594 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
595 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800596 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800597 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
598 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900599 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
600 // TODO: randomize address for tethering too, similarly to wifi
601 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
602 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800603 } else {
604 // BT configures the interface elsewhere: only start DHCP.
605 // TODO: make all tethering types behave the same way, and delete the bluetooth
606 // code that calls into NetworkManagementService directly.
607 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
608 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
609 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
610 }
611 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
612 } catch (IllegalArgumentException e) {
613 mLog.e("Error selecting ipv4 address", e);
614 if (!enabled) stopDhcp();
615 return false;
markchien74a4fa92019-09-09 20:50:49 +0800616 }
617
markchien12c5bb82020-01-07 14:43:17 +0800618 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800619 if (mInterfaceType == TetheringManager.TETHERING_WIFI
620 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800621 // The WiFi stack has ownership of the interface up/down state.
622 // It is unclear whether the Bluetooth or USB stacks will manage their own
623 // state.
624 setIfaceUp = null;
625 } else {
626 setIfaceUp = enabled;
627 }
628 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
629 mLog.e("Error configuring interface");
630 if (!enabled) stopDhcp();
631 return false;
632 }
markchien74a4fa92019-09-09 20:50:49 +0800633
markchien74a4fa92019-09-09 20:50:49 +0800634 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800635 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
636 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800637 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800638 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800639 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800640 mLinkProperties.addRoute(route);
641 } else {
markchien12c5bb82020-01-07 14:43:17 +0800642 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800643 mLinkProperties.removeRoute(route);
644 }
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000645
646 return configureDhcp(enabled, srvAddr, prefixLen);
markchien74a4fa92019-09-09 20:50:49 +0800647 }
648
649 private String getRandomWifiIPv4Address() {
650 try {
651 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
652 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
653 return InetAddress.getByAddress(bytes).getHostAddress();
654 } catch (Exception e) {
655 return WIFI_HOST_IFACE_ADDR;
656 }
657 }
658
659 private boolean startIPv6() {
660 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
661 if (mInterfaceParams == null) {
662 mLog.e("Failed to find InterfaceParams");
663 stopIPv6();
664 return false;
665 }
666
667 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
668 if (!mRaDaemon.start()) {
669 stopIPv6();
670 return false;
671 }
672
673 return true;
674 }
675
676 private void stopIPv6() {
677 mInterfaceParams = null;
678 setRaParams(null);
679
680 if (mRaDaemon != null) {
681 mRaDaemon.stop();
682 mRaDaemon = null;
683 }
684 }
685
686 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
687 // LinkProperties. These have extraneous data filtered out and only the
688 // necessary prefixes included (per its prefix distribution policy).
689 //
690 // TODO: Evaluate using a data structure than is more directly suited to
691 // communicating only the relevant information.
692 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
693 if (mRaDaemon == null) return;
694
695 // Avoid unnecessary work on spurious updates.
696 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
697 return;
698 }
699
700 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900701 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800702
703 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900704 final String upstreamIface = v6only.getInterfaceName();
705
markchien74a4fa92019-09-09 20:50:49 +0800706 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800707 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
708 // the ethernet header size. This makes kernel ebpf tethering offload happy.
709 // This hack should be reverted once we have the kernel fixed up.
710 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
711 // see RouterAdvertisementDaemon.java putMtu()
712 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800713 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
714
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900715 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800716
717 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
718 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
719
720 final IpPrefix prefix = new IpPrefix(
721 linkAddr.getAddress(), linkAddr.getPrefixLength());
722 params.prefixes.add(prefix);
723
724 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
725 if (dnsServer != null) {
726 params.dnses.add(dnsServer);
727 }
728 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900729
730 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800731 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900732
markchien74a4fa92019-09-09 20:50:49 +0800733 // If v6only is null, we pass in null to setRaParams(), which handles
734 // deprecation of any existing RA data.
735
736 setRaParams(params);
737 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900738
739 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
740 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800741 }
742
743 private void configureLocalIPv6Routes(
744 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
745 // [1] Remove the routes that are deprecated.
746 if (!deprecatedPrefixes.isEmpty()) {
747 final ArrayList<RouteInfo> toBeRemoved =
748 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800749 // Remove routes from local network.
750 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
751 mNetd, toBeRemoved);
752 if (removalFailures > 0) {
753 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
754 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800755 }
756
757 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
758 }
759
760 // [2] Add only the routes that have not previously been added.
761 if (newPrefixes != null && !newPrefixes.isEmpty()) {
762 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
763 if (mLastRaParams != null) {
764 addedPrefixes.removeAll(mLastRaParams.prefixes);
765 }
766
767 if (!addedPrefixes.isEmpty()) {
768 final ArrayList<RouteInfo> toBeAdded =
769 getLocalRoutesFor(mIfaceName, addedPrefixes);
770 try {
markchien12c5bb82020-01-07 14:43:17 +0800771 // It's safe to call networkAddInterface() even if
772 // the interface is already in the local_network.
773 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
774 try {
775 // Add routes from local network. Note that adding routes that
776 // already exist does not cause an error (EEXIST is silently ignored).
777 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
778 } catch (IllegalStateException e) {
779 mLog.e("Failed to add IPv6 routes to local table: " + e);
780 }
781 } catch (ServiceSpecificException | RemoteException e) {
782 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800783 }
784
785 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
786 }
787 }
788 }
789
790 private void configureLocalIPv6Dns(
791 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
792 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
793 if (mNetd == null) {
794 if (newDnses != null) newDnses.clear();
795 mLog.e("No netd service instance available; not setting local IPv6 addresses");
796 return;
797 }
798
799 // [1] Remove deprecated local DNS IP addresses.
800 if (!deprecatedDnses.isEmpty()) {
801 for (Inet6Address dns : deprecatedDnses) {
802 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
803 mLog.e("Failed to remove local dns IP " + dns);
804 }
805
806 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
807 }
808 }
809
810 // [2] Add only the local DNS IP addresses that have not previously been added.
811 if (newDnses != null && !newDnses.isEmpty()) {
812 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
813 if (mLastRaParams != null) {
814 addedDnses.removeAll(mLastRaParams.dnses);
815 }
816
817 for (Inet6Address dns : addedDnses) {
818 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
819 mLog.e("Failed to add local dns IP " + dns);
820 newDnses.remove(dns);
821 }
822
823 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
824 }
825 }
826
827 try {
828 mNetd.tetherApplyDnsInterfaces();
829 } catch (ServiceSpecificException | RemoteException e) {
830 mLog.e("Failed to update local DNS caching server");
831 if (newDnses != null) newDnses.clear();
832 }
833 }
834
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900835 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
836 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000837 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900838 mIpv6ForwardingRules.put(rule.address, rule);
839 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000840 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900841 }
842 }
843
844 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
845 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000846 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900847 if (removeFromMap) {
848 mIpv6ForwardingRules.remove(rule.address);
849 }
850 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000851 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900852 }
853 }
854
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000855 private void clearIpv6ForwardingRules() {
856 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
857 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
858 }
859 mIpv6ForwardingRules.clear();
860 }
861
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900862 // Convenience method to replace a rule with the same rule on a new upstream interface.
863 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
864 // Relies on the fact that rules are in a map indexed by IP address.
865 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
866 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
867 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
868 }
869
870 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
871 // changes or if a neighbor event is received.
872 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
873 NeighborEvent e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000874 // If we no longer have an upstream, clear forwarding rules and do nothing else.
875 if (upstreamIfindex == 0) {
876 clearIpv6ForwardingRules();
877 return;
878 }
879
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900880 // If the upstream interface has changed, remove all rules and re-add them with the new
881 // upstream interface.
882 if (prevUpstreamIfindex != upstreamIfindex) {
883 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
884 updateIpv6ForwardingRule(rule, upstreamIfindex);
885 }
886 }
887
888 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000889 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900890 if (e == null) return;
891 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
892 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
893 return;
894 }
895
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000896 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900897 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
898 e.macAddr);
899 if (e.isValid()) {
900 addIpv6ForwardingRule(rule);
901 } else {
902 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
903 }
904 }
905
906 private void handleNeighborEvent(NeighborEvent e) {
907 if (mInterfaceParams != null
908 && mInterfaceParams.index == e.ifindex
909 && mInterfaceParams.hasMacAddress) {
910 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
911 }
912 }
913
markchien74a4fa92019-09-09 20:50:49 +0800914 private byte getHopLimit(String upstreamIface) {
915 try {
916 int upstreamHopLimit = Integer.parseUnsignedInt(
917 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
918 // Add one hop to account for this forwarding device
919 upstreamHopLimit++;
920 // Cap the hop limit to 255.
921 return (byte) Integer.min(upstreamHopLimit, 255);
922 } catch (Exception e) {
923 mLog.e("Failed to find upstream interface hop limit", e);
924 }
925 return RaParams.DEFAULT_HOPLIMIT;
926 }
927
928 private void setRaParams(RaParams newParams) {
929 if (mRaDaemon != null) {
930 final RaParams deprecatedParams =
931 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
932
933 configureLocalIPv6Routes(deprecatedParams.prefixes,
934 (newParams != null) ? newParams.prefixes : null);
935
936 configureLocalIPv6Dns(deprecatedParams.dnses,
937 (newParams != null) ? newParams.dnses : null);
938
939 mRaDaemon.buildNewRa(deprecatedParams, newParams);
940 }
941
942 mLastRaParams = newParams;
943 }
944
945 private void logMessage(State state, int what) {
946 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
947 }
948
949 private void sendInterfaceState(int newInterfaceState) {
950 mServingMode = newInterfaceState;
951 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
952 sendLinkProperties();
953 }
954
955 private void sendLinkProperties() {
956 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
957 }
958
959 private void resetLinkProperties() {
960 mLinkProperties.clear();
961 mLinkProperties.setInterfaceName(mIfaceName);
962 }
963
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000964 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
965 if (request == null) return;
966
967 mStaticIpv4ServerAddr = request.localIPv4Address;
968 mStaticIpv4ClientAddr = request.staticClientAddress;
969 }
970
markchien74a4fa92019-09-09 20:50:49 +0800971 class InitialState extends State {
972 @Override
973 public void enter() {
974 sendInterfaceState(STATE_AVAILABLE);
975 }
976
977 @Override
978 public boolean processMessage(Message message) {
979 logMessage(this, message.what);
980 switch (message.what) {
981 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800982 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800983 switch (message.arg1) {
984 case STATE_LOCAL_ONLY:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000985 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800986 transitionTo(mLocalHotspotState);
987 break;
988 case STATE_TETHERED:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000989 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800990 transitionTo(mTetheredState);
991 break;
992 default:
993 mLog.e("Invalid tethering interface serving state specified.");
994 }
995 break;
996 case CMD_INTERFACE_DOWN:
997 transitionTo(mUnavailableState);
998 break;
999 case CMD_IPV6_TETHER_UPDATE:
1000 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1001 break;
1002 default:
1003 return NOT_HANDLED;
1004 }
1005 return HANDLED;
1006 }
1007 }
1008
1009 class BaseServingState extends State {
1010 @Override
1011 public void enter() {
1012 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001013 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001014 return;
1015 }
1016
1017 try {
markchien12c5bb82020-01-07 14:43:17 +08001018 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1019 mIpv4Address.getPrefixLength());
1020 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +08001021 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +08001022 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +08001023 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001024 return;
1025 }
1026
1027 if (!startIPv6()) {
1028 mLog.e("Failed to startIPv6");
1029 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1030 return;
1031 }
1032 }
1033
1034 @Override
1035 public void exit() {
1036 // Note that at this point, we're leaving the tethered state. We can fail any
1037 // of these operations, but it doesn't really change that we have to try them
1038 // all in sequence.
1039 stopIPv6();
1040
1041 try {
markchien12c5bb82020-01-07 14:43:17 +08001042 NetdUtils.untetherInterface(mNetd, mIfaceName);
1043 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001044 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001045 mLog.e("Failed to untether interface: " + e);
1046 }
1047
1048 stopIPv4();
1049
1050 resetLinkProperties();
1051 }
1052
1053 @Override
1054 public boolean processMessage(Message message) {
1055 logMessage(this, message.what);
1056 switch (message.what) {
1057 case CMD_TETHER_UNREQUESTED:
1058 transitionTo(mInitialState);
1059 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1060 break;
1061 case CMD_INTERFACE_DOWN:
1062 transitionTo(mUnavailableState);
1063 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1064 break;
1065 case CMD_IPV6_TETHER_UPDATE:
1066 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1067 sendLinkProperties();
1068 break;
1069 case CMD_IP_FORWARDING_ENABLE_ERROR:
1070 case CMD_IP_FORWARDING_DISABLE_ERROR:
1071 case CMD_START_TETHERING_ERROR:
1072 case CMD_STOP_TETHERING_ERROR:
1073 case CMD_SET_DNS_FORWARDERS_ERROR:
markchienf1332572020-03-19 13:37:43 +08001074 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001075 transitionTo(mInitialState);
1076 break;
1077 default:
1078 return false;
1079 }
1080 return true;
1081 }
1082 }
1083
1084 // Handling errors in BaseServingState.enter() by transitioning is
1085 // problematic because transitioning during a multi-state jump yields
1086 // a Log.wtf(). Ultimately, there should be only one ServingState,
1087 // and forwarding and NAT rules should be handled by a coordinating
1088 // functional element outside of IpServer.
1089 class LocalHotspotState extends BaseServingState {
1090 @Override
1091 public void enter() {
1092 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001093 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001094 transitionTo(mInitialState);
1095 }
1096
1097 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1098 sendInterfaceState(STATE_LOCAL_ONLY);
1099 }
1100
1101 @Override
1102 public boolean processMessage(Message message) {
1103 if (super.processMessage(message)) return true;
1104
1105 logMessage(this, message.what);
1106 switch (message.what) {
1107 case CMD_TETHER_REQUESTED:
1108 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1109 break;
1110 case CMD_TETHER_CONNECTION_CHANGED:
1111 // Ignored in local hotspot state.
1112 break;
1113 default:
1114 return false;
1115 }
1116 return true;
1117 }
1118 }
1119
1120 // Handling errors in BaseServingState.enter() by transitioning is
1121 // problematic because transitioning during a multi-state jump yields
1122 // a Log.wtf(). Ultimately, there should be only one ServingState,
1123 // and forwarding and NAT rules should be handled by a coordinating
1124 // functional element outside of IpServer.
1125 class TetheredState extends BaseServingState {
1126 @Override
1127 public void enter() {
1128 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001129 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001130 transitionTo(mInitialState);
1131 }
1132
1133 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1134 sendInterfaceState(STATE_TETHERED);
1135 }
1136
1137 @Override
1138 public void exit() {
1139 cleanupUpstream();
1140 super.exit();
1141 }
1142
1143 private void cleanupUpstream() {
1144 if (mUpstreamIfaceSet == null) return;
1145
1146 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1147 mUpstreamIfaceSet = null;
Automerger Merge Workerf1194882020-02-25 04:04:44 +00001148 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001149 }
1150
1151 private void cleanupUpstreamInterface(String upstreamIface) {
1152 // Note that we don't care about errors here.
1153 // Sometimes interfaces are gone before we get
1154 // to remove their rules, which generates errors.
1155 // Just do the best we can.
1156 try {
markchien12c5bb82020-01-07 14:43:17 +08001157 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1158 } catch (RemoteException | ServiceSpecificException e) {
1159 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001160 }
1161 try {
markchien12c5bb82020-01-07 14:43:17 +08001162 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1163 } catch (RemoteException | ServiceSpecificException e) {
1164 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001165 }
1166 }
1167
1168 @Override
1169 public boolean processMessage(Message message) {
1170 if (super.processMessage(message)) return true;
1171
1172 logMessage(this, message.what);
1173 switch (message.what) {
1174 case CMD_TETHER_REQUESTED:
1175 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1176 break;
1177 case CMD_TETHER_CONNECTION_CHANGED:
1178 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1179 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1180 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1181 break;
1182 }
1183
1184 if (newUpstreamIfaceSet == null) {
1185 cleanupUpstream();
1186 break;
1187 }
1188
1189 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1190 cleanupUpstreamInterface(removed);
1191 }
1192
1193 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1194 // This makes the call to cleanupUpstream() in the error
1195 // path for any interface neatly cleanup all the interfaces.
1196 mUpstreamIfaceSet = newUpstreamIfaceSet;
1197
1198 for (String ifname : added) {
1199 try {
markchien12c5bb82020-01-07 14:43:17 +08001200 mNetd.tetherAddForward(mIfaceName, ifname);
1201 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1202 } catch (RemoteException | ServiceSpecificException e) {
1203 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001204 cleanupUpstream();
markchienf1332572020-03-19 13:37:43 +08001205 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001206 transitionTo(mInitialState);
1207 return true;
1208 }
1209 }
1210 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001211 case CMD_NEIGHBOR_EVENT:
1212 handleNeighborEvent((NeighborEvent) message.obj);
1213 break;
markchien74a4fa92019-09-09 20:50:49 +08001214 default:
1215 return false;
1216 }
1217 return true;
1218 }
1219
1220 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1221 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1222 if (mUpstreamIfaceSet != null && newIfaces != null) {
1223 return mUpstreamIfaceSet.equals(newIfaces);
1224 }
1225 return false;
1226 }
1227
1228 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1229 if (mUpstreamIfaceSet == null) return new HashSet<>();
1230
1231 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1232 removed.removeAll(newIfaces.ifnames);
1233 return removed;
1234 }
1235
1236 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1237 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1238 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1239 return added;
1240 }
1241 }
1242
1243 /**
1244 * This state is terminal for the per interface state machine. At this
1245 * point, the master state machine should have removed this interface
1246 * specific state machine from its list of possible recipients of
1247 * tethering requests. The state machine itself will hang around until
1248 * the garbage collector finds it.
1249 */
1250 class UnavailableState extends State {
1251 @Override
1252 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001253 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001254 sendInterfaceState(STATE_UNAVAILABLE);
1255 }
1256 }
1257
1258 // Accumulate routes representing "prefixes to be assigned to the local
1259 // interface", for subsequent modification of local_network routing.
1260 private static ArrayList<RouteInfo> getLocalRoutesFor(
1261 String ifname, HashSet<IpPrefix> prefixes) {
1262 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1263 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001264 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001265 }
1266 return localRoutes;
1267 }
1268
1269 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1270 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1271 final byte[] dnsBytes = localPrefix.getRawAddress();
1272 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1273 try {
1274 return Inet6Address.getByAddress(null, dnsBytes, 0);
1275 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001276 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001277 return null;
1278 }
1279 }
1280
1281 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1282 final byte random = (byte) (new Random()).nextInt();
1283 for (int value : excluded) {
1284 if (random == value) return dflt;
1285 }
1286 return random;
1287 }
1288}