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