blob: b4d49c02b085a333f7c11f0d2a9800c6a3d42122 [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();
613 params.mtu = v6only.getMtu();
614 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
615
616 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(v6only.getInterfaceName());
617
618 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
619 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
620
621 final IpPrefix prefix = new IpPrefix(
622 linkAddr.getAddress(), linkAddr.getPrefixLength());
623 params.prefixes.add(prefix);
624
625 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
626 if (dnsServer != null) {
627 params.dnses.add(dnsServer);
628 }
629 }
630 }
631 // If v6only is null, we pass in null to setRaParams(), which handles
632 // deprecation of any existing RA data.
633
634 setRaParams(params);
635 mLastIPv6LinkProperties = v6only;
636 }
637
638 private void configureLocalIPv6Routes(
639 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
640 // [1] Remove the routes that are deprecated.
641 if (!deprecatedPrefixes.isEmpty()) {
642 final ArrayList<RouteInfo> toBeRemoved =
643 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800644 // Remove routes from local network.
645 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
646 mNetd, toBeRemoved);
647 if (removalFailures > 0) {
648 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
649 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800650 }
651
652 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
653 }
654
655 // [2] Add only the routes that have not previously been added.
656 if (newPrefixes != null && !newPrefixes.isEmpty()) {
657 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
658 if (mLastRaParams != null) {
659 addedPrefixes.removeAll(mLastRaParams.prefixes);
660 }
661
662 if (!addedPrefixes.isEmpty()) {
663 final ArrayList<RouteInfo> toBeAdded =
664 getLocalRoutesFor(mIfaceName, addedPrefixes);
665 try {
markchien12c5bb82020-01-07 14:43:17 +0800666 // It's safe to call networkAddInterface() even if
667 // the interface is already in the local_network.
668 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
669 try {
670 // Add routes from local network. Note that adding routes that
671 // already exist does not cause an error (EEXIST is silently ignored).
672 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
673 } catch (IllegalStateException e) {
674 mLog.e("Failed to add IPv6 routes to local table: " + e);
675 }
676 } catch (ServiceSpecificException | RemoteException e) {
677 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800678 }
679
680 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
681 }
682 }
683 }
684
685 private void configureLocalIPv6Dns(
686 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
687 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
688 if (mNetd == null) {
689 if (newDnses != null) newDnses.clear();
690 mLog.e("No netd service instance available; not setting local IPv6 addresses");
691 return;
692 }
693
694 // [1] Remove deprecated local DNS IP addresses.
695 if (!deprecatedDnses.isEmpty()) {
696 for (Inet6Address dns : deprecatedDnses) {
697 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
698 mLog.e("Failed to remove local dns IP " + dns);
699 }
700
701 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
702 }
703 }
704
705 // [2] Add only the local DNS IP addresses that have not previously been added.
706 if (newDnses != null && !newDnses.isEmpty()) {
707 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
708 if (mLastRaParams != null) {
709 addedDnses.removeAll(mLastRaParams.dnses);
710 }
711
712 for (Inet6Address dns : addedDnses) {
713 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
714 mLog.e("Failed to add local dns IP " + dns);
715 newDnses.remove(dns);
716 }
717
718 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
719 }
720 }
721
722 try {
723 mNetd.tetherApplyDnsInterfaces();
724 } catch (ServiceSpecificException | RemoteException e) {
725 mLog.e("Failed to update local DNS caching server");
726 if (newDnses != null) newDnses.clear();
727 }
728 }
729
730 private byte getHopLimit(String upstreamIface) {
731 try {
732 int upstreamHopLimit = Integer.parseUnsignedInt(
733 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
734 // Add one hop to account for this forwarding device
735 upstreamHopLimit++;
736 // Cap the hop limit to 255.
737 return (byte) Integer.min(upstreamHopLimit, 255);
738 } catch (Exception e) {
739 mLog.e("Failed to find upstream interface hop limit", e);
740 }
741 return RaParams.DEFAULT_HOPLIMIT;
742 }
743
744 private void setRaParams(RaParams newParams) {
745 if (mRaDaemon != null) {
746 final RaParams deprecatedParams =
747 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
748
749 configureLocalIPv6Routes(deprecatedParams.prefixes,
750 (newParams != null) ? newParams.prefixes : null);
751
752 configureLocalIPv6Dns(deprecatedParams.dnses,
753 (newParams != null) ? newParams.dnses : null);
754
755 mRaDaemon.buildNewRa(deprecatedParams, newParams);
756 }
757
758 mLastRaParams = newParams;
759 }
760
761 private void logMessage(State state, int what) {
762 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
763 }
764
765 private void sendInterfaceState(int newInterfaceState) {
766 mServingMode = newInterfaceState;
767 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
768 sendLinkProperties();
769 }
770
771 private void sendLinkProperties() {
772 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
773 }
774
775 private void resetLinkProperties() {
776 mLinkProperties.clear();
777 mLinkProperties.setInterfaceName(mIfaceName);
778 }
779
780 class InitialState extends State {
781 @Override
782 public void enter() {
783 sendInterfaceState(STATE_AVAILABLE);
784 }
785
786 @Override
787 public boolean processMessage(Message message) {
788 logMessage(this, message.what);
789 switch (message.what) {
790 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800791 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800792 switch (message.arg1) {
793 case STATE_LOCAL_ONLY:
794 transitionTo(mLocalHotspotState);
795 break;
796 case STATE_TETHERED:
797 transitionTo(mTetheredState);
798 break;
799 default:
800 mLog.e("Invalid tethering interface serving state specified.");
801 }
802 break;
803 case CMD_INTERFACE_DOWN:
804 transitionTo(mUnavailableState);
805 break;
806 case CMD_IPV6_TETHER_UPDATE:
807 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
808 break;
809 default:
810 return NOT_HANDLED;
811 }
812 return HANDLED;
813 }
814 }
815
816 class BaseServingState extends State {
817 @Override
818 public void enter() {
819 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800820 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800821 return;
822 }
823
824 try {
markchien12c5bb82020-01-07 14:43:17 +0800825 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
826 mIpv4Address.getPrefixLength());
827 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +0800828 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +0800829 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800830 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800831 return;
832 }
833
834 if (!startIPv6()) {
835 mLog.e("Failed to startIPv6");
836 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
837 return;
838 }
839 }
840
841 @Override
842 public void exit() {
843 // Note that at this point, we're leaving the tethered state. We can fail any
844 // of these operations, but it doesn't really change that we have to try them
845 // all in sequence.
846 stopIPv6();
847
848 try {
markchien12c5bb82020-01-07 14:43:17 +0800849 NetdUtils.untetherInterface(mNetd, mIfaceName);
850 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +0800851 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800852 mLog.e("Failed to untether interface: " + e);
853 }
854
855 stopIPv4();
856
857 resetLinkProperties();
858 }
859
860 @Override
861 public boolean processMessage(Message message) {
862 logMessage(this, message.what);
863 switch (message.what) {
864 case CMD_TETHER_UNREQUESTED:
865 transitionTo(mInitialState);
866 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
867 break;
868 case CMD_INTERFACE_DOWN:
869 transitionTo(mUnavailableState);
870 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
871 break;
872 case CMD_IPV6_TETHER_UPDATE:
873 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
874 sendLinkProperties();
875 break;
876 case CMD_IP_FORWARDING_ENABLE_ERROR:
877 case CMD_IP_FORWARDING_DISABLE_ERROR:
878 case CMD_START_TETHERING_ERROR:
879 case CMD_STOP_TETHERING_ERROR:
880 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +0800881 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800882 transitionTo(mInitialState);
883 break;
884 default:
885 return false;
886 }
887 return true;
888 }
889 }
890
891 // Handling errors in BaseServingState.enter() by transitioning is
892 // problematic because transitioning during a multi-state jump yields
893 // a Log.wtf(). Ultimately, there should be only one ServingState,
894 // and forwarding and NAT rules should be handled by a coordinating
895 // functional element outside of IpServer.
896 class LocalHotspotState extends BaseServingState {
897 @Override
898 public void enter() {
899 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800900 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800901 transitionTo(mInitialState);
902 }
903
904 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
905 sendInterfaceState(STATE_LOCAL_ONLY);
906 }
907
908 @Override
909 public boolean processMessage(Message message) {
910 if (super.processMessage(message)) return true;
911
912 logMessage(this, message.what);
913 switch (message.what) {
914 case CMD_TETHER_REQUESTED:
915 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
916 break;
917 case CMD_TETHER_CONNECTION_CHANGED:
918 // Ignored in local hotspot state.
919 break;
920 default:
921 return false;
922 }
923 return true;
924 }
925 }
926
927 // Handling errors in BaseServingState.enter() by transitioning is
928 // problematic because transitioning during a multi-state jump yields
929 // a Log.wtf(). Ultimately, there should be only one ServingState,
930 // and forwarding and NAT rules should be handled by a coordinating
931 // functional element outside of IpServer.
932 class TetheredState extends BaseServingState {
933 @Override
934 public void enter() {
935 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800936 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800937 transitionTo(mInitialState);
938 }
939
940 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
941 sendInterfaceState(STATE_TETHERED);
942 }
943
944 @Override
945 public void exit() {
946 cleanupUpstream();
947 super.exit();
948 }
949
950 private void cleanupUpstream() {
951 if (mUpstreamIfaceSet == null) return;
952
953 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
954 mUpstreamIfaceSet = null;
955 }
956
957 private void cleanupUpstreamInterface(String upstreamIface) {
958 // Note that we don't care about errors here.
959 // Sometimes interfaces are gone before we get
960 // to remove their rules, which generates errors.
961 // Just do the best we can.
962 try {
markchien12c5bb82020-01-07 14:43:17 +0800963 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
964 } catch (RemoteException | ServiceSpecificException e) {
965 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800966 }
967 try {
markchien12c5bb82020-01-07 14:43:17 +0800968 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
969 } catch (RemoteException | ServiceSpecificException e) {
970 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800971 }
972 }
973
974 @Override
975 public boolean processMessage(Message message) {
976 if (super.processMessage(message)) return true;
977
978 logMessage(this, message.what);
979 switch (message.what) {
980 case CMD_TETHER_REQUESTED:
981 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
982 break;
983 case CMD_TETHER_CONNECTION_CHANGED:
984 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
985 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
986 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
987 break;
988 }
989
990 if (newUpstreamIfaceSet == null) {
991 cleanupUpstream();
992 break;
993 }
994
995 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
996 cleanupUpstreamInterface(removed);
997 }
998
999 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1000 // This makes the call to cleanupUpstream() in the error
1001 // path for any interface neatly cleanup all the interfaces.
1002 mUpstreamIfaceSet = newUpstreamIfaceSet;
1003
1004 for (String ifname : added) {
1005 try {
markchien12c5bb82020-01-07 14:43:17 +08001006 mNetd.tetherAddForward(mIfaceName, ifname);
1007 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1008 } catch (RemoteException | ServiceSpecificException e) {
1009 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001010 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +08001011 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001012 transitionTo(mInitialState);
1013 return true;
1014 }
1015 }
1016 break;
1017 default:
1018 return false;
1019 }
1020 return true;
1021 }
1022
1023 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1024 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1025 if (mUpstreamIfaceSet != null && newIfaces != null) {
1026 return mUpstreamIfaceSet.equals(newIfaces);
1027 }
1028 return false;
1029 }
1030
1031 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1032 if (mUpstreamIfaceSet == null) return new HashSet<>();
1033
1034 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1035 removed.removeAll(newIfaces.ifnames);
1036 return removed;
1037 }
1038
1039 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1040 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1041 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1042 return added;
1043 }
1044 }
1045
1046 /**
1047 * This state is terminal for the per interface state machine. At this
1048 * point, the master state machine should have removed this interface
1049 * specific state machine from its list of possible recipients of
1050 * tethering requests. The state machine itself will hang around until
1051 * the garbage collector finds it.
1052 */
1053 class UnavailableState extends State {
1054 @Override
1055 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001056 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001057 sendInterfaceState(STATE_UNAVAILABLE);
1058 }
1059 }
1060
1061 // Accumulate routes representing "prefixes to be assigned to the local
1062 // interface", for subsequent modification of local_network routing.
1063 private static ArrayList<RouteInfo> getLocalRoutesFor(
1064 String ifname, HashSet<IpPrefix> prefixes) {
1065 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1066 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001067 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001068 }
1069 return localRoutes;
1070 }
1071
1072 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1073 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1074 final byte[] dnsBytes = localPrefix.getRawAddress();
1075 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1076 try {
1077 return Inet6Address.getByAddress(null, dnsBytes, 0);
1078 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001079 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001080 return null;
1081 }
1082 }
1083
1084 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1085 final byte random = (byte) (new Random()).nextInt();
1086 for (int value : excluded) {
1087 if (random == value) return dflt;
1088 }
1089 return random;
1090 }
1091}