blob: 8116057a336a86843339890782bec08ab2e67b7a [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;
markchien74a4fa92019-09-09 20:50:49 +080021import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090022import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH;
markchien74a4fa92019-09-09 20:50:49 +080023import static android.net.util.NetworkConstants.FF;
24import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
25import static android.net.util.NetworkConstants.asByte;
markchien6cf0e552019-12-06 15:24:53 +080026import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
markchien74a4fa92019-09-09 20:50:49 +080027
markchien74a4fa92019-09-09 20:50:49 +080028import android.net.INetd;
29import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080030import android.net.IpPrefix;
31import android.net.LinkAddress;
32import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090033import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080034import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090035import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080036import android.net.TetheringManager;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090037import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080038import android.net.dhcp.DhcpServerCallbacks;
39import android.net.dhcp.DhcpServingParamsParcel;
40import android.net.dhcp.DhcpServingParamsParcelExt;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090041import android.net.dhcp.IDhcpLeaseCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.dhcp.IDhcpServer;
43import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080044import android.net.shared.NetdUtils;
45import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.util.InterfaceParams;
47import android.net.util.InterfaceSet;
markchien74a4fa92019-09-09 20:50:49 +080048import android.net.util.SharedLog;
markchien74a4fa92019-09-09 20:50:49 +080049import android.os.Looper;
50import android.os.Message;
51import android.os.RemoteException;
52import android.os.ServiceSpecificException;
53import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080054import android.util.SparseArray;
55
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090056import androidx.annotation.NonNull;
57
markchien74a4fa92019-09-09 20:50:49 +080058import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080059import com.android.internal.util.State;
60import com.android.internal.util.StateMachine;
61
62import java.net.Inet4Address;
63import java.net.Inet6Address;
64import java.net.InetAddress;
65import java.net.UnknownHostException;
66import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090067import java.util.Arrays;
68import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080069import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090070import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080071import java.util.Objects;
72import java.util.Random;
73import java.util.Set;
74
75/**
76 * Provides the interface to IP-layer serving functionality for a given network
77 * interface, e.g. for tethering or "local-only hotspot" mode.
78 *
79 * @hide
80 */
81public class IpServer extends StateMachine {
82 public static final int STATE_UNAVAILABLE = 0;
83 public static final int STATE_AVAILABLE = 1;
84 public static final int STATE_TETHERED = 2;
85 public static final int STATE_LOCAL_ONLY = 3;
86
87 /** Get string name of |state|.*/
88 public static String getStateString(int state) {
89 switch (state) {
90 case STATE_UNAVAILABLE: return "UNAVAILABLE";
91 case STATE_AVAILABLE: return "AVAILABLE";
92 case STATE_TETHERED: return "TETHERED";
93 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
94 }
95 return "UNKNOWN: " + state;
96 }
97
98 private static final byte DOUG_ADAMS = (byte) 42;
99
100 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
101 private static final int USB_PREFIX_LENGTH = 24;
102 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
103 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
104 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
105 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900106 private static final String ETHERNET_IFACE_ADDR = "192.168.50.1";
107 private static final int ETHERNET_IFACE_PREFIX_LENGTH = 24;
markchien74a4fa92019-09-09 20:50:49 +0800108
109 // TODO: have PanService use some visible version of this constant
110 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
111 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
112
113 // TODO: have this configurable
114 private static final int DHCP_LEASE_TIME_SECS = 3600;
115
116 private static final String TAG = "IpServer";
117 private static final boolean DBG = false;
118 private static final boolean VDBG = false;
119 private static final Class[] sMessageClasses = {
120 IpServer.class
121 };
122 private static final SparseArray<String> sMagicDecoderRing =
123 MessageUtils.findMessageNames(sMessageClasses);
124
125 /** IpServer callback. */
126 public static class Callback {
127 /**
128 * Notify that |who| has changed its tethering state.
129 *
130 * @param who the calling instance of IpServer
131 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800132 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800133 */
markchien9d353822019-12-16 20:15:20 +0800134 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800135
136 /**
137 * Notify that |who| has new LinkProperties.
138 *
139 * @param who the calling instance of IpServer
140 * @param newLp the new LinkProperties to report
141 */
markchien9d353822019-12-16 20:15:20 +0800142 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900143
144 /**
145 * Notify that the DHCP leases changed in one of the IpServers.
146 */
147 public void dhcpLeasesChanged() { }
markchien74a4fa92019-09-09 20:50:49 +0800148 }
149
150 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800151 public abstract static class Dependencies {
markchien74a4fa92019-09-09 20:50:49 +0800152 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
153 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
154 return new RouterAdvertisementDaemon(ifParams);
155 }
156
157 /** Get |ifName|'s interface information.*/
158 public InterfaceParams getInterfaceParams(String ifName) {
159 return InterfaceParams.getByName(ifName);
160 }
161
markchien9d353822019-12-16 20:15:20 +0800162 /** Create a DhcpServer instance to be used by IpServer. */
163 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
164 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800165 }
166
markchien74a4fa92019-09-09 20:50:49 +0800167 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800168 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800169 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800170 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800171 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800172 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800173 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800174 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800175 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800176 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800177 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800178 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800179 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800180 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800181 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800182 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800183 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800184 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800185 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800186 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
markchien74a4fa92019-09-09 20:50:49 +0800187
188 private final State mInitialState;
189 private final State mLocalHotspotState;
190 private final State mTetheredState;
191 private final State mUnavailableState;
192
193 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800194 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800195 private final Callback mCallback;
196 private final InterfaceController mInterfaceCtrl;
197
198 private final String mIfaceName;
199 private final int mInterfaceType;
200 private final LinkProperties mLinkProperties;
201 private final boolean mUsingLegacyDhcp;
202
203 private final Dependencies mDeps;
204
205 private int mLastError;
206 private int mServingMode;
207 private InterfaceSet mUpstreamIfaceSet; // may change over time
208 private InterfaceParams mInterfaceParams;
209 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
210 // properties are those selected by the IPv6TetheringCoordinator and relayed
211 // to us. By comparison, mLinkProperties contains the addresses and directly
212 // connected routes that have been formed from these properties iff. we have
213 // succeeded in configuring them and are able to announce them within Router
214 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
215 private LinkProperties mLastIPv6LinkProperties;
216 private RouterAdvertisementDaemon mRaDaemon;
217
218 // To be accessed only on the handler thread
219 private int mDhcpServerStartIndex = 0;
220 private IDhcpServer mDhcpServer;
221 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800222 private LinkAddress mIpv4Address;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900223 @NonNull
224 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800225
226 public IpServer(
227 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800228 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800229 super(ifaceName, looper);
230 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800231 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800232 mCallback = callback;
233 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
234 mIfaceName = ifaceName;
235 mInterfaceType = interfaceType;
236 mLinkProperties = new LinkProperties();
237 mUsingLegacyDhcp = usingLegacyDhcp;
238 mDeps = deps;
239 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800240 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800241 mServingMode = STATE_AVAILABLE;
242
243 mInitialState = new InitialState();
244 mLocalHotspotState = new LocalHotspotState();
245 mTetheredState = new TetheredState();
246 mUnavailableState = new UnavailableState();
247 addState(mInitialState);
248 addState(mLocalHotspotState);
249 addState(mTetheredState);
250 addState(mUnavailableState);
251
252 setInitialState(mInitialState);
253 }
254
255 /** Interface name which IpServer served.*/
256 public String interfaceName() {
257 return mIfaceName;
258 }
259
260 /**
markchien9b4d7572019-12-25 19:40:32 +0800261 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800262 */
263 public int interfaceType() {
264 return mInterfaceType;
265 }
266
267 /** Last error from this IpServer. */
268 public int lastError() {
269 return mLastError;
270 }
271
272 /** Serving mode is the current state of IpServer state machine. */
273 public int servingMode() {
274 return mServingMode;
275 }
276
277 /** The properties of the network link which IpServer is serving. */
278 public LinkProperties linkProperties() {
279 return new LinkProperties(mLinkProperties);
280 }
281
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900282 /**
283 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
284 * thread.
285 */
286 public List<TetheredClient> getAllLeases() {
287 return Collections.unmodifiableList(mDhcpLeases);
288 }
289
markchien74a4fa92019-09-09 20:50:49 +0800290 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
291 public void stop() {
292 sendMessage(CMD_INTERFACE_DOWN);
293 }
294
295 /**
296 * Tethering is canceled. IpServer state machine will be available and wait for
297 * next tethering request.
298 */
299 public void unwanted() {
300 sendMessage(CMD_TETHER_UNREQUESTED);
301 }
302
303 /** Internals. */
304
305 private boolean startIPv4() {
306 return configureIPv4(true);
307 }
308
309 /**
310 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
311 * handler.
312 *
313 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
314 * with different implementations of the callback, to differentiate handling of success/error in
315 * each call.
316 */
317 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
318 @Override
319 public void onStatusAvailable(int statusCode) {
320 getHandler().post(() -> callback(statusCode));
321 }
322
323 public abstract void callback(int statusCode);
324
325 @Override
326 public int getInterfaceVersion() {
327 return this.VERSION;
328 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900329
330 @Override
331 public String getInterfaceHash() {
332 return this.HASH;
333 }
markchien74a4fa92019-09-09 20:50:49 +0800334 }
335
336 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
337 private final int mStartIndex;
338
339 private DhcpServerCallbacksImpl(int startIndex) {
340 mStartIndex = startIndex;
341 }
342
343 @Override
344 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
345 getHandler().post(() -> {
346 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
347 if (mStartIndex != mDhcpServerStartIndex) {
348 // This start request is obsolete. When the |server| binder token goes out of
349 // scope, the garbage collector will finalize it, which causes the network stack
350 // process garbage collector to collect the server itself.
351 return;
352 }
353
354 if (statusCode != STATUS_SUCCESS) {
355 mLog.e("Error obtaining DHCP server: " + statusCode);
356 handleError();
357 return;
358 }
359
360 mDhcpServer = server;
361 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900362 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800363 @Override
364 public void callback(int startStatusCode) {
365 if (startStatusCode != STATUS_SUCCESS) {
366 mLog.e("Error starting DHCP server: " + startStatusCode);
367 handleError();
368 }
369 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900370 }, new DhcpLeaseCallback());
markchien74a4fa92019-09-09 20:50:49 +0800371 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800372 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800373 }
374 });
375 }
376
377 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800378 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800379 transitionTo(mInitialState);
380 }
381 }
382
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900383 private class DhcpLeaseCallback extends IDhcpLeaseCallbacks.Stub {
384 @Override
385 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
386 final ArrayList<TetheredClient> leases = new ArrayList<>();
387 for (DhcpLeaseParcelable lease : leaseParcelables) {
388 final LinkAddress address = new LinkAddress(
389 intToInet4AddressHTH(lease.netAddr), lease.prefixLength);
390
391 final MacAddress macAddress;
392 try {
393 macAddress = MacAddress.fromBytes(lease.hwAddr);
394 } catch (IllegalArgumentException e) {
395 Log.wtf(TAG, "Invalid address received from DhcpServer: "
396 + Arrays.toString(lease.hwAddr));
397 return;
398 }
399
400 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
401 address, lease.hostname, lease.expTime);
402 leases.add(new TetheredClient(
403 macAddress,
404 Collections.singletonList(addressInfo),
405 mInterfaceType));
406 }
407
408 getHandler().post(() -> {
409 mDhcpLeases = leases;
410 mCallback.dhcpLeasesChanged();
411 });
412 }
413
414 @Override
415 public int getInterfaceVersion() {
416 return this.VERSION;
417 }
418
419 @Override
420 public String getInterfaceHash() throws RemoteException {
421 return this.HASH;
422 }
423 }
424
markchien74a4fa92019-09-09 20:50:49 +0800425 private boolean startDhcp(Inet4Address addr, int prefixLen) {
426 if (mUsingLegacyDhcp) {
427 return true;
428 }
429 final DhcpServingParamsParcel params;
430 params = new DhcpServingParamsParcelExt()
431 .setDefaultRouters(addr)
432 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
433 .setDnsServers(addr)
434 .setServerAddr(new LinkAddress(addr, prefixLen))
435 .setMetered(true);
436 // TODO: also advertise link MTU
437
438 mDhcpServerStartIndex++;
439 mDeps.makeDhcpServer(
440 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
441 return true;
442 }
443
444 private void stopDhcp() {
445 // Make all previous start requests obsolete so servers are not started later
446 mDhcpServerStartIndex++;
447
448 if (mDhcpServer != null) {
449 try {
450 mDhcpServer.stop(new OnHandlerStatusCallback() {
451 @Override
452 public void callback(int statusCode) {
453 if (statusCode != STATUS_SUCCESS) {
454 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800455 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800456 // Not much more we can do here
457 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900458 mDhcpLeases.clear();
459 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800460 }
461 });
462 mDhcpServer = null;
463 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800464 mLog.e("Error stopping DHCP", e);
465 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800466 }
467 }
468 }
469
470 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
471 if (enable) {
472 return startDhcp(addr, prefixLen);
473 } else {
474 stopDhcp();
475 return true;
476 }
477 }
478
479 private void stopIPv4() {
480 configureIPv4(false);
481 // NOTE: All of configureIPv4() will be refactored out of existence
482 // into calls to InterfaceController, shared with startIPv4().
483 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800484 mIpv4Address = null;
markchien74a4fa92019-09-09 20:50:49 +0800485 }
486
markchien74a4fa92019-09-09 20:50:49 +0800487 private boolean configureIPv4(boolean enabled) {
488 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
489
490 // TODO: Replace this hard-coded information with dynamically selected
491 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800492 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800493 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800494 try {
Milim Lee45a971b2019-10-17 05:02:33 +0900495 if (mInterfaceType == TetheringManager.TETHERING_USB
496 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800497 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
498 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800499 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800500 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
501 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800502 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800503 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
504 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900505 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
506 // TODO: randomize address for tethering too, similarly to wifi
507 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
508 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800509 } else {
510 // BT configures the interface elsewhere: only start DHCP.
511 // TODO: make all tethering types behave the same way, and delete the bluetooth
512 // code that calls into NetworkManagementService directly.
513 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
514 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
515 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
516 }
517 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
518 } catch (IllegalArgumentException e) {
519 mLog.e("Error selecting ipv4 address", e);
520 if (!enabled) stopDhcp();
521 return false;
markchien74a4fa92019-09-09 20:50:49 +0800522 }
523
markchien12c5bb82020-01-07 14:43:17 +0800524 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800525 if (mInterfaceType == TetheringManager.TETHERING_WIFI
526 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800527 // The WiFi stack has ownership of the interface up/down state.
528 // It is unclear whether the Bluetooth or USB stacks will manage their own
529 // state.
530 setIfaceUp = null;
531 } else {
532 setIfaceUp = enabled;
533 }
534 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
535 mLog.e("Error configuring interface");
536 if (!enabled) stopDhcp();
537 return false;
538 }
markchien74a4fa92019-09-09 20:50:49 +0800539
markchien12c5bb82020-01-07 14:43:17 +0800540 if (!configureDhcp(enabled, srvAddr, prefixLen)) {
markchien74a4fa92019-09-09 20:50:49 +0800541 return false;
542 }
543
544 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800545 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
546 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800547 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800548 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800549 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800550 mLinkProperties.addRoute(route);
551 } else {
markchien12c5bb82020-01-07 14:43:17 +0800552 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800553 mLinkProperties.removeRoute(route);
554 }
555 return true;
556 }
557
558 private String getRandomWifiIPv4Address() {
559 try {
560 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
561 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
562 return InetAddress.getByAddress(bytes).getHostAddress();
563 } catch (Exception e) {
564 return WIFI_HOST_IFACE_ADDR;
565 }
566 }
567
568 private boolean startIPv6() {
569 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
570 if (mInterfaceParams == null) {
571 mLog.e("Failed to find InterfaceParams");
572 stopIPv6();
573 return false;
574 }
575
576 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
577 if (!mRaDaemon.start()) {
578 stopIPv6();
579 return false;
580 }
581
582 return true;
583 }
584
585 private void stopIPv6() {
586 mInterfaceParams = null;
587 setRaParams(null);
588
589 if (mRaDaemon != null) {
590 mRaDaemon.stop();
591 mRaDaemon = null;
592 }
593 }
594
595 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
596 // LinkProperties. These have extraneous data filtered out and only the
597 // necessary prefixes included (per its prefix distribution policy).
598 //
599 // TODO: Evaluate using a data structure than is more directly suited to
600 // communicating only the relevant information.
601 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
602 if (mRaDaemon == null) return;
603
604 // Avoid unnecessary work on spurious updates.
605 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
606 return;
607 }
608
609 RaParams params = null;
610
611 if (v6only != null) {
612 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800613 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
614 // the ethernet header size. This makes kernel ebpf tethering offload happy.
615 // This hack should be reverted once we have the kernel fixed up.
616 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
617 // see RouterAdvertisementDaemon.java putMtu()
618 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800619 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
620
621 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(v6only.getInterfaceName());
622
623 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
624 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
625
626 final IpPrefix prefix = new IpPrefix(
627 linkAddr.getAddress(), linkAddr.getPrefixLength());
628 params.prefixes.add(prefix);
629
630 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
631 if (dnsServer != null) {
632 params.dnses.add(dnsServer);
633 }
634 }
635 }
636 // If v6only is null, we pass in null to setRaParams(), which handles
637 // deprecation of any existing RA data.
638
639 setRaParams(params);
640 mLastIPv6LinkProperties = v6only;
641 }
642
643 private void configureLocalIPv6Routes(
644 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
645 // [1] Remove the routes that are deprecated.
646 if (!deprecatedPrefixes.isEmpty()) {
647 final ArrayList<RouteInfo> toBeRemoved =
648 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800649 // Remove routes from local network.
650 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
651 mNetd, toBeRemoved);
652 if (removalFailures > 0) {
653 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
654 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800655 }
656
657 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
658 }
659
660 // [2] Add only the routes that have not previously been added.
661 if (newPrefixes != null && !newPrefixes.isEmpty()) {
662 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
663 if (mLastRaParams != null) {
664 addedPrefixes.removeAll(mLastRaParams.prefixes);
665 }
666
667 if (!addedPrefixes.isEmpty()) {
668 final ArrayList<RouteInfo> toBeAdded =
669 getLocalRoutesFor(mIfaceName, addedPrefixes);
670 try {
markchien12c5bb82020-01-07 14:43:17 +0800671 // It's safe to call networkAddInterface() even if
672 // the interface is already in the local_network.
673 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
674 try {
675 // Add routes from local network. Note that adding routes that
676 // already exist does not cause an error (EEXIST is silently ignored).
677 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
678 } catch (IllegalStateException e) {
679 mLog.e("Failed to add IPv6 routes to local table: " + e);
680 }
681 } catch (ServiceSpecificException | RemoteException e) {
682 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800683 }
684
685 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
686 }
687 }
688 }
689
690 private void configureLocalIPv6Dns(
691 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
692 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
693 if (mNetd == null) {
694 if (newDnses != null) newDnses.clear();
695 mLog.e("No netd service instance available; not setting local IPv6 addresses");
696 return;
697 }
698
699 // [1] Remove deprecated local DNS IP addresses.
700 if (!deprecatedDnses.isEmpty()) {
701 for (Inet6Address dns : deprecatedDnses) {
702 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
703 mLog.e("Failed to remove local dns IP " + dns);
704 }
705
706 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
707 }
708 }
709
710 // [2] Add only the local DNS IP addresses that have not previously been added.
711 if (newDnses != null && !newDnses.isEmpty()) {
712 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
713 if (mLastRaParams != null) {
714 addedDnses.removeAll(mLastRaParams.dnses);
715 }
716
717 for (Inet6Address dns : addedDnses) {
718 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
719 mLog.e("Failed to add local dns IP " + dns);
720 newDnses.remove(dns);
721 }
722
723 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
724 }
725 }
726
727 try {
728 mNetd.tetherApplyDnsInterfaces();
729 } catch (ServiceSpecificException | RemoteException e) {
730 mLog.e("Failed to update local DNS caching server");
731 if (newDnses != null) newDnses.clear();
732 }
733 }
734
735 private byte getHopLimit(String upstreamIface) {
736 try {
737 int upstreamHopLimit = Integer.parseUnsignedInt(
738 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
739 // Add one hop to account for this forwarding device
740 upstreamHopLimit++;
741 // Cap the hop limit to 255.
742 return (byte) Integer.min(upstreamHopLimit, 255);
743 } catch (Exception e) {
744 mLog.e("Failed to find upstream interface hop limit", e);
745 }
746 return RaParams.DEFAULT_HOPLIMIT;
747 }
748
749 private void setRaParams(RaParams newParams) {
750 if (mRaDaemon != null) {
751 final RaParams deprecatedParams =
752 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
753
754 configureLocalIPv6Routes(deprecatedParams.prefixes,
755 (newParams != null) ? newParams.prefixes : null);
756
757 configureLocalIPv6Dns(deprecatedParams.dnses,
758 (newParams != null) ? newParams.dnses : null);
759
760 mRaDaemon.buildNewRa(deprecatedParams, newParams);
761 }
762
763 mLastRaParams = newParams;
764 }
765
766 private void logMessage(State state, int what) {
767 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
768 }
769
770 private void sendInterfaceState(int newInterfaceState) {
771 mServingMode = newInterfaceState;
772 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
773 sendLinkProperties();
774 }
775
776 private void sendLinkProperties() {
777 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
778 }
779
780 private void resetLinkProperties() {
781 mLinkProperties.clear();
782 mLinkProperties.setInterfaceName(mIfaceName);
783 }
784
785 class InitialState extends State {
786 @Override
787 public void enter() {
788 sendInterfaceState(STATE_AVAILABLE);
789 }
790
791 @Override
792 public boolean processMessage(Message message) {
793 logMessage(this, message.what);
794 switch (message.what) {
795 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800796 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800797 switch (message.arg1) {
798 case STATE_LOCAL_ONLY:
799 transitionTo(mLocalHotspotState);
800 break;
801 case STATE_TETHERED:
802 transitionTo(mTetheredState);
803 break;
804 default:
805 mLog.e("Invalid tethering interface serving state specified.");
806 }
807 break;
808 case CMD_INTERFACE_DOWN:
809 transitionTo(mUnavailableState);
810 break;
811 case CMD_IPV6_TETHER_UPDATE:
812 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
813 break;
814 default:
815 return NOT_HANDLED;
816 }
817 return HANDLED;
818 }
819 }
820
821 class BaseServingState extends State {
822 @Override
823 public void enter() {
824 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800825 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800826 return;
827 }
828
829 try {
markchien12c5bb82020-01-07 14:43:17 +0800830 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
831 mIpv4Address.getPrefixLength());
832 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +0800833 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +0800834 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800835 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800836 return;
837 }
838
839 if (!startIPv6()) {
840 mLog.e("Failed to startIPv6");
841 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
842 return;
843 }
844 }
845
846 @Override
847 public void exit() {
848 // Note that at this point, we're leaving the tethered state. We can fail any
849 // of these operations, but it doesn't really change that we have to try them
850 // all in sequence.
851 stopIPv6();
852
853 try {
markchien12c5bb82020-01-07 14:43:17 +0800854 NetdUtils.untetherInterface(mNetd, mIfaceName);
855 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +0800856 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800857 mLog.e("Failed to untether interface: " + e);
858 }
859
860 stopIPv4();
861
862 resetLinkProperties();
863 }
864
865 @Override
866 public boolean processMessage(Message message) {
867 logMessage(this, message.what);
868 switch (message.what) {
869 case CMD_TETHER_UNREQUESTED:
870 transitionTo(mInitialState);
871 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
872 break;
873 case CMD_INTERFACE_DOWN:
874 transitionTo(mUnavailableState);
875 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
876 break;
877 case CMD_IPV6_TETHER_UPDATE:
878 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
879 sendLinkProperties();
880 break;
881 case CMD_IP_FORWARDING_ENABLE_ERROR:
882 case CMD_IP_FORWARDING_DISABLE_ERROR:
883 case CMD_START_TETHERING_ERROR:
884 case CMD_STOP_TETHERING_ERROR:
885 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +0800886 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800887 transitionTo(mInitialState);
888 break;
889 default:
890 return false;
891 }
892 return true;
893 }
894 }
895
896 // Handling errors in BaseServingState.enter() by transitioning is
897 // problematic because transitioning during a multi-state jump yields
898 // a Log.wtf(). Ultimately, there should be only one ServingState,
899 // and forwarding and NAT rules should be handled by a coordinating
900 // functional element outside of IpServer.
901 class LocalHotspotState extends BaseServingState {
902 @Override
903 public void enter() {
904 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800905 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800906 transitionTo(mInitialState);
907 }
908
909 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
910 sendInterfaceState(STATE_LOCAL_ONLY);
911 }
912
913 @Override
914 public boolean processMessage(Message message) {
915 if (super.processMessage(message)) return true;
916
917 logMessage(this, message.what);
918 switch (message.what) {
919 case CMD_TETHER_REQUESTED:
920 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
921 break;
922 case CMD_TETHER_CONNECTION_CHANGED:
923 // Ignored in local hotspot state.
924 break;
925 default:
926 return false;
927 }
928 return true;
929 }
930 }
931
932 // Handling errors in BaseServingState.enter() by transitioning is
933 // problematic because transitioning during a multi-state jump yields
934 // a Log.wtf(). Ultimately, there should be only one ServingState,
935 // and forwarding and NAT rules should be handled by a coordinating
936 // functional element outside of IpServer.
937 class TetheredState extends BaseServingState {
938 @Override
939 public void enter() {
940 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800941 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800942 transitionTo(mInitialState);
943 }
944
945 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
946 sendInterfaceState(STATE_TETHERED);
947 }
948
949 @Override
950 public void exit() {
951 cleanupUpstream();
952 super.exit();
953 }
954
955 private void cleanupUpstream() {
956 if (mUpstreamIfaceSet == null) return;
957
958 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
959 mUpstreamIfaceSet = null;
960 }
961
962 private void cleanupUpstreamInterface(String upstreamIface) {
963 // Note that we don't care about errors here.
964 // Sometimes interfaces are gone before we get
965 // to remove their rules, which generates errors.
966 // Just do the best we can.
967 try {
markchien12c5bb82020-01-07 14:43:17 +0800968 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
969 } catch (RemoteException | ServiceSpecificException e) {
970 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800971 }
972 try {
markchien12c5bb82020-01-07 14:43:17 +0800973 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
974 } catch (RemoteException | ServiceSpecificException e) {
975 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800976 }
977 }
978
979 @Override
980 public boolean processMessage(Message message) {
981 if (super.processMessage(message)) return true;
982
983 logMessage(this, message.what);
984 switch (message.what) {
985 case CMD_TETHER_REQUESTED:
986 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
987 break;
988 case CMD_TETHER_CONNECTION_CHANGED:
989 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
990 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
991 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
992 break;
993 }
994
995 if (newUpstreamIfaceSet == null) {
996 cleanupUpstream();
997 break;
998 }
999
1000 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1001 cleanupUpstreamInterface(removed);
1002 }
1003
1004 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1005 // This makes the call to cleanupUpstream() in the error
1006 // path for any interface neatly cleanup all the interfaces.
1007 mUpstreamIfaceSet = newUpstreamIfaceSet;
1008
1009 for (String ifname : added) {
1010 try {
markchien12c5bb82020-01-07 14:43:17 +08001011 mNetd.tetherAddForward(mIfaceName, ifname);
1012 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1013 } catch (RemoteException | ServiceSpecificException e) {
1014 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001015 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +08001016 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001017 transitionTo(mInitialState);
1018 return true;
1019 }
1020 }
1021 break;
1022 default:
1023 return false;
1024 }
1025 return true;
1026 }
1027
1028 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1029 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1030 if (mUpstreamIfaceSet != null && newIfaces != null) {
1031 return mUpstreamIfaceSet.equals(newIfaces);
1032 }
1033 return false;
1034 }
1035
1036 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1037 if (mUpstreamIfaceSet == null) return new HashSet<>();
1038
1039 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1040 removed.removeAll(newIfaces.ifnames);
1041 return removed;
1042 }
1043
1044 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1045 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1046 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1047 return added;
1048 }
1049 }
1050
1051 /**
1052 * This state is terminal for the per interface state machine. At this
1053 * point, the master state machine should have removed this interface
1054 * specific state machine from its list of possible recipients of
1055 * tethering requests. The state machine itself will hang around until
1056 * the garbage collector finds it.
1057 */
1058 class UnavailableState extends State {
1059 @Override
1060 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001061 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001062 sendInterfaceState(STATE_UNAVAILABLE);
1063 }
1064 }
1065
1066 // Accumulate routes representing "prefixes to be assigned to the local
1067 // interface", for subsequent modification of local_network routing.
1068 private static ArrayList<RouteInfo> getLocalRoutesFor(
1069 String ifname, HashSet<IpPrefix> prefixes) {
1070 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1071 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001072 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001073 }
1074 return localRoutes;
1075 }
1076
1077 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1078 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1079 final byte[] dnsBytes = localPrefix.getRawAddress();
1080 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1081 try {
1082 return Inet6Address.getByAddress(null, dnsBytes, 0);
1083 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001084 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001085 return null;
1086 }
1087 }
1088
1089 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1090 final byte random = (byte) (new Random()).nextInt();
1091 for (int value : excluded) {
1092 if (random == value) return dflt;
1093 }
1094 return random;
1095 }
1096}