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