blob: 673cbf09d259637aee30801d33987c36c3364d3f [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;
markchien74a4fa92019-09-09 20:50:49 +080022import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
23import static android.net.util.NetworkConstants.asByte;
markchienc9daba32020-02-12 00:19:21 +080024import static android.net.util.PrefixUtils.asIpPrefix;
markchien6cf0e552019-12-06 15:24:53 +080025import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090026import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080027
Chalard Jean78701642020-07-31 20:00:30 +090028import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
29
markchien74a4fa92019-09-09 20:50:49 +080030import android.net.INetd;
31import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080032import android.net.IpPrefix;
33import android.net.LinkAddress;
34import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090035import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080036import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090037import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080038import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080039import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090040import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080041import android.net.dhcp.DhcpServerCallbacks;
42import android.net.dhcp.DhcpServingParamsParcel;
43import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090044import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080045import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090046import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080047import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080048import android.net.shared.NetdUtils;
49import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080050import android.net.util.InterfaceParams;
51import android.net.util.InterfaceSet;
Xiao Ma4455d6b2020-04-09 10:13:44 +090052import android.net.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080053import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090054import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080055import android.os.Looper;
56import android.os.Message;
57import android.os.RemoteException;
58import android.os.ServiceSpecificException;
59import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080060import android.util.SparseArray;
61
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090062import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090063import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090064
markchien74a4fa92019-09-09 20:50:49 +080065import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080066import com.android.internal.util.State;
67import com.android.internal.util.StateMachine;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080068import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chenb150b872020-05-23 22:54:49 +080069import com.android.networkstack.tethering.BpfCoordinator.Ipv6ForwardingRule;
markchienc9daba32020-02-12 00:19:21 +080070import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +080071
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090072import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080073import java.net.Inet4Address;
74import java.net.Inet6Address;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090075import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080076import java.net.UnknownHostException;
77import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090078import java.util.Arrays;
79import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080080import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090081import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080082import java.util.Objects;
83import java.util.Random;
84import java.util.Set;
85
86/**
87 * Provides the interface to IP-layer serving functionality for a given network
88 * interface, e.g. for tethering or "local-only hotspot" mode.
89 *
90 * @hide
91 */
92public class IpServer extends StateMachine {
93 public static final int STATE_UNAVAILABLE = 0;
94 public static final int STATE_AVAILABLE = 1;
95 public static final int STATE_TETHERED = 2;
96 public static final int STATE_LOCAL_ONLY = 3;
97
98 /** Get string name of |state|.*/
99 public static String getStateString(int state) {
100 switch (state) {
101 case STATE_UNAVAILABLE: return "UNAVAILABLE";
102 case STATE_AVAILABLE: return "AVAILABLE";
103 case STATE_TETHERED: return "TETHERED";
104 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
105 }
106 return "UNKNOWN: " + state;
107 }
108
109 private static final byte DOUG_ADAMS = (byte) 42;
110
markchien74a4fa92019-09-09 20:50:49 +0800111 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800112 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800113
114 // TODO: have this configurable
115 private static final int DHCP_LEASE_TIME_SECS = 3600;
116
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900117 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
118
markchien74a4fa92019-09-09 20:50:49 +0800119 private static final String TAG = "IpServer";
120 private static final boolean DBG = false;
121 private static final boolean VDBG = false;
122 private static final Class[] sMessageClasses = {
123 IpServer.class
124 };
125 private static final SparseArray<String> sMagicDecoderRing =
126 MessageUtils.findMessageNames(sMessageClasses);
127
128 /** IpServer callback. */
129 public static class Callback {
130 /**
131 * Notify that |who| has changed its tethering state.
132 *
133 * @param who the calling instance of IpServer
134 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800135 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800136 */
markchien9d353822019-12-16 20:15:20 +0800137 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800138
139 /**
140 * Notify that |who| has new LinkProperties.
141 *
142 * @param who the calling instance of IpServer
143 * @param newLp the new LinkProperties to report
144 */
markchien9d353822019-12-16 20:15:20 +0800145 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900146
147 /**
148 * Notify that the DHCP leases changed in one of the IpServers.
149 */
150 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800151
152 /**
153 * Request Tethering change.
154 *
155 * @param tetheringType the downstream type of this IpServer.
156 * @param enabled enable or disable tethering.
157 */
158 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800159 }
160
161 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800162 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900163 /** Create an IpNeighborMonitor to be used by this IpServer */
164 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
165 IpNeighborMonitor.NeighborEventConsumer consumer) {
166 return new IpNeighborMonitor(handler, log, consumer);
167 }
168
markchien74a4fa92019-09-09 20:50:49 +0800169 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
170 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
171 return new RouterAdvertisementDaemon(ifParams);
172 }
173
174 /** Get |ifName|'s interface information.*/
175 public InterfaceParams getInterfaceParams(String ifName) {
176 return InterfaceParams.getByName(ifName);
177 }
178
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900179 /** Get |ifName|'s interface index. */
180 public int getIfindex(String ifName) {
181 try {
182 return NetworkInterface.getByName(ifName).getIndex();
183 } catch (IOException | NullPointerException e) {
184 Log.e(TAG, "Can't determine interface index for interface " + ifName);
185 return 0;
186 }
187 }
markchienc9daba32020-02-12 00:19:21 +0800188
markchien9d353822019-12-16 20:15:20 +0800189 /** Create a DhcpServer instance to be used by IpServer. */
190 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
191 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800192 }
193
markchien74a4fa92019-09-09 20:50:49 +0800194 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800195 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800196 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800197 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800198 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800199 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800200 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
201 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800202 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800203 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
204 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800205 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800206 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
207 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800209 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800211 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
212 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800213 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800214 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800215 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800216 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800217 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900218 // new neighbor cache entry on our interface
219 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900220 // request from DHCP server that it wants to have a new prefix
221 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800222 // request from PrivateAddressCoordinator to restart tethering.
223 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800224
225 private final State mInitialState;
226 private final State mLocalHotspotState;
227 private final State mTetheredState;
228 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800229 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800230
231 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800232 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800233 @NonNull
234 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800235 private final Callback mCallback;
236 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800237 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800238
239 private final String mIfaceName;
240 private final int mInterfaceType;
241 private final LinkProperties mLinkProperties;
242 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800243 private final boolean mUsingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800244
245 private final Dependencies mDeps;
246
247 private int mLastError;
248 private int mServingMode;
249 private InterfaceSet mUpstreamIfaceSet; // may change over time
250 private InterfaceParams mInterfaceParams;
251 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
252 // properties are those selected by the IPv6TetheringCoordinator and relayed
253 // to us. By comparison, mLinkProperties contains the addresses and directly
254 // connected routes that have been formed from these properties iff. we have
255 // succeeded in configuring them and are able to announce them within Router
256 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
257 private LinkProperties mLastIPv6LinkProperties;
258 private RouterAdvertisementDaemon mRaDaemon;
259
260 // To be accessed only on the handler thread
261 private int mDhcpServerStartIndex = 0;
262 private IDhcpServer mDhcpServer;
263 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800264
265 private LinkAddress mStaticIpv4ServerAddr;
266 private LinkAddress mStaticIpv4ClientAddr;
267
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900268 @NonNull
269 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800270
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900271 private int mLastIPv6UpstreamIfindex = 0;
272
273 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
274 public void accept(NeighborEvent e) {
275 sendMessage(CMD_NEIGHBOR_EVENT, e);
276 }
277 }
278
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900279 private final IpNeighborMonitor mIpNeighborMonitor;
280
markchienc9daba32020-02-12 00:19:21 +0800281 private LinkAddress mIpv4Address;
282
Hungming Chen5bc3af92020-05-12 19:15:24 +0800283 // TODO: Add a dependency object to pass the data members or variables from the tethering
284 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800285 public IpServer(
286 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800287 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
288 boolean usingLegacyDhcp, boolean usingBpfOffload,
markchienc9daba32020-02-12 00:19:21 +0800289 PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800290 super(ifaceName, looper);
291 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800292 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800293 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800294 mCallback = callback;
295 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
296 mIfaceName = ifaceName;
297 mInterfaceType = interfaceType;
298 mLinkProperties = new LinkProperties();
299 mUsingLegacyDhcp = usingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800300 mUsingBpfOffload = usingBpfOffload;
markchienc9daba32020-02-12 00:19:21 +0800301 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800302 mDeps = deps;
303 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800304 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800305 mServingMode = STATE_AVAILABLE;
306
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900307 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
308 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800309
Hungming Chen5bc3af92020-05-12 19:15:24 +0800310 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800311 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800312 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800313 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800314 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
315 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900316 }
317
markchien74a4fa92019-09-09 20:50:49 +0800318 mInitialState = new InitialState();
319 mLocalHotspotState = new LocalHotspotState();
320 mTetheredState = new TetheredState();
321 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800322 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800323 addState(mInitialState);
324 addState(mLocalHotspotState);
325 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800326 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800327 addState(mUnavailableState);
328
329 setInitialState(mInitialState);
330 }
331
332 /** Interface name which IpServer served.*/
333 public String interfaceName() {
334 return mIfaceName;
335 }
336
337 /**
markchien9b4d7572019-12-25 19:40:32 +0800338 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800339 */
340 public int interfaceType() {
341 return mInterfaceType;
342 }
343
344 /** Last error from this IpServer. */
345 public int lastError() {
346 return mLastError;
347 }
348
349 /** Serving mode is the current state of IpServer state machine. */
350 public int servingMode() {
351 return mServingMode;
352 }
353
354 /** The properties of the network link which IpServer is serving. */
355 public LinkProperties linkProperties() {
356 return new LinkProperties(mLinkProperties);
357 }
358
markchienc9daba32020-02-12 00:19:21 +0800359 /** The address which IpServer is using. */
360 public LinkAddress getAddress() {
361 return mIpv4Address;
362 }
363
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900364 /**
365 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
366 * thread.
367 */
368 public List<TetheredClient> getAllLeases() {
369 return Collections.unmodifiableList(mDhcpLeases);
370 }
371
markchien74a4fa92019-09-09 20:50:49 +0800372 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
373 public void stop() {
374 sendMessage(CMD_INTERFACE_DOWN);
375 }
376
377 /**
378 * Tethering is canceled. IpServer state machine will be available and wait for
379 * next tethering request.
380 */
381 public void unwanted() {
382 sendMessage(CMD_TETHER_UNREQUESTED);
383 }
384
385 /** Internals. */
386
387 private boolean startIPv4() {
388 return configureIPv4(true);
389 }
390
391 /**
392 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
393 * handler.
394 *
395 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
396 * with different implementations of the callback, to differentiate handling of success/error in
397 * each call.
398 */
399 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
400 @Override
401 public void onStatusAvailable(int statusCode) {
402 getHandler().post(() -> callback(statusCode));
403 }
404
405 public abstract void callback(int statusCode);
406
407 @Override
408 public int getInterfaceVersion() {
409 return this.VERSION;
410 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900411
412 @Override
413 public String getInterfaceHash() {
414 return this.HASH;
415 }
markchien74a4fa92019-09-09 20:50:49 +0800416 }
417
418 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
419 private final int mStartIndex;
420
421 private DhcpServerCallbacksImpl(int startIndex) {
422 mStartIndex = startIndex;
423 }
424
425 @Override
426 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
427 getHandler().post(() -> {
428 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
429 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800430 // This start request is obsolete. Explicitly stop the DHCP server to shut
431 // down its thread. When the |server| binder token goes out of scope, the
432 // garbage collector will finalize it, which causes the network stack process
433 // garbage collector to collect the server itself.
434 try {
435 server.stop(null);
436 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800437 return;
438 }
439
440 if (statusCode != STATUS_SUCCESS) {
441 mLog.e("Error obtaining DHCP server: " + statusCode);
442 handleError();
443 return;
444 }
445
446 mDhcpServer = server;
447 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900448 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800449 @Override
450 public void callback(int startStatusCode) {
451 if (startStatusCode != STATUS_SUCCESS) {
452 mLog.e("Error starting DHCP server: " + startStatusCode);
453 handleError();
454 }
455 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900456 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800457 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800458 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800459 }
460 });
461 }
462
463 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800464 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800465 transitionTo(mInitialState);
466 }
467 }
468
Xiao Ma4455d6b2020-04-09 10:13:44 +0900469 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900470 @Override
471 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
472 final ArrayList<TetheredClient> leases = new ArrayList<>();
473 for (DhcpLeaseParcelable lease : leaseParcelables) {
474 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900475 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
476 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
477 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900478
479 final MacAddress macAddress;
480 try {
481 macAddress = MacAddress.fromBytes(lease.hwAddr);
482 } catch (IllegalArgumentException e) {
483 Log.wtf(TAG, "Invalid address received from DhcpServer: "
484 + Arrays.toString(lease.hwAddr));
485 return;
486 }
487
488 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900489 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900490 leases.add(new TetheredClient(
491 macAddress,
492 Collections.singletonList(addressInfo),
493 mInterfaceType));
494 }
495
496 getHandler().post(() -> {
497 mDhcpLeases = leases;
498 mCallback.dhcpLeasesChanged();
499 });
500 }
501
502 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900503 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
504 Objects.requireNonNull(currentPrefix);
505 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900506 }
507
508 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900509 public int getInterfaceVersion() {
510 return this.VERSION;
511 }
512
513 @Override
514 public String getInterfaceHash() throws RemoteException {
515 return this.HASH;
516 }
517 }
518
Xiao Ma4455d6b2020-04-09 10:13:44 +0900519 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
520 Objects.requireNonNull(ipv4Address);
521 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
522 }
523
524 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
525 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
526 @Nullable Inet4Address clientAddr) {
527 final boolean changePrefixOnDecline =
528 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
529 return new DhcpServingParamsParcelExt()
530 .setDefaultRouters(defaultRouter)
531 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
532 .setDnsServers(dnsServer)
533 .setServerAddr(serverAddr)
534 .setMetered(true)
535 .setSingleClientAddr(clientAddr)
536 .setChangePrefixOnDecline(changePrefixOnDecline);
537 // TODO: also advertise link MTU
538 }
539
markchien245352e2020-02-27 20:27:18 +0800540 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800541 if (mUsingLegacyDhcp) {
542 return true;
543 }
markchien245352e2020-02-27 20:27:18 +0800544
545 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800546 final Inet4Address clientAddr = clientLinkAddr == null ? null :
547 (Inet4Address) clientLinkAddr.getAddress();
548
Xiao Ma4455d6b2020-04-09 10:13:44 +0900549 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
550 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800551 mDhcpServerStartIndex++;
552 mDeps.makeDhcpServer(
553 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
554 return true;
555 }
556
557 private void stopDhcp() {
558 // Make all previous start requests obsolete so servers are not started later
559 mDhcpServerStartIndex++;
560
561 if (mDhcpServer != null) {
562 try {
563 mDhcpServer.stop(new OnHandlerStatusCallback() {
564 @Override
565 public void callback(int statusCode) {
566 if (statusCode != STATUS_SUCCESS) {
567 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800568 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800569 // Not much more we can do here
570 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900571 mDhcpLeases.clear();
572 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800573 }
574 });
575 mDhcpServer = null;
576 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900577 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800578 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800579 }
580 }
581 }
582
markchien245352e2020-02-27 20:27:18 +0800583 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
584 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800585 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800586 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800587 } else {
588 stopDhcp();
589 return true;
590 }
591 }
592
593 private void stopIPv4() {
594 configureIPv4(false);
595 // NOTE: All of configureIPv4() will be refactored out of existence
596 // into calls to InterfaceController, shared with startIPv4().
597 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800598 mPrivateAddressCoordinator.releaseDownstream(this);
markchien12c5bb82020-01-07 14:43:17 +0800599 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800600 mStaticIpv4ServerAddr = null;
601 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800602 }
603
markchien74a4fa92019-09-09 20:50:49 +0800604 private boolean configureIPv4(boolean enabled) {
605 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
606
markchienc9daba32020-02-12 00:19:21 +0800607 if (enabled) {
608 mIpv4Address = requestIpv4Address();
609 }
610
611 if (mIpv4Address == null) {
612 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800613 return false;
markchien74a4fa92019-09-09 20:50:49 +0800614 }
615
markchienc9daba32020-02-12 00:19:21 +0800616 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
617 // BT configures the interface elsewhere: only start DHCP.
618 // TODO: make all tethering types behave the same way, and delete the bluetooth
619 // code that calls into NetworkManagementService directly.
620 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
621 }
622
623 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
624
markchien12c5bb82020-01-07 14:43:17 +0800625 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800626 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900627 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200628 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
629 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900630 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800631 // It is unclear whether the Bluetooth or USB stacks will manage their own
632 // state.
633 setIfaceUp = null;
634 } else {
635 setIfaceUp = enabled;
636 }
637 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
638 mLog.e("Error configuring interface");
639 if (!enabled) stopDhcp();
640 return false;
641 }
markchien74a4fa92019-09-09 20:50:49 +0800642
markchien74a4fa92019-09-09 20:50:49 +0800643 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800644 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900645 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800646 } else {
markchien12c5bb82020-01-07 14:43:17 +0800647 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900648 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800649 }
markchien245352e2020-02-27 20:27:18 +0800650 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800651 }
652
markchienc9daba32020-02-12 00:19:21 +0800653 private LinkAddress requestIpv4Address() {
654 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800655
markchienc9daba32020-02-12 00:19:21 +0800656 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
657 return new LinkAddress(BLUETOOTH_IFACE_ADDR);
658 }
659
660 return mPrivateAddressCoordinator.requestDownstreamAddress(this);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900661 }
662
markchien74a4fa92019-09-09 20:50:49 +0800663 private boolean startIPv6() {
664 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
665 if (mInterfaceParams == null) {
666 mLog.e("Failed to find InterfaceParams");
667 stopIPv6();
668 return false;
669 }
670
671 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
672 if (!mRaDaemon.start()) {
673 stopIPv6();
674 return false;
675 }
676
677 return true;
678 }
679
680 private void stopIPv6() {
681 mInterfaceParams = null;
682 setRaParams(null);
683
684 if (mRaDaemon != null) {
685 mRaDaemon.stop();
686 mRaDaemon = null;
687 }
688 }
689
690 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
691 // LinkProperties. These have extraneous data filtered out and only the
692 // necessary prefixes included (per its prefix distribution policy).
693 //
694 // TODO: Evaluate using a data structure than is more directly suited to
695 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800696 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800697 if (mRaDaemon == null) return;
698
699 // Avoid unnecessary work on spurious updates.
700 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
701 return;
702 }
703
704 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900705 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800706
707 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900708 final String upstreamIface = v6only.getInterfaceName();
709
markchien74a4fa92019-09-09 20:50:49 +0800710 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700711 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800712 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
713
markchiend63c4f32020-05-21 17:38:28 +0800714 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800715
716 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
717 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
718
719 final IpPrefix prefix = new IpPrefix(
720 linkAddr.getAddress(), linkAddr.getPrefixLength());
721 params.prefixes.add(prefix);
722
723 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
724 if (dnsServer != null) {
725 params.dnses.add(dnsServer);
726 }
727 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900728
729 upstreamIfindex = mDeps.getIfindex(upstreamIface);
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800730
731 // Add upstream index to name mapping for the tether stats usage in the coordinator.
732 // Although this mapping could be added by both class Tethering and IpServer, adding
733 // mapping from IpServer guarantees that the mapping is added before the adding
734 // forwarding rules. That is because there are different state machines in both
735 // classes. It is hard to guarantee the link property update order between multiple
736 // state machines.
737 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfindex, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800738 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900739
markchien74a4fa92019-09-09 20:50:49 +0800740 // If v6only is null, we pass in null to setRaParams(), which handles
741 // deprecation of any existing RA data.
742
743 setRaParams(params);
744 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900745
746 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
747 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800748 }
749
Xiao Ma4455d6b2020-04-09 10:13:44 +0900750 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
751 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
752 mNetd, toBeRemoved);
753 if (removalFailures > 0) {
754 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
755 removalFailures));
756 }
757
758 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
759 }
760
761 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
762 try {
763 // It's safe to call networkAddInterface() even if
764 // the interface is already in the local_network.
765 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
766 try {
767 // Add routes from local network. Note that adding routes that
768 // already exist does not cause an error (EEXIST is silently ignored).
769 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
770 } catch (IllegalStateException e) {
771 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
772 return;
773 }
774 } catch (ServiceSpecificException | RemoteException e) {
775 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
776 return;
777 }
778
779 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
780 }
781
markchien74a4fa92019-09-09 20:50:49 +0800782 private void configureLocalIPv6Routes(
783 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
784 // [1] Remove the routes that are deprecated.
785 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900786 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800787 }
788
789 // [2] Add only the routes that have not previously been added.
790 if (newPrefixes != null && !newPrefixes.isEmpty()) {
791 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
792 if (mLastRaParams != null) {
793 addedPrefixes.removeAll(mLastRaParams.prefixes);
794 }
795
796 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900797 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800798 }
799 }
800 }
801
802 private void configureLocalIPv6Dns(
803 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
804 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
805 if (mNetd == null) {
806 if (newDnses != null) newDnses.clear();
807 mLog.e("No netd service instance available; not setting local IPv6 addresses");
808 return;
809 }
810
811 // [1] Remove deprecated local DNS IP addresses.
812 if (!deprecatedDnses.isEmpty()) {
813 for (Inet6Address dns : deprecatedDnses) {
814 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
815 mLog.e("Failed to remove local dns IP " + dns);
816 }
817
818 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
819 }
820 }
821
822 // [2] Add only the local DNS IP addresses that have not previously been added.
823 if (newDnses != null && !newDnses.isEmpty()) {
824 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
825 if (mLastRaParams != null) {
826 addedDnses.removeAll(mLastRaParams.dnses);
827 }
828
829 for (Inet6Address dns : addedDnses) {
830 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
831 mLog.e("Failed to add local dns IP " + dns);
832 newDnses.remove(dns);
833 }
834
835 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
836 }
837 }
838
839 try {
840 mNetd.tetherApplyDnsInterfaces();
841 } catch (ServiceSpecificException | RemoteException e) {
842 mLog.e("Failed to update local DNS caching server");
843 if (newDnses != null) newDnses.clear();
844 }
845 }
846
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900847 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800848 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
849 // offload is disabled. Add this check just in case.
850 // TODO: Perhaps remove this protection check.
851 if (!mUsingBpfOffload) return;
852
Hungming Chen269c0882020-05-06 14:57:35 +0800853 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900854 }
855
Hungming Chen269c0882020-05-06 14:57:35 +0800856 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800857 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800858 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800859 if (!mUsingBpfOffload) return;
860
Hungming Chen269c0882020-05-06 14:57:35 +0800861 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900862 }
863
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900864 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800865 if (!mUsingBpfOffload) return;
866
867 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900868 }
869
Hungming Chen269c0882020-05-06 14:57:35 +0800870 private void updateIpv6ForwardingRule(int newIfindex) {
871 // TODO: Perhaps remove this protection check.
872 // See the related comment in #addIpv6ForwardingRule.
873 if (!mUsingBpfOffload) return;
874
875 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900876 }
877
878 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
879 // changes or if a neighbor event is received.
880 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
881 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900882 // If we no longer have an upstream, clear forwarding rules and do nothing else.
883 if (upstreamIfindex == 0) {
884 clearIpv6ForwardingRules();
885 return;
886 }
887
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900888 // If the upstream interface has changed, remove all rules and re-add them with the new
889 // upstream interface.
890 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800891 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900892 }
893
894 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900895 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900896 if (e == null) return;
897 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
898 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
899 return;
900 }
901
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900902 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
903 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
904 // add rules with a null MAC, only delete them.
905 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900906 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900907 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900908 if (e.isValid()) {
909 addIpv6ForwardingRule(rule);
910 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800911 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900912 }
913 }
914
915 private void handleNeighborEvent(NeighborEvent e) {
916 if (mInterfaceParams != null
917 && mInterfaceParams.index == e.ifindex
918 && mInterfaceParams.hasMacAddress) {
919 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
920 }
921 }
922
Xiao Ma4455d6b2020-04-09 10:13:44 +0900923 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
924 if (!currentPrefix.contains(mIpv4Address.getAddress())
925 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
926 Log.e(TAG, "Invalid prefix: " + currentPrefix);
927 return;
928 }
929
930 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchienc9daba32020-02-12 00:19:21 +0800931 mIpv4Address = requestIpv4Address();
932 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900933 mLog.e("Fail to request a new downstream prefix");
934 return;
935 }
markchienc9daba32020-02-12 00:19:21 +0800936 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +0900937
938 // Add new IPv4 address on the interface.
939 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
940 mLog.e("Failed to add new IP " + srvAddr);
941 return;
942 }
943
944 // Remove deprecated routes from local network.
945 removeRoutesFromLocalNetwork(
946 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
947 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
948
949 // Add new routes to local network.
950 addRoutesToLocalNetwork(
951 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
952 mLinkProperties.addLinkAddress(mIpv4Address);
953
954 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
955 // listen on the interface configured with new IPv4 address, that results DNS validation
956 // failure of downstream client even if appropriate routes have been configured.
957 try {
958 mNetd.tetherApplyDnsInterfaces();
959 } catch (ServiceSpecificException | RemoteException e) {
960 mLog.e("Failed to update local DNS caching server");
961 return;
962 }
963 sendLinkProperties();
964
965 // Notify DHCP server that new prefix/route has been applied on IpServer.
966 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
967 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
968 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
969 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
970 try {
971 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
972 @Override
973 public void callback(int statusCode) {
974 if (statusCode != STATUS_SUCCESS) {
975 mLog.e("Error updating DHCP serving params: " + statusCode);
976 }
977 }
978 });
979 } catch (RemoteException e) {
980 mLog.e("Error updating DHCP serving params", e);
981 }
982 }
983
markchiend63c4f32020-05-21 17:38:28 +0800984 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +0800985 try {
986 int upstreamHopLimit = Integer.parseUnsignedInt(
987 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +0800988 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +0800989 // Cap the hop limit to 255.
990 return (byte) Integer.min(upstreamHopLimit, 255);
991 } catch (Exception e) {
992 mLog.e("Failed to find upstream interface hop limit", e);
993 }
994 return RaParams.DEFAULT_HOPLIMIT;
995 }
996
997 private void setRaParams(RaParams newParams) {
998 if (mRaDaemon != null) {
999 final RaParams deprecatedParams =
1000 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1001
1002 configureLocalIPv6Routes(deprecatedParams.prefixes,
1003 (newParams != null) ? newParams.prefixes : null);
1004
1005 configureLocalIPv6Dns(deprecatedParams.dnses,
1006 (newParams != null) ? newParams.dnses : null);
1007
1008 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1009 }
1010
1011 mLastRaParams = newParams;
1012 }
1013
1014 private void logMessage(State state, int what) {
1015 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
1016 }
1017
1018 private void sendInterfaceState(int newInterfaceState) {
1019 mServingMode = newInterfaceState;
1020 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1021 sendLinkProperties();
1022 }
1023
1024 private void sendLinkProperties() {
1025 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1026 }
1027
1028 private void resetLinkProperties() {
1029 mLinkProperties.clear();
1030 mLinkProperties.setInterfaceName(mIfaceName);
1031 }
1032
markchienf053e4b2020-03-16 21:49:48 +08001033 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001034 // Ignore static address configuration if they are invalid or null. In theory, static
1035 // addresses should not be invalid here because TetheringManager do not allow caller to
1036 // specify invalid static address configuration.
1037 if (request == null || request.localIPv4Address == null
1038 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1039 request.localIPv4Address, request.staticClientAddress)) {
1040 return;
1041 }
markchienf053e4b2020-03-16 21:49:48 +08001042
1043 mStaticIpv4ServerAddr = request.localIPv4Address;
1044 mStaticIpv4ClientAddr = request.staticClientAddress;
1045 }
1046
markchien74a4fa92019-09-09 20:50:49 +08001047 class InitialState extends State {
1048 @Override
1049 public void enter() {
1050 sendInterfaceState(STATE_AVAILABLE);
1051 }
1052
1053 @Override
1054 public boolean processMessage(Message message) {
1055 logMessage(this, message.what);
1056 switch (message.what) {
1057 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001058 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001059 switch (message.arg1) {
1060 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001061 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001062 transitionTo(mLocalHotspotState);
1063 break;
1064 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001065 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001066 transitionTo(mTetheredState);
1067 break;
1068 default:
1069 mLog.e("Invalid tethering interface serving state specified.");
1070 }
1071 break;
1072 case CMD_INTERFACE_DOWN:
1073 transitionTo(mUnavailableState);
1074 break;
1075 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001076 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001077 break;
1078 default:
1079 return NOT_HANDLED;
1080 }
1081 return HANDLED;
1082 }
1083 }
1084
1085 class BaseServingState extends State {
1086 @Override
1087 public void enter() {
1088 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001089 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001090 return;
1091 }
1092
1093 try {
markchienc9daba32020-02-12 00:19:21 +08001094 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001095 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001096 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001097 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001098 return;
1099 }
1100
1101 if (!startIPv6()) {
1102 mLog.e("Failed to startIPv6");
1103 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1104 return;
1105 }
1106 }
1107
1108 @Override
1109 public void exit() {
1110 // Note that at this point, we're leaving the tethered state. We can fail any
1111 // of these operations, but it doesn't really change that we have to try them
1112 // all in sequence.
1113 stopIPv6();
1114
1115 try {
markchien12c5bb82020-01-07 14:43:17 +08001116 NetdUtils.untetherInterface(mNetd, mIfaceName);
1117 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001118 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001119 mLog.e("Failed to untether interface: " + e);
1120 }
1121
1122 stopIPv4();
1123
1124 resetLinkProperties();
1125 }
1126
1127 @Override
1128 public boolean processMessage(Message message) {
1129 logMessage(this, message.what);
1130 switch (message.what) {
1131 case CMD_TETHER_UNREQUESTED:
1132 transitionTo(mInitialState);
1133 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1134 break;
1135 case CMD_INTERFACE_DOWN:
1136 transitionTo(mUnavailableState);
1137 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1138 break;
1139 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001140 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001141 sendLinkProperties();
1142 break;
1143 case CMD_IP_FORWARDING_ENABLE_ERROR:
1144 case CMD_IP_FORWARDING_DISABLE_ERROR:
1145 case CMD_START_TETHERING_ERROR:
1146 case CMD_STOP_TETHERING_ERROR:
1147 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001148 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001149 transitionTo(mInitialState);
1150 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001151 case CMD_NEW_PREFIX_REQUEST:
1152 handleNewPrefixRequest((IpPrefix) message.obj);
1153 break;
markchienc9daba32020-02-12 00:19:21 +08001154 case CMD_NOTIFY_PREFIX_CONFLICT:
1155 mLog.i("restart tethering: " + mInterfaceType);
1156 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1157 transitionTo(mWaitingForRestartState);
1158 break;
markchien74a4fa92019-09-09 20:50:49 +08001159 default:
1160 return false;
1161 }
1162 return true;
1163 }
1164 }
1165
1166 // Handling errors in BaseServingState.enter() by transitioning is
1167 // problematic because transitioning during a multi-state jump yields
1168 // a Log.wtf(). Ultimately, there should be only one ServingState,
1169 // and forwarding and NAT rules should be handled by a coordinating
1170 // functional element outside of IpServer.
1171 class LocalHotspotState extends BaseServingState {
1172 @Override
1173 public void enter() {
1174 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001175 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001176 transitionTo(mInitialState);
1177 }
1178
1179 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1180 sendInterfaceState(STATE_LOCAL_ONLY);
1181 }
1182
1183 @Override
1184 public boolean processMessage(Message message) {
1185 if (super.processMessage(message)) return true;
1186
1187 logMessage(this, message.what);
1188 switch (message.what) {
1189 case CMD_TETHER_REQUESTED:
1190 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1191 break;
1192 case CMD_TETHER_CONNECTION_CHANGED:
1193 // Ignored in local hotspot state.
1194 break;
1195 default:
1196 return false;
1197 }
1198 return true;
1199 }
1200 }
1201
1202 // Handling errors in BaseServingState.enter() by transitioning is
1203 // problematic because transitioning during a multi-state jump yields
1204 // a Log.wtf(). Ultimately, there should be only one ServingState,
1205 // and forwarding and NAT rules should be handled by a coordinating
1206 // functional element outside of IpServer.
1207 class TetheredState extends BaseServingState {
1208 @Override
1209 public void enter() {
1210 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001211 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001212 transitionTo(mInitialState);
1213 }
1214
1215 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1216 sendInterfaceState(STATE_TETHERED);
1217 }
1218
1219 @Override
1220 public void exit() {
1221 cleanupUpstream();
1222 super.exit();
1223 }
1224
1225 private void cleanupUpstream() {
1226 if (mUpstreamIfaceSet == null) return;
1227
1228 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1229 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001230 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001231 }
1232
1233 private void cleanupUpstreamInterface(String upstreamIface) {
1234 // Note that we don't care about errors here.
1235 // Sometimes interfaces are gone before we get
1236 // to remove their rules, which generates errors.
1237 // Just do the best we can.
1238 try {
markchien12c5bb82020-01-07 14:43:17 +08001239 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1240 } catch (RemoteException | ServiceSpecificException e) {
1241 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001242 }
1243 try {
markchien12c5bb82020-01-07 14:43:17 +08001244 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1245 } catch (RemoteException | ServiceSpecificException e) {
1246 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001247 }
1248 }
1249
1250 @Override
1251 public boolean processMessage(Message message) {
1252 if (super.processMessage(message)) return true;
1253
1254 logMessage(this, message.what);
1255 switch (message.what) {
1256 case CMD_TETHER_REQUESTED:
1257 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1258 break;
1259 case CMD_TETHER_CONNECTION_CHANGED:
1260 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1261 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1262 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1263 break;
1264 }
1265
1266 if (newUpstreamIfaceSet == null) {
1267 cleanupUpstream();
1268 break;
1269 }
1270
1271 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1272 cleanupUpstreamInterface(removed);
1273 }
1274
1275 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1276 // This makes the call to cleanupUpstream() in the error
1277 // path for any interface neatly cleanup all the interfaces.
1278 mUpstreamIfaceSet = newUpstreamIfaceSet;
1279
1280 for (String ifname : added) {
1281 try {
markchien12c5bb82020-01-07 14:43:17 +08001282 mNetd.tetherAddForward(mIfaceName, ifname);
1283 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1284 } catch (RemoteException | ServiceSpecificException e) {
1285 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001286 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001287 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001288 transitionTo(mInitialState);
1289 return true;
1290 }
1291 }
1292 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001293 case CMD_NEIGHBOR_EVENT:
1294 handleNeighborEvent((NeighborEvent) message.obj);
1295 break;
markchien74a4fa92019-09-09 20:50:49 +08001296 default:
1297 return false;
1298 }
1299 return true;
1300 }
1301
1302 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1303 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1304 if (mUpstreamIfaceSet != null && newIfaces != null) {
1305 return mUpstreamIfaceSet.equals(newIfaces);
1306 }
1307 return false;
1308 }
1309
1310 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1311 if (mUpstreamIfaceSet == null) return new HashSet<>();
1312
1313 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1314 removed.removeAll(newIfaces.ifnames);
1315 return removed;
1316 }
1317
1318 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1319 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1320 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1321 return added;
1322 }
1323 }
1324
1325 /**
1326 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001327 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001328 * specific state machine from its list of possible recipients of
1329 * tethering requests. The state machine itself will hang around until
1330 * the garbage collector finds it.
1331 */
1332 class UnavailableState extends State {
1333 @Override
1334 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001335 mIpNeighborMonitor.stop();
markchien9b4d7572019-12-25 19:40:32 +08001336 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001337 sendInterfaceState(STATE_UNAVAILABLE);
1338 }
1339 }
1340
markchienc9daba32020-02-12 00:19:21 +08001341 class WaitingForRestartState extends State {
1342 @Override
1343 public boolean processMessage(Message message) {
1344 logMessage(this, message.what);
1345 switch (message.what) {
1346 case CMD_TETHER_UNREQUESTED:
1347 transitionTo(mInitialState);
1348 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1349 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1350 break;
1351 case CMD_INTERFACE_DOWN:
1352 transitionTo(mUnavailableState);
1353 mLog.i("Untethered (interface down) and restarting" + mIfaceName);
1354 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1355 break;
1356 default:
1357 return false;
1358 }
1359 return true;
1360 }
1361 }
1362
markchien74a4fa92019-09-09 20:50:49 +08001363 // Accumulate routes representing "prefixes to be assigned to the local
1364 // interface", for subsequent modification of local_network routing.
1365 private static ArrayList<RouteInfo> getLocalRoutesFor(
1366 String ifname, HashSet<IpPrefix> prefixes) {
1367 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1368 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001369 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001370 }
1371 return localRoutes;
1372 }
1373
1374 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1375 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1376 final byte[] dnsBytes = localPrefix.getRawAddress();
1377 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1378 try {
1379 return Inet6Address.getByAddress(null, dnsBytes, 0);
1380 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001381 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001382 return null;
1383 }
1384 }
1385
1386 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1387 final byte random = (byte) (new Random()).nextInt();
1388 for (int value : excluded) {
1389 if (random == value) return dflt;
1390 }
1391 return random;
1392 }
1393}