blob: 4306cf0bd5f304f9b274ff9666c4c5211e8d06cc [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;
96
97 // TODO: have PanService use some visible version of this constant
98 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
99 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
100
101 // TODO: have this configurable
102 private static final int DHCP_LEASE_TIME_SECS = 3600;
103
104 private static final String TAG = "IpServer";
105 private static final boolean DBG = false;
106 private static final boolean VDBG = false;
107 private static final Class[] sMessageClasses = {
108 IpServer.class
109 };
110 private static final SparseArray<String> sMagicDecoderRing =
111 MessageUtils.findMessageNames(sMessageClasses);
112
113 /** IpServer callback. */
114 public static class Callback {
115 /**
116 * Notify that |who| has changed its tethering state.
117 *
118 * @param who the calling instance of IpServer
119 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800120 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800121 */
markchien9d353822019-12-16 20:15:20 +0800122 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800123
124 /**
125 * Notify that |who| has new LinkProperties.
126 *
127 * @param who the calling instance of IpServer
128 * @param newLp the new LinkProperties to report
129 */
markchien9d353822019-12-16 20:15:20 +0800130 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
markchien74a4fa92019-09-09 20:50:49 +0800131 }
132
133 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800134 public abstract static class Dependencies {
markchien74a4fa92019-09-09 20:50:49 +0800135 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
136 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
137 return new RouterAdvertisementDaemon(ifParams);
138 }
139
140 /** Get |ifName|'s interface information.*/
141 public InterfaceParams getInterfaceParams(String ifName) {
142 return InterfaceParams.getByName(ifName);
143 }
144
markchien9d353822019-12-16 20:15:20 +0800145 /** Create a DhcpServer instance to be used by IpServer. */
146 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
147 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800148 }
149
markchien74a4fa92019-09-09 20:50:49 +0800150 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800151 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800152 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800153 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800154 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800155 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800156 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800157 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800158 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800159 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800160 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800161 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800162 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800163 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800164 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800165 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800166 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800167 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800168 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800169 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
markchien74a4fa92019-09-09 20:50:49 +0800170
171 private final State mInitialState;
172 private final State mLocalHotspotState;
173 private final State mTetheredState;
174 private final State mUnavailableState;
175
176 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800177 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800178 private final Callback mCallback;
179 private final InterfaceController mInterfaceCtrl;
180
181 private final String mIfaceName;
182 private final int mInterfaceType;
183 private final LinkProperties mLinkProperties;
184 private final boolean mUsingLegacyDhcp;
185
186 private final Dependencies mDeps;
187
188 private int mLastError;
189 private int mServingMode;
190 private InterfaceSet mUpstreamIfaceSet; // may change over time
191 private InterfaceParams mInterfaceParams;
192 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
193 // properties are those selected by the IPv6TetheringCoordinator and relayed
194 // to us. By comparison, mLinkProperties contains the addresses and directly
195 // connected routes that have been formed from these properties iff. we have
196 // succeeded in configuring them and are able to announce them within Router
197 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
198 private LinkProperties mLastIPv6LinkProperties;
199 private RouterAdvertisementDaemon mRaDaemon;
200
201 // To be accessed only on the handler thread
202 private int mDhcpServerStartIndex = 0;
203 private IDhcpServer mDhcpServer;
204 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800205 private LinkAddress mIpv4Address;
markchien74a4fa92019-09-09 20:50:49 +0800206
207 public IpServer(
208 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800209 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800210 super(ifaceName, looper);
211 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800212 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800213 mCallback = callback;
214 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
215 mIfaceName = ifaceName;
216 mInterfaceType = interfaceType;
217 mLinkProperties = new LinkProperties();
218 mUsingLegacyDhcp = usingLegacyDhcp;
219 mDeps = deps;
220 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800221 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800222 mServingMode = STATE_AVAILABLE;
223
224 mInitialState = new InitialState();
225 mLocalHotspotState = new LocalHotspotState();
226 mTetheredState = new TetheredState();
227 mUnavailableState = new UnavailableState();
228 addState(mInitialState);
229 addState(mLocalHotspotState);
230 addState(mTetheredState);
231 addState(mUnavailableState);
232
233 setInitialState(mInitialState);
234 }
235
236 /** Interface name which IpServer served.*/
237 public String interfaceName() {
238 return mIfaceName;
239 }
240
241 /**
markchien9b4d7572019-12-25 19:40:32 +0800242 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800243 */
244 public int interfaceType() {
245 return mInterfaceType;
246 }
247
248 /** Last error from this IpServer. */
249 public int lastError() {
250 return mLastError;
251 }
252
253 /** Serving mode is the current state of IpServer state machine. */
254 public int servingMode() {
255 return mServingMode;
256 }
257
258 /** The properties of the network link which IpServer is serving. */
259 public LinkProperties linkProperties() {
260 return new LinkProperties(mLinkProperties);
261 }
262
263 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
264 public void stop() {
265 sendMessage(CMD_INTERFACE_DOWN);
266 }
267
268 /**
269 * Tethering is canceled. IpServer state machine will be available and wait for
270 * next tethering request.
271 */
272 public void unwanted() {
273 sendMessage(CMD_TETHER_UNREQUESTED);
274 }
275
276 /** Internals. */
277
278 private boolean startIPv4() {
279 return configureIPv4(true);
280 }
281
282 /**
283 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
284 * handler.
285 *
286 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
287 * with different implementations of the callback, to differentiate handling of success/error in
288 * each call.
289 */
290 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
291 @Override
292 public void onStatusAvailable(int statusCode) {
293 getHandler().post(() -> callback(statusCode));
294 }
295
296 public abstract void callback(int statusCode);
297
298 @Override
299 public int getInterfaceVersion() {
300 return this.VERSION;
301 }
302 }
303
304 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
305 private final int mStartIndex;
306
307 private DhcpServerCallbacksImpl(int startIndex) {
308 mStartIndex = startIndex;
309 }
310
311 @Override
312 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
313 getHandler().post(() -> {
314 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
315 if (mStartIndex != mDhcpServerStartIndex) {
316 // This start request is obsolete. When the |server| binder token goes out of
317 // scope, the garbage collector will finalize it, which causes the network stack
318 // process garbage collector to collect the server itself.
319 return;
320 }
321
322 if (statusCode != STATUS_SUCCESS) {
323 mLog.e("Error obtaining DHCP server: " + statusCode);
324 handleError();
325 return;
326 }
327
328 mDhcpServer = server;
329 try {
330 mDhcpServer.start(new OnHandlerStatusCallback() {
331 @Override
332 public void callback(int startStatusCode) {
333 if (startStatusCode != STATUS_SUCCESS) {
334 mLog.e("Error starting DHCP server: " + startStatusCode);
335 handleError();
336 }
337 }
338 });
339 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800340 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800341 }
342 });
343 }
344
345 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800346 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800347 transitionTo(mInitialState);
348 }
349 }
350
351 private boolean startDhcp(Inet4Address addr, int prefixLen) {
352 if (mUsingLegacyDhcp) {
353 return true;
354 }
355 final DhcpServingParamsParcel params;
356 params = new DhcpServingParamsParcelExt()
357 .setDefaultRouters(addr)
358 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
359 .setDnsServers(addr)
360 .setServerAddr(new LinkAddress(addr, prefixLen))
361 .setMetered(true);
362 // TODO: also advertise link MTU
363
364 mDhcpServerStartIndex++;
365 mDeps.makeDhcpServer(
366 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
367 return true;
368 }
369
370 private void stopDhcp() {
371 // Make all previous start requests obsolete so servers are not started later
372 mDhcpServerStartIndex++;
373
374 if (mDhcpServer != null) {
375 try {
376 mDhcpServer.stop(new OnHandlerStatusCallback() {
377 @Override
378 public void callback(int statusCode) {
379 if (statusCode != STATUS_SUCCESS) {
380 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800381 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800382 // Not much more we can do here
383 }
384 }
385 });
386 mDhcpServer = null;
387 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800388 mLog.e("Error stopping DHCP", e);
389 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800390 }
391 }
392 }
393
394 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
395 if (enable) {
396 return startDhcp(addr, prefixLen);
397 } else {
398 stopDhcp();
399 return true;
400 }
401 }
402
403 private void stopIPv4() {
404 configureIPv4(false);
405 // NOTE: All of configureIPv4() will be refactored out of existence
406 // into calls to InterfaceController, shared with startIPv4().
407 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800408 mIpv4Address = null;
markchien74a4fa92019-09-09 20:50:49 +0800409 }
410
markchien74a4fa92019-09-09 20:50:49 +0800411 private boolean configureIPv4(boolean enabled) {
412 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
413
414 // TODO: Replace this hard-coded information with dynamically selected
415 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800416 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800417 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800418 try {
markchien9b4d7572019-12-25 19:40:32 +0800419 if (mInterfaceType == TetheringManager.TETHERING_USB) {
markchien12c5bb82020-01-07 14:43:17 +0800420 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
421 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800422 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800423 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
424 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800425 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800426 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
427 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
428 } else {
429 // BT configures the interface elsewhere: only start DHCP.
430 // TODO: make all tethering types behave the same way, and delete the bluetooth
431 // code that calls into NetworkManagementService directly.
432 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
433 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
434 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
435 }
436 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
437 } catch (IllegalArgumentException e) {
438 mLog.e("Error selecting ipv4 address", e);
439 if (!enabled) stopDhcp();
440 return false;
markchien74a4fa92019-09-09 20:50:49 +0800441 }
442
markchien12c5bb82020-01-07 14:43:17 +0800443 final Boolean setIfaceUp;
markchien9b4d7572019-12-25 19:40:32 +0800444 if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800445 // The WiFi stack has ownership of the interface up/down state.
446 // It is unclear whether the Bluetooth or USB stacks will manage their own
447 // state.
448 setIfaceUp = null;
449 } else {
450 setIfaceUp = enabled;
451 }
452 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
453 mLog.e("Error configuring interface");
454 if (!enabled) stopDhcp();
455 return false;
456 }
markchien74a4fa92019-09-09 20:50:49 +0800457
markchien12c5bb82020-01-07 14:43:17 +0800458 if (!configureDhcp(enabled, srvAddr, prefixLen)) {
markchien74a4fa92019-09-09 20:50:49 +0800459 return false;
460 }
461
462 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800463 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
464 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800465 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800466 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800467 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800468 mLinkProperties.addRoute(route);
469 } else {
markchien12c5bb82020-01-07 14:43:17 +0800470 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800471 mLinkProperties.removeRoute(route);
472 }
473 return true;
474 }
475
476 private String getRandomWifiIPv4Address() {
477 try {
478 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
479 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
480 return InetAddress.getByAddress(bytes).getHostAddress();
481 } catch (Exception e) {
482 return WIFI_HOST_IFACE_ADDR;
483 }
484 }
485
486 private boolean startIPv6() {
487 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
488 if (mInterfaceParams == null) {
489 mLog.e("Failed to find InterfaceParams");
490 stopIPv6();
491 return false;
492 }
493
494 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
495 if (!mRaDaemon.start()) {
496 stopIPv6();
497 return false;
498 }
499
500 return true;
501 }
502
503 private void stopIPv6() {
504 mInterfaceParams = null;
505 setRaParams(null);
506
507 if (mRaDaemon != null) {
508 mRaDaemon.stop();
509 mRaDaemon = null;
510 }
511 }
512
513 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
514 // LinkProperties. These have extraneous data filtered out and only the
515 // necessary prefixes included (per its prefix distribution policy).
516 //
517 // TODO: Evaluate using a data structure than is more directly suited to
518 // communicating only the relevant information.
519 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
520 if (mRaDaemon == null) return;
521
522 // Avoid unnecessary work on spurious updates.
523 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
524 return;
525 }
526
527 RaParams params = null;
528
529 if (v6only != null) {
530 params = new RaParams();
531 params.mtu = v6only.getMtu();
532 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
533
534 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(v6only.getInterfaceName());
535
536 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
537 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
538
539 final IpPrefix prefix = new IpPrefix(
540 linkAddr.getAddress(), linkAddr.getPrefixLength());
541 params.prefixes.add(prefix);
542
543 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
544 if (dnsServer != null) {
545 params.dnses.add(dnsServer);
546 }
547 }
548 }
549 // If v6only is null, we pass in null to setRaParams(), which handles
550 // deprecation of any existing RA data.
551
552 setRaParams(params);
553 mLastIPv6LinkProperties = v6only;
554 }
555
556 private void configureLocalIPv6Routes(
557 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
558 // [1] Remove the routes that are deprecated.
559 if (!deprecatedPrefixes.isEmpty()) {
560 final ArrayList<RouteInfo> toBeRemoved =
561 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800562 // Remove routes from local network.
563 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
564 mNetd, toBeRemoved);
565 if (removalFailures > 0) {
566 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
567 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800568 }
569
570 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
571 }
572
573 // [2] Add only the routes that have not previously been added.
574 if (newPrefixes != null && !newPrefixes.isEmpty()) {
575 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
576 if (mLastRaParams != null) {
577 addedPrefixes.removeAll(mLastRaParams.prefixes);
578 }
579
580 if (!addedPrefixes.isEmpty()) {
581 final ArrayList<RouteInfo> toBeAdded =
582 getLocalRoutesFor(mIfaceName, addedPrefixes);
583 try {
markchien12c5bb82020-01-07 14:43:17 +0800584 // It's safe to call networkAddInterface() even if
585 // the interface is already in the local_network.
586 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
587 try {
588 // Add routes from local network. Note that adding routes that
589 // already exist does not cause an error (EEXIST is silently ignored).
590 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
591 } catch (IllegalStateException e) {
592 mLog.e("Failed to add IPv6 routes to local table: " + e);
593 }
594 } catch (ServiceSpecificException | RemoteException e) {
595 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800596 }
597
598 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
599 }
600 }
601 }
602
603 private void configureLocalIPv6Dns(
604 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
605 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
606 if (mNetd == null) {
607 if (newDnses != null) newDnses.clear();
608 mLog.e("No netd service instance available; not setting local IPv6 addresses");
609 return;
610 }
611
612 // [1] Remove deprecated local DNS IP addresses.
613 if (!deprecatedDnses.isEmpty()) {
614 for (Inet6Address dns : deprecatedDnses) {
615 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
616 mLog.e("Failed to remove local dns IP " + dns);
617 }
618
619 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
620 }
621 }
622
623 // [2] Add only the local DNS IP addresses that have not previously been added.
624 if (newDnses != null && !newDnses.isEmpty()) {
625 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
626 if (mLastRaParams != null) {
627 addedDnses.removeAll(mLastRaParams.dnses);
628 }
629
630 for (Inet6Address dns : addedDnses) {
631 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
632 mLog.e("Failed to add local dns IP " + dns);
633 newDnses.remove(dns);
634 }
635
636 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
637 }
638 }
639
640 try {
641 mNetd.tetherApplyDnsInterfaces();
642 } catch (ServiceSpecificException | RemoteException e) {
643 mLog.e("Failed to update local DNS caching server");
644 if (newDnses != null) newDnses.clear();
645 }
646 }
647
648 private byte getHopLimit(String upstreamIface) {
649 try {
650 int upstreamHopLimit = Integer.parseUnsignedInt(
651 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
652 // Add one hop to account for this forwarding device
653 upstreamHopLimit++;
654 // Cap the hop limit to 255.
655 return (byte) Integer.min(upstreamHopLimit, 255);
656 } catch (Exception e) {
657 mLog.e("Failed to find upstream interface hop limit", e);
658 }
659 return RaParams.DEFAULT_HOPLIMIT;
660 }
661
662 private void setRaParams(RaParams newParams) {
663 if (mRaDaemon != null) {
664 final RaParams deprecatedParams =
665 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
666
667 configureLocalIPv6Routes(deprecatedParams.prefixes,
668 (newParams != null) ? newParams.prefixes : null);
669
670 configureLocalIPv6Dns(deprecatedParams.dnses,
671 (newParams != null) ? newParams.dnses : null);
672
673 mRaDaemon.buildNewRa(deprecatedParams, newParams);
674 }
675
676 mLastRaParams = newParams;
677 }
678
679 private void logMessage(State state, int what) {
680 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
681 }
682
683 private void sendInterfaceState(int newInterfaceState) {
684 mServingMode = newInterfaceState;
685 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
686 sendLinkProperties();
687 }
688
689 private void sendLinkProperties() {
690 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
691 }
692
693 private void resetLinkProperties() {
694 mLinkProperties.clear();
695 mLinkProperties.setInterfaceName(mIfaceName);
696 }
697
698 class InitialState extends State {
699 @Override
700 public void enter() {
701 sendInterfaceState(STATE_AVAILABLE);
702 }
703
704 @Override
705 public boolean processMessage(Message message) {
706 logMessage(this, message.what);
707 switch (message.what) {
708 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800709 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800710 switch (message.arg1) {
711 case STATE_LOCAL_ONLY:
712 transitionTo(mLocalHotspotState);
713 break;
714 case STATE_TETHERED:
715 transitionTo(mTetheredState);
716 break;
717 default:
718 mLog.e("Invalid tethering interface serving state specified.");
719 }
720 break;
721 case CMD_INTERFACE_DOWN:
722 transitionTo(mUnavailableState);
723 break;
724 case CMD_IPV6_TETHER_UPDATE:
725 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
726 break;
727 default:
728 return NOT_HANDLED;
729 }
730 return HANDLED;
731 }
732 }
733
734 class BaseServingState extends State {
735 @Override
736 public void enter() {
737 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800738 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800739 return;
740 }
741
742 try {
markchien12c5bb82020-01-07 14:43:17 +0800743 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
744 mIpv4Address.getPrefixLength());
745 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
746 } catch (RemoteException | ServiceSpecificException e) {
markchien74a4fa92019-09-09 20:50:49 +0800747 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800748 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800749 return;
750 }
751
752 if (!startIPv6()) {
753 mLog.e("Failed to startIPv6");
754 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
755 return;
756 }
757 }
758
759 @Override
760 public void exit() {
761 // Note that at this point, we're leaving the tethered state. We can fail any
762 // of these operations, but it doesn't really change that we have to try them
763 // all in sequence.
764 stopIPv6();
765
766 try {
markchien12c5bb82020-01-07 14:43:17 +0800767 NetdUtils.untetherInterface(mNetd, mIfaceName);
768 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +0800769 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800770 mLog.e("Failed to untether interface: " + e);
771 }
772
773 stopIPv4();
774
775 resetLinkProperties();
776 }
777
778 @Override
779 public boolean processMessage(Message message) {
780 logMessage(this, message.what);
781 switch (message.what) {
782 case CMD_TETHER_UNREQUESTED:
783 transitionTo(mInitialState);
784 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
785 break;
786 case CMD_INTERFACE_DOWN:
787 transitionTo(mUnavailableState);
788 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
789 break;
790 case CMD_IPV6_TETHER_UPDATE:
791 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
792 sendLinkProperties();
793 break;
794 case CMD_IP_FORWARDING_ENABLE_ERROR:
795 case CMD_IP_FORWARDING_DISABLE_ERROR:
796 case CMD_START_TETHERING_ERROR:
797 case CMD_STOP_TETHERING_ERROR:
798 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +0800799 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800800 transitionTo(mInitialState);
801 break;
802 default:
803 return false;
804 }
805 return true;
806 }
807 }
808
809 // Handling errors in BaseServingState.enter() by transitioning is
810 // problematic because transitioning during a multi-state jump yields
811 // a Log.wtf(). Ultimately, there should be only one ServingState,
812 // and forwarding and NAT rules should be handled by a coordinating
813 // functional element outside of IpServer.
814 class LocalHotspotState extends BaseServingState {
815 @Override
816 public void enter() {
817 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800818 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800819 transitionTo(mInitialState);
820 }
821
822 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
823 sendInterfaceState(STATE_LOCAL_ONLY);
824 }
825
826 @Override
827 public boolean processMessage(Message message) {
828 if (super.processMessage(message)) return true;
829
830 logMessage(this, message.what);
831 switch (message.what) {
832 case CMD_TETHER_REQUESTED:
833 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
834 break;
835 case CMD_TETHER_CONNECTION_CHANGED:
836 // Ignored in local hotspot state.
837 break;
838 default:
839 return false;
840 }
841 return true;
842 }
843 }
844
845 // Handling errors in BaseServingState.enter() by transitioning is
846 // problematic because transitioning during a multi-state jump yields
847 // a Log.wtf(). Ultimately, there should be only one ServingState,
848 // and forwarding and NAT rules should be handled by a coordinating
849 // functional element outside of IpServer.
850 class TetheredState extends BaseServingState {
851 @Override
852 public void enter() {
853 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800854 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800855 transitionTo(mInitialState);
856 }
857
858 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
859 sendInterfaceState(STATE_TETHERED);
860 }
861
862 @Override
863 public void exit() {
864 cleanupUpstream();
865 super.exit();
866 }
867
868 private void cleanupUpstream() {
869 if (mUpstreamIfaceSet == null) return;
870
871 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
872 mUpstreamIfaceSet = null;
873 }
874
875 private void cleanupUpstreamInterface(String upstreamIface) {
876 // Note that we don't care about errors here.
877 // Sometimes interfaces are gone before we get
878 // to remove their rules, which generates errors.
879 // Just do the best we can.
880 try {
markchien12c5bb82020-01-07 14:43:17 +0800881 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
882 } catch (RemoteException | ServiceSpecificException e) {
883 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800884 }
885 try {
markchien12c5bb82020-01-07 14:43:17 +0800886 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
887 } catch (RemoteException | ServiceSpecificException e) {
888 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800889 }
890 }
891
892 @Override
893 public boolean processMessage(Message message) {
894 if (super.processMessage(message)) return true;
895
896 logMessage(this, message.what);
897 switch (message.what) {
898 case CMD_TETHER_REQUESTED:
899 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
900 break;
901 case CMD_TETHER_CONNECTION_CHANGED:
902 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
903 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
904 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
905 break;
906 }
907
908 if (newUpstreamIfaceSet == null) {
909 cleanupUpstream();
910 break;
911 }
912
913 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
914 cleanupUpstreamInterface(removed);
915 }
916
917 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
918 // This makes the call to cleanupUpstream() in the error
919 // path for any interface neatly cleanup all the interfaces.
920 mUpstreamIfaceSet = newUpstreamIfaceSet;
921
922 for (String ifname : added) {
923 try {
markchien12c5bb82020-01-07 14:43:17 +0800924 mNetd.tetherAddForward(mIfaceName, ifname);
925 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
926 } catch (RemoteException | ServiceSpecificException e) {
927 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800928 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +0800929 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800930 transitionTo(mInitialState);
931 return true;
932 }
933 }
934 break;
935 default:
936 return false;
937 }
938 return true;
939 }
940
941 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
942 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
943 if (mUpstreamIfaceSet != null && newIfaces != null) {
944 return mUpstreamIfaceSet.equals(newIfaces);
945 }
946 return false;
947 }
948
949 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
950 if (mUpstreamIfaceSet == null) return new HashSet<>();
951
952 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
953 removed.removeAll(newIfaces.ifnames);
954 return removed;
955 }
956
957 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
958 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
959 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
960 return added;
961 }
962 }
963
964 /**
965 * This state is terminal for the per interface state machine. At this
966 * point, the master state machine should have removed this interface
967 * specific state machine from its list of possible recipients of
968 * tethering requests. The state machine itself will hang around until
969 * the garbage collector finds it.
970 */
971 class UnavailableState extends State {
972 @Override
973 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +0800974 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800975 sendInterfaceState(STATE_UNAVAILABLE);
976 }
977 }
978
979 // Accumulate routes representing "prefixes to be assigned to the local
980 // interface", for subsequent modification of local_network routing.
981 private static ArrayList<RouteInfo> getLocalRoutesFor(
982 String ifname, HashSet<IpPrefix> prefixes) {
983 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
984 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +0800985 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +0800986 }
987 return localRoutes;
988 }
989
990 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
991 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
992 final byte[] dnsBytes = localPrefix.getRawAddress();
993 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
994 try {
995 return Inet6Address.getByAddress(null, dnsBytes, 0);
996 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +0800997 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +0800998 return null;
999 }
1000 }
1001
1002 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1003 final byte random = (byte) (new Random()).nextInt();
1004 for (int value : excluded) {
1005 if (random == value) return dflt;
1006 }
1007 return random;
1008 }
1009}