blob: 6ac467e39a9dabfaeee72270cbb0646b27571aaa [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;
29import android.net.INetworkStatsService;
markchien74a4fa92019-09-09 20:50:49 +080030import android.net.IpPrefix;
31import android.net.LinkAddress;
32import android.net.LinkProperties;
markchien74a4fa92019-09-09 20:50:49 +080033import android.net.RouteInfo;
markchien9b4d7572019-12-25 19:40:32 +080034import android.net.TetheringManager;
markchien74a4fa92019-09-09 20:50:49 +080035import android.net.dhcp.DhcpServerCallbacks;
36import android.net.dhcp.DhcpServingParamsParcel;
37import android.net.dhcp.DhcpServingParamsParcelExt;
38import android.net.dhcp.IDhcpServer;
39import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080040import android.net.shared.NetdUtils;
41import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.util.InterfaceParams;
43import android.net.util.InterfaceSet;
markchien74a4fa92019-09-09 20:50:49 +080044import android.net.util.SharedLog;
markchien74a4fa92019-09-09 20:50:49 +080045import android.os.Looper;
46import android.os.Message;
47import android.os.RemoteException;
48import android.os.ServiceSpecificException;
49import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080050import android.util.SparseArray;
51
52import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080053import com.android.internal.util.State;
54import com.android.internal.util.StateMachine;
55
56import java.net.Inet4Address;
57import java.net.Inet6Address;
58import java.net.InetAddress;
59import java.net.UnknownHostException;
60import java.util.ArrayList;
61import java.util.HashSet;
62import java.util.Objects;
63import java.util.Random;
64import java.util.Set;
65
66/**
67 * Provides the interface to IP-layer serving functionality for a given network
68 * interface, e.g. for tethering or "local-only hotspot" mode.
69 *
70 * @hide
71 */
72public class IpServer extends StateMachine {
73 public static final int STATE_UNAVAILABLE = 0;
74 public static final int STATE_AVAILABLE = 1;
75 public static final int STATE_TETHERED = 2;
76 public static final int STATE_LOCAL_ONLY = 3;
77
78 /** Get string name of |state|.*/
79 public static String getStateString(int state) {
80 switch (state) {
81 case STATE_UNAVAILABLE: return "UNAVAILABLE";
82 case STATE_AVAILABLE: return "AVAILABLE";
83 case STATE_TETHERED: return "TETHERED";
84 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
85 }
86 return "UNKNOWN: " + state;
87 }
88
89 private static final byte DOUG_ADAMS = (byte) 42;
90
91 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
92 private static final int USB_PREFIX_LENGTH = 24;
93 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
94 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
95 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
96 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
97
98 // TODO: have PanService use some visible version of this constant
99 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
100 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
101
102 // TODO: have this configurable
103 private static final int DHCP_LEASE_TIME_SECS = 3600;
104
105 private static final String TAG = "IpServer";
106 private static final boolean DBG = false;
107 private static final boolean VDBG = false;
108 private static final Class[] sMessageClasses = {
109 IpServer.class
110 };
111 private static final SparseArray<String> sMagicDecoderRing =
112 MessageUtils.findMessageNames(sMessageClasses);
113
114 /** IpServer callback. */
115 public static class Callback {
116 /**
117 * Notify that |who| has changed its tethering state.
118 *
119 * @param who the calling instance of IpServer
120 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800121 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800122 */
markchien9d353822019-12-16 20:15:20 +0800123 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800124
125 /**
126 * Notify that |who| has new LinkProperties.
127 *
128 * @param who the calling instance of IpServer
129 * @param newLp the new LinkProperties to report
130 */
markchien9d353822019-12-16 20:15:20 +0800131 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
markchien74a4fa92019-09-09 20:50:49 +0800132 }
133
134 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800135 public abstract static class Dependencies {
markchien74a4fa92019-09-09 20:50:49 +0800136 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
137 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
138 return new RouterAdvertisementDaemon(ifParams);
139 }
140
141 /** Get |ifName|'s interface information.*/
142 public InterfaceParams getInterfaceParams(String ifName) {
143 return InterfaceParams.getByName(ifName);
144 }
145
markchien9d353822019-12-16 20:15:20 +0800146 /** Create a DhcpServer instance to be used by IpServer. */
147 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
148 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800149 }
150
markchien74a4fa92019-09-09 20:50:49 +0800151 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800152 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800153 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800154 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800155 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800156 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800157 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800158 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800159 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800160 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800161 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800162 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800163 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800164 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800165 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800166 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800167 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800168 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800169 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800170 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
markchien74a4fa92019-09-09 20:50:49 +0800171
172 private final State mInitialState;
173 private final State mLocalHotspotState;
174 private final State mTetheredState;
175 private final State mUnavailableState;
176
177 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800178 private final INetd mNetd;
179 private final INetworkStatsService mStatsService;
180 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,
markchien12c5bb82020-01-07 14:43:17 +0800211 INetd netd, INetworkStatsService statsService, Callback callback,
212 boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800213 super(ifaceName, looper);
214 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800215 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800216 mStatsService = statsService;
217 mCallback = callback;
218 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
219 mIfaceName = ifaceName;
220 mInterfaceType = interfaceType;
221 mLinkProperties = new LinkProperties();
222 mUsingLegacyDhcp = usingLegacyDhcp;
223 mDeps = deps;
224 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800225 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800226 mServingMode = STATE_AVAILABLE;
227
228 mInitialState = new InitialState();
229 mLocalHotspotState = new LocalHotspotState();
230 mTetheredState = new TetheredState();
231 mUnavailableState = new UnavailableState();
232 addState(mInitialState);
233 addState(mLocalHotspotState);
234 addState(mTetheredState);
235 addState(mUnavailableState);
236
237 setInitialState(mInitialState);
238 }
239
240 /** Interface name which IpServer served.*/
241 public String interfaceName() {
242 return mIfaceName;
243 }
244
245 /**
markchien9b4d7572019-12-25 19:40:32 +0800246 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800247 */
248 public int interfaceType() {
249 return mInterfaceType;
250 }
251
252 /** Last error from this IpServer. */
253 public int lastError() {
254 return mLastError;
255 }
256
257 /** Serving mode is the current state of IpServer state machine. */
258 public int servingMode() {
259 return mServingMode;
260 }
261
262 /** The properties of the network link which IpServer is serving. */
263 public LinkProperties linkProperties() {
264 return new LinkProperties(mLinkProperties);
265 }
266
267 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
268 public void stop() {
269 sendMessage(CMD_INTERFACE_DOWN);
270 }
271
272 /**
273 * Tethering is canceled. IpServer state machine will be available and wait for
274 * next tethering request.
275 */
276 public void unwanted() {
277 sendMessage(CMD_TETHER_UNREQUESTED);
278 }
279
280 /** Internals. */
281
282 private boolean startIPv4() {
283 return configureIPv4(true);
284 }
285
286 /**
287 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
288 * handler.
289 *
290 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
291 * with different implementations of the callback, to differentiate handling of success/error in
292 * each call.
293 */
294 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
295 @Override
296 public void onStatusAvailable(int statusCode) {
297 getHandler().post(() -> callback(statusCode));
298 }
299
300 public abstract void callback(int statusCode);
301
302 @Override
303 public int getInterfaceVersion() {
304 return this.VERSION;
305 }
306 }
307
308 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
309 private final int mStartIndex;
310
311 private DhcpServerCallbacksImpl(int startIndex) {
312 mStartIndex = startIndex;
313 }
314
315 @Override
316 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
317 getHandler().post(() -> {
318 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
319 if (mStartIndex != mDhcpServerStartIndex) {
320 // This start request is obsolete. When the |server| binder token goes out of
321 // scope, the garbage collector will finalize it, which causes the network stack
322 // process garbage collector to collect the server itself.
323 return;
324 }
325
326 if (statusCode != STATUS_SUCCESS) {
327 mLog.e("Error obtaining DHCP server: " + statusCode);
328 handleError();
329 return;
330 }
331
332 mDhcpServer = server;
333 try {
334 mDhcpServer.start(new OnHandlerStatusCallback() {
335 @Override
336 public void callback(int startStatusCode) {
337 if (startStatusCode != STATUS_SUCCESS) {
338 mLog.e("Error starting DHCP server: " + startStatusCode);
339 handleError();
340 }
341 }
342 });
343 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800344 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800345 }
346 });
347 }
348
349 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800350 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800351 transitionTo(mInitialState);
352 }
353 }
354
355 private boolean startDhcp(Inet4Address addr, int prefixLen) {
356 if (mUsingLegacyDhcp) {
357 return true;
358 }
359 final DhcpServingParamsParcel params;
360 params = new DhcpServingParamsParcelExt()
361 .setDefaultRouters(addr)
362 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
363 .setDnsServers(addr)
364 .setServerAddr(new LinkAddress(addr, prefixLen))
365 .setMetered(true);
366 // TODO: also advertise link MTU
367
368 mDhcpServerStartIndex++;
369 mDeps.makeDhcpServer(
370 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
371 return true;
372 }
373
374 private void stopDhcp() {
375 // Make all previous start requests obsolete so servers are not started later
376 mDhcpServerStartIndex++;
377
378 if (mDhcpServer != null) {
379 try {
380 mDhcpServer.stop(new OnHandlerStatusCallback() {
381 @Override
382 public void callback(int statusCode) {
383 if (statusCode != STATUS_SUCCESS) {
384 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800385 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800386 // Not much more we can do here
387 }
388 }
389 });
390 mDhcpServer = null;
391 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800392 mLog.e("Error stopping DHCP", e);
393 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800394 }
395 }
396 }
397
398 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
399 if (enable) {
400 return startDhcp(addr, prefixLen);
401 } else {
402 stopDhcp();
403 return true;
404 }
405 }
406
407 private void stopIPv4() {
408 configureIPv4(false);
409 // NOTE: All of configureIPv4() will be refactored out of existence
410 // into calls to InterfaceController, shared with startIPv4().
411 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800412 mIpv4Address = null;
markchien74a4fa92019-09-09 20:50:49 +0800413 }
414
markchien74a4fa92019-09-09 20:50:49 +0800415 private boolean configureIPv4(boolean enabled) {
416 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
417
418 // TODO: Replace this hard-coded information with dynamically selected
419 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800420 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800421 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800422 try {
markchien9b4d7572019-12-25 19:40:32 +0800423 if (mInterfaceType == TetheringManager.TETHERING_USB) {
markchien12c5bb82020-01-07 14:43:17 +0800424 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
425 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800426 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800427 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
428 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800429 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800430 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
431 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
432 } else {
433 // BT configures the interface elsewhere: only start DHCP.
434 // TODO: make all tethering types behave the same way, and delete the bluetooth
435 // code that calls into NetworkManagementService directly.
436 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
437 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
438 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
439 }
440 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
441 } catch (IllegalArgumentException e) {
442 mLog.e("Error selecting ipv4 address", e);
443 if (!enabled) stopDhcp();
444 return false;
markchien74a4fa92019-09-09 20:50:49 +0800445 }
446
markchien12c5bb82020-01-07 14:43:17 +0800447 final Boolean setIfaceUp;
markchien9b4d7572019-12-25 19:40:32 +0800448 if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800449 // The WiFi stack has ownership of the interface up/down state.
450 // It is unclear whether the Bluetooth or USB stacks will manage their own
451 // state.
452 setIfaceUp = null;
453 } else {
454 setIfaceUp = enabled;
455 }
456 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
457 mLog.e("Error configuring interface");
458 if (!enabled) stopDhcp();
459 return false;
460 }
markchien74a4fa92019-09-09 20:50:49 +0800461
markchien12c5bb82020-01-07 14:43:17 +0800462 if (!configureDhcp(enabled, srvAddr, prefixLen)) {
markchien74a4fa92019-09-09 20:50:49 +0800463 return false;
464 }
465
466 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800467 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
468 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800469 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800470 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800471 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800472 mLinkProperties.addRoute(route);
473 } else {
markchien12c5bb82020-01-07 14:43:17 +0800474 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800475 mLinkProperties.removeRoute(route);
476 }
477 return true;
478 }
479
480 private String getRandomWifiIPv4Address() {
481 try {
482 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
483 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
484 return InetAddress.getByAddress(bytes).getHostAddress();
485 } catch (Exception e) {
486 return WIFI_HOST_IFACE_ADDR;
487 }
488 }
489
490 private boolean startIPv6() {
491 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
492 if (mInterfaceParams == null) {
493 mLog.e("Failed to find InterfaceParams");
494 stopIPv6();
495 return false;
496 }
497
498 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
499 if (!mRaDaemon.start()) {
500 stopIPv6();
501 return false;
502 }
503
504 return true;
505 }
506
507 private void stopIPv6() {
508 mInterfaceParams = null;
509 setRaParams(null);
510
511 if (mRaDaemon != null) {
512 mRaDaemon.stop();
513 mRaDaemon = null;
514 }
515 }
516
517 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
518 // LinkProperties. These have extraneous data filtered out and only the
519 // necessary prefixes included (per its prefix distribution policy).
520 //
521 // TODO: Evaluate using a data structure than is more directly suited to
522 // communicating only the relevant information.
523 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
524 if (mRaDaemon == null) return;
525
526 // Avoid unnecessary work on spurious updates.
527 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
528 return;
529 }
530
531 RaParams params = null;
532
533 if (v6only != null) {
534 params = new RaParams();
535 params.mtu = v6only.getMtu();
536 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
537
538 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(v6only.getInterfaceName());
539
540 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
541 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
542
543 final IpPrefix prefix = new IpPrefix(
544 linkAddr.getAddress(), linkAddr.getPrefixLength());
545 params.prefixes.add(prefix);
546
547 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
548 if (dnsServer != null) {
549 params.dnses.add(dnsServer);
550 }
551 }
552 }
553 // If v6only is null, we pass in null to setRaParams(), which handles
554 // deprecation of any existing RA data.
555
556 setRaParams(params);
557 mLastIPv6LinkProperties = v6only;
558 }
559
560 private void configureLocalIPv6Routes(
561 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
562 // [1] Remove the routes that are deprecated.
563 if (!deprecatedPrefixes.isEmpty()) {
564 final ArrayList<RouteInfo> toBeRemoved =
565 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800566 // Remove routes from local network.
567 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
568 mNetd, toBeRemoved);
569 if (removalFailures > 0) {
570 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
571 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800572 }
573
574 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
575 }
576
577 // [2] Add only the routes that have not previously been added.
578 if (newPrefixes != null && !newPrefixes.isEmpty()) {
579 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
580 if (mLastRaParams != null) {
581 addedPrefixes.removeAll(mLastRaParams.prefixes);
582 }
583
584 if (!addedPrefixes.isEmpty()) {
585 final ArrayList<RouteInfo> toBeAdded =
586 getLocalRoutesFor(mIfaceName, addedPrefixes);
587 try {
markchien12c5bb82020-01-07 14:43:17 +0800588 // It's safe to call networkAddInterface() even if
589 // the interface is already in the local_network.
590 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
591 try {
592 // Add routes from local network. Note that adding routes that
593 // already exist does not cause an error (EEXIST is silently ignored).
594 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
595 } catch (IllegalStateException e) {
596 mLog.e("Failed to add IPv6 routes to local table: " + e);
597 }
598 } catch (ServiceSpecificException | RemoteException e) {
599 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800600 }
601
602 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
603 }
604 }
605 }
606
607 private void configureLocalIPv6Dns(
608 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
609 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
610 if (mNetd == null) {
611 if (newDnses != null) newDnses.clear();
612 mLog.e("No netd service instance available; not setting local IPv6 addresses");
613 return;
614 }
615
616 // [1] Remove deprecated local DNS IP addresses.
617 if (!deprecatedDnses.isEmpty()) {
618 for (Inet6Address dns : deprecatedDnses) {
619 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
620 mLog.e("Failed to remove local dns IP " + dns);
621 }
622
623 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
624 }
625 }
626
627 // [2] Add only the local DNS IP addresses that have not previously been added.
628 if (newDnses != null && !newDnses.isEmpty()) {
629 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
630 if (mLastRaParams != null) {
631 addedDnses.removeAll(mLastRaParams.dnses);
632 }
633
634 for (Inet6Address dns : addedDnses) {
635 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
636 mLog.e("Failed to add local dns IP " + dns);
637 newDnses.remove(dns);
638 }
639
640 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
641 }
642 }
643
644 try {
645 mNetd.tetherApplyDnsInterfaces();
646 } catch (ServiceSpecificException | RemoteException e) {
647 mLog.e("Failed to update local DNS caching server");
648 if (newDnses != null) newDnses.clear();
649 }
650 }
651
652 private byte getHopLimit(String upstreamIface) {
653 try {
654 int upstreamHopLimit = Integer.parseUnsignedInt(
655 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
656 // Add one hop to account for this forwarding device
657 upstreamHopLimit++;
658 // Cap the hop limit to 255.
659 return (byte) Integer.min(upstreamHopLimit, 255);
660 } catch (Exception e) {
661 mLog.e("Failed to find upstream interface hop limit", e);
662 }
663 return RaParams.DEFAULT_HOPLIMIT;
664 }
665
666 private void setRaParams(RaParams newParams) {
667 if (mRaDaemon != null) {
668 final RaParams deprecatedParams =
669 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
670
671 configureLocalIPv6Routes(deprecatedParams.prefixes,
672 (newParams != null) ? newParams.prefixes : null);
673
674 configureLocalIPv6Dns(deprecatedParams.dnses,
675 (newParams != null) ? newParams.dnses : null);
676
677 mRaDaemon.buildNewRa(deprecatedParams, newParams);
678 }
679
680 mLastRaParams = newParams;
681 }
682
683 private void logMessage(State state, int what) {
684 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
685 }
686
687 private void sendInterfaceState(int newInterfaceState) {
688 mServingMode = newInterfaceState;
689 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
690 sendLinkProperties();
691 }
692
693 private void sendLinkProperties() {
694 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
695 }
696
697 private void resetLinkProperties() {
698 mLinkProperties.clear();
699 mLinkProperties.setInterfaceName(mIfaceName);
700 }
701
702 class InitialState extends State {
703 @Override
704 public void enter() {
705 sendInterfaceState(STATE_AVAILABLE);
706 }
707
708 @Override
709 public boolean processMessage(Message message) {
710 logMessage(this, message.what);
711 switch (message.what) {
712 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800713 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800714 switch (message.arg1) {
715 case STATE_LOCAL_ONLY:
716 transitionTo(mLocalHotspotState);
717 break;
718 case STATE_TETHERED:
719 transitionTo(mTetheredState);
720 break;
721 default:
722 mLog.e("Invalid tethering interface serving state specified.");
723 }
724 break;
725 case CMD_INTERFACE_DOWN:
726 transitionTo(mUnavailableState);
727 break;
728 case CMD_IPV6_TETHER_UPDATE:
729 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
730 break;
731 default:
732 return NOT_HANDLED;
733 }
734 return HANDLED;
735 }
736 }
737
738 class BaseServingState extends State {
739 @Override
740 public void enter() {
741 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800742 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800743 return;
744 }
745
746 try {
markchien12c5bb82020-01-07 14:43:17 +0800747 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
748 mIpv4Address.getPrefixLength());
749 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
750 } catch (RemoteException | ServiceSpecificException e) {
markchien74a4fa92019-09-09 20:50:49 +0800751 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800752 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800753 return;
754 }
755
756 if (!startIPv6()) {
757 mLog.e("Failed to startIPv6");
758 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
759 return;
760 }
761 }
762
763 @Override
764 public void exit() {
765 // Note that at this point, we're leaving the tethered state. We can fail any
766 // of these operations, but it doesn't really change that we have to try them
767 // all in sequence.
768 stopIPv6();
769
770 try {
markchien12c5bb82020-01-07 14:43:17 +0800771 NetdUtils.untetherInterface(mNetd, mIfaceName);
772 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +0800773 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800774 mLog.e("Failed to untether interface: " + e);
775 }
776
777 stopIPv4();
778
779 resetLinkProperties();
780 }
781
782 @Override
783 public boolean processMessage(Message message) {
784 logMessage(this, message.what);
785 switch (message.what) {
786 case CMD_TETHER_UNREQUESTED:
787 transitionTo(mInitialState);
788 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
789 break;
790 case CMD_INTERFACE_DOWN:
791 transitionTo(mUnavailableState);
792 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
793 break;
794 case CMD_IPV6_TETHER_UPDATE:
795 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
796 sendLinkProperties();
797 break;
798 case CMD_IP_FORWARDING_ENABLE_ERROR:
799 case CMD_IP_FORWARDING_DISABLE_ERROR:
800 case CMD_START_TETHERING_ERROR:
801 case CMD_STOP_TETHERING_ERROR:
802 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +0800803 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800804 transitionTo(mInitialState);
805 break;
806 default:
807 return false;
808 }
809 return true;
810 }
811 }
812
813 // Handling errors in BaseServingState.enter() by transitioning is
814 // problematic because transitioning during a multi-state jump yields
815 // a Log.wtf(). Ultimately, there should be only one ServingState,
816 // and forwarding and NAT rules should be handled by a coordinating
817 // functional element outside of IpServer.
818 class LocalHotspotState extends BaseServingState {
819 @Override
820 public void enter() {
821 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800822 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800823 transitionTo(mInitialState);
824 }
825
826 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
827 sendInterfaceState(STATE_LOCAL_ONLY);
828 }
829
830 @Override
831 public boolean processMessage(Message message) {
832 if (super.processMessage(message)) return true;
833
834 logMessage(this, message.what);
835 switch (message.what) {
836 case CMD_TETHER_REQUESTED:
837 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
838 break;
839 case CMD_TETHER_CONNECTION_CHANGED:
840 // Ignored in local hotspot state.
841 break;
842 default:
843 return false;
844 }
845 return true;
846 }
847 }
848
849 // Handling errors in BaseServingState.enter() by transitioning is
850 // problematic because transitioning during a multi-state jump yields
851 // a Log.wtf(). Ultimately, there should be only one ServingState,
852 // and forwarding and NAT rules should be handled by a coordinating
853 // functional element outside of IpServer.
854 class TetheredState extends BaseServingState {
855 @Override
856 public void enter() {
857 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800858 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800859 transitionTo(mInitialState);
860 }
861
862 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
863 sendInterfaceState(STATE_TETHERED);
864 }
865
866 @Override
867 public void exit() {
868 cleanupUpstream();
869 super.exit();
870 }
871
872 private void cleanupUpstream() {
873 if (mUpstreamIfaceSet == null) return;
874
875 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
876 mUpstreamIfaceSet = null;
877 }
878
879 private void cleanupUpstreamInterface(String upstreamIface) {
880 // Note that we don't care about errors here.
881 // Sometimes interfaces are gone before we get
882 // to remove their rules, which generates errors.
883 // Just do the best we can.
884 try {
885 // About to tear down NAT; gather remaining statistics.
886 mStatsService.forceUpdate();
887 } catch (Exception e) {
markchien12c5bb82020-01-07 14:43:17 +0800888 mLog.e("Exception in forceUpdate: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800889 }
890 try {
markchien12c5bb82020-01-07 14:43:17 +0800891 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
892 } catch (RemoteException | ServiceSpecificException e) {
893 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800894 }
895 try {
markchien12c5bb82020-01-07 14:43:17 +0800896 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
897 } catch (RemoteException | ServiceSpecificException e) {
898 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800899 }
900 }
901
902 @Override
903 public boolean processMessage(Message message) {
904 if (super.processMessage(message)) return true;
905
906 logMessage(this, message.what);
907 switch (message.what) {
908 case CMD_TETHER_REQUESTED:
909 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
910 break;
911 case CMD_TETHER_CONNECTION_CHANGED:
912 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
913 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
914 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
915 break;
916 }
917
918 if (newUpstreamIfaceSet == null) {
919 cleanupUpstream();
920 break;
921 }
922
923 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
924 cleanupUpstreamInterface(removed);
925 }
926
927 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
928 // This makes the call to cleanupUpstream() in the error
929 // path for any interface neatly cleanup all the interfaces.
930 mUpstreamIfaceSet = newUpstreamIfaceSet;
931
932 for (String ifname : added) {
933 try {
markchien12c5bb82020-01-07 14:43:17 +0800934 mNetd.tetherAddForward(mIfaceName, ifname);
935 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
936 } catch (RemoteException | ServiceSpecificException e) {
937 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800938 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +0800939 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800940 transitionTo(mInitialState);
941 return true;
942 }
943 }
944 break;
945 default:
946 return false;
947 }
948 return true;
949 }
950
951 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
952 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
953 if (mUpstreamIfaceSet != null && newIfaces != null) {
954 return mUpstreamIfaceSet.equals(newIfaces);
955 }
956 return false;
957 }
958
959 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
960 if (mUpstreamIfaceSet == null) return new HashSet<>();
961
962 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
963 removed.removeAll(newIfaces.ifnames);
964 return removed;
965 }
966
967 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
968 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
969 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
970 return added;
971 }
972 }
973
974 /**
975 * This state is terminal for the per interface state machine. At this
976 * point, the master state machine should have removed this interface
977 * specific state machine from its list of possible recipients of
978 * tethering requests. The state machine itself will hang around until
979 * the garbage collector finds it.
980 */
981 class UnavailableState extends State {
982 @Override
983 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +0800984 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800985 sendInterfaceState(STATE_UNAVAILABLE);
986 }
987 }
988
989 // Accumulate routes representing "prefixes to be assigned to the local
990 // interface", for subsequent modification of local_network routing.
991 private static ArrayList<RouteInfo> getLocalRoutesFor(
992 String ifname, HashSet<IpPrefix> prefixes) {
993 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
994 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +0800995 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +0800996 }
997 return localRoutes;
998 }
999
1000 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1001 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1002 final byte[] dnsBytes = localPrefix.getRawAddress();
1003 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1004 try {
1005 return Inet6Address.getByAddress(null, dnsBytes, 0);
1006 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001007 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001008 return null;
1009 }
1010 }
1011
1012 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1013 final byte random = (byte) (new Random()).nextInt();
1014 for (int value : excluded) {
1015 if (random == value) return dflt;
1016 }
1017 return random;
1018 }
1019}