blob: 99e2fb14e8646ada9cb54fb1461164e3bd4ec01b [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;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090044import android.net.dhcp.IDhcpLeaseCallbacks;
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
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900452 private class DhcpLeaseCallback extends IDhcpLeaseCallbacks.Stub {
453 @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
486 public int getInterfaceVersion() {
487 return this.VERSION;
488 }
489
490 @Override
491 public String getInterfaceHash() throws RemoteException {
492 return this.HASH;
493 }
494 }
495
markchien245352e2020-02-27 20:27:18 +0800496 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800497 if (mUsingLegacyDhcp) {
498 return true;
499 }
markchien245352e2020-02-27 20:27:18 +0800500
501 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
502 final int prefixLen = serverLinkAddr.getPrefixLength();
503 final Inet4Address clientAddr = clientLinkAddr == null ? null :
504 (Inet4Address) clientLinkAddr.getAddress();
505
markchien74a4fa92019-09-09 20:50:49 +0800506 final DhcpServingParamsParcel params;
507 params = new DhcpServingParamsParcelExt()
508 .setDefaultRouters(addr)
509 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
510 .setDnsServers(addr)
markchien245352e2020-02-27 20:27:18 +0800511 .setServerAddr(serverLinkAddr)
512 .setMetered(true)
513 .setSingleClientAddr(clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800514 // TODO: also advertise link MTU
515
516 mDhcpServerStartIndex++;
517 mDeps.makeDhcpServer(
518 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
519 return true;
520 }
521
522 private void stopDhcp() {
523 // Make all previous start requests obsolete so servers are not started later
524 mDhcpServerStartIndex++;
525
526 if (mDhcpServer != null) {
527 try {
528 mDhcpServer.stop(new OnHandlerStatusCallback() {
529 @Override
530 public void callback(int statusCode) {
531 if (statusCode != STATUS_SUCCESS) {
532 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800533 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800534 // Not much more we can do here
535 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900536 mDhcpLeases.clear();
537 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800538 }
539 });
540 mDhcpServer = null;
541 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800542 mLog.e("Error stopping DHCP", e);
543 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800544 }
545 }
546 }
547
markchien245352e2020-02-27 20:27:18 +0800548 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
549 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800550 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800551 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800552 } else {
553 stopDhcp();
554 return true;
555 }
556 }
557
558 private void stopIPv4() {
559 configureIPv4(false);
560 // NOTE: All of configureIPv4() will be refactored out of existence
561 // into calls to InterfaceController, shared with startIPv4().
562 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800563 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800564 mStaticIpv4ServerAddr = null;
565 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800566 }
567
markchien74a4fa92019-09-09 20:50:49 +0800568 private boolean configureIPv4(boolean enabled) {
569 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
570
571 // TODO: Replace this hard-coded information with dynamically selected
572 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800573 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800574 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800575 try {
markchienf053e4b2020-03-16 21:49:48 +0800576 if (mStaticIpv4ServerAddr != null) {
577 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
578 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
579 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900580 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800581 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
582 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800583 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800584 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
585 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800586 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800587 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
588 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900589 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
590 // TODO: randomize address for tethering too, similarly to wifi
591 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
592 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800593 } else {
594 // BT configures the interface elsewhere: only start DHCP.
595 // TODO: make all tethering types behave the same way, and delete the bluetooth
596 // code that calls into NetworkManagementService directly.
597 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
598 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
markchien245352e2020-02-27 20:27:18 +0800599 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
markchien12c5bb82020-01-07 14:43:17 +0800600 }
601 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
602 } catch (IllegalArgumentException e) {
603 mLog.e("Error selecting ipv4 address", e);
604 if (!enabled) stopDhcp();
605 return false;
markchien74a4fa92019-09-09 20:50:49 +0800606 }
607
markchien12c5bb82020-01-07 14:43:17 +0800608 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800609 if (mInterfaceType == TetheringManager.TETHERING_WIFI
610 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800611 // The WiFi stack has ownership of the interface up/down state.
612 // It is unclear whether the Bluetooth or USB stacks will manage their own
613 // state.
614 setIfaceUp = null;
615 } else {
616 setIfaceUp = enabled;
617 }
618 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
619 mLog.e("Error configuring interface");
620 if (!enabled) stopDhcp();
621 return false;
622 }
markchien74a4fa92019-09-09 20:50:49 +0800623
markchien74a4fa92019-09-09 20:50:49 +0800624 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800625 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
626 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800627 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800628 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800629 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800630 mLinkProperties.addRoute(route);
631 } else {
markchien12c5bb82020-01-07 14:43:17 +0800632 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800633 mLinkProperties.removeRoute(route);
634 }
markchienf053e4b2020-03-16 21:49:48 +0800635
markchien245352e2020-02-27 20:27:18 +0800636 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800637 }
638
639 private String getRandomWifiIPv4Address() {
640 try {
641 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
642 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
643 return InetAddress.getByAddress(bytes).getHostAddress();
644 } catch (Exception e) {
645 return WIFI_HOST_IFACE_ADDR;
646 }
647 }
648
649 private boolean startIPv6() {
650 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
651 if (mInterfaceParams == null) {
652 mLog.e("Failed to find InterfaceParams");
653 stopIPv6();
654 return false;
655 }
656
657 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
658 if (!mRaDaemon.start()) {
659 stopIPv6();
660 return false;
661 }
662
663 return true;
664 }
665
666 private void stopIPv6() {
667 mInterfaceParams = null;
668 setRaParams(null);
669
670 if (mRaDaemon != null) {
671 mRaDaemon.stop();
672 mRaDaemon = null;
673 }
674 }
675
676 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
677 // LinkProperties. These have extraneous data filtered out and only the
678 // necessary prefixes included (per its prefix distribution policy).
679 //
680 // TODO: Evaluate using a data structure than is more directly suited to
681 // communicating only the relevant information.
682 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
683 if (mRaDaemon == null) return;
684
685 // Avoid unnecessary work on spurious updates.
686 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
687 return;
688 }
689
690 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900691 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800692
693 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900694 final String upstreamIface = v6only.getInterfaceName();
695
markchien74a4fa92019-09-09 20:50:49 +0800696 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800697 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
698 // the ethernet header size. This makes kernel ebpf tethering offload happy.
699 // This hack should be reverted once we have the kernel fixed up.
700 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
701 // see RouterAdvertisementDaemon.java putMtu()
702 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800703 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
704
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900705 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800706
707 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
708 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
709
710 final IpPrefix prefix = new IpPrefix(
711 linkAddr.getAddress(), linkAddr.getPrefixLength());
712 params.prefixes.add(prefix);
713
714 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
715 if (dnsServer != null) {
716 params.dnses.add(dnsServer);
717 }
718 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900719
720 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800721 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900722
markchien74a4fa92019-09-09 20:50:49 +0800723 // If v6only is null, we pass in null to setRaParams(), which handles
724 // deprecation of any existing RA data.
725
726 setRaParams(params);
727 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900728
729 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
730 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800731 }
732
733 private void configureLocalIPv6Routes(
734 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
735 // [1] Remove the routes that are deprecated.
736 if (!deprecatedPrefixes.isEmpty()) {
737 final ArrayList<RouteInfo> toBeRemoved =
738 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800739 // Remove routes from local network.
740 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
741 mNetd, toBeRemoved);
742 if (removalFailures > 0) {
743 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
744 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800745 }
746
747 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
748 }
749
750 // [2] Add only the routes that have not previously been added.
751 if (newPrefixes != null && !newPrefixes.isEmpty()) {
752 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
753 if (mLastRaParams != null) {
754 addedPrefixes.removeAll(mLastRaParams.prefixes);
755 }
756
757 if (!addedPrefixes.isEmpty()) {
758 final ArrayList<RouteInfo> toBeAdded =
759 getLocalRoutesFor(mIfaceName, addedPrefixes);
760 try {
markchien12c5bb82020-01-07 14:43:17 +0800761 // It's safe to call networkAddInterface() even if
762 // the interface is already in the local_network.
763 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
764 try {
765 // Add routes from local network. Note that adding routes that
766 // already exist does not cause an error (EEXIST is silently ignored).
767 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
768 } catch (IllegalStateException e) {
769 mLog.e("Failed to add IPv6 routes to local table: " + e);
770 }
771 } catch (ServiceSpecificException | RemoteException e) {
772 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800773 }
774
775 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
776 }
777 }
778 }
779
780 private void configureLocalIPv6Dns(
781 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
782 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
783 if (mNetd == null) {
784 if (newDnses != null) newDnses.clear();
785 mLog.e("No netd service instance available; not setting local IPv6 addresses");
786 return;
787 }
788
789 // [1] Remove deprecated local DNS IP addresses.
790 if (!deprecatedDnses.isEmpty()) {
791 for (Inet6Address dns : deprecatedDnses) {
792 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
793 mLog.e("Failed to remove local dns IP " + dns);
794 }
795
796 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
797 }
798 }
799
800 // [2] Add only the local DNS IP addresses that have not previously been added.
801 if (newDnses != null && !newDnses.isEmpty()) {
802 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
803 if (mLastRaParams != null) {
804 addedDnses.removeAll(mLastRaParams.dnses);
805 }
806
807 for (Inet6Address dns : addedDnses) {
808 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
809 mLog.e("Failed to add local dns IP " + dns);
810 newDnses.remove(dns);
811 }
812
813 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
814 }
815 }
816
817 try {
818 mNetd.tetherApplyDnsInterfaces();
819 } catch (ServiceSpecificException | RemoteException e) {
820 mLog.e("Failed to update local DNS caching server");
821 if (newDnses != null) newDnses.clear();
822 }
823 }
824
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900825 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
826 try {
827 mNetd.tetherRuleAddDownstreamIpv6(mInterfaceParams.index, rule.upstreamIfindex,
828 rule.address.getAddress(), mInterfaceParams.macAddr.toByteArray(),
829 rule.dstMac.toByteArray());
830 mIpv6ForwardingRules.put(rule.address, rule);
831 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900832 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900833 }
834 }
835
836 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
837 try {
838 mNetd.tetherRuleRemoveDownstreamIpv6(rule.upstreamIfindex, rule.address.getAddress());
839 if (removeFromMap) {
840 mIpv6ForwardingRules.remove(rule.address);
841 }
842 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900843 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900844 }
845 }
846
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900847 private void clearIpv6ForwardingRules() {
848 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
849 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
850 }
851 mIpv6ForwardingRules.clear();
852 }
853
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900854 // Convenience method to replace a rule with the same rule on a new upstream interface.
855 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
856 // Relies on the fact that rules are in a map indexed by IP address.
857 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
858 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
859 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
860 }
861
862 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
863 // changes or if a neighbor event is received.
864 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
865 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900866 // If we no longer have an upstream, clear forwarding rules and do nothing else.
867 if (upstreamIfindex == 0) {
868 clearIpv6ForwardingRules();
869 return;
870 }
871
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900872 // If the upstream interface has changed, remove all rules and re-add them with the new
873 // upstream interface.
874 if (prevUpstreamIfindex != upstreamIfindex) {
875 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
876 updateIpv6ForwardingRule(rule, upstreamIfindex);
877 }
878 }
879
880 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900881 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900882 if (e == null) return;
883 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
884 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
885 return;
886 }
887
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900888 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900889 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
890 e.macAddr);
891 if (e.isValid()) {
892 addIpv6ForwardingRule(rule);
893 } else {
894 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
895 }
896 }
897
898 private void handleNeighborEvent(NeighborEvent e) {
899 if (mInterfaceParams != null
900 && mInterfaceParams.index == e.ifindex
901 && mInterfaceParams.hasMacAddress) {
902 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
903 }
904 }
905
markchien74a4fa92019-09-09 20:50:49 +0800906 private byte getHopLimit(String upstreamIface) {
907 try {
908 int upstreamHopLimit = Integer.parseUnsignedInt(
909 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
910 // Add one hop to account for this forwarding device
911 upstreamHopLimit++;
912 // Cap the hop limit to 255.
913 return (byte) Integer.min(upstreamHopLimit, 255);
914 } catch (Exception e) {
915 mLog.e("Failed to find upstream interface hop limit", e);
916 }
917 return RaParams.DEFAULT_HOPLIMIT;
918 }
919
920 private void setRaParams(RaParams newParams) {
921 if (mRaDaemon != null) {
922 final RaParams deprecatedParams =
923 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
924
925 configureLocalIPv6Routes(deprecatedParams.prefixes,
926 (newParams != null) ? newParams.prefixes : null);
927
928 configureLocalIPv6Dns(deprecatedParams.dnses,
929 (newParams != null) ? newParams.dnses : null);
930
931 mRaDaemon.buildNewRa(deprecatedParams, newParams);
932 }
933
934 mLastRaParams = newParams;
935 }
936
937 private void logMessage(State state, int what) {
938 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
939 }
940
941 private void sendInterfaceState(int newInterfaceState) {
942 mServingMode = newInterfaceState;
943 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
944 sendLinkProperties();
945 }
946
947 private void sendLinkProperties() {
948 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
949 }
950
951 private void resetLinkProperties() {
952 mLinkProperties.clear();
953 mLinkProperties.setInterfaceName(mIfaceName);
954 }
955
markchienf053e4b2020-03-16 21:49:48 +0800956 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +0800957 // Ignore static address configuration if they are invalid or null. In theory, static
958 // addresses should not be invalid here because TetheringManager do not allow caller to
959 // specify invalid static address configuration.
960 if (request == null || request.localIPv4Address == null
961 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
962 request.localIPv4Address, request.staticClientAddress)) {
963 return;
964 }
markchienf053e4b2020-03-16 21:49:48 +0800965
966 mStaticIpv4ServerAddr = request.localIPv4Address;
967 mStaticIpv4ClientAddr = request.staticClientAddress;
968 }
969
markchien74a4fa92019-09-09 20:50:49 +0800970 class InitialState extends State {
971 @Override
972 public void enter() {
973 sendInterfaceState(STATE_AVAILABLE);
974 }
975
976 @Override
977 public boolean processMessage(Message message) {
978 logMessage(this, message.what);
979 switch (message.what) {
980 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800981 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800982 switch (message.arg1) {
983 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +0800984 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800985 transitionTo(mLocalHotspotState);
986 break;
987 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +0800988 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800989 transitionTo(mTetheredState);
990 break;
991 default:
992 mLog.e("Invalid tethering interface serving state specified.");
993 }
994 break;
995 case CMD_INTERFACE_DOWN:
996 transitionTo(mUnavailableState);
997 break;
998 case CMD_IPV6_TETHER_UPDATE:
999 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1000 break;
1001 default:
1002 return NOT_HANDLED;
1003 }
1004 return HANDLED;
1005 }
1006 }
1007
1008 class BaseServingState extends State {
1009 @Override
1010 public void enter() {
1011 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001012 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001013 return;
1014 }
1015
1016 try {
markchien12c5bb82020-01-07 14:43:17 +08001017 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1018 mIpv4Address.getPrefixLength());
1019 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +08001020 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +08001021 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +08001022 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001023 return;
1024 }
1025
1026 if (!startIPv6()) {
1027 mLog.e("Failed to startIPv6");
1028 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1029 return;
1030 }
1031 }
1032
1033 @Override
1034 public void exit() {
1035 // Note that at this point, we're leaving the tethered state. We can fail any
1036 // of these operations, but it doesn't really change that we have to try them
1037 // all in sequence.
1038 stopIPv6();
1039
1040 try {
markchien12c5bb82020-01-07 14:43:17 +08001041 NetdUtils.untetherInterface(mNetd, mIfaceName);
1042 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001043 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001044 mLog.e("Failed to untether interface: " + e);
1045 }
1046
1047 stopIPv4();
1048
1049 resetLinkProperties();
1050 }
1051
1052 @Override
1053 public boolean processMessage(Message message) {
1054 logMessage(this, message.what);
1055 switch (message.what) {
1056 case CMD_TETHER_UNREQUESTED:
1057 transitionTo(mInitialState);
1058 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1059 break;
1060 case CMD_INTERFACE_DOWN:
1061 transitionTo(mUnavailableState);
1062 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1063 break;
1064 case CMD_IPV6_TETHER_UPDATE:
1065 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1066 sendLinkProperties();
1067 break;
1068 case CMD_IP_FORWARDING_ENABLE_ERROR:
1069 case CMD_IP_FORWARDING_DISABLE_ERROR:
1070 case CMD_START_TETHERING_ERROR:
1071 case CMD_STOP_TETHERING_ERROR:
1072 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +08001073 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001074 transitionTo(mInitialState);
1075 break;
1076 default:
1077 return false;
1078 }
1079 return true;
1080 }
1081 }
1082
1083 // Handling errors in BaseServingState.enter() by transitioning is
1084 // problematic because transitioning during a multi-state jump yields
1085 // a Log.wtf(). Ultimately, there should be only one ServingState,
1086 // and forwarding and NAT rules should be handled by a coordinating
1087 // functional element outside of IpServer.
1088 class LocalHotspotState extends BaseServingState {
1089 @Override
1090 public void enter() {
1091 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001092 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001093 transitionTo(mInitialState);
1094 }
1095
1096 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1097 sendInterfaceState(STATE_LOCAL_ONLY);
1098 }
1099
1100 @Override
1101 public boolean processMessage(Message message) {
1102 if (super.processMessage(message)) return true;
1103
1104 logMessage(this, message.what);
1105 switch (message.what) {
1106 case CMD_TETHER_REQUESTED:
1107 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1108 break;
1109 case CMD_TETHER_CONNECTION_CHANGED:
1110 // Ignored in local hotspot state.
1111 break;
1112 default:
1113 return false;
1114 }
1115 return true;
1116 }
1117 }
1118
1119 // Handling errors in BaseServingState.enter() by transitioning is
1120 // problematic because transitioning during a multi-state jump yields
1121 // a Log.wtf(). Ultimately, there should be only one ServingState,
1122 // and forwarding and NAT rules should be handled by a coordinating
1123 // functional element outside of IpServer.
1124 class TetheredState extends BaseServingState {
1125 @Override
1126 public void enter() {
1127 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001128 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001129 transitionTo(mInitialState);
1130 }
1131
1132 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1133 sendInterfaceState(STATE_TETHERED);
1134 }
1135
1136 @Override
1137 public void exit() {
1138 cleanupUpstream();
1139 super.exit();
1140 }
1141
1142 private void cleanupUpstream() {
1143 if (mUpstreamIfaceSet == null) return;
1144
1145 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1146 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001147 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001148 }
1149
1150 private void cleanupUpstreamInterface(String upstreamIface) {
1151 // Note that we don't care about errors here.
1152 // Sometimes interfaces are gone before we get
1153 // to remove their rules, which generates errors.
1154 // Just do the best we can.
1155 try {
markchien12c5bb82020-01-07 14:43:17 +08001156 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1157 } catch (RemoteException | ServiceSpecificException e) {
1158 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001159 }
1160 try {
markchien12c5bb82020-01-07 14:43:17 +08001161 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1162 } catch (RemoteException | ServiceSpecificException e) {
1163 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001164 }
1165 }
1166
1167 @Override
1168 public boolean processMessage(Message message) {
1169 if (super.processMessage(message)) return true;
1170
1171 logMessage(this, message.what);
1172 switch (message.what) {
1173 case CMD_TETHER_REQUESTED:
1174 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1175 break;
1176 case CMD_TETHER_CONNECTION_CHANGED:
1177 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1178 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1179 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1180 break;
1181 }
1182
1183 if (newUpstreamIfaceSet == null) {
1184 cleanupUpstream();
1185 break;
1186 }
1187
1188 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1189 cleanupUpstreamInterface(removed);
1190 }
1191
1192 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1193 // This makes the call to cleanupUpstream() in the error
1194 // path for any interface neatly cleanup all the interfaces.
1195 mUpstreamIfaceSet = newUpstreamIfaceSet;
1196
1197 for (String ifname : added) {
1198 try {
markchien12c5bb82020-01-07 14:43:17 +08001199 mNetd.tetherAddForward(mIfaceName, ifname);
1200 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1201 } catch (RemoteException | ServiceSpecificException e) {
1202 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001203 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +08001204 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001205 transitionTo(mInitialState);
1206 return true;
1207 }
1208 }
1209 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001210 case CMD_NEIGHBOR_EVENT:
1211 handleNeighborEvent((NeighborEvent) message.obj);
1212 break;
markchien74a4fa92019-09-09 20:50:49 +08001213 default:
1214 return false;
1215 }
1216 return true;
1217 }
1218
1219 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1220 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1221 if (mUpstreamIfaceSet != null && newIfaces != null) {
1222 return mUpstreamIfaceSet.equals(newIfaces);
1223 }
1224 return false;
1225 }
1226
1227 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1228 if (mUpstreamIfaceSet == null) return new HashSet<>();
1229
1230 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1231 removed.removeAll(newIfaces.ifnames);
1232 return removed;
1233 }
1234
1235 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1236 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1237 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1238 return added;
1239 }
1240 }
1241
1242 /**
1243 * This state is terminal for the per interface state machine. At this
1244 * point, the master state machine should have removed this interface
1245 * specific state machine from its list of possible recipients of
1246 * tethering requests. The state machine itself will hang around until
1247 * the garbage collector finds it.
1248 */
1249 class UnavailableState extends State {
1250 @Override
1251 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001252 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001253 sendInterfaceState(STATE_UNAVAILABLE);
1254 }
1255 }
1256
1257 // Accumulate routes representing "prefixes to be assigned to the local
1258 // interface", for subsequent modification of local_network routing.
1259 private static ArrayList<RouteInfo> getLocalRoutesFor(
1260 String ifname, HashSet<IpPrefix> prefixes) {
1261 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1262 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001263 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001264 }
1265 return localRoutes;
1266 }
1267
1268 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1269 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1270 final byte[] dnsBytes = localPrefix.getRawAddress();
1271 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1272 try {
1273 return Inet6Address.getByAddress(null, dnsBytes, 0);
1274 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001275 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001276 return null;
1277 }
1278 }
1279
1280 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1281 final byte random = (byte) (new Random()).nextInt();
1282 for (int value : excluded) {
1283 if (random == value) return dflt;
1284 }
1285 return random;
1286 }
1287}