blob: 83727bcdc67e5377ec89ff4a8e39c803f83fd11c [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
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900125 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
126
markchien74a4fa92019-09-09 20:50:49 +0800127 private static final String TAG = "IpServer";
128 private static final boolean DBG = false;
129 private static final boolean VDBG = false;
130 private static final Class[] sMessageClasses = {
131 IpServer.class
132 };
133 private static final SparseArray<String> sMagicDecoderRing =
134 MessageUtils.findMessageNames(sMessageClasses);
135
136 /** IpServer callback. */
137 public static class Callback {
138 /**
139 * Notify that |who| has changed its tethering state.
140 *
141 * @param who the calling instance of IpServer
142 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800143 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800144 */
markchien9d353822019-12-16 20:15:20 +0800145 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800146
147 /**
148 * Notify that |who| has new LinkProperties.
149 *
150 * @param who the calling instance of IpServer
151 * @param newLp the new LinkProperties to report
152 */
markchien9d353822019-12-16 20:15:20 +0800153 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900154
155 /**
156 * Notify that the DHCP leases changed in one of the IpServers.
157 */
158 public void dhcpLeasesChanged() { }
markchien74a4fa92019-09-09 20:50:49 +0800159 }
160
161 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800162 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900163 /** Create an IpNeighborMonitor to be used by this IpServer */
164 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
165 IpNeighborMonitor.NeighborEventConsumer consumer) {
166 return new IpNeighborMonitor(handler, log, consumer);
167 }
168
markchien74a4fa92019-09-09 20:50:49 +0800169 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
170 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
171 return new RouterAdvertisementDaemon(ifParams);
172 }
173
174 /** Get |ifName|'s interface information.*/
175 public InterfaceParams getInterfaceParams(String ifName) {
176 return InterfaceParams.getByName(ifName);
177 }
178
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900179 /** Get |ifName|'s interface index. */
180 public int getIfindex(String ifName) {
181 try {
182 return NetworkInterface.getByName(ifName).getIndex();
183 } catch (IOException | NullPointerException e) {
184 Log.e(TAG, "Can't determine interface index for interface " + ifName);
185 return 0;
186 }
187 }
markchien9d353822019-12-16 20:15:20 +0800188 /** Create a DhcpServer instance to be used by IpServer. */
189 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
190 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800191 }
192
markchien74a4fa92019-09-09 20:50:49 +0800193 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800194 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800195 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800196 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800197 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800198 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800199 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800200 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800201 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800202 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800203 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800204 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800205 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800206 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800207 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800209 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800211 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900213 // new neighbor cache entry on our interface
214 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
markchien74a4fa92019-09-09 20:50:49 +0800215
216 private final State mInitialState;
217 private final State mLocalHotspotState;
218 private final State mTetheredState;
219 private final State mUnavailableState;
220
221 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800222 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800223 private final Callback mCallback;
224 private final InterfaceController mInterfaceCtrl;
225
226 private final String mIfaceName;
227 private final int mInterfaceType;
228 private final LinkProperties mLinkProperties;
229 private final boolean mUsingLegacyDhcp;
230
231 private final Dependencies mDeps;
232
233 private int mLastError;
234 private int mServingMode;
235 private InterfaceSet mUpstreamIfaceSet; // may change over time
236 private InterfaceParams mInterfaceParams;
237 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
238 // properties are those selected by the IPv6TetheringCoordinator and relayed
239 // to us. By comparison, mLinkProperties contains the addresses and directly
240 // connected routes that have been formed from these properties iff. we have
241 // succeeded in configuring them and are able to announce them within Router
242 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
243 private LinkProperties mLastIPv6LinkProperties;
244 private RouterAdvertisementDaemon mRaDaemon;
245
246 // To be accessed only on the handler thread
247 private int mDhcpServerStartIndex = 0;
248 private IDhcpServer mDhcpServer;
249 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800250 private LinkAddress mIpv4Address;
markchienf053e4b2020-03-16 21:49:48 +0800251
252 private LinkAddress mStaticIpv4ServerAddr;
253 private LinkAddress mStaticIpv4ClientAddr;
254
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900255 @NonNull
256 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800257
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900258 private int mLastIPv6UpstreamIfindex = 0;
259
260 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
261 public void accept(NeighborEvent e) {
262 sendMessage(CMD_NEIGHBOR_EVENT, e);
263 }
264 }
265
266 static class Ipv6ForwardingRule {
267 public final int upstreamIfindex;
268 public final int downstreamIfindex;
269 public final Inet6Address address;
270 public final MacAddress srcMac;
271 public final MacAddress dstMac;
272
273 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
274 MacAddress srcMac, MacAddress dstMac) {
275 this.upstreamIfindex = upstreamIfindex;
276 this.downstreamIfindex = downstreamIfIndex;
277 this.address = address;
278 this.srcMac = srcMac;
279 this.dstMac = dstMac;
280 }
281
282 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
283 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
284 dstMac);
285 }
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900286
287 // Don't manipulate TetherOffloadRuleParcel directly because implementing onNewUpstream()
288 // would be error-prone due to generated stable AIDL classes not having a copy constructor.
289 public TetherOffloadRuleParcel toTetherOffloadRuleParcel() {
290 final TetherOffloadRuleParcel parcel = new TetherOffloadRuleParcel();
291 parcel.inputInterfaceIndex = upstreamIfindex;
292 parcel.outputInterfaceIndex = downstreamIfindex;
293 parcel.destination = address.getAddress();
294 parcel.prefixLength = 128;
295 parcel.srcL2Address = srcMac.toByteArray();
296 parcel.dstL2Address = dstMac.toByteArray();
297 return parcel;
298 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900299 }
300 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
301 new LinkedHashMap<>();
302
303 private final IpNeighborMonitor mIpNeighborMonitor;
304
markchien74a4fa92019-09-09 20:50:49 +0800305 public IpServer(
306 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800307 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800308 super(ifaceName, looper);
309 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800310 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800311 mCallback = callback;
312 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
313 mIfaceName = ifaceName;
314 mInterfaceType = interfaceType;
315 mLinkProperties = new LinkProperties();
316 mUsingLegacyDhcp = usingLegacyDhcp;
317 mDeps = deps;
318 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800319 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800320 mServingMode = STATE_AVAILABLE;
321
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900322 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
323 new MyNeighborEventConsumer());
324 if (!mIpNeighborMonitor.start()) {
325 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
326 }
327
markchien74a4fa92019-09-09 20:50:49 +0800328 mInitialState = new InitialState();
329 mLocalHotspotState = new LocalHotspotState();
330 mTetheredState = new TetheredState();
331 mUnavailableState = new UnavailableState();
332 addState(mInitialState);
333 addState(mLocalHotspotState);
334 addState(mTetheredState);
335 addState(mUnavailableState);
336
337 setInitialState(mInitialState);
338 }
339
340 /** Interface name which IpServer served.*/
341 public String interfaceName() {
342 return mIfaceName;
343 }
344
345 /**
markchien9b4d7572019-12-25 19:40:32 +0800346 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800347 */
348 public int interfaceType() {
349 return mInterfaceType;
350 }
351
352 /** Last error from this IpServer. */
353 public int lastError() {
354 return mLastError;
355 }
356
357 /** Serving mode is the current state of IpServer state machine. */
358 public int servingMode() {
359 return mServingMode;
360 }
361
362 /** The properties of the network link which IpServer is serving. */
363 public LinkProperties linkProperties() {
364 return new LinkProperties(mLinkProperties);
365 }
366
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900367 /**
368 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
369 * thread.
370 */
371 public List<TetheredClient> getAllLeases() {
372 return Collections.unmodifiableList(mDhcpLeases);
373 }
374
markchien74a4fa92019-09-09 20:50:49 +0800375 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
376 public void stop() {
377 sendMessage(CMD_INTERFACE_DOWN);
378 }
379
380 /**
381 * Tethering is canceled. IpServer state machine will be available and wait for
382 * next tethering request.
383 */
384 public void unwanted() {
385 sendMessage(CMD_TETHER_UNREQUESTED);
386 }
387
388 /** Internals. */
389
390 private boolean startIPv4() {
391 return configureIPv4(true);
392 }
393
394 /**
395 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
396 * handler.
397 *
398 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
399 * with different implementations of the callback, to differentiate handling of success/error in
400 * each call.
401 */
402 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
403 @Override
404 public void onStatusAvailable(int statusCode) {
405 getHandler().post(() -> callback(statusCode));
406 }
407
408 public abstract void callback(int statusCode);
409
410 @Override
411 public int getInterfaceVersion() {
412 return this.VERSION;
413 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900414
415 @Override
416 public String getInterfaceHash() {
417 return this.HASH;
418 }
markchien74a4fa92019-09-09 20:50:49 +0800419 }
420
421 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
422 private final int mStartIndex;
423
424 private DhcpServerCallbacksImpl(int startIndex) {
425 mStartIndex = startIndex;
426 }
427
428 @Override
429 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
430 getHandler().post(() -> {
431 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
432 if (mStartIndex != mDhcpServerStartIndex) {
433 // This start request is obsolete. When the |server| binder token goes out of
434 // scope, the garbage collector will finalize it, which causes the network stack
435 // process garbage collector to collect the server itself.
436 return;
437 }
438
439 if (statusCode != STATUS_SUCCESS) {
440 mLog.e("Error obtaining DHCP server: " + statusCode);
441 handleError();
442 return;
443 }
444
445 mDhcpServer = server;
446 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900447 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800448 @Override
449 public void callback(int startStatusCode) {
450 if (startStatusCode != STATUS_SUCCESS) {
451 mLog.e("Error starting DHCP server: " + startStatusCode);
452 handleError();
453 }
454 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900455 }, new DhcpLeaseCallback());
markchien74a4fa92019-09-09 20:50:49 +0800456 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800457 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800458 }
459 });
460 }
461
462 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800463 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800464 transitionTo(mInitialState);
465 }
466 }
467
Xiao Ma49889dd2020-04-03 17:01:33 +0900468 private class DhcpLeaseCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900469 @Override
470 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
471 final ArrayList<TetheredClient> leases = new ArrayList<>();
472 for (DhcpLeaseParcelable lease : leaseParcelables) {
473 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900474 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
475 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
476 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900477
478 final MacAddress macAddress;
479 try {
480 macAddress = MacAddress.fromBytes(lease.hwAddr);
481 } catch (IllegalArgumentException e) {
482 Log.wtf(TAG, "Invalid address received from DhcpServer: "
483 + Arrays.toString(lease.hwAddr));
484 return;
485 }
486
487 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900488 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900489 leases.add(new TetheredClient(
490 macAddress,
491 Collections.singletonList(addressInfo),
492 mInterfaceType));
493 }
494
495 getHandler().post(() -> {
496 mDhcpLeases = leases;
497 mCallback.dhcpLeasesChanged();
498 });
499 }
500
501 @Override
Xiao Ma49889dd2020-04-03 17:01:33 +0900502 public void onNewPrefixRequest(IpPrefix currentPrefix) {
503 //TODO: add specific implementation.
504 }
505
506 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900507 public int getInterfaceVersion() {
508 return this.VERSION;
509 }
510
511 @Override
512 public String getInterfaceHash() throws RemoteException {
513 return this.HASH;
514 }
515 }
516
markchien245352e2020-02-27 20:27:18 +0800517 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800518 if (mUsingLegacyDhcp) {
519 return true;
520 }
markchien245352e2020-02-27 20:27:18 +0800521
522 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
523 final int prefixLen = serverLinkAddr.getPrefixLength();
524 final Inet4Address clientAddr = clientLinkAddr == null ? null :
525 (Inet4Address) clientLinkAddr.getAddress();
526
markchien74a4fa92019-09-09 20:50:49 +0800527 final DhcpServingParamsParcel params;
528 params = new DhcpServingParamsParcelExt()
529 .setDefaultRouters(addr)
530 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
531 .setDnsServers(addr)
markchien245352e2020-02-27 20:27:18 +0800532 .setServerAddr(serverLinkAddr)
533 .setMetered(true)
534 .setSingleClientAddr(clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800535 // TODO: also advertise link MTU
536
537 mDhcpServerStartIndex++;
538 mDeps.makeDhcpServer(
539 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
540 return true;
541 }
542
543 private void stopDhcp() {
544 // Make all previous start requests obsolete so servers are not started later
545 mDhcpServerStartIndex++;
546
547 if (mDhcpServer != null) {
548 try {
549 mDhcpServer.stop(new OnHandlerStatusCallback() {
550 @Override
551 public void callback(int statusCode) {
552 if (statusCode != STATUS_SUCCESS) {
553 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800554 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800555 // Not much more we can do here
556 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900557 mDhcpLeases.clear();
558 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800559 }
560 });
561 mDhcpServer = null;
562 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800563 mLog.e("Error stopping DHCP", e);
564 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800565 }
566 }
567 }
568
markchien245352e2020-02-27 20:27:18 +0800569 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
570 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800571 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800572 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800573 } else {
574 stopDhcp();
575 return true;
576 }
577 }
578
579 private void stopIPv4() {
580 configureIPv4(false);
581 // NOTE: All of configureIPv4() will be refactored out of existence
582 // into calls to InterfaceController, shared with startIPv4().
583 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800584 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800585 mStaticIpv4ServerAddr = null;
586 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800587 }
588
markchien74a4fa92019-09-09 20:50:49 +0800589 private boolean configureIPv4(boolean enabled) {
590 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
591
592 // TODO: Replace this hard-coded information with dynamically selected
593 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800594 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800595 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800596 try {
markchienf053e4b2020-03-16 21:49:48 +0800597 if (mStaticIpv4ServerAddr != null) {
598 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
599 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
600 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900601 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800602 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
603 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800604 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800605 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
606 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800607 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800608 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
609 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900610 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
611 // TODO: randomize address for tethering too, similarly to wifi
612 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
613 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800614 } else {
615 // BT configures the interface elsewhere: only start DHCP.
616 // TODO: make all tethering types behave the same way, and delete the bluetooth
617 // code that calls into NetworkManagementService directly.
618 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
619 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
markchien245352e2020-02-27 20:27:18 +0800620 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
markchien12c5bb82020-01-07 14:43:17 +0800621 }
622 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
623 } catch (IllegalArgumentException e) {
624 mLog.e("Error selecting ipv4 address", e);
625 if (!enabled) stopDhcp();
626 return false;
markchien74a4fa92019-09-09 20:50:49 +0800627 }
628
markchien12c5bb82020-01-07 14:43:17 +0800629 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800630 if (mInterfaceType == TetheringManager.TETHERING_WIFI
631 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800632 // The WiFi stack has ownership of the interface up/down state.
633 // It is unclear whether the Bluetooth or USB stacks will manage their own
634 // state.
635 setIfaceUp = null;
636 } else {
637 setIfaceUp = enabled;
638 }
639 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
640 mLog.e("Error configuring interface");
641 if (!enabled) stopDhcp();
642 return false;
643 }
markchien74a4fa92019-09-09 20:50:49 +0800644
markchien74a4fa92019-09-09 20:50:49 +0800645 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800646 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
647 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800648 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800649 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800650 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800651 mLinkProperties.addRoute(route);
652 } else {
markchien12c5bb82020-01-07 14:43:17 +0800653 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800654 mLinkProperties.removeRoute(route);
655 }
markchienf053e4b2020-03-16 21:49:48 +0800656
markchien245352e2020-02-27 20:27:18 +0800657 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800658 }
659
660 private String getRandomWifiIPv4Address() {
661 try {
662 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
663 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
664 return InetAddress.getByAddress(bytes).getHostAddress();
665 } catch (Exception e) {
666 return WIFI_HOST_IFACE_ADDR;
667 }
668 }
669
670 private boolean startIPv6() {
671 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
672 if (mInterfaceParams == null) {
673 mLog.e("Failed to find InterfaceParams");
674 stopIPv6();
675 return false;
676 }
677
678 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
679 if (!mRaDaemon.start()) {
680 stopIPv6();
681 return false;
682 }
683
684 return true;
685 }
686
687 private void stopIPv6() {
688 mInterfaceParams = null;
689 setRaParams(null);
690
691 if (mRaDaemon != null) {
692 mRaDaemon.stop();
693 mRaDaemon = null;
694 }
695 }
696
697 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
698 // LinkProperties. These have extraneous data filtered out and only the
699 // necessary prefixes included (per its prefix distribution policy).
700 //
701 // TODO: Evaluate using a data structure than is more directly suited to
702 // communicating only the relevant information.
703 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
704 if (mRaDaemon == null) return;
705
706 // Avoid unnecessary work on spurious updates.
707 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
708 return;
709 }
710
711 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900712 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800713
714 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900715 final String upstreamIface = v6only.getInterfaceName();
716
markchien74a4fa92019-09-09 20:50:49 +0800717 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800718 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
719 // the ethernet header size. This makes kernel ebpf tethering offload happy.
720 // This hack should be reverted once we have the kernel fixed up.
721 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
722 // see RouterAdvertisementDaemon.java putMtu()
723 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800724 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
725
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900726 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800727
728 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
729 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
730
731 final IpPrefix prefix = new IpPrefix(
732 linkAddr.getAddress(), linkAddr.getPrefixLength());
733 params.prefixes.add(prefix);
734
735 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
736 if (dnsServer != null) {
737 params.dnses.add(dnsServer);
738 }
739 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900740
741 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800742 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900743
markchien74a4fa92019-09-09 20:50:49 +0800744 // If v6only is null, we pass in null to setRaParams(), which handles
745 // deprecation of any existing RA data.
746
747 setRaParams(params);
748 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900749
750 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
751 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800752 }
753
754 private void configureLocalIPv6Routes(
755 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
756 // [1] Remove the routes that are deprecated.
757 if (!deprecatedPrefixes.isEmpty()) {
758 final ArrayList<RouteInfo> toBeRemoved =
759 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800760 // Remove routes from local network.
761 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
762 mNetd, toBeRemoved);
763 if (removalFailures > 0) {
764 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
765 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800766 }
767
768 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
769 }
770
771 // [2] Add only the routes that have not previously been added.
772 if (newPrefixes != null && !newPrefixes.isEmpty()) {
773 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
774 if (mLastRaParams != null) {
775 addedPrefixes.removeAll(mLastRaParams.prefixes);
776 }
777
778 if (!addedPrefixes.isEmpty()) {
779 final ArrayList<RouteInfo> toBeAdded =
780 getLocalRoutesFor(mIfaceName, addedPrefixes);
781 try {
markchien12c5bb82020-01-07 14:43:17 +0800782 // It's safe to call networkAddInterface() even if
783 // the interface is already in the local_network.
784 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
785 try {
786 // Add routes from local network. Note that adding routes that
787 // already exist does not cause an error (EEXIST is silently ignored).
788 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
789 } catch (IllegalStateException e) {
790 mLog.e("Failed to add IPv6 routes to local table: " + e);
791 }
792 } catch (ServiceSpecificException | RemoteException e) {
793 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800794 }
795
796 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
797 }
798 }
799 }
800
801 private void configureLocalIPv6Dns(
802 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
803 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
804 if (mNetd == null) {
805 if (newDnses != null) newDnses.clear();
806 mLog.e("No netd service instance available; not setting local IPv6 addresses");
807 return;
808 }
809
810 // [1] Remove deprecated local DNS IP addresses.
811 if (!deprecatedDnses.isEmpty()) {
812 for (Inet6Address dns : deprecatedDnses) {
813 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
814 mLog.e("Failed to remove local dns IP " + dns);
815 }
816
817 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
818 }
819 }
820
821 // [2] Add only the local DNS IP addresses that have not previously been added.
822 if (newDnses != null && !newDnses.isEmpty()) {
823 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
824 if (mLastRaParams != null) {
825 addedDnses.removeAll(mLastRaParams.dnses);
826 }
827
828 for (Inet6Address dns : addedDnses) {
829 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
830 mLog.e("Failed to add local dns IP " + dns);
831 newDnses.remove(dns);
832 }
833
834 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
835 }
836 }
837
838 try {
839 mNetd.tetherApplyDnsInterfaces();
840 } catch (ServiceSpecificException | RemoteException e) {
841 mLog.e("Failed to update local DNS caching server");
842 if (newDnses != null) newDnses.clear();
843 }
844 }
845
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900846 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
847 try {
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900848 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900849 mIpv6ForwardingRules.put(rule.address, rule);
850 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900851 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900852 }
853 }
854
855 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
856 try {
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900857 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900858 if (removeFromMap) {
859 mIpv6ForwardingRules.remove(rule.address);
860 }
861 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900862 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900863 }
864 }
865
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900866 private void clearIpv6ForwardingRules() {
867 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
868 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
869 }
870 mIpv6ForwardingRules.clear();
871 }
872
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900873 // Convenience method to replace a rule with the same rule on a new upstream interface.
874 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
875 // Relies on the fact that rules are in a map indexed by IP address.
876 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
877 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
878 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
879 }
880
881 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
882 // changes or if a neighbor event is received.
883 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
884 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900885 // If we no longer have an upstream, clear forwarding rules and do nothing else.
886 if (upstreamIfindex == 0) {
887 clearIpv6ForwardingRules();
888 return;
889 }
890
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900891 // If the upstream interface has changed, remove all rules and re-add them with the new
892 // upstream interface.
893 if (prevUpstreamIfindex != upstreamIfindex) {
894 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
895 updateIpv6ForwardingRule(rule, upstreamIfindex);
896 }
897 }
898
899 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900900 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900901 if (e == null) return;
902 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
903 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
904 return;
905 }
906
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900907 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
908 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
909 // add rules with a null MAC, only delete them.
910 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900911 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900912 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900913 if (e.isValid()) {
914 addIpv6ForwardingRule(rule);
915 } else {
916 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
917 }
918 }
919
920 private void handleNeighborEvent(NeighborEvent e) {
921 if (mInterfaceParams != null
922 && mInterfaceParams.index == e.ifindex
923 && mInterfaceParams.hasMacAddress) {
924 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
925 }
926 }
927
markchien74a4fa92019-09-09 20:50:49 +0800928 private byte getHopLimit(String upstreamIface) {
929 try {
930 int upstreamHopLimit = Integer.parseUnsignedInt(
931 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
932 // Add one hop to account for this forwarding device
933 upstreamHopLimit++;
934 // Cap the hop limit to 255.
935 return (byte) Integer.min(upstreamHopLimit, 255);
936 } catch (Exception e) {
937 mLog.e("Failed to find upstream interface hop limit", e);
938 }
939 return RaParams.DEFAULT_HOPLIMIT;
940 }
941
942 private void setRaParams(RaParams newParams) {
943 if (mRaDaemon != null) {
944 final RaParams deprecatedParams =
945 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
946
947 configureLocalIPv6Routes(deprecatedParams.prefixes,
948 (newParams != null) ? newParams.prefixes : null);
949
950 configureLocalIPv6Dns(deprecatedParams.dnses,
951 (newParams != null) ? newParams.dnses : null);
952
953 mRaDaemon.buildNewRa(deprecatedParams, newParams);
954 }
955
956 mLastRaParams = newParams;
957 }
958
959 private void logMessage(State state, int what) {
960 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
961 }
962
963 private void sendInterfaceState(int newInterfaceState) {
964 mServingMode = newInterfaceState;
965 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
966 sendLinkProperties();
967 }
968
969 private void sendLinkProperties() {
970 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
971 }
972
973 private void resetLinkProperties() {
974 mLinkProperties.clear();
975 mLinkProperties.setInterfaceName(mIfaceName);
976 }
977
markchienf053e4b2020-03-16 21:49:48 +0800978 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +0800979 // Ignore static address configuration if they are invalid or null. In theory, static
980 // addresses should not be invalid here because TetheringManager do not allow caller to
981 // specify invalid static address configuration.
982 if (request == null || request.localIPv4Address == null
983 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
984 request.localIPv4Address, request.staticClientAddress)) {
985 return;
986 }
markchienf053e4b2020-03-16 21:49:48 +0800987
988 mStaticIpv4ServerAddr = request.localIPv4Address;
989 mStaticIpv4ClientAddr = request.staticClientAddress;
990 }
991
markchien74a4fa92019-09-09 20:50:49 +0800992 class InitialState extends State {
993 @Override
994 public void enter() {
995 sendInterfaceState(STATE_AVAILABLE);
996 }
997
998 @Override
999 public boolean processMessage(Message message) {
1000 logMessage(this, message.what);
1001 switch (message.what) {
1002 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001003 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001004 switch (message.arg1) {
1005 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001006 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001007 transitionTo(mLocalHotspotState);
1008 break;
1009 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001010 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001011 transitionTo(mTetheredState);
1012 break;
1013 default:
1014 mLog.e("Invalid tethering interface serving state specified.");
1015 }
1016 break;
1017 case CMD_INTERFACE_DOWN:
1018 transitionTo(mUnavailableState);
1019 break;
1020 case CMD_IPV6_TETHER_UPDATE:
1021 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1022 break;
1023 default:
1024 return NOT_HANDLED;
1025 }
1026 return HANDLED;
1027 }
1028 }
1029
1030 class BaseServingState extends State {
1031 @Override
1032 public void enter() {
1033 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001034 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001035 return;
1036 }
1037
1038 try {
markchien12c5bb82020-01-07 14:43:17 +08001039 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1040 mIpv4Address.getPrefixLength());
1041 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +08001042 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +08001043 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +08001044 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001045 return;
1046 }
1047
1048 if (!startIPv6()) {
1049 mLog.e("Failed to startIPv6");
1050 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1051 return;
1052 }
1053 }
1054
1055 @Override
1056 public void exit() {
1057 // Note that at this point, we're leaving the tethered state. We can fail any
1058 // of these operations, but it doesn't really change that we have to try them
1059 // all in sequence.
1060 stopIPv6();
1061
1062 try {
markchien12c5bb82020-01-07 14:43:17 +08001063 NetdUtils.untetherInterface(mNetd, mIfaceName);
1064 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001065 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001066 mLog.e("Failed to untether interface: " + e);
1067 }
1068
1069 stopIPv4();
1070
1071 resetLinkProperties();
1072 }
1073
1074 @Override
1075 public boolean processMessage(Message message) {
1076 logMessage(this, message.what);
1077 switch (message.what) {
1078 case CMD_TETHER_UNREQUESTED:
1079 transitionTo(mInitialState);
1080 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1081 break;
1082 case CMD_INTERFACE_DOWN:
1083 transitionTo(mUnavailableState);
1084 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1085 break;
1086 case CMD_IPV6_TETHER_UPDATE:
1087 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1088 sendLinkProperties();
1089 break;
1090 case CMD_IP_FORWARDING_ENABLE_ERROR:
1091 case CMD_IP_FORWARDING_DISABLE_ERROR:
1092 case CMD_START_TETHERING_ERROR:
1093 case CMD_STOP_TETHERING_ERROR:
1094 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001095 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001096 transitionTo(mInitialState);
1097 break;
1098 default:
1099 return false;
1100 }
1101 return true;
1102 }
1103 }
1104
1105 // Handling errors in BaseServingState.enter() by transitioning is
1106 // problematic because transitioning during a multi-state jump yields
1107 // a Log.wtf(). Ultimately, there should be only one ServingState,
1108 // and forwarding and NAT rules should be handled by a coordinating
1109 // functional element outside of IpServer.
1110 class LocalHotspotState extends BaseServingState {
1111 @Override
1112 public void enter() {
1113 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001114 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001115 transitionTo(mInitialState);
1116 }
1117
1118 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1119 sendInterfaceState(STATE_LOCAL_ONLY);
1120 }
1121
1122 @Override
1123 public boolean processMessage(Message message) {
1124 if (super.processMessage(message)) return true;
1125
1126 logMessage(this, message.what);
1127 switch (message.what) {
1128 case CMD_TETHER_REQUESTED:
1129 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1130 break;
1131 case CMD_TETHER_CONNECTION_CHANGED:
1132 // Ignored in local hotspot state.
1133 break;
1134 default:
1135 return false;
1136 }
1137 return true;
1138 }
1139 }
1140
1141 // Handling errors in BaseServingState.enter() by transitioning is
1142 // problematic because transitioning during a multi-state jump yields
1143 // a Log.wtf(). Ultimately, there should be only one ServingState,
1144 // and forwarding and NAT rules should be handled by a coordinating
1145 // functional element outside of IpServer.
1146 class TetheredState extends BaseServingState {
1147 @Override
1148 public void enter() {
1149 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001150 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001151 transitionTo(mInitialState);
1152 }
1153
1154 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1155 sendInterfaceState(STATE_TETHERED);
1156 }
1157
1158 @Override
1159 public void exit() {
1160 cleanupUpstream();
1161 super.exit();
1162 }
1163
1164 private void cleanupUpstream() {
1165 if (mUpstreamIfaceSet == null) return;
1166
1167 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1168 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001169 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001170 }
1171
1172 private void cleanupUpstreamInterface(String upstreamIface) {
1173 // Note that we don't care about errors here.
1174 // Sometimes interfaces are gone before we get
1175 // to remove their rules, which generates errors.
1176 // Just do the best we can.
1177 try {
markchien12c5bb82020-01-07 14:43:17 +08001178 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1179 } catch (RemoteException | ServiceSpecificException e) {
1180 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001181 }
1182 try {
markchien12c5bb82020-01-07 14:43:17 +08001183 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1184 } catch (RemoteException | ServiceSpecificException e) {
1185 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001186 }
1187 }
1188
1189 @Override
1190 public boolean processMessage(Message message) {
1191 if (super.processMessage(message)) return true;
1192
1193 logMessage(this, message.what);
1194 switch (message.what) {
1195 case CMD_TETHER_REQUESTED:
1196 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1197 break;
1198 case CMD_TETHER_CONNECTION_CHANGED:
1199 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1200 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1201 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1202 break;
1203 }
1204
1205 if (newUpstreamIfaceSet == null) {
1206 cleanupUpstream();
1207 break;
1208 }
1209
1210 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1211 cleanupUpstreamInterface(removed);
1212 }
1213
1214 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1215 // This makes the call to cleanupUpstream() in the error
1216 // path for any interface neatly cleanup all the interfaces.
1217 mUpstreamIfaceSet = newUpstreamIfaceSet;
1218
1219 for (String ifname : added) {
1220 try {
markchien12c5bb82020-01-07 14:43:17 +08001221 mNetd.tetherAddForward(mIfaceName, ifname);
1222 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1223 } catch (RemoteException | ServiceSpecificException e) {
1224 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001225 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001226 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001227 transitionTo(mInitialState);
1228 return true;
1229 }
1230 }
1231 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001232 case CMD_NEIGHBOR_EVENT:
1233 handleNeighborEvent((NeighborEvent) message.obj);
1234 break;
markchien74a4fa92019-09-09 20:50:49 +08001235 default:
1236 return false;
1237 }
1238 return true;
1239 }
1240
1241 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1242 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1243 if (mUpstreamIfaceSet != null && newIfaces != null) {
1244 return mUpstreamIfaceSet.equals(newIfaces);
1245 }
1246 return false;
1247 }
1248
1249 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1250 if (mUpstreamIfaceSet == null) return new HashSet<>();
1251
1252 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1253 removed.removeAll(newIfaces.ifnames);
1254 return removed;
1255 }
1256
1257 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1258 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1259 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1260 return added;
1261 }
1262 }
1263
1264 /**
1265 * This state is terminal for the per interface state machine. At this
1266 * point, the master state machine should have removed this interface
1267 * specific state machine from its list of possible recipients of
1268 * tethering requests. The state machine itself will hang around until
1269 * the garbage collector finds it.
1270 */
1271 class UnavailableState extends State {
1272 @Override
1273 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001274 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001275 sendInterfaceState(STATE_UNAVAILABLE);
1276 }
1277 }
1278
1279 // Accumulate routes representing "prefixes to be assigned to the local
1280 // interface", for subsequent modification of local_network routing.
1281 private static ArrayList<RouteInfo> getLocalRoutesFor(
1282 String ifname, HashSet<IpPrefix> prefixes) {
1283 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1284 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001285 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001286 }
1287 return localRoutes;
1288 }
1289
1290 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1291 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1292 final byte[] dnsBytes = localPrefix.getRawAddress();
1293 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1294 try {
1295 return Inet6Address.getByAddress(null, dnsBytes, 0);
1296 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001297 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001298 return null;
1299 }
1300 }
1301
1302 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1303 final byte random = (byte) (new Random()).nextInt();
1304 for (int value : excluded) {
1305 if (random == value) return dflt;
1306 }
1307 return random;
1308 }
1309}