blob: 190d2509864422e0fe478b841c5b9dc7819d92b6 [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 }
304 }
305
306 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
307 private final int mStartIndex;
308
309 private DhcpServerCallbacksImpl(int startIndex) {
310 mStartIndex = startIndex;
311 }
312
313 @Override
314 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
315 getHandler().post(() -> {
316 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
317 if (mStartIndex != mDhcpServerStartIndex) {
318 // This start request is obsolete. When the |server| binder token goes out of
319 // scope, the garbage collector will finalize it, which causes the network stack
320 // process garbage collector to collect the server itself.
321 return;
322 }
323
324 if (statusCode != STATUS_SUCCESS) {
325 mLog.e("Error obtaining DHCP server: " + statusCode);
326 handleError();
327 return;
328 }
329
330 mDhcpServer = server;
331 try {
332 mDhcpServer.start(new OnHandlerStatusCallback() {
333 @Override
334 public void callback(int startStatusCode) {
335 if (startStatusCode != STATUS_SUCCESS) {
336 mLog.e("Error starting DHCP server: " + startStatusCode);
337 handleError();
338 }
339 }
340 });
341 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800342 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800343 }
344 });
345 }
346
347 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800348 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800349 transitionTo(mInitialState);
350 }
351 }
352
353 private boolean startDhcp(Inet4Address addr, int prefixLen) {
354 if (mUsingLegacyDhcp) {
355 return true;
356 }
357 final DhcpServingParamsParcel params;
358 params = new DhcpServingParamsParcelExt()
359 .setDefaultRouters(addr)
360 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
361 .setDnsServers(addr)
362 .setServerAddr(new LinkAddress(addr, prefixLen))
363 .setMetered(true);
364 // TODO: also advertise link MTU
365
366 mDhcpServerStartIndex++;
367 mDeps.makeDhcpServer(
368 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
369 return true;
370 }
371
372 private void stopDhcp() {
373 // Make all previous start requests obsolete so servers are not started later
374 mDhcpServerStartIndex++;
375
376 if (mDhcpServer != null) {
377 try {
378 mDhcpServer.stop(new OnHandlerStatusCallback() {
379 @Override
380 public void callback(int statusCode) {
381 if (statusCode != STATUS_SUCCESS) {
382 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800383 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800384 // Not much more we can do here
385 }
386 }
387 });
388 mDhcpServer = null;
389 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800390 mLog.e("Error stopping DHCP", e);
391 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800392 }
393 }
394 }
395
396 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
397 if (enable) {
398 return startDhcp(addr, prefixLen);
399 } else {
400 stopDhcp();
401 return true;
402 }
403 }
404
405 private void stopIPv4() {
406 configureIPv4(false);
407 // NOTE: All of configureIPv4() will be refactored out of existence
408 // into calls to InterfaceController, shared with startIPv4().
409 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800410 mIpv4Address = null;
markchien74a4fa92019-09-09 20:50:49 +0800411 }
412
markchien74a4fa92019-09-09 20:50:49 +0800413 private boolean configureIPv4(boolean enabled) {
414 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
415
416 // TODO: Replace this hard-coded information with dynamically selected
417 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800418 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800419 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800420 try {
Milim Lee45a971b2019-10-17 05:02:33 +0900421 if (mInterfaceType == TetheringManager.TETHERING_USB
422 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800423 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
424 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800425 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800426 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
427 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800428 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800429 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
430 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900431 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
432 // TODO: randomize address for tethering too, similarly to wifi
433 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
434 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800435 } else {
436 // BT configures the interface elsewhere: only start DHCP.
437 // TODO: make all tethering types behave the same way, and delete the bluetooth
438 // code that calls into NetworkManagementService directly.
439 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
440 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
441 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
442 }
443 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
444 } catch (IllegalArgumentException e) {
445 mLog.e("Error selecting ipv4 address", e);
446 if (!enabled) stopDhcp();
447 return false;
markchien74a4fa92019-09-09 20:50:49 +0800448 }
449
markchien12c5bb82020-01-07 14:43:17 +0800450 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800451 if (mInterfaceType == TetheringManager.TETHERING_WIFI
452 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800453 // The WiFi stack has ownership of the interface up/down state.
454 // It is unclear whether the Bluetooth or USB stacks will manage their own
455 // state.
456 setIfaceUp = null;
457 } else {
458 setIfaceUp = enabled;
459 }
460 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
461 mLog.e("Error configuring interface");
462 if (!enabled) stopDhcp();
463 return false;
464 }
markchien74a4fa92019-09-09 20:50:49 +0800465
markchien12c5bb82020-01-07 14:43:17 +0800466 if (!configureDhcp(enabled, srvAddr, prefixLen)) {
markchien74a4fa92019-09-09 20:50:49 +0800467 return false;
468 }
469
470 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800471 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
472 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800473 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800474 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800475 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800476 mLinkProperties.addRoute(route);
477 } else {
markchien12c5bb82020-01-07 14:43:17 +0800478 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800479 mLinkProperties.removeRoute(route);
480 }
481 return true;
482 }
483
484 private String getRandomWifiIPv4Address() {
485 try {
486 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
487 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
488 return InetAddress.getByAddress(bytes).getHostAddress();
489 } catch (Exception e) {
490 return WIFI_HOST_IFACE_ADDR;
491 }
492 }
493
494 private boolean startIPv6() {
495 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
496 if (mInterfaceParams == null) {
497 mLog.e("Failed to find InterfaceParams");
498 stopIPv6();
499 return false;
500 }
501
502 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
503 if (!mRaDaemon.start()) {
504 stopIPv6();
505 return false;
506 }
507
508 return true;
509 }
510
511 private void stopIPv6() {
512 mInterfaceParams = null;
513 setRaParams(null);
514
515 if (mRaDaemon != null) {
516 mRaDaemon.stop();
517 mRaDaemon = null;
518 }
519 }
520
521 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
522 // LinkProperties. These have extraneous data filtered out and only the
523 // necessary prefixes included (per its prefix distribution policy).
524 //
525 // TODO: Evaluate using a data structure than is more directly suited to
526 // communicating only the relevant information.
527 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
528 if (mRaDaemon == null) return;
529
530 // Avoid unnecessary work on spurious updates.
531 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
532 return;
533 }
534
535 RaParams params = null;
536
537 if (v6only != null) {
538 params = new RaParams();
539 params.mtu = v6only.getMtu();
540 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
541
542 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(v6only.getInterfaceName());
543
544 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
545 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
546
547 final IpPrefix prefix = new IpPrefix(
548 linkAddr.getAddress(), linkAddr.getPrefixLength());
549 params.prefixes.add(prefix);
550
551 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
552 if (dnsServer != null) {
553 params.dnses.add(dnsServer);
554 }
555 }
556 }
557 // If v6only is null, we pass in null to setRaParams(), which handles
558 // deprecation of any existing RA data.
559
560 setRaParams(params);
561 mLastIPv6LinkProperties = v6only;
562 }
563
564 private void configureLocalIPv6Routes(
565 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
566 // [1] Remove the routes that are deprecated.
567 if (!deprecatedPrefixes.isEmpty()) {
568 final ArrayList<RouteInfo> toBeRemoved =
569 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800570 // Remove routes from local network.
571 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
572 mNetd, toBeRemoved);
573 if (removalFailures > 0) {
574 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
575 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800576 }
577
578 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
579 }
580
581 // [2] Add only the routes that have not previously been added.
582 if (newPrefixes != null && !newPrefixes.isEmpty()) {
583 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
584 if (mLastRaParams != null) {
585 addedPrefixes.removeAll(mLastRaParams.prefixes);
586 }
587
588 if (!addedPrefixes.isEmpty()) {
589 final ArrayList<RouteInfo> toBeAdded =
590 getLocalRoutesFor(mIfaceName, addedPrefixes);
591 try {
markchien12c5bb82020-01-07 14:43:17 +0800592 // It's safe to call networkAddInterface() even if
593 // the interface is already in the local_network.
594 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
595 try {
596 // Add routes from local network. Note that adding routes that
597 // already exist does not cause an error (EEXIST is silently ignored).
598 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
599 } catch (IllegalStateException e) {
600 mLog.e("Failed to add IPv6 routes to local table: " + e);
601 }
602 } catch (ServiceSpecificException | RemoteException e) {
603 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800604 }
605
606 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
607 }
608 }
609 }
610
611 private void configureLocalIPv6Dns(
612 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
613 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
614 if (mNetd == null) {
615 if (newDnses != null) newDnses.clear();
616 mLog.e("No netd service instance available; not setting local IPv6 addresses");
617 return;
618 }
619
620 // [1] Remove deprecated local DNS IP addresses.
621 if (!deprecatedDnses.isEmpty()) {
622 for (Inet6Address dns : deprecatedDnses) {
623 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
624 mLog.e("Failed to remove local dns IP " + dns);
625 }
626
627 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
628 }
629 }
630
631 // [2] Add only the local DNS IP addresses that have not previously been added.
632 if (newDnses != null && !newDnses.isEmpty()) {
633 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
634 if (mLastRaParams != null) {
635 addedDnses.removeAll(mLastRaParams.dnses);
636 }
637
638 for (Inet6Address dns : addedDnses) {
639 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
640 mLog.e("Failed to add local dns IP " + dns);
641 newDnses.remove(dns);
642 }
643
644 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
645 }
646 }
647
648 try {
649 mNetd.tetherApplyDnsInterfaces();
650 } catch (ServiceSpecificException | RemoteException e) {
651 mLog.e("Failed to update local DNS caching server");
652 if (newDnses != null) newDnses.clear();
653 }
654 }
655
656 private byte getHopLimit(String upstreamIface) {
657 try {
658 int upstreamHopLimit = Integer.parseUnsignedInt(
659 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
660 // Add one hop to account for this forwarding device
661 upstreamHopLimit++;
662 // Cap the hop limit to 255.
663 return (byte) Integer.min(upstreamHopLimit, 255);
664 } catch (Exception e) {
665 mLog.e("Failed to find upstream interface hop limit", e);
666 }
667 return RaParams.DEFAULT_HOPLIMIT;
668 }
669
670 private void setRaParams(RaParams newParams) {
671 if (mRaDaemon != null) {
672 final RaParams deprecatedParams =
673 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
674
675 configureLocalIPv6Routes(deprecatedParams.prefixes,
676 (newParams != null) ? newParams.prefixes : null);
677
678 configureLocalIPv6Dns(deprecatedParams.dnses,
679 (newParams != null) ? newParams.dnses : null);
680
681 mRaDaemon.buildNewRa(deprecatedParams, newParams);
682 }
683
684 mLastRaParams = newParams;
685 }
686
687 private void logMessage(State state, int what) {
688 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
689 }
690
691 private void sendInterfaceState(int newInterfaceState) {
692 mServingMode = newInterfaceState;
693 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
694 sendLinkProperties();
695 }
696
697 private void sendLinkProperties() {
698 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
699 }
700
701 private void resetLinkProperties() {
702 mLinkProperties.clear();
703 mLinkProperties.setInterfaceName(mIfaceName);
704 }
705
706 class InitialState extends State {
707 @Override
708 public void enter() {
709 sendInterfaceState(STATE_AVAILABLE);
710 }
711
712 @Override
713 public boolean processMessage(Message message) {
714 logMessage(this, message.what);
715 switch (message.what) {
716 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800717 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800718 switch (message.arg1) {
719 case STATE_LOCAL_ONLY:
720 transitionTo(mLocalHotspotState);
721 break;
722 case STATE_TETHERED:
723 transitionTo(mTetheredState);
724 break;
725 default:
726 mLog.e("Invalid tethering interface serving state specified.");
727 }
728 break;
729 case CMD_INTERFACE_DOWN:
730 transitionTo(mUnavailableState);
731 break;
732 case CMD_IPV6_TETHER_UPDATE:
733 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
734 break;
735 default:
736 return NOT_HANDLED;
737 }
738 return HANDLED;
739 }
740 }
741
742 class BaseServingState extends State {
743 @Override
744 public void enter() {
745 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800746 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800747 return;
748 }
749
750 try {
markchien12c5bb82020-01-07 14:43:17 +0800751 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
752 mIpv4Address.getPrefixLength());
753 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
754 } catch (RemoteException | ServiceSpecificException e) {
markchien74a4fa92019-09-09 20:50:49 +0800755 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800756 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800757 return;
758 }
759
760 if (!startIPv6()) {
761 mLog.e("Failed to startIPv6");
762 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
763 return;
764 }
765 }
766
767 @Override
768 public void exit() {
769 // Note that at this point, we're leaving the tethered state. We can fail any
770 // of these operations, but it doesn't really change that we have to try them
771 // all in sequence.
772 stopIPv6();
773
774 try {
markchien12c5bb82020-01-07 14:43:17 +0800775 NetdUtils.untetherInterface(mNetd, mIfaceName);
776 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +0800777 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800778 mLog.e("Failed to untether interface: " + e);
779 }
780
781 stopIPv4();
782
783 resetLinkProperties();
784 }
785
786 @Override
787 public boolean processMessage(Message message) {
788 logMessage(this, message.what);
789 switch (message.what) {
790 case CMD_TETHER_UNREQUESTED:
791 transitionTo(mInitialState);
792 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
793 break;
794 case CMD_INTERFACE_DOWN:
795 transitionTo(mUnavailableState);
796 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
797 break;
798 case CMD_IPV6_TETHER_UPDATE:
799 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
800 sendLinkProperties();
801 break;
802 case CMD_IP_FORWARDING_ENABLE_ERROR:
803 case CMD_IP_FORWARDING_DISABLE_ERROR:
804 case CMD_START_TETHERING_ERROR:
805 case CMD_STOP_TETHERING_ERROR:
806 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +0800807 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800808 transitionTo(mInitialState);
809 break;
810 default:
811 return false;
812 }
813 return true;
814 }
815 }
816
817 // Handling errors in BaseServingState.enter() by transitioning is
818 // problematic because transitioning during a multi-state jump yields
819 // a Log.wtf(). Ultimately, there should be only one ServingState,
820 // and forwarding and NAT rules should be handled by a coordinating
821 // functional element outside of IpServer.
822 class LocalHotspotState extends BaseServingState {
823 @Override
824 public void enter() {
825 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800826 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800827 transitionTo(mInitialState);
828 }
829
830 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
831 sendInterfaceState(STATE_LOCAL_ONLY);
832 }
833
834 @Override
835 public boolean processMessage(Message message) {
836 if (super.processMessage(message)) return true;
837
838 logMessage(this, message.what);
839 switch (message.what) {
840 case CMD_TETHER_REQUESTED:
841 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
842 break;
843 case CMD_TETHER_CONNECTION_CHANGED:
844 // Ignored in local hotspot state.
845 break;
846 default:
847 return false;
848 }
849 return true;
850 }
851 }
852
853 // Handling errors in BaseServingState.enter() by transitioning is
854 // problematic because transitioning during a multi-state jump yields
855 // a Log.wtf(). Ultimately, there should be only one ServingState,
856 // and forwarding and NAT rules should be handled by a coordinating
857 // functional element outside of IpServer.
858 class TetheredState extends BaseServingState {
859 @Override
860 public void enter() {
861 super.enter();
markchien9b4d7572019-12-25 19:40:32 +0800862 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +0800863 transitionTo(mInitialState);
864 }
865
866 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
867 sendInterfaceState(STATE_TETHERED);
868 }
869
870 @Override
871 public void exit() {
872 cleanupUpstream();
873 super.exit();
874 }
875
876 private void cleanupUpstream() {
877 if (mUpstreamIfaceSet == null) return;
878
879 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
880 mUpstreamIfaceSet = null;
881 }
882
883 private void cleanupUpstreamInterface(String upstreamIface) {
884 // Note that we don't care about errors here.
885 // Sometimes interfaces are gone before we get
886 // to remove their rules, which generates errors.
887 // Just do the best we can.
888 try {
markchien12c5bb82020-01-07 14:43:17 +0800889 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
890 } catch (RemoteException | ServiceSpecificException e) {
891 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800892 }
893 try {
markchien12c5bb82020-01-07 14:43:17 +0800894 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
895 } catch (RemoteException | ServiceSpecificException e) {
896 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800897 }
898 }
899
900 @Override
901 public boolean processMessage(Message message) {
902 if (super.processMessage(message)) return true;
903
904 logMessage(this, message.what);
905 switch (message.what) {
906 case CMD_TETHER_REQUESTED:
907 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
908 break;
909 case CMD_TETHER_CONNECTION_CHANGED:
910 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
911 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
912 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
913 break;
914 }
915
916 if (newUpstreamIfaceSet == null) {
917 cleanupUpstream();
918 break;
919 }
920
921 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
922 cleanupUpstreamInterface(removed);
923 }
924
925 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
926 // This makes the call to cleanupUpstream() in the error
927 // path for any interface neatly cleanup all the interfaces.
928 mUpstreamIfaceSet = newUpstreamIfaceSet;
929
930 for (String ifname : added) {
931 try {
markchien12c5bb82020-01-07 14:43:17 +0800932 mNetd.tetherAddForward(mIfaceName, ifname);
933 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
934 } catch (RemoteException | ServiceSpecificException e) {
935 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +0800936 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +0800937 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800938 transitionTo(mInitialState);
939 return true;
940 }
941 }
942 break;
943 default:
944 return false;
945 }
946 return true;
947 }
948
949 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
950 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
951 if (mUpstreamIfaceSet != null && newIfaces != null) {
952 return mUpstreamIfaceSet.equals(newIfaces);
953 }
954 return false;
955 }
956
957 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
958 if (mUpstreamIfaceSet == null) return new HashSet<>();
959
960 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
961 removed.removeAll(newIfaces.ifnames);
962 return removed;
963 }
964
965 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
966 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
967 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
968 return added;
969 }
970 }
971
972 /**
973 * This state is terminal for the per interface state machine. At this
974 * point, the master state machine should have removed this interface
975 * specific state machine from its list of possible recipients of
976 * tethering requests. The state machine itself will hang around until
977 * the garbage collector finds it.
978 */
979 class UnavailableState extends State {
980 @Override
981 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +0800982 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800983 sendInterfaceState(STATE_UNAVAILABLE);
984 }
985 }
986
987 // Accumulate routes representing "prefixes to be assigned to the local
988 // interface", for subsequent modification of local_network routing.
989 private static ArrayList<RouteInfo> getLocalRoutesFor(
990 String ifname, HashSet<IpPrefix> prefixes) {
991 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
992 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +0800993 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +0800994 }
995 return localRoutes;
996 }
997
998 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
999 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1000 final byte[] dnsBytes = localPrefix.getRawAddress();
1001 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1002 try {
1003 return Inet6Address.getByAddress(null, dnsBytes, 0);
1004 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001005 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001006 return null;
1007 }
1008 }
1009
1010 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1011 final byte random = (byte) (new Random()).nextInt();
1012 for (int value : excluded) {
1013 if (random == value) return dflt;
1014 }
1015 return random;
1016 }
1017}