blob: 1dac5b7846495932f4f1556de8b3fbb136888082 [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;
Xiao Ma49889dd2020-04-03 17:01:33 +090045import android.net.dhcp.IDhcpEventCallbacks;
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
Xiao Ma49889dd2020-04-03 17:01:33 +0900466 private class DhcpLeaseCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900467 @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
Xiao Ma49889dd2020-04-03 17:01:33 +0900500 public void onNewPrefixRequest(IpPrefix currentPrefix) {
501 //TODO: add specific implementation.
502 }
503
504 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900505 public int getInterfaceVersion() {
506 return this.VERSION;
507 }
508
509 @Override
510 public String getInterfaceHash() throws RemoteException {
511 return this.HASH;
512 }
513 }
514
markchien245352e2020-02-27 20:27:18 +0800515 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800516 if (mUsingLegacyDhcp) {
517 return true;
518 }
markchien245352e2020-02-27 20:27:18 +0800519
520 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
521 final int prefixLen = serverLinkAddr.getPrefixLength();
522 final Inet4Address clientAddr = clientLinkAddr == null ? null :
523 (Inet4Address) clientLinkAddr.getAddress();
524
markchien74a4fa92019-09-09 20:50:49 +0800525 final DhcpServingParamsParcel params;
526 params = new DhcpServingParamsParcelExt()
527 .setDefaultRouters(addr)
528 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
529 .setDnsServers(addr)
markchien245352e2020-02-27 20:27:18 +0800530 .setServerAddr(serverLinkAddr)
531 .setMetered(true)
532 .setSingleClientAddr(clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800533 // TODO: also advertise link MTU
534
535 mDhcpServerStartIndex++;
536 mDeps.makeDhcpServer(
537 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
538 return true;
539 }
540
541 private void stopDhcp() {
542 // Make all previous start requests obsolete so servers are not started later
543 mDhcpServerStartIndex++;
544
545 if (mDhcpServer != null) {
546 try {
547 mDhcpServer.stop(new OnHandlerStatusCallback() {
548 @Override
549 public void callback(int statusCode) {
550 if (statusCode != STATUS_SUCCESS) {
551 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800552 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800553 // Not much more we can do here
554 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900555 mDhcpLeases.clear();
556 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800557 }
558 });
559 mDhcpServer = null;
560 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800561 mLog.e("Error stopping DHCP", e);
562 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800563 }
564 }
565 }
566
markchien245352e2020-02-27 20:27:18 +0800567 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
568 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800569 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800570 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800571 } else {
572 stopDhcp();
573 return true;
574 }
575 }
576
577 private void stopIPv4() {
578 configureIPv4(false);
579 // NOTE: All of configureIPv4() will be refactored out of existence
580 // into calls to InterfaceController, shared with startIPv4().
581 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800582 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800583 mStaticIpv4ServerAddr = null;
584 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800585 }
586
markchien74a4fa92019-09-09 20:50:49 +0800587 private boolean configureIPv4(boolean enabled) {
588 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
589
590 // TODO: Replace this hard-coded information with dynamically selected
591 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800592 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800593 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800594 try {
markchienf053e4b2020-03-16 21:49:48 +0800595 if (mStaticIpv4ServerAddr != null) {
596 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
597 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
598 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900599 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800600 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
601 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800602 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800603 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
604 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800605 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800606 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
607 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900608 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
609 // TODO: randomize address for tethering too, similarly to wifi
610 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
611 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800612 } else {
613 // BT configures the interface elsewhere: only start DHCP.
614 // TODO: make all tethering types behave the same way, and delete the bluetooth
615 // code that calls into NetworkManagementService directly.
616 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
617 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
markchien245352e2020-02-27 20:27:18 +0800618 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
markchien12c5bb82020-01-07 14:43:17 +0800619 }
620 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
621 } catch (IllegalArgumentException e) {
622 mLog.e("Error selecting ipv4 address", e);
623 if (!enabled) stopDhcp();
624 return false;
markchien74a4fa92019-09-09 20:50:49 +0800625 }
626
markchien12c5bb82020-01-07 14:43:17 +0800627 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800628 if (mInterfaceType == TetheringManager.TETHERING_WIFI
629 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800630 // The WiFi stack has ownership of the interface up/down state.
631 // It is unclear whether the Bluetooth or USB stacks will manage their own
632 // state.
633 setIfaceUp = null;
634 } else {
635 setIfaceUp = enabled;
636 }
637 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
638 mLog.e("Error configuring interface");
639 if (!enabled) stopDhcp();
640 return false;
641 }
markchien74a4fa92019-09-09 20:50:49 +0800642
markchien74a4fa92019-09-09 20:50:49 +0800643 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800644 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
645 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800646 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800647 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800648 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800649 mLinkProperties.addRoute(route);
650 } else {
markchien12c5bb82020-01-07 14:43:17 +0800651 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800652 mLinkProperties.removeRoute(route);
653 }
markchienf053e4b2020-03-16 21:49:48 +0800654
markchien245352e2020-02-27 20:27:18 +0800655 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800656 }
657
658 private String getRandomWifiIPv4Address() {
659 try {
660 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
661 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
662 return InetAddress.getByAddress(bytes).getHostAddress();
663 } catch (Exception e) {
664 return WIFI_HOST_IFACE_ADDR;
665 }
666 }
667
668 private boolean startIPv6() {
669 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
670 if (mInterfaceParams == null) {
671 mLog.e("Failed to find InterfaceParams");
672 stopIPv6();
673 return false;
674 }
675
676 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
677 if (!mRaDaemon.start()) {
678 stopIPv6();
679 return false;
680 }
681
682 return true;
683 }
684
685 private void stopIPv6() {
686 mInterfaceParams = null;
687 setRaParams(null);
688
689 if (mRaDaemon != null) {
690 mRaDaemon.stop();
691 mRaDaemon = null;
692 }
693 }
694
695 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
696 // LinkProperties. These have extraneous data filtered out and only the
697 // necessary prefixes included (per its prefix distribution policy).
698 //
699 // TODO: Evaluate using a data structure than is more directly suited to
700 // communicating only the relevant information.
701 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
702 if (mRaDaemon == null) return;
703
704 // Avoid unnecessary work on spurious updates.
705 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
706 return;
707 }
708
709 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900710 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800711
712 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900713 final String upstreamIface = v6only.getInterfaceName();
714
markchien74a4fa92019-09-09 20:50:49 +0800715 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800716 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
717 // the ethernet header size. This makes kernel ebpf tethering offload happy.
718 // This hack should be reverted once we have the kernel fixed up.
719 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
720 // see RouterAdvertisementDaemon.java putMtu()
721 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800722 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
723
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900724 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800725
726 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
727 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
728
729 final IpPrefix prefix = new IpPrefix(
730 linkAddr.getAddress(), linkAddr.getPrefixLength());
731 params.prefixes.add(prefix);
732
733 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
734 if (dnsServer != null) {
735 params.dnses.add(dnsServer);
736 }
737 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900738
739 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800740 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900741
markchien74a4fa92019-09-09 20:50:49 +0800742 // If v6only is null, we pass in null to setRaParams(), which handles
743 // deprecation of any existing RA data.
744
745 setRaParams(params);
746 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900747
748 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
749 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800750 }
751
752 private void configureLocalIPv6Routes(
753 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
754 // [1] Remove the routes that are deprecated.
755 if (!deprecatedPrefixes.isEmpty()) {
756 final ArrayList<RouteInfo> toBeRemoved =
757 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800758 // Remove routes from local network.
759 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
760 mNetd, toBeRemoved);
761 if (removalFailures > 0) {
762 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
763 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800764 }
765
766 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
767 }
768
769 // [2] Add only the routes that have not previously been added.
770 if (newPrefixes != null && !newPrefixes.isEmpty()) {
771 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
772 if (mLastRaParams != null) {
773 addedPrefixes.removeAll(mLastRaParams.prefixes);
774 }
775
776 if (!addedPrefixes.isEmpty()) {
777 final ArrayList<RouteInfo> toBeAdded =
778 getLocalRoutesFor(mIfaceName, addedPrefixes);
779 try {
markchien12c5bb82020-01-07 14:43:17 +0800780 // It's safe to call networkAddInterface() even if
781 // the interface is already in the local_network.
782 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
783 try {
784 // Add routes from local network. Note that adding routes that
785 // already exist does not cause an error (EEXIST is silently ignored).
786 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
787 } catch (IllegalStateException e) {
788 mLog.e("Failed to add IPv6 routes to local table: " + e);
789 }
790 } catch (ServiceSpecificException | RemoteException e) {
791 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800792 }
793
794 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
795 }
796 }
797 }
798
799 private void configureLocalIPv6Dns(
800 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
801 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
802 if (mNetd == null) {
803 if (newDnses != null) newDnses.clear();
804 mLog.e("No netd service instance available; not setting local IPv6 addresses");
805 return;
806 }
807
808 // [1] Remove deprecated local DNS IP addresses.
809 if (!deprecatedDnses.isEmpty()) {
810 for (Inet6Address dns : deprecatedDnses) {
811 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
812 mLog.e("Failed to remove local dns IP " + dns);
813 }
814
815 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
816 }
817 }
818
819 // [2] Add only the local DNS IP addresses that have not previously been added.
820 if (newDnses != null && !newDnses.isEmpty()) {
821 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
822 if (mLastRaParams != null) {
823 addedDnses.removeAll(mLastRaParams.dnses);
824 }
825
826 for (Inet6Address dns : addedDnses) {
827 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
828 mLog.e("Failed to add local dns IP " + dns);
829 newDnses.remove(dns);
830 }
831
832 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
833 }
834 }
835
836 try {
837 mNetd.tetherApplyDnsInterfaces();
838 } catch (ServiceSpecificException | RemoteException e) {
839 mLog.e("Failed to update local DNS caching server");
840 if (newDnses != null) newDnses.clear();
841 }
842 }
843
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900844 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
845 try {
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900846 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900847 mIpv6ForwardingRules.put(rule.address, rule);
848 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900849 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900850 }
851 }
852
853 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
854 try {
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900855 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900856 if (removeFromMap) {
857 mIpv6ForwardingRules.remove(rule.address);
858 }
859 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900860 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900861 }
862 }
863
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900864 private void clearIpv6ForwardingRules() {
865 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
866 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
867 }
868 mIpv6ForwardingRules.clear();
869 }
870
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900871 // Convenience method to replace a rule with the same rule on a new upstream interface.
872 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
873 // Relies on the fact that rules are in a map indexed by IP address.
874 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
875 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
876 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
877 }
878
879 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
880 // changes or if a neighbor event is received.
881 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
882 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900883 // If we no longer have an upstream, clear forwarding rules and do nothing else.
884 if (upstreamIfindex == 0) {
885 clearIpv6ForwardingRules();
886 return;
887 }
888
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900889 // If the upstream interface has changed, remove all rules and re-add them with the new
890 // upstream interface.
891 if (prevUpstreamIfindex != upstreamIfindex) {
892 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
893 updateIpv6ForwardingRule(rule, upstreamIfindex);
894 }
895 }
896
897 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900898 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900899 if (e == null) return;
900 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
901 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
902 return;
903 }
904
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900905 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900906 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
907 e.macAddr);
908 if (e.isValid()) {
909 addIpv6ForwardingRule(rule);
910 } else {
911 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
912 }
913 }
914
915 private void handleNeighborEvent(NeighborEvent e) {
916 if (mInterfaceParams != null
917 && mInterfaceParams.index == e.ifindex
918 && mInterfaceParams.hasMacAddress) {
919 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
920 }
921 }
922
markchien74a4fa92019-09-09 20:50:49 +0800923 private byte getHopLimit(String upstreamIface) {
924 try {
925 int upstreamHopLimit = Integer.parseUnsignedInt(
926 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
927 // Add one hop to account for this forwarding device
928 upstreamHopLimit++;
929 // Cap the hop limit to 255.
930 return (byte) Integer.min(upstreamHopLimit, 255);
931 } catch (Exception e) {
932 mLog.e("Failed to find upstream interface hop limit", e);
933 }
934 return RaParams.DEFAULT_HOPLIMIT;
935 }
936
937 private void setRaParams(RaParams newParams) {
938 if (mRaDaemon != null) {
939 final RaParams deprecatedParams =
940 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
941
942 configureLocalIPv6Routes(deprecatedParams.prefixes,
943 (newParams != null) ? newParams.prefixes : null);
944
945 configureLocalIPv6Dns(deprecatedParams.dnses,
946 (newParams != null) ? newParams.dnses : null);
947
948 mRaDaemon.buildNewRa(deprecatedParams, newParams);
949 }
950
951 mLastRaParams = newParams;
952 }
953
954 private void logMessage(State state, int what) {
955 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
956 }
957
958 private void sendInterfaceState(int newInterfaceState) {
959 mServingMode = newInterfaceState;
960 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
961 sendLinkProperties();
962 }
963
964 private void sendLinkProperties() {
965 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
966 }
967
968 private void resetLinkProperties() {
969 mLinkProperties.clear();
970 mLinkProperties.setInterfaceName(mIfaceName);
971 }
972
markchienf053e4b2020-03-16 21:49:48 +0800973 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +0800974 // Ignore static address configuration if they are invalid or null. In theory, static
975 // addresses should not be invalid here because TetheringManager do not allow caller to
976 // specify invalid static address configuration.
977 if (request == null || request.localIPv4Address == null
978 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
979 request.localIPv4Address, request.staticClientAddress)) {
980 return;
981 }
markchienf053e4b2020-03-16 21:49:48 +0800982
983 mStaticIpv4ServerAddr = request.localIPv4Address;
984 mStaticIpv4ClientAddr = request.staticClientAddress;
985 }
986
markchien74a4fa92019-09-09 20:50:49 +0800987 class InitialState extends State {
988 @Override
989 public void enter() {
990 sendInterfaceState(STATE_AVAILABLE);
991 }
992
993 @Override
994 public boolean processMessage(Message message) {
995 logMessage(this, message.what);
996 switch (message.what) {
997 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800998 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800999 switch (message.arg1) {
1000 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001001 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001002 transitionTo(mLocalHotspotState);
1003 break;
1004 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001005 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001006 transitionTo(mTetheredState);
1007 break;
1008 default:
1009 mLog.e("Invalid tethering interface serving state specified.");
1010 }
1011 break;
1012 case CMD_INTERFACE_DOWN:
1013 transitionTo(mUnavailableState);
1014 break;
1015 case CMD_IPV6_TETHER_UPDATE:
1016 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1017 break;
1018 default:
1019 return NOT_HANDLED;
1020 }
1021 return HANDLED;
1022 }
1023 }
1024
1025 class BaseServingState extends State {
1026 @Override
1027 public void enter() {
1028 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001029 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001030 return;
1031 }
1032
1033 try {
markchien12c5bb82020-01-07 14:43:17 +08001034 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1035 mIpv4Address.getPrefixLength());
1036 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +08001037 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +08001038 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +08001039 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001040 return;
1041 }
1042
1043 if (!startIPv6()) {
1044 mLog.e("Failed to startIPv6");
1045 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1046 return;
1047 }
1048 }
1049
1050 @Override
1051 public void exit() {
1052 // Note that at this point, we're leaving the tethered state. We can fail any
1053 // of these operations, but it doesn't really change that we have to try them
1054 // all in sequence.
1055 stopIPv6();
1056
1057 try {
markchien12c5bb82020-01-07 14:43:17 +08001058 NetdUtils.untetherInterface(mNetd, mIfaceName);
1059 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001060 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001061 mLog.e("Failed to untether interface: " + e);
1062 }
1063
1064 stopIPv4();
1065
1066 resetLinkProperties();
1067 }
1068
1069 @Override
1070 public boolean processMessage(Message message) {
1071 logMessage(this, message.what);
1072 switch (message.what) {
1073 case CMD_TETHER_UNREQUESTED:
1074 transitionTo(mInitialState);
1075 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1076 break;
1077 case CMD_INTERFACE_DOWN:
1078 transitionTo(mUnavailableState);
1079 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1080 break;
1081 case CMD_IPV6_TETHER_UPDATE:
1082 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1083 sendLinkProperties();
1084 break;
1085 case CMD_IP_FORWARDING_ENABLE_ERROR:
1086 case CMD_IP_FORWARDING_DISABLE_ERROR:
1087 case CMD_START_TETHERING_ERROR:
1088 case CMD_STOP_TETHERING_ERROR:
1089 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001090 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001091 transitionTo(mInitialState);
1092 break;
1093 default:
1094 return false;
1095 }
1096 return true;
1097 }
1098 }
1099
1100 // Handling errors in BaseServingState.enter() by transitioning is
1101 // problematic because transitioning during a multi-state jump yields
1102 // a Log.wtf(). Ultimately, there should be only one ServingState,
1103 // and forwarding and NAT rules should be handled by a coordinating
1104 // functional element outside of IpServer.
1105 class LocalHotspotState extends BaseServingState {
1106 @Override
1107 public void enter() {
1108 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001109 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001110 transitionTo(mInitialState);
1111 }
1112
1113 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1114 sendInterfaceState(STATE_LOCAL_ONLY);
1115 }
1116
1117 @Override
1118 public boolean processMessage(Message message) {
1119 if (super.processMessage(message)) return true;
1120
1121 logMessage(this, message.what);
1122 switch (message.what) {
1123 case CMD_TETHER_REQUESTED:
1124 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1125 break;
1126 case CMD_TETHER_CONNECTION_CHANGED:
1127 // Ignored in local hotspot state.
1128 break;
1129 default:
1130 return false;
1131 }
1132 return true;
1133 }
1134 }
1135
1136 // Handling errors in BaseServingState.enter() by transitioning is
1137 // problematic because transitioning during a multi-state jump yields
1138 // a Log.wtf(). Ultimately, there should be only one ServingState,
1139 // and forwarding and NAT rules should be handled by a coordinating
1140 // functional element outside of IpServer.
1141 class TetheredState extends BaseServingState {
1142 @Override
1143 public void enter() {
1144 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001145 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001146 transitionTo(mInitialState);
1147 }
1148
1149 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1150 sendInterfaceState(STATE_TETHERED);
1151 }
1152
1153 @Override
1154 public void exit() {
1155 cleanupUpstream();
1156 super.exit();
1157 }
1158
1159 private void cleanupUpstream() {
1160 if (mUpstreamIfaceSet == null) return;
1161
1162 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1163 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001164 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001165 }
1166
1167 private void cleanupUpstreamInterface(String upstreamIface) {
1168 // Note that we don't care about errors here.
1169 // Sometimes interfaces are gone before we get
1170 // to remove their rules, which generates errors.
1171 // Just do the best we can.
1172 try {
markchien12c5bb82020-01-07 14:43:17 +08001173 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1174 } catch (RemoteException | ServiceSpecificException e) {
1175 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001176 }
1177 try {
markchien12c5bb82020-01-07 14:43:17 +08001178 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1179 } catch (RemoteException | ServiceSpecificException e) {
1180 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001181 }
1182 }
1183
1184 @Override
1185 public boolean processMessage(Message message) {
1186 if (super.processMessage(message)) return true;
1187
1188 logMessage(this, message.what);
1189 switch (message.what) {
1190 case CMD_TETHER_REQUESTED:
1191 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1192 break;
1193 case CMD_TETHER_CONNECTION_CHANGED:
1194 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1195 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1196 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1197 break;
1198 }
1199
1200 if (newUpstreamIfaceSet == null) {
1201 cleanupUpstream();
1202 break;
1203 }
1204
1205 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1206 cleanupUpstreamInterface(removed);
1207 }
1208
1209 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1210 // This makes the call to cleanupUpstream() in the error
1211 // path for any interface neatly cleanup all the interfaces.
1212 mUpstreamIfaceSet = newUpstreamIfaceSet;
1213
1214 for (String ifname : added) {
1215 try {
markchien12c5bb82020-01-07 14:43:17 +08001216 mNetd.tetherAddForward(mIfaceName, ifname);
1217 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1218 } catch (RemoteException | ServiceSpecificException e) {
1219 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001220 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001221 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001222 transitionTo(mInitialState);
1223 return true;
1224 }
1225 }
1226 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001227 case CMD_NEIGHBOR_EVENT:
1228 handleNeighborEvent((NeighborEvent) message.obj);
1229 break;
markchien74a4fa92019-09-09 20:50:49 +08001230 default:
1231 return false;
1232 }
1233 return true;
1234 }
1235
1236 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1237 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1238 if (mUpstreamIfaceSet != null && newIfaces != null) {
1239 return mUpstreamIfaceSet.equals(newIfaces);
1240 }
1241 return false;
1242 }
1243
1244 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1245 if (mUpstreamIfaceSet == null) return new HashSet<>();
1246
1247 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1248 removed.removeAll(newIfaces.ifnames);
1249 return removed;
1250 }
1251
1252 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1253 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1254 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1255 return added;
1256 }
1257 }
1258
1259 /**
1260 * This state is terminal for the per interface state machine. At this
1261 * point, the master state machine should have removed this interface
1262 * specific state machine from its list of possible recipients of
1263 * tethering requests. The state machine itself will hang around until
1264 * the garbage collector finds it.
1265 */
1266 class UnavailableState extends State {
1267 @Override
1268 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001269 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001270 sendInterfaceState(STATE_UNAVAILABLE);
1271 }
1272 }
1273
1274 // Accumulate routes representing "prefixes to be assigned to the local
1275 // interface", for subsequent modification of local_network routing.
1276 private static ArrayList<RouteInfo> getLocalRoutesFor(
1277 String ifname, HashSet<IpPrefix> prefixes) {
1278 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1279 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001280 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001281 }
1282 return localRoutes;
1283 }
1284
1285 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1286 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1287 final byte[] dnsBytes = localPrefix.getRawAddress();
1288 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1289 try {
1290 return Inet6Address.getByAddress(null, dnsBytes, 0);
1291 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001292 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001293 return null;
1294 }
1295 }
1296
1297 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1298 final byte random = (byte) (new Random()).nextInt();
1299 for (int value : excluded) {
1300 if (random == value) return dflt;
1301 }
1302 return random;
1303 }
1304}