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