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