blob: 69885d04bffa8881f22a7ffd77e2e3c8d6f52969 [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;
markchien245352e2020-02-27 20:27:18 +080021import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080022import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090023import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH;
markchien74a4fa92019-09-09 20:50:49 +080024import static android.net.util.NetworkConstants.FF;
25import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
26import static android.net.util.NetworkConstants.asByte;
markchien6cf0e552019-12-06 15:24:53 +080027import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090028import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080029
markchien74a4fa92019-09-09 20:50:49 +080030import android.net.INetd;
31import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080032import android.net.IpPrefix;
33import android.net.LinkAddress;
34import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090035import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080036import android.net.RouteInfo;
Lorenzo Colittibeb28402020-04-03 22:05:14 +090037import android.net.TetherOffloadRuleParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090038import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080039import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080040import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090041import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.dhcp.DhcpServerCallbacks;
43import android.net.dhcp.DhcpServingParamsParcel;
44import android.net.dhcp.DhcpServingParamsParcelExt;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090045import android.net.dhcp.IDhcpLeaseCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090047import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080048import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080049import android.net.shared.NetdUtils;
50import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080051import android.net.util.InterfaceParams;
52import android.net.util.InterfaceSet;
markchien74a4fa92019-09-09 20:50:49 +080053import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090054import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080055import android.os.Looper;
56import android.os.Message;
57import android.os.RemoteException;
58import android.os.ServiceSpecificException;
59import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080060import android.util.SparseArray;
61
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090062import androidx.annotation.NonNull;
63
markchien74a4fa92019-09-09 20:50:49 +080064import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080065import com.android.internal.util.State;
66import com.android.internal.util.StateMachine;
67
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090068import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080069import java.net.Inet4Address;
70import java.net.Inet6Address;
71import java.net.InetAddress;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090072import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080073import java.net.UnknownHostException;
74import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090075import java.util.Arrays;
76import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080077import java.util.HashSet;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090078import java.util.LinkedHashMap;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090079import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080080import java.util.Objects;
81import java.util.Random;
82import java.util.Set;
83
84/**
85 * Provides the interface to IP-layer serving functionality for a given network
86 * interface, e.g. for tethering or "local-only hotspot" mode.
87 *
88 * @hide
89 */
90public class IpServer extends StateMachine {
91 public static final int STATE_UNAVAILABLE = 0;
92 public static final int STATE_AVAILABLE = 1;
93 public static final int STATE_TETHERED = 2;
94 public static final int STATE_LOCAL_ONLY = 3;
95
96 /** Get string name of |state|.*/
97 public static String getStateString(int state) {
98 switch (state) {
99 case STATE_UNAVAILABLE: return "UNAVAILABLE";
100 case STATE_AVAILABLE: return "AVAILABLE";
101 case STATE_TETHERED: return "TETHERED";
102 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
103 }
104 return "UNKNOWN: " + state;
105 }
106
107 private static final byte DOUG_ADAMS = (byte) 42;
108
109 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
110 private static final int USB_PREFIX_LENGTH = 24;
111 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
112 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
113 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
114 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900115 private static final String ETHERNET_IFACE_ADDR = "192.168.50.1";
116 private static final int ETHERNET_IFACE_PREFIX_LENGTH = 24;
markchien74a4fa92019-09-09 20:50:49 +0800117
118 // TODO: have PanService use some visible version of this constant
119 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
120 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
121
122 // TODO: have this configurable
123 private static final int DHCP_LEASE_TIME_SECS = 3600;
124
125 private static final String TAG = "IpServer";
126 private static final boolean DBG = false;
127 private static final boolean VDBG = false;
128 private static final Class[] sMessageClasses = {
129 IpServer.class
130 };
131 private static final SparseArray<String> sMagicDecoderRing =
132 MessageUtils.findMessageNames(sMessageClasses);
133
134 /** IpServer callback. */
135 public static class Callback {
136 /**
137 * Notify that |who| has changed its tethering state.
138 *
139 * @param who the calling instance of IpServer
140 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800141 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800142 */
markchien9d353822019-12-16 20:15:20 +0800143 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800144
145 /**
146 * Notify that |who| has new LinkProperties.
147 *
148 * @param who the calling instance of IpServer
149 * @param newLp the new LinkProperties to report
150 */
markchien9d353822019-12-16 20:15:20 +0800151 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900152
153 /**
154 * Notify that the DHCP leases changed in one of the IpServers.
155 */
156 public void dhcpLeasesChanged() { }
markchien74a4fa92019-09-09 20:50:49 +0800157 }
158
159 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800160 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900161 /** Create an IpNeighborMonitor to be used by this IpServer */
162 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
163 IpNeighborMonitor.NeighborEventConsumer consumer) {
164 return new IpNeighborMonitor(handler, log, consumer);
165 }
166
markchien74a4fa92019-09-09 20:50:49 +0800167 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
168 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
169 return new RouterAdvertisementDaemon(ifParams);
170 }
171
172 /** Get |ifName|'s interface information.*/
173 public InterfaceParams getInterfaceParams(String ifName) {
174 return InterfaceParams.getByName(ifName);
175 }
176
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900177 /** Get |ifName|'s interface index. */
178 public int getIfindex(String ifName) {
179 try {
180 return NetworkInterface.getByName(ifName).getIndex();
181 } catch (IOException | NullPointerException e) {
182 Log.e(TAG, "Can't determine interface index for interface " + ifName);
183 return 0;
184 }
185 }
markchien9d353822019-12-16 20:15:20 +0800186 /** Create a DhcpServer instance to be used by IpServer. */
187 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
188 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800189 }
190
markchien74a4fa92019-09-09 20:50:49 +0800191 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800192 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800193 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800194 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800195 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800196 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800197 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800198 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800199 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800200 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800201 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800202 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800203 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800204 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800205 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800206 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800207 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800209 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900211 // new neighbor cache entry on our interface
212 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
markchien74a4fa92019-09-09 20:50:49 +0800213
214 private final State mInitialState;
215 private final State mLocalHotspotState;
216 private final State mTetheredState;
217 private final State mUnavailableState;
218
219 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800220 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800221 private final Callback mCallback;
222 private final InterfaceController mInterfaceCtrl;
223
224 private final String mIfaceName;
225 private final int mInterfaceType;
226 private final LinkProperties mLinkProperties;
227 private final boolean mUsingLegacyDhcp;
228
229 private final Dependencies mDeps;
230
231 private int mLastError;
232 private int mServingMode;
233 private InterfaceSet mUpstreamIfaceSet; // may change over time
234 private InterfaceParams mInterfaceParams;
235 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
236 // properties are those selected by the IPv6TetheringCoordinator and relayed
237 // to us. By comparison, mLinkProperties contains the addresses and directly
238 // connected routes that have been formed from these properties iff. we have
239 // succeeded in configuring them and are able to announce them within Router
240 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
241 private LinkProperties mLastIPv6LinkProperties;
242 private RouterAdvertisementDaemon mRaDaemon;
243
244 // To be accessed only on the handler thread
245 private int mDhcpServerStartIndex = 0;
246 private IDhcpServer mDhcpServer;
247 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800248 private LinkAddress mIpv4Address;
markchienf053e4b2020-03-16 21:49:48 +0800249
250 private LinkAddress mStaticIpv4ServerAddr;
251 private LinkAddress mStaticIpv4ClientAddr;
252
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900253 @NonNull
254 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800255
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900256 private int mLastIPv6UpstreamIfindex = 0;
257
258 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
259 public void accept(NeighborEvent e) {
260 sendMessage(CMD_NEIGHBOR_EVENT, e);
261 }
262 }
263
264 static class Ipv6ForwardingRule {
265 public final int upstreamIfindex;
266 public final int downstreamIfindex;
267 public final Inet6Address address;
268 public final MacAddress srcMac;
269 public final MacAddress dstMac;
270
271 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
272 MacAddress srcMac, MacAddress dstMac) {
273 this.upstreamIfindex = upstreamIfindex;
274 this.downstreamIfindex = downstreamIfIndex;
275 this.address = address;
276 this.srcMac = srcMac;
277 this.dstMac = dstMac;
278 }
279
280 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
281 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
282 dstMac);
283 }
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900284
285 // Don't manipulate TetherOffloadRuleParcel directly because implementing onNewUpstream()
286 // would be error-prone due to generated stable AIDL classes not having a copy constructor.
287 public TetherOffloadRuleParcel toTetherOffloadRuleParcel() {
288 final TetherOffloadRuleParcel parcel = new TetherOffloadRuleParcel();
289 parcel.inputInterfaceIndex = upstreamIfindex;
290 parcel.outputInterfaceIndex = downstreamIfindex;
291 parcel.destination = address.getAddress();
292 parcel.prefixLength = 128;
293 parcel.srcL2Address = srcMac.toByteArray();
294 parcel.dstL2Address = dstMac.toByteArray();
295 return parcel;
296 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900297 }
298 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
299 new LinkedHashMap<>();
300
301 private final IpNeighborMonitor mIpNeighborMonitor;
302
markchien74a4fa92019-09-09 20:50:49 +0800303 public IpServer(
304 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800305 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800306 super(ifaceName, looper);
307 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800308 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800309 mCallback = callback;
310 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
311 mIfaceName = ifaceName;
312 mInterfaceType = interfaceType;
313 mLinkProperties = new LinkProperties();
314 mUsingLegacyDhcp = usingLegacyDhcp;
315 mDeps = deps;
316 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800317 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800318 mServingMode = STATE_AVAILABLE;
319
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900320 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
321 new MyNeighborEventConsumer());
322 if (!mIpNeighborMonitor.start()) {
323 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
324 }
325
markchien74a4fa92019-09-09 20:50:49 +0800326 mInitialState = new InitialState();
327 mLocalHotspotState = new LocalHotspotState();
328 mTetheredState = new TetheredState();
329 mUnavailableState = new UnavailableState();
330 addState(mInitialState);
331 addState(mLocalHotspotState);
332 addState(mTetheredState);
333 addState(mUnavailableState);
334
335 setInitialState(mInitialState);
336 }
337
338 /** Interface name which IpServer served.*/
339 public String interfaceName() {
340 return mIfaceName;
341 }
342
343 /**
markchien9b4d7572019-12-25 19:40:32 +0800344 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800345 */
346 public int interfaceType() {
347 return mInterfaceType;
348 }
349
350 /** Last error from this IpServer. */
351 public int lastError() {
352 return mLastError;
353 }
354
355 /** Serving mode is the current state of IpServer state machine. */
356 public int servingMode() {
357 return mServingMode;
358 }
359
360 /** The properties of the network link which IpServer is serving. */
361 public LinkProperties linkProperties() {
362 return new LinkProperties(mLinkProperties);
363 }
364
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900365 /**
366 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
367 * thread.
368 */
369 public List<TetheredClient> getAllLeases() {
370 return Collections.unmodifiableList(mDhcpLeases);
371 }
372
markchien74a4fa92019-09-09 20:50:49 +0800373 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
374 public void stop() {
375 sendMessage(CMD_INTERFACE_DOWN);
376 }
377
378 /**
379 * Tethering is canceled. IpServer state machine will be available and wait for
380 * next tethering request.
381 */
382 public void unwanted() {
383 sendMessage(CMD_TETHER_UNREQUESTED);
384 }
385
386 /** Internals. */
387
388 private boolean startIPv4() {
389 return configureIPv4(true);
390 }
391
392 /**
393 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
394 * handler.
395 *
396 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
397 * with different implementations of the callback, to differentiate handling of success/error in
398 * each call.
399 */
400 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
401 @Override
402 public void onStatusAvailable(int statusCode) {
403 getHandler().post(() -> callback(statusCode));
404 }
405
406 public abstract void callback(int statusCode);
407
408 @Override
409 public int getInterfaceVersion() {
410 return this.VERSION;
411 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900412
413 @Override
414 public String getInterfaceHash() {
415 return this.HASH;
416 }
markchien74a4fa92019-09-09 20:50:49 +0800417 }
418
419 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
420 private final int mStartIndex;
421
422 private DhcpServerCallbacksImpl(int startIndex) {
423 mStartIndex = startIndex;
424 }
425
426 @Override
427 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
428 getHandler().post(() -> {
429 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
430 if (mStartIndex != mDhcpServerStartIndex) {
431 // This start request is obsolete. When the |server| binder token goes out of
432 // scope, the garbage collector will finalize it, which causes the network stack
433 // process garbage collector to collect the server itself.
434 return;
435 }
436
437 if (statusCode != STATUS_SUCCESS) {
438 mLog.e("Error obtaining DHCP server: " + statusCode);
439 handleError();
440 return;
441 }
442
443 mDhcpServer = server;
444 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900445 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800446 @Override
447 public void callback(int startStatusCode) {
448 if (startStatusCode != STATUS_SUCCESS) {
449 mLog.e("Error starting DHCP server: " + startStatusCode);
450 handleError();
451 }
452 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900453 }, new DhcpLeaseCallback());
markchien74a4fa92019-09-09 20:50:49 +0800454 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800455 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800456 }
457 });
458 }
459
460 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800461 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800462 transitionTo(mInitialState);
463 }
464 }
465
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900466 private class DhcpLeaseCallback extends IDhcpLeaseCallbacks.Stub {
467 @Override
468 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
469 final ArrayList<TetheredClient> leases = new ArrayList<>();
470 for (DhcpLeaseParcelable lease : leaseParcelables) {
471 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900472 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
473 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
474 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900475
476 final MacAddress macAddress;
477 try {
478 macAddress = MacAddress.fromBytes(lease.hwAddr);
479 } catch (IllegalArgumentException e) {
480 Log.wtf(TAG, "Invalid address received from DhcpServer: "
481 + Arrays.toString(lease.hwAddr));
482 return;
483 }
484
485 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900486 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900487 leases.add(new TetheredClient(
488 macAddress,
489 Collections.singletonList(addressInfo),
490 mInterfaceType));
491 }
492
493 getHandler().post(() -> {
494 mDhcpLeases = leases;
495 mCallback.dhcpLeasesChanged();
496 });
497 }
498
499 @Override
500 public int getInterfaceVersion() {
501 return this.VERSION;
502 }
503
504 @Override
505 public String getInterfaceHash() throws RemoteException {
506 return this.HASH;
507 }
508 }
509
markchien245352e2020-02-27 20:27:18 +0800510 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800511 if (mUsingLegacyDhcp) {
512 return true;
513 }
markchien245352e2020-02-27 20:27:18 +0800514
515 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
516 final int prefixLen = serverLinkAddr.getPrefixLength();
517 final Inet4Address clientAddr = clientLinkAddr == null ? null :
518 (Inet4Address) clientLinkAddr.getAddress();
519
markchien74a4fa92019-09-09 20:50:49 +0800520 final DhcpServingParamsParcel params;
521 params = new DhcpServingParamsParcelExt()
522 .setDefaultRouters(addr)
523 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
524 .setDnsServers(addr)
markchien245352e2020-02-27 20:27:18 +0800525 .setServerAddr(serverLinkAddr)
526 .setMetered(true)
527 .setSingleClientAddr(clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800528 // TODO: also advertise link MTU
529
530 mDhcpServerStartIndex++;
531 mDeps.makeDhcpServer(
532 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
533 return true;
534 }
535
536 private void stopDhcp() {
537 // Make all previous start requests obsolete so servers are not started later
538 mDhcpServerStartIndex++;
539
540 if (mDhcpServer != null) {
541 try {
542 mDhcpServer.stop(new OnHandlerStatusCallback() {
543 @Override
544 public void callback(int statusCode) {
545 if (statusCode != STATUS_SUCCESS) {
546 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800547 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800548 // Not much more we can do here
549 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900550 mDhcpLeases.clear();
551 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800552 }
553 });
554 mDhcpServer = null;
555 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800556 mLog.e("Error stopping DHCP", e);
557 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800558 }
559 }
560 }
561
markchien245352e2020-02-27 20:27:18 +0800562 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
563 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800564 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800565 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800566 } else {
567 stopDhcp();
568 return true;
569 }
570 }
571
572 private void stopIPv4() {
573 configureIPv4(false);
574 // NOTE: All of configureIPv4() will be refactored out of existence
575 // into calls to InterfaceController, shared with startIPv4().
576 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800577 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800578 mStaticIpv4ServerAddr = null;
579 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800580 }
581
markchien74a4fa92019-09-09 20:50:49 +0800582 private boolean configureIPv4(boolean enabled) {
583 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
584
585 // TODO: Replace this hard-coded information with dynamically selected
586 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800587 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800588 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800589 try {
markchienf053e4b2020-03-16 21:49:48 +0800590 if (mStaticIpv4ServerAddr != null) {
591 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
592 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
593 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900594 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800595 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
596 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800597 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800598 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
599 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800600 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800601 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
602 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900603 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
604 // TODO: randomize address for tethering too, similarly to wifi
605 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
606 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800607 } else {
608 // BT configures the interface elsewhere: only start DHCP.
609 // TODO: make all tethering types behave the same way, and delete the bluetooth
610 // code that calls into NetworkManagementService directly.
611 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
612 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
markchien245352e2020-02-27 20:27:18 +0800613 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
markchien12c5bb82020-01-07 14:43:17 +0800614 }
615 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
616 } catch (IllegalArgumentException e) {
617 mLog.e("Error selecting ipv4 address", e);
618 if (!enabled) stopDhcp();
619 return false;
markchien74a4fa92019-09-09 20:50:49 +0800620 }
621
markchien12c5bb82020-01-07 14:43:17 +0800622 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800623 if (mInterfaceType == TetheringManager.TETHERING_WIFI
624 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800625 // The WiFi stack has ownership of the interface up/down state.
626 // It is unclear whether the Bluetooth or USB stacks will manage their own
627 // state.
628 setIfaceUp = null;
629 } else {
630 setIfaceUp = enabled;
631 }
632 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
633 mLog.e("Error configuring interface");
634 if (!enabled) stopDhcp();
635 return false;
636 }
markchien74a4fa92019-09-09 20:50:49 +0800637
markchien74a4fa92019-09-09 20:50:49 +0800638 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800639 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
640 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800641 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800642 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800643 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800644 mLinkProperties.addRoute(route);
645 } else {
markchien12c5bb82020-01-07 14:43:17 +0800646 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800647 mLinkProperties.removeRoute(route);
648 }
markchienf053e4b2020-03-16 21:49:48 +0800649
markchien245352e2020-02-27 20:27:18 +0800650 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800651 }
652
653 private String getRandomWifiIPv4Address() {
654 try {
655 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
656 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
657 return InetAddress.getByAddress(bytes).getHostAddress();
658 } catch (Exception e) {
659 return WIFI_HOST_IFACE_ADDR;
660 }
661 }
662
663 private boolean startIPv6() {
664 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
665 if (mInterfaceParams == null) {
666 mLog.e("Failed to find InterfaceParams");
667 stopIPv6();
668 return false;
669 }
670
671 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
672 if (!mRaDaemon.start()) {
673 stopIPv6();
674 return false;
675 }
676
677 return true;
678 }
679
680 private void stopIPv6() {
681 mInterfaceParams = null;
682 setRaParams(null);
683
684 if (mRaDaemon != null) {
685 mRaDaemon.stop();
686 mRaDaemon = null;
687 }
688 }
689
690 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
691 // LinkProperties. These have extraneous data filtered out and only the
692 // necessary prefixes included (per its prefix distribution policy).
693 //
694 // TODO: Evaluate using a data structure than is more directly suited to
695 // communicating only the relevant information.
696 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
697 if (mRaDaemon == null) return;
698
699 // Avoid unnecessary work on spurious updates.
700 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
701 return;
702 }
703
704 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900705 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800706
707 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900708 final String upstreamIface = v6only.getInterfaceName();
709
markchien74a4fa92019-09-09 20:50:49 +0800710 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800711 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
712 // the ethernet header size. This makes kernel ebpf tethering offload happy.
713 // This hack should be reverted once we have the kernel fixed up.
714 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
715 // see RouterAdvertisementDaemon.java putMtu()
716 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800717 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
718
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900719 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800720
721 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
722 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
723
724 final IpPrefix prefix = new IpPrefix(
725 linkAddr.getAddress(), linkAddr.getPrefixLength());
726 params.prefixes.add(prefix);
727
728 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
729 if (dnsServer != null) {
730 params.dnses.add(dnsServer);
731 }
732 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900733
734 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800735 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900736
markchien74a4fa92019-09-09 20:50:49 +0800737 // If v6only is null, we pass in null to setRaParams(), which handles
738 // deprecation of any existing RA data.
739
740 setRaParams(params);
741 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900742
743 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
744 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800745 }
746
747 private void configureLocalIPv6Routes(
748 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
749 // [1] Remove the routes that are deprecated.
750 if (!deprecatedPrefixes.isEmpty()) {
751 final ArrayList<RouteInfo> toBeRemoved =
752 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800753 // Remove routes from local network.
754 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
755 mNetd, toBeRemoved);
756 if (removalFailures > 0) {
757 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
758 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800759 }
760
761 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
762 }
763
764 // [2] Add only the routes that have not previously been added.
765 if (newPrefixes != null && !newPrefixes.isEmpty()) {
766 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
767 if (mLastRaParams != null) {
768 addedPrefixes.removeAll(mLastRaParams.prefixes);
769 }
770
771 if (!addedPrefixes.isEmpty()) {
772 final ArrayList<RouteInfo> toBeAdded =
773 getLocalRoutesFor(mIfaceName, addedPrefixes);
774 try {
markchien12c5bb82020-01-07 14:43:17 +0800775 // It's safe to call networkAddInterface() even if
776 // the interface is already in the local_network.
777 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
778 try {
779 // Add routes from local network. Note that adding routes that
780 // already exist does not cause an error (EEXIST is silently ignored).
781 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
782 } catch (IllegalStateException e) {
783 mLog.e("Failed to add IPv6 routes to local table: " + e);
784 }
785 } catch (ServiceSpecificException | RemoteException e) {
786 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800787 }
788
789 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
790 }
791 }
792 }
793
794 private void configureLocalIPv6Dns(
795 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
796 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
797 if (mNetd == null) {
798 if (newDnses != null) newDnses.clear();
799 mLog.e("No netd service instance available; not setting local IPv6 addresses");
800 return;
801 }
802
803 // [1] Remove deprecated local DNS IP addresses.
804 if (!deprecatedDnses.isEmpty()) {
805 for (Inet6Address dns : deprecatedDnses) {
806 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
807 mLog.e("Failed to remove local dns IP " + dns);
808 }
809
810 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
811 }
812 }
813
814 // [2] Add only the local DNS IP addresses that have not previously been added.
815 if (newDnses != null && !newDnses.isEmpty()) {
816 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
817 if (mLastRaParams != null) {
818 addedDnses.removeAll(mLastRaParams.dnses);
819 }
820
821 for (Inet6Address dns : addedDnses) {
822 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
823 mLog.e("Failed to add local dns IP " + dns);
824 newDnses.remove(dns);
825 }
826
827 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
828 }
829 }
830
831 try {
832 mNetd.tetherApplyDnsInterfaces();
833 } catch (ServiceSpecificException | RemoteException e) {
834 mLog.e("Failed to update local DNS caching server");
835 if (newDnses != null) newDnses.clear();
836 }
837 }
838
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900839 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
840 try {
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900841 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900842 mIpv6ForwardingRules.put(rule.address, rule);
843 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900844 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900845 }
846 }
847
848 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
849 try {
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900850 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900851 if (removeFromMap) {
852 mIpv6ForwardingRules.remove(rule.address);
853 }
854 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900855 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900856 }
857 }
858
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900859 private void clearIpv6ForwardingRules() {
860 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
861 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
862 }
863 mIpv6ForwardingRules.clear();
864 }
865
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900866 // Convenience method to replace a rule with the same rule on a new upstream interface.
867 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
868 // Relies on the fact that rules are in a map indexed by IP address.
869 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
870 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
871 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
872 }
873
874 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
875 // changes or if a neighbor event is received.
876 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
877 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900878 // If we no longer have an upstream, clear forwarding rules and do nothing else.
879 if (upstreamIfindex == 0) {
880 clearIpv6ForwardingRules();
881 return;
882 }
883
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900884 // If the upstream interface has changed, remove all rules and re-add them with the new
885 // upstream interface.
886 if (prevUpstreamIfindex != upstreamIfindex) {
887 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
888 updateIpv6ForwardingRule(rule, upstreamIfindex);
889 }
890 }
891
892 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900893 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900894 if (e == null) return;
895 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
896 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
897 return;
898 }
899
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900900 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900901 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
902 e.macAddr);
903 if (e.isValid()) {
904 addIpv6ForwardingRule(rule);
905 } else {
906 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
907 }
908 }
909
910 private void handleNeighborEvent(NeighborEvent e) {
911 if (mInterfaceParams != null
912 && mInterfaceParams.index == e.ifindex
913 && mInterfaceParams.hasMacAddress) {
914 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
915 }
916 }
917
markchien74a4fa92019-09-09 20:50:49 +0800918 private byte getHopLimit(String upstreamIface) {
919 try {
920 int upstreamHopLimit = Integer.parseUnsignedInt(
921 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
922 // Add one hop to account for this forwarding device
923 upstreamHopLimit++;
924 // Cap the hop limit to 255.
925 return (byte) Integer.min(upstreamHopLimit, 255);
926 } catch (Exception e) {
927 mLog.e("Failed to find upstream interface hop limit", e);
928 }
929 return RaParams.DEFAULT_HOPLIMIT;
930 }
931
932 private void setRaParams(RaParams newParams) {
933 if (mRaDaemon != null) {
934 final RaParams deprecatedParams =
935 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
936
937 configureLocalIPv6Routes(deprecatedParams.prefixes,
938 (newParams != null) ? newParams.prefixes : null);
939
940 configureLocalIPv6Dns(deprecatedParams.dnses,
941 (newParams != null) ? newParams.dnses : null);
942
943 mRaDaemon.buildNewRa(deprecatedParams, newParams);
944 }
945
946 mLastRaParams = newParams;
947 }
948
949 private void logMessage(State state, int what) {
950 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
951 }
952
953 private void sendInterfaceState(int newInterfaceState) {
954 mServingMode = newInterfaceState;
955 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
956 sendLinkProperties();
957 }
958
959 private void sendLinkProperties() {
960 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
961 }
962
963 private void resetLinkProperties() {
964 mLinkProperties.clear();
965 mLinkProperties.setInterfaceName(mIfaceName);
966 }
967
markchienf053e4b2020-03-16 21:49:48 +0800968 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +0800969 // Ignore static address configuration if they are invalid or null. In theory, static
970 // addresses should not be invalid here because TetheringManager do not allow caller to
971 // specify invalid static address configuration.
972 if (request == null || request.localIPv4Address == null
973 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
974 request.localIPv4Address, request.staticClientAddress)) {
975 return;
976 }
markchienf053e4b2020-03-16 21:49:48 +0800977
978 mStaticIpv4ServerAddr = request.localIPv4Address;
979 mStaticIpv4ClientAddr = request.staticClientAddress;
980 }
981
markchien74a4fa92019-09-09 20:50:49 +0800982 class InitialState extends State {
983 @Override
984 public void enter() {
985 sendInterfaceState(STATE_AVAILABLE);
986 }
987
988 @Override
989 public boolean processMessage(Message message) {
990 logMessage(this, message.what);
991 switch (message.what) {
992 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800993 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800994 switch (message.arg1) {
995 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +0800996 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800997 transitionTo(mLocalHotspotState);
998 break;
999 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001000 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001001 transitionTo(mTetheredState);
1002 break;
1003 default:
1004 mLog.e("Invalid tethering interface serving state specified.");
1005 }
1006 break;
1007 case CMD_INTERFACE_DOWN:
1008 transitionTo(mUnavailableState);
1009 break;
1010 case CMD_IPV6_TETHER_UPDATE:
1011 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1012 break;
1013 default:
1014 return NOT_HANDLED;
1015 }
1016 return HANDLED;
1017 }
1018 }
1019
1020 class BaseServingState extends State {
1021 @Override
1022 public void enter() {
1023 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001024 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001025 return;
1026 }
1027
1028 try {
markchien12c5bb82020-01-07 14:43:17 +08001029 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1030 mIpv4Address.getPrefixLength());
1031 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +08001032 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +08001033 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +08001034 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001035 return;
1036 }
1037
1038 if (!startIPv6()) {
1039 mLog.e("Failed to startIPv6");
1040 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1041 return;
1042 }
1043 }
1044
1045 @Override
1046 public void exit() {
1047 // Note that at this point, we're leaving the tethered state. We can fail any
1048 // of these operations, but it doesn't really change that we have to try them
1049 // all in sequence.
1050 stopIPv6();
1051
1052 try {
markchien12c5bb82020-01-07 14:43:17 +08001053 NetdUtils.untetherInterface(mNetd, mIfaceName);
1054 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001055 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001056 mLog.e("Failed to untether interface: " + e);
1057 }
1058
1059 stopIPv4();
1060
1061 resetLinkProperties();
1062 }
1063
1064 @Override
1065 public boolean processMessage(Message message) {
1066 logMessage(this, message.what);
1067 switch (message.what) {
1068 case CMD_TETHER_UNREQUESTED:
1069 transitionTo(mInitialState);
1070 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1071 break;
1072 case CMD_INTERFACE_DOWN:
1073 transitionTo(mUnavailableState);
1074 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1075 break;
1076 case CMD_IPV6_TETHER_UPDATE:
1077 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1078 sendLinkProperties();
1079 break;
1080 case CMD_IP_FORWARDING_ENABLE_ERROR:
1081 case CMD_IP_FORWARDING_DISABLE_ERROR:
1082 case CMD_START_TETHERING_ERROR:
1083 case CMD_STOP_TETHERING_ERROR:
1084 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001085 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001086 transitionTo(mInitialState);
1087 break;
1088 default:
1089 return false;
1090 }
1091 return true;
1092 }
1093 }
1094
1095 // Handling errors in BaseServingState.enter() by transitioning is
1096 // problematic because transitioning during a multi-state jump yields
1097 // a Log.wtf(). Ultimately, there should be only one ServingState,
1098 // and forwarding and NAT rules should be handled by a coordinating
1099 // functional element outside of IpServer.
1100 class LocalHotspotState extends BaseServingState {
1101 @Override
1102 public void enter() {
1103 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001104 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001105 transitionTo(mInitialState);
1106 }
1107
1108 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1109 sendInterfaceState(STATE_LOCAL_ONLY);
1110 }
1111
1112 @Override
1113 public boolean processMessage(Message message) {
1114 if (super.processMessage(message)) return true;
1115
1116 logMessage(this, message.what);
1117 switch (message.what) {
1118 case CMD_TETHER_REQUESTED:
1119 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1120 break;
1121 case CMD_TETHER_CONNECTION_CHANGED:
1122 // Ignored in local hotspot state.
1123 break;
1124 default:
1125 return false;
1126 }
1127 return true;
1128 }
1129 }
1130
1131 // Handling errors in BaseServingState.enter() by transitioning is
1132 // problematic because transitioning during a multi-state jump yields
1133 // a Log.wtf(). Ultimately, there should be only one ServingState,
1134 // and forwarding and NAT rules should be handled by a coordinating
1135 // functional element outside of IpServer.
1136 class TetheredState extends BaseServingState {
1137 @Override
1138 public void enter() {
1139 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001140 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001141 transitionTo(mInitialState);
1142 }
1143
1144 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1145 sendInterfaceState(STATE_TETHERED);
1146 }
1147
1148 @Override
1149 public void exit() {
1150 cleanupUpstream();
1151 super.exit();
1152 }
1153
1154 private void cleanupUpstream() {
1155 if (mUpstreamIfaceSet == null) return;
1156
1157 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1158 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001159 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001160 }
1161
1162 private void cleanupUpstreamInterface(String upstreamIface) {
1163 // Note that we don't care about errors here.
1164 // Sometimes interfaces are gone before we get
1165 // to remove their rules, which generates errors.
1166 // Just do the best we can.
1167 try {
markchien12c5bb82020-01-07 14:43:17 +08001168 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1169 } catch (RemoteException | ServiceSpecificException e) {
1170 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001171 }
1172 try {
markchien12c5bb82020-01-07 14:43:17 +08001173 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1174 } catch (RemoteException | ServiceSpecificException e) {
1175 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001176 }
1177 }
1178
1179 @Override
1180 public boolean processMessage(Message message) {
1181 if (super.processMessage(message)) return true;
1182
1183 logMessage(this, message.what);
1184 switch (message.what) {
1185 case CMD_TETHER_REQUESTED:
1186 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1187 break;
1188 case CMD_TETHER_CONNECTION_CHANGED:
1189 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1190 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1191 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1192 break;
1193 }
1194
1195 if (newUpstreamIfaceSet == null) {
1196 cleanupUpstream();
1197 break;
1198 }
1199
1200 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1201 cleanupUpstreamInterface(removed);
1202 }
1203
1204 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1205 // This makes the call to cleanupUpstream() in the error
1206 // path for any interface neatly cleanup all the interfaces.
1207 mUpstreamIfaceSet = newUpstreamIfaceSet;
1208
1209 for (String ifname : added) {
1210 try {
markchien12c5bb82020-01-07 14:43:17 +08001211 mNetd.tetherAddForward(mIfaceName, ifname);
1212 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1213 } catch (RemoteException | ServiceSpecificException e) {
1214 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001215 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001216 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001217 transitionTo(mInitialState);
1218 return true;
1219 }
1220 }
1221 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001222 case CMD_NEIGHBOR_EVENT:
1223 handleNeighborEvent((NeighborEvent) message.obj);
1224 break;
markchien74a4fa92019-09-09 20:50:49 +08001225 default:
1226 return false;
1227 }
1228 return true;
1229 }
1230
1231 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1232 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1233 if (mUpstreamIfaceSet != null && newIfaces != null) {
1234 return mUpstreamIfaceSet.equals(newIfaces);
1235 }
1236 return false;
1237 }
1238
1239 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1240 if (mUpstreamIfaceSet == null) return new HashSet<>();
1241
1242 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1243 removed.removeAll(newIfaces.ifnames);
1244 return removed;
1245 }
1246
1247 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1248 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1249 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1250 return added;
1251 }
1252 }
1253
1254 /**
1255 * This state is terminal for the per interface state machine. At this
1256 * point, the master state machine should have removed this interface
1257 * specific state machine from its list of possible recipients of
1258 * tethering requests. The state machine itself will hang around until
1259 * the garbage collector finds it.
1260 */
1261 class UnavailableState extends State {
1262 @Override
1263 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001264 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001265 sendInterfaceState(STATE_UNAVAILABLE);
1266 }
1267 }
1268
1269 // Accumulate routes representing "prefixes to be assigned to the local
1270 // interface", for subsequent modification of local_network routing.
1271 private static ArrayList<RouteInfo> getLocalRoutesFor(
1272 String ifname, HashSet<IpPrefix> prefixes) {
1273 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1274 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001275 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001276 }
1277 return localRoutes;
1278 }
1279
1280 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1281 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1282 final byte[] dnsBytes = localPrefix.getRawAddress();
1283 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1284 try {
1285 return Inet6Address.getByAddress(null, dnsBytes, 0);
1286 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001287 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001288 return null;
1289 }
1290 }
1291
1292 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1293 final byte random = (byte) (new Random()).nextInt();
1294 for (int value : excluded) {
1295 if (random == value) return dflt;
1296 }
1297 return random;
1298 }
1299}