blob: 2653b6d23ac9ba7a211a7ff113eb57f646cfaa08 [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;
22import static android.net.util.NetworkConstants.FF;
23import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
24import static android.net.util.NetworkConstants.asByte;
markchien6cf0e552019-12-06 15:24:53 +080025import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
markchien74a4fa92019-09-09 20:50:49 +080026
markchien74a4fa92019-09-09 20:50:49 +080027import android.net.INetd;
28import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080029import android.net.IpPrefix;
30import android.net.LinkAddress;
31import android.net.LinkProperties;
markchien74a4fa92019-09-09 20:50:49 +080032import android.net.RouteInfo;
markchien9b4d7572019-12-25 19:40:32 +080033import android.net.TetheringManager;
markchien74a4fa92019-09-09 20:50:49 +080034import android.net.dhcp.DhcpServerCallbacks;
35import android.net.dhcp.DhcpServingParamsParcel;
36import android.net.dhcp.DhcpServingParamsParcelExt;
37import android.net.dhcp.IDhcpServer;
38import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080039import android.net.shared.NetdUtils;
40import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080041import android.net.util.InterfaceParams;
42import android.net.util.InterfaceSet;
markchien74a4fa92019-09-09 20:50:49 +080043import android.net.util.SharedLog;
markchien74a4fa92019-09-09 20:50:49 +080044import android.os.Looper;
45import android.os.Message;
46import android.os.RemoteException;
47import android.os.ServiceSpecificException;
48import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080049import android.util.SparseArray;
50
51import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080052import com.android.internal.util.State;
53import com.android.internal.util.StateMachine;
54
55import java.net.Inet4Address;
56import java.net.Inet6Address;
57import java.net.InetAddress;
58import java.net.UnknownHostException;
59import java.util.ArrayList;
60import java.util.HashSet;
61import java.util.Objects;
62import java.util.Random;
63import java.util.Set;
64
65/**
66 * Provides the interface to IP-layer serving functionality for a given network
67 * interface, e.g. for tethering or "local-only hotspot" mode.
68 *
69 * @hide
70 */
71public class IpServer extends StateMachine {
72 public static final int STATE_UNAVAILABLE = 0;
73 public static final int STATE_AVAILABLE = 1;
74 public static final int STATE_TETHERED = 2;
75 public static final int STATE_LOCAL_ONLY = 3;
76
77 /** Get string name of |state|.*/
78 public static String getStateString(int state) {
79 switch (state) {
80 case STATE_UNAVAILABLE: return "UNAVAILABLE";
81 case STATE_AVAILABLE: return "AVAILABLE";
82 case STATE_TETHERED: return "TETHERED";
83 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
84 }
85 return "UNKNOWN: " + state;
86 }
87
88 private static final byte DOUG_ADAMS = (byte) 42;
89
90 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
91 private static final int USB_PREFIX_LENGTH = 24;
92 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
93 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
94 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
95 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +090096 private static final String ETHERNET_IFACE_ADDR = "192.168.50.1";
97 private static final int ETHERNET_IFACE_PREFIX_LENGTH = 24;
markchien74a4fa92019-09-09 20:50:49 +080098
99 // TODO: have PanService use some visible version of this constant
100 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
101 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
102
103 // TODO: have this configurable
104 private static final int DHCP_LEASE_TIME_SECS = 3600;
105
106 private static final String TAG = "IpServer";
107 private static final boolean DBG = false;
108 private static final boolean VDBG = false;
109 private static final Class[] sMessageClasses = {
110 IpServer.class
111 };
112 private static final SparseArray<String> sMagicDecoderRing =
113 MessageUtils.findMessageNames(sMessageClasses);
114
115 /** IpServer callback. */
116 public static class Callback {
117 /**
118 * Notify that |who| has changed its tethering state.
119 *
120 * @param who the calling instance of IpServer
121 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800122 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800123 */
markchien9d353822019-12-16 20:15:20 +0800124 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800125
126 /**
127 * Notify that |who| has new LinkProperties.
128 *
129 * @param who the calling instance of IpServer
130 * @param newLp the new LinkProperties to report
131 */
markchien9d353822019-12-16 20:15:20 +0800132 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
markchien74a4fa92019-09-09 20:50:49 +0800133 }
134
135 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800136 public abstract static class Dependencies {
markchien74a4fa92019-09-09 20:50:49 +0800137 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
138 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
139 return new RouterAdvertisementDaemon(ifParams);
140 }
141
142 /** Get |ifName|'s interface information.*/
143 public InterfaceParams getInterfaceParams(String ifName) {
144 return InterfaceParams.getByName(ifName);
145 }
146
markchien9d353822019-12-16 20:15:20 +0800147 /** Create a DhcpServer instance to be used by IpServer. */
148 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
149 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800150 }
151
markchien74a4fa92019-09-09 20:50:49 +0800152 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800153 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800154 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800155 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800156 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800157 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800158 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800159 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800160 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800161 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800162 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800163 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800164 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800165 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800166 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800167 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800168 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800169 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800170 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800171 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
markchien74a4fa92019-09-09 20:50:49 +0800172
173 private final State mInitialState;
174 private final State mLocalHotspotState;
175 private final State mTetheredState;
176 private final State mUnavailableState;
177
178 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800179 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800180 private final Callback mCallback;
181 private final InterfaceController mInterfaceCtrl;
182
183 private final String mIfaceName;
184 private final int mInterfaceType;
185 private final LinkProperties mLinkProperties;
186 private final boolean mUsingLegacyDhcp;
187
188 private final Dependencies mDeps;
189
190 private int mLastError;
191 private int mServingMode;
192 private InterfaceSet mUpstreamIfaceSet; // may change over time
193 private InterfaceParams mInterfaceParams;
194 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
195 // properties are those selected by the IPv6TetheringCoordinator and relayed
196 // to us. By comparison, mLinkProperties contains the addresses and directly
197 // connected routes that have been formed from these properties iff. we have
198 // succeeded in configuring them and are able to announce them within Router
199 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
200 private LinkProperties mLastIPv6LinkProperties;
201 private RouterAdvertisementDaemon mRaDaemon;
202
203 // To be accessed only on the handler thread
204 private int mDhcpServerStartIndex = 0;
205 private IDhcpServer mDhcpServer;
206 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800207 private LinkAddress mIpv4Address;
markchien74a4fa92019-09-09 20:50:49 +0800208
209 public IpServer(
210 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800211 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800212 super(ifaceName, looper);
213 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800214 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800215 mCallback = callback;
216 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
217 mIfaceName = ifaceName;
218 mInterfaceType = interfaceType;
219 mLinkProperties = new LinkProperties();
220 mUsingLegacyDhcp = usingLegacyDhcp;
221 mDeps = deps;
222 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800223 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800224 mServingMode = STATE_AVAILABLE;
225
226 mInitialState = new InitialState();
227 mLocalHotspotState = new LocalHotspotState();
228 mTetheredState = new TetheredState();
229 mUnavailableState = new UnavailableState();
230 addState(mInitialState);
231 addState(mLocalHotspotState);
232 addState(mTetheredState);
233 addState(mUnavailableState);
234
235 setInitialState(mInitialState);
236 }
237
238 /** Interface name which IpServer served.*/
239 public String interfaceName() {
240 return mIfaceName;
241 }
242
243 /**
markchien9b4d7572019-12-25 19:40:32 +0800244 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800245 */
246 public int interfaceType() {
247 return mInterfaceType;
248 }
249
250 /** Last error from this IpServer. */
251 public int lastError() {
252 return mLastError;
253 }
254
255 /** Serving mode is the current state of IpServer state machine. */
256 public int servingMode() {
257 return mServingMode;
258 }
259
260 /** The properties of the network link which IpServer is serving. */
261 public LinkProperties linkProperties() {
262 return new LinkProperties(mLinkProperties);
263 }
264
265 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
266 public void stop() {
267 sendMessage(CMD_INTERFACE_DOWN);
268 }
269
270 /**
271 * Tethering is canceled. IpServer state machine will be available and wait for
272 * next tethering request.
273 */
274 public void unwanted() {
275 sendMessage(CMD_TETHER_UNREQUESTED);
276 }
277
278 /** Internals. */
279
280 private boolean startIPv4() {
281 return configureIPv4(true);
282 }
283
284 /**
285 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
286 * handler.
287 *
288 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
289 * with different implementations of the callback, to differentiate handling of success/error in
290 * each call.
291 */
292 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
293 @Override
294 public void onStatusAvailable(int statusCode) {
295 getHandler().post(() -> callback(statusCode));
296 }
297
298 public abstract void callback(int statusCode);
299
300 @Override
301 public int getInterfaceVersion() {
302 return this.VERSION;
303 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900304
305 @Override
306 public String getInterfaceHash() {
307 return this.HASH;
308 }
markchien74a4fa92019-09-09 20:50:49 +0800309 }
310
311 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
312 private final int mStartIndex;
313
314 private DhcpServerCallbacksImpl(int startIndex) {
315 mStartIndex = startIndex;
316 }
317
318 @Override
319 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
320 getHandler().post(() -> {
321 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
322 if (mStartIndex != mDhcpServerStartIndex) {
323 // This start request is obsolete. When the |server| binder token goes out of
324 // scope, the garbage collector will finalize it, which causes the network stack
325 // process garbage collector to collect the server itself.
326 return;
327 }
328
329 if (statusCode != STATUS_SUCCESS) {
330 mLog.e("Error obtaining DHCP server: " + statusCode);
331 handleError();
332 return;
333 }
334
335 mDhcpServer = server;
336 try {
337 mDhcpServer.start(new OnHandlerStatusCallback() {
338 @Override
339 public void callback(int startStatusCode) {
340 if (startStatusCode != STATUS_SUCCESS) {
341 mLog.e("Error starting DHCP server: " + startStatusCode);
342 handleError();
343 }
344 }
345 });
346 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800347 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800348 }
349 });
350 }
351
352 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800353 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800354 transitionTo(mInitialState);
355 }
356 }
357
358 private boolean startDhcp(Inet4Address addr, int prefixLen) {
359 if (mUsingLegacyDhcp) {
360 return true;
361 }
362 final DhcpServingParamsParcel params;
363 params = new DhcpServingParamsParcelExt()
364 .setDefaultRouters(addr)
365 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
366 .setDnsServers(addr)
367 .setServerAddr(new LinkAddress(addr, prefixLen))
368 .setMetered(true);
369 // TODO: also advertise link MTU
370
371 mDhcpServerStartIndex++;
372 mDeps.makeDhcpServer(
373 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
374 return true;
375 }
376
377 private void stopDhcp() {
378 // Make all previous start requests obsolete so servers are not started later
379 mDhcpServerStartIndex++;
380
381 if (mDhcpServer != null) {
382 try {
383 mDhcpServer.stop(new OnHandlerStatusCallback() {
384 @Override
385 public void callback(int statusCode) {
386 if (statusCode != STATUS_SUCCESS) {
387 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800388 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800389 // Not much more we can do here
390 }
391 }
392 });
393 mDhcpServer = null;
394 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800395 mLog.e("Error stopping DHCP", e);
396 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800397 }
398 }
399 }
400
401 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
402 if (enable) {
403 return startDhcp(addr, prefixLen);
404 } else {
405 stopDhcp();
406 return true;
407 }
408 }
409
410 private void stopIPv4() {
411 configureIPv4(false);
412 // NOTE: All of configureIPv4() will be refactored out of existence
413 // into calls to InterfaceController, shared with startIPv4().
414 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800415 mIpv4Address = null;
markchien74a4fa92019-09-09 20:50:49 +0800416 }
417
markchien74a4fa92019-09-09 20:50:49 +0800418 private boolean configureIPv4(boolean enabled) {
419 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
420
421 // TODO: Replace this hard-coded information with dynamically selected
422 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800423 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800424 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800425 try {
Milim Lee45a971b2019-10-17 05:02:33 +0900426 if (mInterfaceType == TetheringManager.TETHERING_USB
427 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800428 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
429 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800430 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800431 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
432 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800433 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800434 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
435 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900436 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
437 // TODO: randomize address for tethering too, similarly to wifi
438 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
439 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800440 } else {
441 // BT configures the interface elsewhere: only start DHCP.
442 // TODO: make all tethering types behave the same way, and delete the bluetooth
443 // code that calls into NetworkManagementService directly.
444 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
445 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
446 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
447 }
448 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
449 } catch (IllegalArgumentException e) {
450 mLog.e("Error selecting ipv4 address", e);
451 if (!enabled) stopDhcp();
452 return false;
markchien74a4fa92019-09-09 20:50:49 +0800453 }
454
markchien12c5bb82020-01-07 14:43:17 +0800455 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800456 if (mInterfaceType == TetheringManager.TETHERING_WIFI
457 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800458 // The WiFi stack has ownership of the interface up/down state.
459 // It is unclear whether the Bluetooth or USB stacks will manage their own
460 // state.
461 setIfaceUp = null;
462 } else {
463 setIfaceUp = enabled;
464 }
465 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
466 mLog.e("Error configuring interface");
467 if (!enabled) stopDhcp();
468 return false;
469 }
markchien74a4fa92019-09-09 20:50:49 +0800470
markchien12c5bb82020-01-07 14:43:17 +0800471 if (!configureDhcp(enabled, srvAddr, prefixLen)) {
markchien74a4fa92019-09-09 20:50:49 +0800472 return false;
473 }
474
475 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800476 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
477 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800478 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800479 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800480 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800481 mLinkProperties.addRoute(route);
482 } else {
markchien12c5bb82020-01-07 14:43:17 +0800483 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800484 mLinkProperties.removeRoute(route);
485 }
486 return true;
487 }
488
489 private String getRandomWifiIPv4Address() {
490 try {
491 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
492 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
493 return InetAddress.getByAddress(bytes).getHostAddress();
494 } catch (Exception e) {
495 return WIFI_HOST_IFACE_ADDR;
496 }
497 }
498
499 private boolean startIPv6() {
500 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
501 if (mInterfaceParams == null) {
502 mLog.e("Failed to find InterfaceParams");
503 stopIPv6();
504 return false;
505 }
506
507 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
508 if (!mRaDaemon.start()) {
509 stopIPv6();
510 return false;
511 }
512
513 return true;
514 }
515
516 private void stopIPv6() {
517 mInterfaceParams = null;
518 setRaParams(null);
519
520 if (mRaDaemon != null) {
521 mRaDaemon.stop();
522 mRaDaemon = null;
523 }
524 }
525
526 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
527 // LinkProperties. These have extraneous data filtered out and only the
528 // necessary prefixes included (per its prefix distribution policy).
529 //
530 // TODO: Evaluate using a data structure than is more directly suited to
531 // communicating only the relevant information.
532 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
533 if (mRaDaemon == null) return;
534
535 // Avoid unnecessary work on spurious updates.
536 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
537 return;
538 }
539
540 RaParams params = null;
541
542 if (v6only != null) {
543 params = new RaParams();
544 params.mtu = v6only.getMtu();
545 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
546
547 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(v6only.getInterfaceName());
548
549 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
550 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
551
552 final IpPrefix prefix = new IpPrefix(
553 linkAddr.getAddress(), linkAddr.getPrefixLength());
554 params.prefixes.add(prefix);
555
556 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
557 if (dnsServer != null) {
558 params.dnses.add(dnsServer);
559 }
560 }
561 }
562 // If v6only is null, we pass in null to setRaParams(), which handles
563 // deprecation of any existing RA data.
564
565 setRaParams(params);
566 mLastIPv6LinkProperties = v6only;
567 }
568
569 private void configureLocalIPv6Routes(
570 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
571 // [1] Remove the routes that are deprecated.
572 if (!deprecatedPrefixes.isEmpty()) {
573 final ArrayList<RouteInfo> toBeRemoved =
574 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800575 // Remove routes from local network.
576 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
577 mNetd, toBeRemoved);
578 if (removalFailures > 0) {
579 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
580 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800581 }
582
583 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
584 }
585
586 // [2] Add only the routes that have not previously been added.
587 if (newPrefixes != null && !newPrefixes.isEmpty()) {
588 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
589 if (mLastRaParams != null) {
590 addedPrefixes.removeAll(mLastRaParams.prefixes);
591 }
592
593 if (!addedPrefixes.isEmpty()) {
594 final ArrayList<RouteInfo> toBeAdded =
595 getLocalRoutesFor(mIfaceName, addedPrefixes);
596 try {
markchien12c5bb82020-01-07 14:43:17 +0800597 // It's safe to call networkAddInterface() even if
598 // the interface is already in the local_network.
599 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
600 try {
601 // Add routes from local network. Note that adding routes that
602 // already exist does not cause an error (EEXIST is silently ignored).
603 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
604 } catch (IllegalStateException e) {
605 mLog.e("Failed to add IPv6 routes to local table: " + e);
606 }
607 } catch (ServiceSpecificException | RemoteException e) {
608 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800609 }
610
611 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
612 }
613 }
614 }
615
616 private void configureLocalIPv6Dns(
617 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
618 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
619 if (mNetd == null) {
620 if (newDnses != null) newDnses.clear();
621 mLog.e("No netd service instance available; not setting local IPv6 addresses");
622 return;
623 }
624
625 // [1] Remove deprecated local DNS IP addresses.
626 if (!deprecatedDnses.isEmpty()) {
627 for (Inet6Address dns : deprecatedDnses) {
628 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
629 mLog.e("Failed to remove local dns IP " + dns);
630 }
631
632 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
633 }
634 }
635
636 // [2] Add only the local DNS IP addresses that have not previously been added.
637 if (newDnses != null && !newDnses.isEmpty()) {
638 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
639 if (mLastRaParams != null) {
640 addedDnses.removeAll(mLastRaParams.dnses);
641 }
642
643 for (Inet6Address dns : addedDnses) {
644 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
645 mLog.e("Failed to add local dns IP " + dns);
646 newDnses.remove(dns);
647 }
648
649 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
650 }
651 }
652
653 try {
654 mNetd.tetherApplyDnsInterfaces();
655 } catch (ServiceSpecificException | RemoteException e) {
656 mLog.e("Failed to update local DNS caching server");
657 if (newDnses != null) newDnses.clear();
658 }
659 }
660
661 private byte getHopLimit(String upstreamIface) {
662 try {
663 int upstreamHopLimit = Integer.parseUnsignedInt(
664 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
665 // Add one hop to account for this forwarding device
666 upstreamHopLimit++;
667 // Cap the hop limit to 255.
668 return (byte) Integer.min(upstreamHopLimit, 255);
669 } catch (Exception e) {
670 mLog.e("Failed to find upstream interface hop limit", e);
671 }
672 return RaParams.DEFAULT_HOPLIMIT;
673 }
674
675 private void setRaParams(RaParams newParams) {
676 if (mRaDaemon != null) {
677 final RaParams deprecatedParams =
678 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
679
680 configureLocalIPv6Routes(deprecatedParams.prefixes,
681 (newParams != null) ? newParams.prefixes : null);
682
683 configureLocalIPv6Dns(deprecatedParams.dnses,
684 (newParams != null) ? newParams.dnses : null);
685
686 mRaDaemon.buildNewRa(deprecatedParams, newParams);
687 }
688
689 mLastRaParams = newParams;
690 }
691
692 private void logMessage(State state, int what) {
693 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
694 }
695
696 private void sendInterfaceState(int newInterfaceState) {
697 mServingMode = newInterfaceState;
698 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
699 sendLinkProperties();
700 }
701
702 private void sendLinkProperties() {
703 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
704 }
705
706 private void resetLinkProperties() {
707 mLinkProperties.clear();
708 mLinkProperties.setInterfaceName(mIfaceName);
709 }
710
711 class InitialState extends State {
712 @Override
713 public void enter() {
714 sendInterfaceState(STATE_AVAILABLE);
715 }
716
717 @Override
718 public boolean processMessage(Message message) {
719 logMessage(this, message.what);
720 switch (message.what) {
721 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800722 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800723 switch (message.arg1) {
724 case STATE_LOCAL_ONLY:
725 transitionTo(mLocalHotspotState);
726 break;
727 case STATE_TETHERED:
728 transitionTo(mTetheredState);
729 break;
730 default:
731 mLog.e("Invalid tethering interface serving state specified.");
732 }
733 break;
734 case CMD_INTERFACE_DOWN:
735 transitionTo(mUnavailableState);
736 break;
737 case CMD_IPV6_TETHER_UPDATE:
738 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
739 break;
740 default:
741 return NOT_HANDLED;
742 }
743 return HANDLED;
744 }
745 }
746
747 class BaseServingState extends State {
748 @Override
749 public void enter() {
750 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800751 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800752 return;
753 }
754
755 try {
markchien12c5bb82020-01-07 14:43:17 +0800756 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
757 mIpv4Address.getPrefixLength());
758 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +0800759 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +0800760 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800761 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800762 return;
763 }
764
765 if (!startIPv6()) {
766 mLog.e("Failed to startIPv6");
767 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
768 return;
769 }
770 }
771
772 @Override
773 public void exit() {
774 // Note that at this point, we're leaving the tethered state. We can fail any
775 // of these operations, but it doesn't really change that we have to try them
776 // all in sequence.
777 stopIPv6();
778
779 try {
markchien12c5bb82020-01-07 14:43:17 +0800780 NetdUtils.untetherInterface(mNetd, mIfaceName);
781 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +0800782 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800783 mLog.e("Failed to untether interface: " + e);
784 }
785
786 stopIPv4();
787
788 resetLinkProperties();
789 }
790
791 @Override
792 public boolean processMessage(Message message) {
793 logMessage(this, message.what);
794 switch (message.what) {
795 case CMD_TETHER_UNREQUESTED:
796 transitionTo(mInitialState);
797 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
798 break;
799 case CMD_INTERFACE_DOWN:
800 transitionTo(mUnavailableState);
801 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
802 break;
803 case CMD_IPV6_TETHER_UPDATE:
804 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
805 sendLinkProperties();
806 break;
807 case CMD_IP_FORWARDING_ENABLE_ERROR:
808 case CMD_IP_FORWARDING_DISABLE_ERROR:
809 case CMD_START_TETHERING_ERROR:
810 case CMD_STOP_TETHERING_ERROR:
811 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +0800812 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800813 transitionTo(mInitialState);
814 break;
815 default:
816 return false;
817 }
818 return true;
819 }
820 }
821
822 // Handling errors in BaseServingState.enter() by transitioning is
823 // problematic because transitioning during a multi-state jump yields
824 // a Log.wtf(). Ultimately, there should be only one ServingState,
825 // and forwarding and NAT rules should be handled by a coordinating
826 // functional element outside of IpServer.
827 class LocalHotspotState extends BaseServingState {
828 @Override
829 public void enter() {
830 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800831 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800832 transitionTo(mInitialState);
833 }
834
835 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
836 sendInterfaceState(STATE_LOCAL_ONLY);
837 }
838
839 @Override
840 public boolean processMessage(Message message) {
841 if (super.processMessage(message)) return true;
842
843 logMessage(this, message.what);
844 switch (message.what) {
845 case CMD_TETHER_REQUESTED:
846 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
847 break;
848 case CMD_TETHER_CONNECTION_CHANGED:
849 // Ignored in local hotspot state.
850 break;
851 default:
852 return false;
853 }
854 return true;
855 }
856 }
857
858 // Handling errors in BaseServingState.enter() by transitioning is
859 // problematic because transitioning during a multi-state jump yields
860 // a Log.wtf(). Ultimately, there should be only one ServingState,
861 // and forwarding and NAT rules should be handled by a coordinating
862 // functional element outside of IpServer.
863 class TetheredState extends BaseServingState {
864 @Override
865 public void enter() {
866 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800867 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800868 transitionTo(mInitialState);
869 }
870
871 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
872 sendInterfaceState(STATE_TETHERED);
873 }
874
875 @Override
876 public void exit() {
877 cleanupUpstream();
878 super.exit();
879 }
880
881 private void cleanupUpstream() {
882 if (mUpstreamIfaceSet == null) return;
883
884 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
885 mUpstreamIfaceSet = null;
886 }
887
888 private void cleanupUpstreamInterface(String upstreamIface) {
889 // Note that we don't care about errors here.
890 // Sometimes interfaces are gone before we get
891 // to remove their rules, which generates errors.
892 // Just do the best we can.
893 try {
markchien12c5bb82020-01-07 14:43:17 +0800894 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
895 } catch (RemoteException | ServiceSpecificException e) {
896 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800897 }
898 try {
markchien12c5bb82020-01-07 14:43:17 +0800899 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
900 } catch (RemoteException | ServiceSpecificException e) {
901 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800902 }
903 }
904
905 @Override
906 public boolean processMessage(Message message) {
907 if (super.processMessage(message)) return true;
908
909 logMessage(this, message.what);
910 switch (message.what) {
911 case CMD_TETHER_REQUESTED:
912 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
913 break;
914 case CMD_TETHER_CONNECTION_CHANGED:
915 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
916 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
917 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
918 break;
919 }
920
921 if (newUpstreamIfaceSet == null) {
922 cleanupUpstream();
923 break;
924 }
925
926 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
927 cleanupUpstreamInterface(removed);
928 }
929
930 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
931 // This makes the call to cleanupUpstream() in the error
932 // path for any interface neatly cleanup all the interfaces.
933 mUpstreamIfaceSet = newUpstreamIfaceSet;
934
935 for (String ifname : added) {
936 try {
markchien12c5bb82020-01-07 14:43:17 +0800937 mNetd.tetherAddForward(mIfaceName, ifname);
938 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
939 } catch (RemoteException | ServiceSpecificException e) {
940 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800941 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +0800942 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800943 transitionTo(mInitialState);
944 return true;
945 }
946 }
947 break;
948 default:
949 return false;
950 }
951 return true;
952 }
953
954 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
955 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
956 if (mUpstreamIfaceSet != null && newIfaces != null) {
957 return mUpstreamIfaceSet.equals(newIfaces);
958 }
959 return false;
960 }
961
962 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
963 if (mUpstreamIfaceSet == null) return new HashSet<>();
964
965 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
966 removed.removeAll(newIfaces.ifnames);
967 return removed;
968 }
969
970 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
971 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
972 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
973 return added;
974 }
975 }
976
977 /**
978 * This state is terminal for the per interface state machine. At this
979 * point, the master state machine should have removed this interface
980 * specific state machine from its list of possible recipients of
981 * tethering requests. The state machine itself will hang around until
982 * the garbage collector finds it.
983 */
984 class UnavailableState extends State {
985 @Override
986 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +0800987 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800988 sendInterfaceState(STATE_UNAVAILABLE);
989 }
990 }
991
992 // Accumulate routes representing "prefixes to be assigned to the local
993 // interface", for subsequent modification of local_network routing.
994 private static ArrayList<RouteInfo> getLocalRoutesFor(
995 String ifname, HashSet<IpPrefix> prefixes) {
996 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
997 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +0800998 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +0800999 }
1000 return localRoutes;
1001 }
1002
1003 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1004 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1005 final byte[] dnsBytes = localPrefix.getRawAddress();
1006 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1007 try {
1008 return Inet6Address.getByAddress(null, dnsBytes, 0);
1009 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001010 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001011 return null;
1012 }
1013 }
1014
1015 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1016 final byte random = (byte) (new Random()).nextInt();
1017 for (int value : excluded) {
1018 if (random == value) return dflt;
1019 }
1020 return random;
1021 }
1022}