blob: 0491ad7c3413e2697756428fae7be7f4a5723580 [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;
Jimmy Chenea902f62019-12-03 11:37:09 +0800444 if (mInterfaceType == TetheringManager.TETHERING_WIFI
445 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800446 // The WiFi stack has ownership of the interface up/down state.
447 // It is unclear whether the Bluetooth or USB stacks will manage their own
448 // state.
449 setIfaceUp = null;
450 } else {
451 setIfaceUp = enabled;
452 }
453 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
454 mLog.e("Error configuring interface");
455 if (!enabled) stopDhcp();
456 return false;
457 }
markchien74a4fa92019-09-09 20:50:49 +0800458
markchien12c5bb82020-01-07 14:43:17 +0800459 if (!configureDhcp(enabled, srvAddr, prefixLen)) {
markchien74a4fa92019-09-09 20:50:49 +0800460 return false;
461 }
462
463 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800464 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
465 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800466 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800467 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800468 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800469 mLinkProperties.addRoute(route);
470 } else {
markchien12c5bb82020-01-07 14:43:17 +0800471 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800472 mLinkProperties.removeRoute(route);
473 }
474 return true;
475 }
476
477 private String getRandomWifiIPv4Address() {
478 try {
479 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
480 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
481 return InetAddress.getByAddress(bytes).getHostAddress();
482 } catch (Exception e) {
483 return WIFI_HOST_IFACE_ADDR;
484 }
485 }
486
487 private boolean startIPv6() {
488 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
489 if (mInterfaceParams == null) {
490 mLog.e("Failed to find InterfaceParams");
491 stopIPv6();
492 return false;
493 }
494
495 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
496 if (!mRaDaemon.start()) {
497 stopIPv6();
498 return false;
499 }
500
501 return true;
502 }
503
504 private void stopIPv6() {
505 mInterfaceParams = null;
506 setRaParams(null);
507
508 if (mRaDaemon != null) {
509 mRaDaemon.stop();
510 mRaDaemon = null;
511 }
512 }
513
514 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
515 // LinkProperties. These have extraneous data filtered out and only the
516 // necessary prefixes included (per its prefix distribution policy).
517 //
518 // TODO: Evaluate using a data structure than is more directly suited to
519 // communicating only the relevant information.
520 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
521 if (mRaDaemon == null) return;
522
523 // Avoid unnecessary work on spurious updates.
524 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
525 return;
526 }
527
528 RaParams params = null;
529
530 if (v6only != null) {
531 params = new RaParams();
532 params.mtu = v6only.getMtu();
533 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
534
535 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(v6only.getInterfaceName());
536
537 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
538 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
539
540 final IpPrefix prefix = new IpPrefix(
541 linkAddr.getAddress(), linkAddr.getPrefixLength());
542 params.prefixes.add(prefix);
543
544 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
545 if (dnsServer != null) {
546 params.dnses.add(dnsServer);
547 }
548 }
549 }
550 // If v6only is null, we pass in null to setRaParams(), which handles
551 // deprecation of any existing RA data.
552
553 setRaParams(params);
554 mLastIPv6LinkProperties = v6only;
555 }
556
557 private void configureLocalIPv6Routes(
558 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
559 // [1] Remove the routes that are deprecated.
560 if (!deprecatedPrefixes.isEmpty()) {
561 final ArrayList<RouteInfo> toBeRemoved =
562 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800563 // Remove routes from local network.
564 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
565 mNetd, toBeRemoved);
566 if (removalFailures > 0) {
567 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
568 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800569 }
570
571 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
572 }
573
574 // [2] Add only the routes that have not previously been added.
575 if (newPrefixes != null && !newPrefixes.isEmpty()) {
576 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
577 if (mLastRaParams != null) {
578 addedPrefixes.removeAll(mLastRaParams.prefixes);
579 }
580
581 if (!addedPrefixes.isEmpty()) {
582 final ArrayList<RouteInfo> toBeAdded =
583 getLocalRoutesFor(mIfaceName, addedPrefixes);
584 try {
markchien12c5bb82020-01-07 14:43:17 +0800585 // It's safe to call networkAddInterface() even if
586 // the interface is already in the local_network.
587 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
588 try {
589 // Add routes from local network. Note that adding routes that
590 // already exist does not cause an error (EEXIST is silently ignored).
591 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
592 } catch (IllegalStateException e) {
593 mLog.e("Failed to add IPv6 routes to local table: " + e);
594 }
595 } catch (ServiceSpecificException | RemoteException e) {
596 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800597 }
598
599 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
600 }
601 }
602 }
603
604 private void configureLocalIPv6Dns(
605 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
606 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
607 if (mNetd == null) {
608 if (newDnses != null) newDnses.clear();
609 mLog.e("No netd service instance available; not setting local IPv6 addresses");
610 return;
611 }
612
613 // [1] Remove deprecated local DNS IP addresses.
614 if (!deprecatedDnses.isEmpty()) {
615 for (Inet6Address dns : deprecatedDnses) {
616 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
617 mLog.e("Failed to remove local dns IP " + dns);
618 }
619
620 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
621 }
622 }
623
624 // [2] Add only the local DNS IP addresses that have not previously been added.
625 if (newDnses != null && !newDnses.isEmpty()) {
626 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
627 if (mLastRaParams != null) {
628 addedDnses.removeAll(mLastRaParams.dnses);
629 }
630
631 for (Inet6Address dns : addedDnses) {
632 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
633 mLog.e("Failed to add local dns IP " + dns);
634 newDnses.remove(dns);
635 }
636
637 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
638 }
639 }
640
641 try {
642 mNetd.tetherApplyDnsInterfaces();
643 } catch (ServiceSpecificException | RemoteException e) {
644 mLog.e("Failed to update local DNS caching server");
645 if (newDnses != null) newDnses.clear();
646 }
647 }
648
649 private byte getHopLimit(String upstreamIface) {
650 try {
651 int upstreamHopLimit = Integer.parseUnsignedInt(
652 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
653 // Add one hop to account for this forwarding device
654 upstreamHopLimit++;
655 // Cap the hop limit to 255.
656 return (byte) Integer.min(upstreamHopLimit, 255);
657 } catch (Exception e) {
658 mLog.e("Failed to find upstream interface hop limit", e);
659 }
660 return RaParams.DEFAULT_HOPLIMIT;
661 }
662
663 private void setRaParams(RaParams newParams) {
664 if (mRaDaemon != null) {
665 final RaParams deprecatedParams =
666 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
667
668 configureLocalIPv6Routes(deprecatedParams.prefixes,
669 (newParams != null) ? newParams.prefixes : null);
670
671 configureLocalIPv6Dns(deprecatedParams.dnses,
672 (newParams != null) ? newParams.dnses : null);
673
674 mRaDaemon.buildNewRa(deprecatedParams, newParams);
675 }
676
677 mLastRaParams = newParams;
678 }
679
680 private void logMessage(State state, int what) {
681 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
682 }
683
684 private void sendInterfaceState(int newInterfaceState) {
685 mServingMode = newInterfaceState;
686 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
687 sendLinkProperties();
688 }
689
690 private void sendLinkProperties() {
691 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
692 }
693
694 private void resetLinkProperties() {
695 mLinkProperties.clear();
696 mLinkProperties.setInterfaceName(mIfaceName);
697 }
698
699 class InitialState extends State {
700 @Override
701 public void enter() {
702 sendInterfaceState(STATE_AVAILABLE);
703 }
704
705 @Override
706 public boolean processMessage(Message message) {
707 logMessage(this, message.what);
708 switch (message.what) {
709 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800710 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800711 switch (message.arg1) {
712 case STATE_LOCAL_ONLY:
713 transitionTo(mLocalHotspotState);
714 break;
715 case STATE_TETHERED:
716 transitionTo(mTetheredState);
717 break;
718 default:
719 mLog.e("Invalid tethering interface serving state specified.");
720 }
721 break;
722 case CMD_INTERFACE_DOWN:
723 transitionTo(mUnavailableState);
724 break;
725 case CMD_IPV6_TETHER_UPDATE:
726 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
727 break;
728 default:
729 return NOT_HANDLED;
730 }
731 return HANDLED;
732 }
733 }
734
735 class BaseServingState extends State {
736 @Override
737 public void enter() {
738 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800739 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800740 return;
741 }
742
743 try {
markchien12c5bb82020-01-07 14:43:17 +0800744 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
745 mIpv4Address.getPrefixLength());
746 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
747 } catch (RemoteException | ServiceSpecificException e) {
markchien74a4fa92019-09-09 20:50:49 +0800748 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800749 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800750 return;
751 }
752
753 if (!startIPv6()) {
754 mLog.e("Failed to startIPv6");
755 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
756 return;
757 }
758 }
759
760 @Override
761 public void exit() {
762 // Note that at this point, we're leaving the tethered state. We can fail any
763 // of these operations, but it doesn't really change that we have to try them
764 // all in sequence.
765 stopIPv6();
766
767 try {
markchien12c5bb82020-01-07 14:43:17 +0800768 NetdUtils.untetherInterface(mNetd, mIfaceName);
769 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +0800770 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800771 mLog.e("Failed to untether interface: " + e);
772 }
773
774 stopIPv4();
775
776 resetLinkProperties();
777 }
778
779 @Override
780 public boolean processMessage(Message message) {
781 logMessage(this, message.what);
782 switch (message.what) {
783 case CMD_TETHER_UNREQUESTED:
784 transitionTo(mInitialState);
785 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
786 break;
787 case CMD_INTERFACE_DOWN:
788 transitionTo(mUnavailableState);
789 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
790 break;
791 case CMD_IPV6_TETHER_UPDATE:
792 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
793 sendLinkProperties();
794 break;
795 case CMD_IP_FORWARDING_ENABLE_ERROR:
796 case CMD_IP_FORWARDING_DISABLE_ERROR:
797 case CMD_START_TETHERING_ERROR:
798 case CMD_STOP_TETHERING_ERROR:
799 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +0800800 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800801 transitionTo(mInitialState);
802 break;
803 default:
804 return false;
805 }
806 return true;
807 }
808 }
809
810 // Handling errors in BaseServingState.enter() by transitioning is
811 // problematic because transitioning during a multi-state jump yields
812 // a Log.wtf(). Ultimately, there should be only one ServingState,
813 // and forwarding and NAT rules should be handled by a coordinating
814 // functional element outside of IpServer.
815 class LocalHotspotState extends BaseServingState {
816 @Override
817 public void enter() {
818 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800819 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800820 transitionTo(mInitialState);
821 }
822
823 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
824 sendInterfaceState(STATE_LOCAL_ONLY);
825 }
826
827 @Override
828 public boolean processMessage(Message message) {
829 if (super.processMessage(message)) return true;
830
831 logMessage(this, message.what);
832 switch (message.what) {
833 case CMD_TETHER_REQUESTED:
834 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
835 break;
836 case CMD_TETHER_CONNECTION_CHANGED:
837 // Ignored in local hotspot state.
838 break;
839 default:
840 return false;
841 }
842 return true;
843 }
844 }
845
846 // Handling errors in BaseServingState.enter() by transitioning is
847 // problematic because transitioning during a multi-state jump yields
848 // a Log.wtf(). Ultimately, there should be only one ServingState,
849 // and forwarding and NAT rules should be handled by a coordinating
850 // functional element outside of IpServer.
851 class TetheredState extends BaseServingState {
852 @Override
853 public void enter() {
854 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800855 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800856 transitionTo(mInitialState);
857 }
858
859 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
860 sendInterfaceState(STATE_TETHERED);
861 }
862
863 @Override
864 public void exit() {
865 cleanupUpstream();
866 super.exit();
867 }
868
869 private void cleanupUpstream() {
870 if (mUpstreamIfaceSet == null) return;
871
872 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
873 mUpstreamIfaceSet = null;
874 }
875
876 private void cleanupUpstreamInterface(String upstreamIface) {
877 // Note that we don't care about errors here.
878 // Sometimes interfaces are gone before we get
879 // to remove their rules, which generates errors.
880 // Just do the best we can.
881 try {
markchien12c5bb82020-01-07 14:43:17 +0800882 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
883 } catch (RemoteException | ServiceSpecificException e) {
884 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800885 }
886 try {
markchien12c5bb82020-01-07 14:43:17 +0800887 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
888 } catch (RemoteException | ServiceSpecificException e) {
889 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800890 }
891 }
892
893 @Override
894 public boolean processMessage(Message message) {
895 if (super.processMessage(message)) return true;
896
897 logMessage(this, message.what);
898 switch (message.what) {
899 case CMD_TETHER_REQUESTED:
900 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
901 break;
902 case CMD_TETHER_CONNECTION_CHANGED:
903 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
904 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
905 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
906 break;
907 }
908
909 if (newUpstreamIfaceSet == null) {
910 cleanupUpstream();
911 break;
912 }
913
914 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
915 cleanupUpstreamInterface(removed);
916 }
917
918 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
919 // This makes the call to cleanupUpstream() in the error
920 // path for any interface neatly cleanup all the interfaces.
921 mUpstreamIfaceSet = newUpstreamIfaceSet;
922
923 for (String ifname : added) {
924 try {
markchien12c5bb82020-01-07 14:43:17 +0800925 mNetd.tetherAddForward(mIfaceName, ifname);
926 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
927 } catch (RemoteException | ServiceSpecificException e) {
928 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800929 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +0800930 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800931 transitionTo(mInitialState);
932 return true;
933 }
934 }
935 break;
936 default:
937 return false;
938 }
939 return true;
940 }
941
942 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
943 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
944 if (mUpstreamIfaceSet != null && newIfaces != null) {
945 return mUpstreamIfaceSet.equals(newIfaces);
946 }
947 return false;
948 }
949
950 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
951 if (mUpstreamIfaceSet == null) return new HashSet<>();
952
953 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
954 removed.removeAll(newIfaces.ifnames);
955 return removed;
956 }
957
958 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
959 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
960 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
961 return added;
962 }
963 }
964
965 /**
966 * This state is terminal for the per interface state machine. At this
967 * point, the master state machine should have removed this interface
968 * specific state machine from its list of possible recipients of
969 * tethering requests. The state machine itself will hang around until
970 * the garbage collector finds it.
971 */
972 class UnavailableState extends State {
973 @Override
974 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +0800975 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800976 sendInterfaceState(STATE_UNAVAILABLE);
977 }
978 }
979
980 // Accumulate routes representing "prefixes to be assigned to the local
981 // interface", for subsequent modification of local_network routing.
982 private static ArrayList<RouteInfo> getLocalRoutesFor(
983 String ifname, HashSet<IpPrefix> prefixes) {
984 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
985 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +0800986 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +0800987 }
988 return localRoutes;
989 }
990
991 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
992 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
993 final byte[] dnsBytes = localPrefix.getRawAddress();
994 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
995 try {
996 return Inet6Address.getByAddress(null, dnsBytes, 0);
997 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +0800998 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +0800999 return null;
1000 }
1001 }
1002
1003 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1004 final byte random = (byte) (new Random()).nextInt();
1005 for (int value : excluded) {
1006 if (random == value) return dflt;
1007 }
1008 return random;
1009 }
1010}