blob: 1671dda4bd57108a9844470e91cc90ae04b84dd4 [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
markchien6cf0e552019-12-06 15:24:53 +080019import static android.net.RouteInfo.RTN_UNICAST;
markchien245352e2020-02-27 20:27:18 +080020import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080021import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090022import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH;
markchien74a4fa92019-09-09 20:50:49 +080023import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
24import static android.net.util.NetworkConstants.asByte;
markchienc9daba32020-02-12 00:19:21 +080025import static android.net.util.PrefixUtils.asIpPrefix;
markchien6cf0e552019-12-06 15:24:53 +080026import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090027import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080028
markchien74a4fa92019-09-09 20:50:49 +080029import android.net.INetd;
30import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080031import android.net.IpPrefix;
32import android.net.LinkAddress;
33import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090034import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080035import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090036import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080037import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080038import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090039import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080040import android.net.dhcp.DhcpServerCallbacks;
41import android.net.dhcp.DhcpServingParamsParcel;
42import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090043import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080044import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090045import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080047import android.net.shared.NetdUtils;
48import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080049import android.net.util.InterfaceParams;
50import android.net.util.InterfaceSet;
Xiao Ma4455d6b2020-04-09 10:13:44 +090051import android.net.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080052import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090053import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080054import android.os.Looper;
55import android.os.Message;
56import android.os.RemoteException;
57import android.os.ServiceSpecificException;
58import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080059import android.util.SparseArray;
60
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090061import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090062import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090063
markchien74a4fa92019-09-09 20:50:49 +080064import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080065import com.android.internal.util.State;
66import com.android.internal.util.StateMachine;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080067import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chenb150b872020-05-23 22:54:49 +080068import com.android.networkstack.tethering.BpfCoordinator.Ipv6ForwardingRule;
markchienc9daba32020-02-12 00:19:21 +080069import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +080070
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090071import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080072import java.net.Inet4Address;
73import java.net.Inet6Address;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090074import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080075import java.net.UnknownHostException;
76import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090077import java.util.Arrays;
78import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080079import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090080import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080081import java.util.Objects;
82import java.util.Random;
83import java.util.Set;
84
85/**
86 * Provides the interface to IP-layer serving functionality for a given network
87 * interface, e.g. for tethering or "local-only hotspot" mode.
88 *
89 * @hide
90 */
91public class IpServer extends StateMachine {
92 public static final int STATE_UNAVAILABLE = 0;
93 public static final int STATE_AVAILABLE = 1;
94 public static final int STATE_TETHERED = 2;
95 public static final int STATE_LOCAL_ONLY = 3;
96
97 /** Get string name of |state|.*/
98 public static String getStateString(int state) {
99 switch (state) {
100 case STATE_UNAVAILABLE: return "UNAVAILABLE";
101 case STATE_AVAILABLE: return "AVAILABLE";
102 case STATE_TETHERED: return "TETHERED";
103 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
104 }
105 return "UNKNOWN: " + state;
106 }
107
108 private static final byte DOUG_ADAMS = (byte) 42;
109
markchien74a4fa92019-09-09 20:50:49 +0800110 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800111 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800112
113 // TODO: have this configurable
114 private static final int DHCP_LEASE_TIME_SECS = 3600;
115
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900116 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
117
markchien74a4fa92019-09-09 20:50:49 +0800118 private static final String TAG = "IpServer";
119 private static final boolean DBG = false;
120 private static final boolean VDBG = false;
121 private static final Class[] sMessageClasses = {
122 IpServer.class
123 };
124 private static final SparseArray<String> sMagicDecoderRing =
125 MessageUtils.findMessageNames(sMessageClasses);
126
127 /** IpServer callback. */
128 public static class Callback {
129 /**
130 * Notify that |who| has changed its tethering state.
131 *
132 * @param who the calling instance of IpServer
133 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800134 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800135 */
markchien9d353822019-12-16 20:15:20 +0800136 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800137
138 /**
139 * Notify that |who| has new LinkProperties.
140 *
141 * @param who the calling instance of IpServer
142 * @param newLp the new LinkProperties to report
143 */
markchien9d353822019-12-16 20:15:20 +0800144 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900145
146 /**
147 * Notify that the DHCP leases changed in one of the IpServers.
148 */
149 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800150
151 /**
152 * Request Tethering change.
153 *
154 * @param tetheringType the downstream type of this IpServer.
155 * @param enabled enable or disable tethering.
156 */
157 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800158 }
159
160 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800161 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900162 /** Create an IpNeighborMonitor to be used by this IpServer */
163 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
164 IpNeighborMonitor.NeighborEventConsumer consumer) {
165 return new IpNeighborMonitor(handler, log, consumer);
166 }
167
markchien74a4fa92019-09-09 20:50:49 +0800168 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
169 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
170 return new RouterAdvertisementDaemon(ifParams);
171 }
172
173 /** Get |ifName|'s interface information.*/
174 public InterfaceParams getInterfaceParams(String ifName) {
175 return InterfaceParams.getByName(ifName);
176 }
177
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900178 /** Get |ifName|'s interface index. */
179 public int getIfindex(String ifName) {
180 try {
181 return NetworkInterface.getByName(ifName).getIndex();
182 } catch (IOException | NullPointerException e) {
183 Log.e(TAG, "Can't determine interface index for interface " + ifName);
184 return 0;
185 }
186 }
markchienc9daba32020-02-12 00:19:21 +0800187
markchien9d353822019-12-16 20:15:20 +0800188 /** Create a DhcpServer instance to be used by IpServer. */
189 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
190 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800191 }
192
markchien74a4fa92019-09-09 20:50:49 +0800193 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800194 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800195 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800196 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800197 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800198 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800199 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800200 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800201 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800202 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800203 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800204 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800205 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800206 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800207 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800209 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800211 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900213 // new neighbor cache entry on our interface
214 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900215 // request from DHCP server that it wants to have a new prefix
216 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800217 // request from PrivateAddressCoordinator to restart tethering.
218 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800219
220 private final State mInitialState;
221 private final State mLocalHotspotState;
222 private final State mTetheredState;
223 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800224 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800225
226 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800227 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800228 @NonNull
229 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800230 private final Callback mCallback;
231 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800232 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800233
234 private final String mIfaceName;
235 private final int mInterfaceType;
236 private final LinkProperties mLinkProperties;
237 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800238 private final boolean mUsingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800239
240 private final Dependencies mDeps;
241
242 private int mLastError;
243 private int mServingMode;
244 private InterfaceSet mUpstreamIfaceSet; // may change over time
245 private InterfaceParams mInterfaceParams;
246 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
247 // properties are those selected by the IPv6TetheringCoordinator and relayed
248 // to us. By comparison, mLinkProperties contains the addresses and directly
249 // connected routes that have been formed from these properties iff. we have
250 // succeeded in configuring them and are able to announce them within Router
251 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
252 private LinkProperties mLastIPv6LinkProperties;
253 private RouterAdvertisementDaemon mRaDaemon;
254
255 // To be accessed only on the handler thread
256 private int mDhcpServerStartIndex = 0;
257 private IDhcpServer mDhcpServer;
258 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800259
260 private LinkAddress mStaticIpv4ServerAddr;
261 private LinkAddress mStaticIpv4ClientAddr;
262
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900263 @NonNull
264 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800265
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900266 private int mLastIPv6UpstreamIfindex = 0;
267
268 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
269 public void accept(NeighborEvent e) {
270 sendMessage(CMD_NEIGHBOR_EVENT, e);
271 }
272 }
273
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900274 private final IpNeighborMonitor mIpNeighborMonitor;
275
markchienc9daba32020-02-12 00:19:21 +0800276 private LinkAddress mIpv4Address;
277
Hungming Chen5bc3af92020-05-12 19:15:24 +0800278 // TODO: Add a dependency object to pass the data members or variables from the tethering
279 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800280 public IpServer(
281 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800282 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
283 boolean usingLegacyDhcp, boolean usingBpfOffload,
markchienc9daba32020-02-12 00:19:21 +0800284 PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800285 super(ifaceName, looper);
286 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800287 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800288 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800289 mCallback = callback;
290 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
291 mIfaceName = ifaceName;
292 mInterfaceType = interfaceType;
293 mLinkProperties = new LinkProperties();
294 mUsingLegacyDhcp = usingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800295 mUsingBpfOffload = usingBpfOffload;
markchienc9daba32020-02-12 00:19:21 +0800296 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800297 mDeps = deps;
298 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800299 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800300 mServingMode = STATE_AVAILABLE;
301
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900302 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
303 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800304
Hungming Chen5bc3af92020-05-12 19:15:24 +0800305 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800306 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800307 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800308 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800309 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
310 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900311 }
312
markchien74a4fa92019-09-09 20:50:49 +0800313 mInitialState = new InitialState();
314 mLocalHotspotState = new LocalHotspotState();
315 mTetheredState = new TetheredState();
316 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800317 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800318 addState(mInitialState);
319 addState(mLocalHotspotState);
320 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800321 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800322 addState(mUnavailableState);
323
324 setInitialState(mInitialState);
325 }
326
327 /** Interface name which IpServer served.*/
328 public String interfaceName() {
329 return mIfaceName;
330 }
331
332 /**
markchien9b4d7572019-12-25 19:40:32 +0800333 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800334 */
335 public int interfaceType() {
336 return mInterfaceType;
337 }
338
339 /** Last error from this IpServer. */
340 public int lastError() {
341 return mLastError;
342 }
343
344 /** Serving mode is the current state of IpServer state machine. */
345 public int servingMode() {
346 return mServingMode;
347 }
348
349 /** The properties of the network link which IpServer is serving. */
350 public LinkProperties linkProperties() {
351 return new LinkProperties(mLinkProperties);
352 }
353
markchienc9daba32020-02-12 00:19:21 +0800354 /** The address which IpServer is using. */
355 public LinkAddress getAddress() {
356 return mIpv4Address;
357 }
358
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900359 /**
360 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
361 * thread.
362 */
363 public List<TetheredClient> getAllLeases() {
364 return Collections.unmodifiableList(mDhcpLeases);
365 }
366
markchien74a4fa92019-09-09 20:50:49 +0800367 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
368 public void stop() {
369 sendMessage(CMD_INTERFACE_DOWN);
370 }
371
372 /**
373 * Tethering is canceled. IpServer state machine will be available and wait for
374 * next tethering request.
375 */
376 public void unwanted() {
377 sendMessage(CMD_TETHER_UNREQUESTED);
378 }
379
380 /** Internals. */
381
382 private boolean startIPv4() {
383 return configureIPv4(true);
384 }
385
386 /**
387 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
388 * handler.
389 *
390 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
391 * with different implementations of the callback, to differentiate handling of success/error in
392 * each call.
393 */
394 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
395 @Override
396 public void onStatusAvailable(int statusCode) {
397 getHandler().post(() -> callback(statusCode));
398 }
399
400 public abstract void callback(int statusCode);
401
402 @Override
403 public int getInterfaceVersion() {
404 return this.VERSION;
405 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900406
407 @Override
408 public String getInterfaceHash() {
409 return this.HASH;
410 }
markchien74a4fa92019-09-09 20:50:49 +0800411 }
412
413 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
414 private final int mStartIndex;
415
416 private DhcpServerCallbacksImpl(int startIndex) {
417 mStartIndex = startIndex;
418 }
419
420 @Override
421 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
422 getHandler().post(() -> {
423 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
424 if (mStartIndex != mDhcpServerStartIndex) {
425 // This start request is obsolete. When the |server| binder token goes out of
426 // scope, the garbage collector will finalize it, which causes the network stack
427 // process garbage collector to collect the server itself.
428 return;
429 }
430
431 if (statusCode != STATUS_SUCCESS) {
432 mLog.e("Error obtaining DHCP server: " + statusCode);
433 handleError();
434 return;
435 }
436
437 mDhcpServer = server;
438 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900439 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800440 @Override
441 public void callback(int startStatusCode) {
442 if (startStatusCode != STATUS_SUCCESS) {
443 mLog.e("Error starting DHCP server: " + startStatusCode);
444 handleError();
445 }
446 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900447 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800448 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800449 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800450 }
451 });
452 }
453
454 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800455 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800456 transitionTo(mInitialState);
457 }
458 }
459
Xiao Ma4455d6b2020-04-09 10:13:44 +0900460 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900461 @Override
462 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
463 final ArrayList<TetheredClient> leases = new ArrayList<>();
464 for (DhcpLeaseParcelable lease : leaseParcelables) {
465 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900466 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
467 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
468 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900469
470 final MacAddress macAddress;
471 try {
472 macAddress = MacAddress.fromBytes(lease.hwAddr);
473 } catch (IllegalArgumentException e) {
474 Log.wtf(TAG, "Invalid address received from DhcpServer: "
475 + Arrays.toString(lease.hwAddr));
476 return;
477 }
478
479 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900480 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900481 leases.add(new TetheredClient(
482 macAddress,
483 Collections.singletonList(addressInfo),
484 mInterfaceType));
485 }
486
487 getHandler().post(() -> {
488 mDhcpLeases = leases;
489 mCallback.dhcpLeasesChanged();
490 });
491 }
492
493 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900494 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
495 Objects.requireNonNull(currentPrefix);
496 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900497 }
498
499 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900500 public int getInterfaceVersion() {
501 return this.VERSION;
502 }
503
504 @Override
505 public String getInterfaceHash() throws RemoteException {
506 return this.HASH;
507 }
508 }
509
Xiao Ma4455d6b2020-04-09 10:13:44 +0900510 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
511 Objects.requireNonNull(ipv4Address);
512 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
513 }
514
515 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
516 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
517 @Nullable Inet4Address clientAddr) {
518 final boolean changePrefixOnDecline =
519 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
520 return new DhcpServingParamsParcelExt()
521 .setDefaultRouters(defaultRouter)
522 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
523 .setDnsServers(dnsServer)
524 .setServerAddr(serverAddr)
525 .setMetered(true)
526 .setSingleClientAddr(clientAddr)
527 .setChangePrefixOnDecline(changePrefixOnDecline);
528 // TODO: also advertise link MTU
529 }
530
markchien245352e2020-02-27 20:27:18 +0800531 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800532 if (mUsingLegacyDhcp) {
533 return true;
534 }
markchien245352e2020-02-27 20:27:18 +0800535
536 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800537 final Inet4Address clientAddr = clientLinkAddr == null ? null :
538 (Inet4Address) clientLinkAddr.getAddress();
539
Xiao Ma4455d6b2020-04-09 10:13:44 +0900540 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
541 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800542 mDhcpServerStartIndex++;
543 mDeps.makeDhcpServer(
544 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
545 return true;
546 }
547
548 private void stopDhcp() {
549 // Make all previous start requests obsolete so servers are not started later
550 mDhcpServerStartIndex++;
551
552 if (mDhcpServer != null) {
553 try {
554 mDhcpServer.stop(new OnHandlerStatusCallback() {
555 @Override
556 public void callback(int statusCode) {
557 if (statusCode != STATUS_SUCCESS) {
558 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800559 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800560 // Not much more we can do here
561 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900562 mDhcpLeases.clear();
563 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800564 }
565 });
566 mDhcpServer = null;
567 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900568 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800569 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800570 }
571 }
572 }
573
markchien245352e2020-02-27 20:27:18 +0800574 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
575 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800576 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800577 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800578 } else {
579 stopDhcp();
580 return true;
581 }
582 }
583
584 private void stopIPv4() {
585 configureIPv4(false);
586 // NOTE: All of configureIPv4() will be refactored out of existence
587 // into calls to InterfaceController, shared with startIPv4().
588 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800589 mPrivateAddressCoordinator.releaseDownstream(this);
markchien12c5bb82020-01-07 14:43:17 +0800590 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800591 mStaticIpv4ServerAddr = null;
592 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800593 }
594
markchien74a4fa92019-09-09 20:50:49 +0800595 private boolean configureIPv4(boolean enabled) {
596 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
597
markchienc9daba32020-02-12 00:19:21 +0800598 if (enabled) {
599 mIpv4Address = requestIpv4Address();
600 }
601
602 if (mIpv4Address == null) {
603 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800604 return false;
markchien74a4fa92019-09-09 20:50:49 +0800605 }
606
markchienc9daba32020-02-12 00:19:21 +0800607 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
608 // BT configures the interface elsewhere: only start DHCP.
609 // TODO: make all tethering types behave the same way, and delete the bluetooth
610 // code that calls into NetworkManagementService directly.
611 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
612 }
613
614 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
615
markchien12c5bb82020-01-07 14:43:17 +0800616 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800617 if (mInterfaceType == TetheringManager.TETHERING_WIFI
618 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800619 // The WiFi stack has ownership of the interface up/down state.
620 // It is unclear whether the Bluetooth or USB stacks will manage their own
621 // state.
622 setIfaceUp = null;
623 } else {
624 setIfaceUp = enabled;
625 }
626 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
627 mLog.e("Error configuring interface");
628 if (!enabled) stopDhcp();
629 return false;
630 }
markchien74a4fa92019-09-09 20:50:49 +0800631
markchien74a4fa92019-09-09 20:50:49 +0800632 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800633 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900634 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800635 } else {
markchien12c5bb82020-01-07 14:43:17 +0800636 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900637 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800638 }
markchien245352e2020-02-27 20:27:18 +0800639 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800640 }
641
markchienc9daba32020-02-12 00:19:21 +0800642 private LinkAddress requestIpv4Address() {
643 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800644
markchienc9daba32020-02-12 00:19:21 +0800645 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
646 return new LinkAddress(BLUETOOTH_IFACE_ADDR);
647 }
648
649 return mPrivateAddressCoordinator.requestDownstreamAddress(this);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900650 }
651
markchien74a4fa92019-09-09 20:50:49 +0800652 private boolean startIPv6() {
653 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
654 if (mInterfaceParams == null) {
655 mLog.e("Failed to find InterfaceParams");
656 stopIPv6();
657 return false;
658 }
659
660 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
661 if (!mRaDaemon.start()) {
662 stopIPv6();
663 return false;
664 }
665
666 return true;
667 }
668
669 private void stopIPv6() {
670 mInterfaceParams = null;
671 setRaParams(null);
672
673 if (mRaDaemon != null) {
674 mRaDaemon.stop();
675 mRaDaemon = null;
676 }
677 }
678
679 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
680 // LinkProperties. These have extraneous data filtered out and only the
681 // necessary prefixes included (per its prefix distribution policy).
682 //
683 // TODO: Evaluate using a data structure than is more directly suited to
684 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800685 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800686 if (mRaDaemon == null) return;
687
688 // Avoid unnecessary work on spurious updates.
689 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
690 return;
691 }
692
693 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900694 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800695
696 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900697 final String upstreamIface = v6only.getInterfaceName();
698
markchien74a4fa92019-09-09 20:50:49 +0800699 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700700 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800701 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
702
markchiend63c4f32020-05-21 17:38:28 +0800703 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800704
705 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
706 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
707
708 final IpPrefix prefix = new IpPrefix(
709 linkAddr.getAddress(), linkAddr.getPrefixLength());
710 params.prefixes.add(prefix);
711
712 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
713 if (dnsServer != null) {
714 params.dnses.add(dnsServer);
715 }
716 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900717
718 upstreamIfindex = mDeps.getIfindex(upstreamIface);
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800719
720 // Add upstream index to name mapping for the tether stats usage in the coordinator.
721 // Although this mapping could be added by both class Tethering and IpServer, adding
722 // mapping from IpServer guarantees that the mapping is added before the adding
723 // forwarding rules. That is because there are different state machines in both
724 // classes. It is hard to guarantee the link property update order between multiple
725 // state machines.
726 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfindex, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800727 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900728
markchien74a4fa92019-09-09 20:50:49 +0800729 // If v6only is null, we pass in null to setRaParams(), which handles
730 // deprecation of any existing RA data.
731
732 setRaParams(params);
733 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900734
735 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
736 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800737 }
738
Xiao Ma4455d6b2020-04-09 10:13:44 +0900739 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
740 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
741 mNetd, toBeRemoved);
742 if (removalFailures > 0) {
743 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
744 removalFailures));
745 }
746
747 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
748 }
749
750 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
751 try {
752 // It's safe to call networkAddInterface() even if
753 // the interface is already in the local_network.
754 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
755 try {
756 // Add routes from local network. Note that adding routes that
757 // already exist does not cause an error (EEXIST is silently ignored).
758 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
759 } catch (IllegalStateException e) {
760 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
761 return;
762 }
763 } catch (ServiceSpecificException | RemoteException e) {
764 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
765 return;
766 }
767
768 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
769 }
770
markchien74a4fa92019-09-09 20:50:49 +0800771 private void configureLocalIPv6Routes(
772 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
773 // [1] Remove the routes that are deprecated.
774 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900775 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800776 }
777
778 // [2] Add only the routes that have not previously been added.
779 if (newPrefixes != null && !newPrefixes.isEmpty()) {
780 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
781 if (mLastRaParams != null) {
782 addedPrefixes.removeAll(mLastRaParams.prefixes);
783 }
784
785 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900786 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800787 }
788 }
789 }
790
791 private void configureLocalIPv6Dns(
792 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
793 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
794 if (mNetd == null) {
795 if (newDnses != null) newDnses.clear();
796 mLog.e("No netd service instance available; not setting local IPv6 addresses");
797 return;
798 }
799
800 // [1] Remove deprecated local DNS IP addresses.
801 if (!deprecatedDnses.isEmpty()) {
802 for (Inet6Address dns : deprecatedDnses) {
803 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
804 mLog.e("Failed to remove local dns IP " + dns);
805 }
806
807 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
808 }
809 }
810
811 // [2] Add only the local DNS IP addresses that have not previously been added.
812 if (newDnses != null && !newDnses.isEmpty()) {
813 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
814 if (mLastRaParams != null) {
815 addedDnses.removeAll(mLastRaParams.dnses);
816 }
817
818 for (Inet6Address dns : addedDnses) {
819 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
820 mLog.e("Failed to add local dns IP " + dns);
821 newDnses.remove(dns);
822 }
823
824 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
825 }
826 }
827
828 try {
829 mNetd.tetherApplyDnsInterfaces();
830 } catch (ServiceSpecificException | RemoteException e) {
831 mLog.e("Failed to update local DNS caching server");
832 if (newDnses != null) newDnses.clear();
833 }
834 }
835
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900836 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800837 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
838 // offload is disabled. Add this check just in case.
839 // TODO: Perhaps remove this protection check.
840 if (!mUsingBpfOffload) return;
841
Hungming Chen269c0882020-05-06 14:57:35 +0800842 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900843 }
844
Hungming Chen269c0882020-05-06 14:57:35 +0800845 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800846 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800847 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800848 if (!mUsingBpfOffload) return;
849
Hungming Chen269c0882020-05-06 14:57:35 +0800850 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900851 }
852
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900853 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800854 if (!mUsingBpfOffload) return;
855
856 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900857 }
858
Hungming Chen269c0882020-05-06 14:57:35 +0800859 private void updateIpv6ForwardingRule(int newIfindex) {
860 // TODO: Perhaps remove this protection check.
861 // See the related comment in #addIpv6ForwardingRule.
862 if (!mUsingBpfOffload) return;
863
864 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900865 }
866
867 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
868 // changes or if a neighbor event is received.
869 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
870 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900871 // If we no longer have an upstream, clear forwarding rules and do nothing else.
872 if (upstreamIfindex == 0) {
873 clearIpv6ForwardingRules();
874 return;
875 }
876
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900877 // If the upstream interface has changed, remove all rules and re-add them with the new
878 // upstream interface.
879 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800880 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900881 }
882
883 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900884 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900885 if (e == null) return;
886 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
887 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
888 return;
889 }
890
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900891 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
892 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
893 // add rules with a null MAC, only delete them.
894 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900895 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900896 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900897 if (e.isValid()) {
898 addIpv6ForwardingRule(rule);
899 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800900 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900901 }
902 }
903
904 private void handleNeighborEvent(NeighborEvent e) {
905 if (mInterfaceParams != null
906 && mInterfaceParams.index == e.ifindex
907 && mInterfaceParams.hasMacAddress) {
908 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
909 }
910 }
911
Xiao Ma4455d6b2020-04-09 10:13:44 +0900912 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
913 if (!currentPrefix.contains(mIpv4Address.getAddress())
914 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
915 Log.e(TAG, "Invalid prefix: " + currentPrefix);
916 return;
917 }
918
919 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchienc9daba32020-02-12 00:19:21 +0800920 mIpv4Address = requestIpv4Address();
921 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900922 mLog.e("Fail to request a new downstream prefix");
923 return;
924 }
markchienc9daba32020-02-12 00:19:21 +0800925 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +0900926
927 // Add new IPv4 address on the interface.
928 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
929 mLog.e("Failed to add new IP " + srvAddr);
930 return;
931 }
932
933 // Remove deprecated routes from local network.
934 removeRoutesFromLocalNetwork(
935 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
936 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
937
938 // Add new routes to local network.
939 addRoutesToLocalNetwork(
940 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
941 mLinkProperties.addLinkAddress(mIpv4Address);
942
943 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
944 // listen on the interface configured with new IPv4 address, that results DNS validation
945 // failure of downstream client even if appropriate routes have been configured.
946 try {
947 mNetd.tetherApplyDnsInterfaces();
948 } catch (ServiceSpecificException | RemoteException e) {
949 mLog.e("Failed to update local DNS caching server");
950 return;
951 }
952 sendLinkProperties();
953
954 // Notify DHCP server that new prefix/route has been applied on IpServer.
955 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
956 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
957 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
958 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
959 try {
960 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
961 @Override
962 public void callback(int statusCode) {
963 if (statusCode != STATUS_SUCCESS) {
964 mLog.e("Error updating DHCP serving params: " + statusCode);
965 }
966 }
967 });
968 } catch (RemoteException e) {
969 mLog.e("Error updating DHCP serving params", e);
970 }
971 }
972
markchiend63c4f32020-05-21 17:38:28 +0800973 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +0800974 try {
975 int upstreamHopLimit = Integer.parseUnsignedInt(
976 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +0800977 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +0800978 // Cap the hop limit to 255.
979 return (byte) Integer.min(upstreamHopLimit, 255);
980 } catch (Exception e) {
981 mLog.e("Failed to find upstream interface hop limit", e);
982 }
983 return RaParams.DEFAULT_HOPLIMIT;
984 }
985
986 private void setRaParams(RaParams newParams) {
987 if (mRaDaemon != null) {
988 final RaParams deprecatedParams =
989 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
990
991 configureLocalIPv6Routes(deprecatedParams.prefixes,
992 (newParams != null) ? newParams.prefixes : null);
993
994 configureLocalIPv6Dns(deprecatedParams.dnses,
995 (newParams != null) ? newParams.dnses : null);
996
997 mRaDaemon.buildNewRa(deprecatedParams, newParams);
998 }
999
1000 mLastRaParams = newParams;
1001 }
1002
1003 private void logMessage(State state, int what) {
1004 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
1005 }
1006
1007 private void sendInterfaceState(int newInterfaceState) {
1008 mServingMode = newInterfaceState;
1009 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1010 sendLinkProperties();
1011 }
1012
1013 private void sendLinkProperties() {
1014 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1015 }
1016
1017 private void resetLinkProperties() {
1018 mLinkProperties.clear();
1019 mLinkProperties.setInterfaceName(mIfaceName);
1020 }
1021
markchienf053e4b2020-03-16 21:49:48 +08001022 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001023 // Ignore static address configuration if they are invalid or null. In theory, static
1024 // addresses should not be invalid here because TetheringManager do not allow caller to
1025 // specify invalid static address configuration.
1026 if (request == null || request.localIPv4Address == null
1027 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1028 request.localIPv4Address, request.staticClientAddress)) {
1029 return;
1030 }
markchienf053e4b2020-03-16 21:49:48 +08001031
1032 mStaticIpv4ServerAddr = request.localIPv4Address;
1033 mStaticIpv4ClientAddr = request.staticClientAddress;
1034 }
1035
markchien74a4fa92019-09-09 20:50:49 +08001036 class InitialState extends State {
1037 @Override
1038 public void enter() {
1039 sendInterfaceState(STATE_AVAILABLE);
1040 }
1041
1042 @Override
1043 public boolean processMessage(Message message) {
1044 logMessage(this, message.what);
1045 switch (message.what) {
1046 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001047 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001048 switch (message.arg1) {
1049 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001050 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001051 transitionTo(mLocalHotspotState);
1052 break;
1053 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001054 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001055 transitionTo(mTetheredState);
1056 break;
1057 default:
1058 mLog.e("Invalid tethering interface serving state specified.");
1059 }
1060 break;
1061 case CMD_INTERFACE_DOWN:
1062 transitionTo(mUnavailableState);
1063 break;
1064 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001065 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001066 break;
1067 default:
1068 return NOT_HANDLED;
1069 }
1070 return HANDLED;
1071 }
1072 }
1073
1074 class BaseServingState extends State {
1075 @Override
1076 public void enter() {
1077 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001078 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001079 return;
1080 }
1081
1082 try {
markchienc9daba32020-02-12 00:19:21 +08001083 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001084 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001085 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001086 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001087 return;
1088 }
1089
1090 if (!startIPv6()) {
1091 mLog.e("Failed to startIPv6");
1092 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1093 return;
1094 }
1095 }
1096
1097 @Override
1098 public void exit() {
1099 // Note that at this point, we're leaving the tethered state. We can fail any
1100 // of these operations, but it doesn't really change that we have to try them
1101 // all in sequence.
1102 stopIPv6();
1103
1104 try {
markchien12c5bb82020-01-07 14:43:17 +08001105 NetdUtils.untetherInterface(mNetd, mIfaceName);
1106 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001107 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001108 mLog.e("Failed to untether interface: " + e);
1109 }
1110
1111 stopIPv4();
1112
1113 resetLinkProperties();
1114 }
1115
1116 @Override
1117 public boolean processMessage(Message message) {
1118 logMessage(this, message.what);
1119 switch (message.what) {
1120 case CMD_TETHER_UNREQUESTED:
1121 transitionTo(mInitialState);
1122 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1123 break;
1124 case CMD_INTERFACE_DOWN:
1125 transitionTo(mUnavailableState);
1126 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1127 break;
1128 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001129 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001130 sendLinkProperties();
1131 break;
1132 case CMD_IP_FORWARDING_ENABLE_ERROR:
1133 case CMD_IP_FORWARDING_DISABLE_ERROR:
1134 case CMD_START_TETHERING_ERROR:
1135 case CMD_STOP_TETHERING_ERROR:
1136 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001137 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001138 transitionTo(mInitialState);
1139 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001140 case CMD_NEW_PREFIX_REQUEST:
1141 handleNewPrefixRequest((IpPrefix) message.obj);
1142 break;
markchienc9daba32020-02-12 00:19:21 +08001143 case CMD_NOTIFY_PREFIX_CONFLICT:
1144 mLog.i("restart tethering: " + mInterfaceType);
1145 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1146 transitionTo(mWaitingForRestartState);
1147 break;
markchien74a4fa92019-09-09 20:50:49 +08001148 default:
1149 return false;
1150 }
1151 return true;
1152 }
1153 }
1154
1155 // Handling errors in BaseServingState.enter() by transitioning is
1156 // problematic because transitioning during a multi-state jump yields
1157 // a Log.wtf(). Ultimately, there should be only one ServingState,
1158 // and forwarding and NAT rules should be handled by a coordinating
1159 // functional element outside of IpServer.
1160 class LocalHotspotState extends BaseServingState {
1161 @Override
1162 public void enter() {
1163 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001164 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001165 transitionTo(mInitialState);
1166 }
1167
1168 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1169 sendInterfaceState(STATE_LOCAL_ONLY);
1170 }
1171
1172 @Override
1173 public boolean processMessage(Message message) {
1174 if (super.processMessage(message)) return true;
1175
1176 logMessage(this, message.what);
1177 switch (message.what) {
1178 case CMD_TETHER_REQUESTED:
1179 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1180 break;
1181 case CMD_TETHER_CONNECTION_CHANGED:
1182 // Ignored in local hotspot state.
1183 break;
1184 default:
1185 return false;
1186 }
1187 return true;
1188 }
1189 }
1190
1191 // Handling errors in BaseServingState.enter() by transitioning is
1192 // problematic because transitioning during a multi-state jump yields
1193 // a Log.wtf(). Ultimately, there should be only one ServingState,
1194 // and forwarding and NAT rules should be handled by a coordinating
1195 // functional element outside of IpServer.
1196 class TetheredState extends BaseServingState {
1197 @Override
1198 public void enter() {
1199 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001200 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001201 transitionTo(mInitialState);
1202 }
1203
1204 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1205 sendInterfaceState(STATE_TETHERED);
1206 }
1207
1208 @Override
1209 public void exit() {
1210 cleanupUpstream();
1211 super.exit();
1212 }
1213
1214 private void cleanupUpstream() {
1215 if (mUpstreamIfaceSet == null) return;
1216
1217 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1218 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001219 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001220 }
1221
1222 private void cleanupUpstreamInterface(String upstreamIface) {
1223 // Note that we don't care about errors here.
1224 // Sometimes interfaces are gone before we get
1225 // to remove their rules, which generates errors.
1226 // Just do the best we can.
1227 try {
markchien12c5bb82020-01-07 14:43:17 +08001228 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1229 } catch (RemoteException | ServiceSpecificException e) {
1230 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001231 }
1232 try {
markchien12c5bb82020-01-07 14:43:17 +08001233 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1234 } catch (RemoteException | ServiceSpecificException e) {
1235 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001236 }
1237 }
1238
1239 @Override
1240 public boolean processMessage(Message message) {
1241 if (super.processMessage(message)) return true;
1242
1243 logMessage(this, message.what);
1244 switch (message.what) {
1245 case CMD_TETHER_REQUESTED:
1246 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1247 break;
1248 case CMD_TETHER_CONNECTION_CHANGED:
1249 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1250 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1251 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1252 break;
1253 }
1254
1255 if (newUpstreamIfaceSet == null) {
1256 cleanupUpstream();
1257 break;
1258 }
1259
1260 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1261 cleanupUpstreamInterface(removed);
1262 }
1263
1264 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1265 // This makes the call to cleanupUpstream() in the error
1266 // path for any interface neatly cleanup all the interfaces.
1267 mUpstreamIfaceSet = newUpstreamIfaceSet;
1268
1269 for (String ifname : added) {
1270 try {
markchien12c5bb82020-01-07 14:43:17 +08001271 mNetd.tetherAddForward(mIfaceName, ifname);
1272 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1273 } catch (RemoteException | ServiceSpecificException e) {
1274 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001275 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001276 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001277 transitionTo(mInitialState);
1278 return true;
1279 }
1280 }
1281 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001282 case CMD_NEIGHBOR_EVENT:
1283 handleNeighborEvent((NeighborEvent) message.obj);
1284 break;
markchien74a4fa92019-09-09 20:50:49 +08001285 default:
1286 return false;
1287 }
1288 return true;
1289 }
1290
1291 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1292 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1293 if (mUpstreamIfaceSet != null && newIfaces != null) {
1294 return mUpstreamIfaceSet.equals(newIfaces);
1295 }
1296 return false;
1297 }
1298
1299 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1300 if (mUpstreamIfaceSet == null) return new HashSet<>();
1301
1302 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1303 removed.removeAll(newIfaces.ifnames);
1304 return removed;
1305 }
1306
1307 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1308 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1309 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1310 return added;
1311 }
1312 }
1313
1314 /**
1315 * This state is terminal for the per interface state machine. At this
1316 * point, the master state machine should have removed this interface
1317 * specific state machine from its list of possible recipients of
1318 * tethering requests. The state machine itself will hang around until
1319 * the garbage collector finds it.
1320 */
1321 class UnavailableState extends State {
1322 @Override
1323 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001324 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001325 sendInterfaceState(STATE_UNAVAILABLE);
1326 }
1327 }
1328
markchienc9daba32020-02-12 00:19:21 +08001329 class WaitingForRestartState extends State {
1330 @Override
1331 public boolean processMessage(Message message) {
1332 logMessage(this, message.what);
1333 switch (message.what) {
1334 case CMD_TETHER_UNREQUESTED:
1335 transitionTo(mInitialState);
1336 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1337 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1338 break;
1339 case CMD_INTERFACE_DOWN:
1340 transitionTo(mUnavailableState);
1341 mLog.i("Untethered (interface down) and restarting" + mIfaceName);
1342 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1343 break;
1344 default:
1345 return false;
1346 }
1347 return true;
1348 }
1349 }
1350
markchien74a4fa92019-09-09 20:50:49 +08001351 // Accumulate routes representing "prefixes to be assigned to the local
1352 // interface", for subsequent modification of local_network routing.
1353 private static ArrayList<RouteInfo> getLocalRoutesFor(
1354 String ifname, HashSet<IpPrefix> prefixes) {
1355 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1356 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001357 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001358 }
1359 return localRoutes;
1360 }
1361
1362 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1363 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1364 final byte[] dnsBytes = localPrefix.getRawAddress();
1365 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1366 try {
1367 return Inet6Address.getByAddress(null, dnsBytes, 0);
1368 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001369 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001370 return null;
1371 }
1372 }
1373
1374 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1375 final byte random = (byte) (new Random()).nextInt();
1376 for (int value : excluded) {
1377 if (random == value) return dflt;
1378 }
1379 return random;
1380 }
1381}