blob: 088b88cb3145827268a97a505a581248294824e2 [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;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090080import java.util.LinkedHashMap;
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;
markchien74a4fa92019-09-09 20:50:49 +0800200 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800201 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800202 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800203 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800204 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800205 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800206 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800207 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800208 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800209 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800210 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800211 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800212 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800213 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900214 // new neighbor cache entry on our interface
215 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900216 // request from DHCP server that it wants to have a new prefix
217 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800218 // request from PrivateAddressCoordinator to restart tethering.
219 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800220
221 private final State mInitialState;
222 private final State mLocalHotspotState;
223 private final State mTetheredState;
224 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800225 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800226
227 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800228 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800229 @NonNull
230 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800231 private final Callback mCallback;
232 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800233 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800234
235 private final String mIfaceName;
236 private final int mInterfaceType;
237 private final LinkProperties mLinkProperties;
238 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800239 private final boolean mUsingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800240
241 private final Dependencies mDeps;
242
243 private int mLastError;
244 private int mServingMode;
245 private InterfaceSet mUpstreamIfaceSet; // may change over time
246 private InterfaceParams mInterfaceParams;
247 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
248 // properties are those selected by the IPv6TetheringCoordinator and relayed
249 // to us. By comparison, mLinkProperties contains the addresses and directly
250 // connected routes that have been formed from these properties iff. we have
251 // succeeded in configuring them and are able to announce them within Router
252 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
253 private LinkProperties mLastIPv6LinkProperties;
254 private RouterAdvertisementDaemon mRaDaemon;
255
256 // To be accessed only on the handler thread
257 private int mDhcpServerStartIndex = 0;
258 private IDhcpServer mDhcpServer;
259 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800260
261 private LinkAddress mStaticIpv4ServerAddr;
262 private LinkAddress mStaticIpv4ClientAddr;
263
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900264 @NonNull
265 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800266
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900267 private int mLastIPv6UpstreamIfindex = 0;
268
269 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
270 public void accept(NeighborEvent e) {
271 sendMessage(CMD_NEIGHBOR_EVENT, e);
272 }
273 }
274
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900275 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
276 new LinkedHashMap<>();
277
278 private final IpNeighborMonitor mIpNeighborMonitor;
279
markchienc9daba32020-02-12 00:19:21 +0800280 private LinkAddress mIpv4Address;
281
Hungming Chen5bc3af92020-05-12 19:15:24 +0800282 // TODO: Add a dependency object to pass the data members or variables from the tethering
283 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800284 public IpServer(
285 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800286 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
287 boolean usingLegacyDhcp, boolean usingBpfOffload,
markchienc9daba32020-02-12 00:19:21 +0800288 PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800289 super(ifaceName, looper);
290 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800291 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800292 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800293 mCallback = callback;
294 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
295 mIfaceName = ifaceName;
296 mInterfaceType = interfaceType;
297 mLinkProperties = new LinkProperties();
298 mUsingLegacyDhcp = usingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800299 mUsingBpfOffload = usingBpfOffload;
markchienc9daba32020-02-12 00:19:21 +0800300 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800301 mDeps = deps;
302 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800303 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800304 mServingMode = STATE_AVAILABLE;
305
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900306 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
307 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800308
Hungming Chen5bc3af92020-05-12 19:15:24 +0800309 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800310 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800311 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800312 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800313 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
314 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900315 }
316
markchien74a4fa92019-09-09 20:50:49 +0800317 mInitialState = new InitialState();
318 mLocalHotspotState = new LocalHotspotState();
319 mTetheredState = new TetheredState();
320 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800321 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800322 addState(mInitialState);
323 addState(mLocalHotspotState);
324 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800325 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800326 addState(mUnavailableState);
327
328 setInitialState(mInitialState);
329 }
330
331 /** Interface name which IpServer served.*/
332 public String interfaceName() {
333 return mIfaceName;
334 }
335
336 /**
markchien9b4d7572019-12-25 19:40:32 +0800337 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800338 */
339 public int interfaceType() {
340 return mInterfaceType;
341 }
342
343 /** Last error from this IpServer. */
344 public int lastError() {
345 return mLastError;
346 }
347
348 /** Serving mode is the current state of IpServer state machine. */
349 public int servingMode() {
350 return mServingMode;
351 }
352
353 /** The properties of the network link which IpServer is serving. */
354 public LinkProperties linkProperties() {
355 return new LinkProperties(mLinkProperties);
356 }
357
markchienc9daba32020-02-12 00:19:21 +0800358 /** The address which IpServer is using. */
359 public LinkAddress getAddress() {
360 return mIpv4Address;
361 }
362
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900363 /**
364 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
365 * thread.
366 */
367 public List<TetheredClient> getAllLeases() {
368 return Collections.unmodifiableList(mDhcpLeases);
369 }
370
markchien74a4fa92019-09-09 20:50:49 +0800371 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
372 public void stop() {
373 sendMessage(CMD_INTERFACE_DOWN);
374 }
375
376 /**
377 * Tethering is canceled. IpServer state machine will be available and wait for
378 * next tethering request.
379 */
380 public void unwanted() {
381 sendMessage(CMD_TETHER_UNREQUESTED);
382 }
383
384 /** Internals. */
385
386 private boolean startIPv4() {
387 return configureIPv4(true);
388 }
389
390 /**
391 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
392 * handler.
393 *
394 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
395 * with different implementations of the callback, to differentiate handling of success/error in
396 * each call.
397 */
398 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
399 @Override
400 public void onStatusAvailable(int statusCode) {
401 getHandler().post(() -> callback(statusCode));
402 }
403
404 public abstract void callback(int statusCode);
405
406 @Override
407 public int getInterfaceVersion() {
408 return this.VERSION;
409 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900410
411 @Override
412 public String getInterfaceHash() {
413 return this.HASH;
414 }
markchien74a4fa92019-09-09 20:50:49 +0800415 }
416
417 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
418 private final int mStartIndex;
419
420 private DhcpServerCallbacksImpl(int startIndex) {
421 mStartIndex = startIndex;
422 }
423
424 @Override
425 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
426 getHandler().post(() -> {
427 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
428 if (mStartIndex != mDhcpServerStartIndex) {
429 // This start request is obsolete. When the |server| binder token goes out of
430 // scope, the garbage collector will finalize it, which causes the network stack
431 // process garbage collector to collect the server itself.
432 return;
433 }
434
435 if (statusCode != STATUS_SUCCESS) {
436 mLog.e("Error obtaining DHCP server: " + statusCode);
437 handleError();
438 return;
439 }
440
441 mDhcpServer = server;
442 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900443 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800444 @Override
445 public void callback(int startStatusCode) {
446 if (startStatusCode != STATUS_SUCCESS) {
447 mLog.e("Error starting DHCP server: " + startStatusCode);
448 handleError();
449 }
450 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900451 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800452 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800453 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800454 }
455 });
456 }
457
458 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800459 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800460 transitionTo(mInitialState);
461 }
462 }
463
Xiao Ma4455d6b2020-04-09 10:13:44 +0900464 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900465 @Override
466 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
467 final ArrayList<TetheredClient> leases = new ArrayList<>();
468 for (DhcpLeaseParcelable lease : leaseParcelables) {
469 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900470 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
471 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
472 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900473
474 final MacAddress macAddress;
475 try {
476 macAddress = MacAddress.fromBytes(lease.hwAddr);
477 } catch (IllegalArgumentException e) {
478 Log.wtf(TAG, "Invalid address received from DhcpServer: "
479 + Arrays.toString(lease.hwAddr));
480 return;
481 }
482
483 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900484 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900485 leases.add(new TetheredClient(
486 macAddress,
487 Collections.singletonList(addressInfo),
488 mInterfaceType));
489 }
490
491 getHandler().post(() -> {
492 mDhcpLeases = leases;
493 mCallback.dhcpLeasesChanged();
494 });
495 }
496
497 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900498 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
499 Objects.requireNonNull(currentPrefix);
500 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900501 }
502
503 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900504 public int getInterfaceVersion() {
505 return this.VERSION;
506 }
507
508 @Override
509 public String getInterfaceHash() throws RemoteException {
510 return this.HASH;
511 }
512 }
513
Xiao Ma4455d6b2020-04-09 10:13:44 +0900514 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
515 Objects.requireNonNull(ipv4Address);
516 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
517 }
518
519 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
520 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
521 @Nullable Inet4Address clientAddr) {
522 final boolean changePrefixOnDecline =
523 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
524 return new DhcpServingParamsParcelExt()
525 .setDefaultRouters(defaultRouter)
526 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
527 .setDnsServers(dnsServer)
528 .setServerAddr(serverAddr)
529 .setMetered(true)
530 .setSingleClientAddr(clientAddr)
531 .setChangePrefixOnDecline(changePrefixOnDecline);
532 // TODO: also advertise link MTU
533 }
534
markchien245352e2020-02-27 20:27:18 +0800535 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800536 if (mUsingLegacyDhcp) {
537 return true;
538 }
markchien245352e2020-02-27 20:27:18 +0800539
540 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800541 final Inet4Address clientAddr = clientLinkAddr == null ? null :
542 (Inet4Address) clientLinkAddr.getAddress();
543
Xiao Ma4455d6b2020-04-09 10:13:44 +0900544 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
545 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800546 mDhcpServerStartIndex++;
547 mDeps.makeDhcpServer(
548 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
549 return true;
550 }
551
552 private void stopDhcp() {
553 // Make all previous start requests obsolete so servers are not started later
554 mDhcpServerStartIndex++;
555
556 if (mDhcpServer != null) {
557 try {
558 mDhcpServer.stop(new OnHandlerStatusCallback() {
559 @Override
560 public void callback(int statusCode) {
561 if (statusCode != STATUS_SUCCESS) {
562 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800563 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800564 // Not much more we can do here
565 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900566 mDhcpLeases.clear();
567 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800568 }
569 });
570 mDhcpServer = null;
571 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900572 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800573 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800574 }
575 }
576 }
577
markchien245352e2020-02-27 20:27:18 +0800578 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
579 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800580 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800581 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800582 } else {
583 stopDhcp();
584 return true;
585 }
586 }
587
588 private void stopIPv4() {
589 configureIPv4(false);
590 // NOTE: All of configureIPv4() will be refactored out of existence
591 // into calls to InterfaceController, shared with startIPv4().
592 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800593 mPrivateAddressCoordinator.releaseDownstream(this);
markchien12c5bb82020-01-07 14:43:17 +0800594 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800595 mStaticIpv4ServerAddr = null;
596 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800597 }
598
markchien74a4fa92019-09-09 20:50:49 +0800599 private boolean configureIPv4(boolean enabled) {
600 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
601
markchienc9daba32020-02-12 00:19:21 +0800602 if (enabled) {
603 mIpv4Address = requestIpv4Address();
604 }
605
606 if (mIpv4Address == null) {
607 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800608 return false;
markchien74a4fa92019-09-09 20:50:49 +0800609 }
610
markchienc9daba32020-02-12 00:19:21 +0800611 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
612 // BT configures the interface elsewhere: only start DHCP.
613 // TODO: make all tethering types behave the same way, and delete the bluetooth
614 // code that calls into NetworkManagementService directly.
615 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
616 }
617
618 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
619
markchien12c5bb82020-01-07 14:43:17 +0800620 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800621 if (mInterfaceType == TetheringManager.TETHERING_WIFI
622 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800623 // The WiFi stack has ownership of the interface up/down state.
624 // It is unclear whether the Bluetooth or USB stacks will manage their own
625 // state.
626 setIfaceUp = null;
627 } else {
628 setIfaceUp = enabled;
629 }
630 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
631 mLog.e("Error configuring interface");
632 if (!enabled) stopDhcp();
633 return false;
634 }
markchien74a4fa92019-09-09 20:50:49 +0800635
markchien74a4fa92019-09-09 20:50:49 +0800636 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800637 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900638 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800639 } else {
markchien12c5bb82020-01-07 14:43:17 +0800640 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900641 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800642 }
markchien245352e2020-02-27 20:27:18 +0800643 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800644 }
645
markchienc9daba32020-02-12 00:19:21 +0800646 private LinkAddress requestIpv4Address() {
647 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800648
markchienc9daba32020-02-12 00:19:21 +0800649 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
650 return new LinkAddress(BLUETOOTH_IFACE_ADDR);
651 }
652
653 return mPrivateAddressCoordinator.requestDownstreamAddress(this);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900654 }
655
markchien74a4fa92019-09-09 20:50:49 +0800656 private boolean startIPv6() {
657 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
658 if (mInterfaceParams == null) {
659 mLog.e("Failed to find InterfaceParams");
660 stopIPv6();
661 return false;
662 }
663
664 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
665 if (!mRaDaemon.start()) {
666 stopIPv6();
667 return false;
668 }
669
670 return true;
671 }
672
673 private void stopIPv6() {
674 mInterfaceParams = null;
675 setRaParams(null);
676
677 if (mRaDaemon != null) {
678 mRaDaemon.stop();
679 mRaDaemon = null;
680 }
681 }
682
683 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
684 // LinkProperties. These have extraneous data filtered out and only the
685 // necessary prefixes included (per its prefix distribution policy).
686 //
687 // TODO: Evaluate using a data structure than is more directly suited to
688 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800689 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800690 if (mRaDaemon == null) return;
691
692 // Avoid unnecessary work on spurious updates.
693 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
694 return;
695 }
696
697 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900698 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800699
700 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900701 final String upstreamIface = v6only.getInterfaceName();
702
markchien74a4fa92019-09-09 20:50:49 +0800703 params = new RaParams();
Hungming Chen3d8fa882020-04-12 14:27:18 +0800704 // When BPF offload is enabled, we advertise an mtu lower by 16, which is the closest
705 // multiple of 8 >= 14, the ethernet header size. This makes kernel ebpf tethering
706 // offload happy. This hack should be reverted once we have the kernel fixed up.
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800707 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
708 // see RouterAdvertisementDaemon.java putMtu()
Hungming Chen3d8fa882020-04-12 14:27:18 +0800709 params.mtu = mUsingBpfOffload ? v6only.getMtu() - 16 : v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800710 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
711
markchiend63c4f32020-05-21 17:38:28 +0800712 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800713
714 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
715 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
716
717 final IpPrefix prefix = new IpPrefix(
718 linkAddr.getAddress(), linkAddr.getPrefixLength());
719 params.prefixes.add(prefix);
720
721 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
722 if (dnsServer != null) {
723 params.dnses.add(dnsServer);
724 }
725 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900726
727 upstreamIfindex = mDeps.getIfindex(upstreamIface);
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800728
729 // Add upstream index to name mapping for the tether stats usage in the coordinator.
730 // Although this mapping could be added by both class Tethering and IpServer, adding
731 // mapping from IpServer guarantees that the mapping is added before the adding
732 // forwarding rules. That is because there are different state machines in both
733 // classes. It is hard to guarantee the link property update order between multiple
734 // state machines.
735 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfindex, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800736 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900737
markchien74a4fa92019-09-09 20:50:49 +0800738 // If v6only is null, we pass in null to setRaParams(), which handles
739 // deprecation of any existing RA data.
740
741 setRaParams(params);
742 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900743
744 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
745 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800746 }
747
Xiao Ma4455d6b2020-04-09 10:13:44 +0900748 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
749 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
750 mNetd, toBeRemoved);
751 if (removalFailures > 0) {
752 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
753 removalFailures));
754 }
755
756 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
757 }
758
759 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
760 try {
761 // It's safe to call networkAddInterface() even if
762 // the interface is already in the local_network.
763 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
764 try {
765 // Add routes from local network. Note that adding routes that
766 // already exist does not cause an error (EEXIST is silently ignored).
767 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
768 } catch (IllegalStateException e) {
769 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
770 return;
771 }
772 } catch (ServiceSpecificException | RemoteException e) {
773 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
774 return;
775 }
776
777 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
778 }
779
markchien74a4fa92019-09-09 20:50:49 +0800780 private void configureLocalIPv6Routes(
781 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
782 // [1] Remove the routes that are deprecated.
783 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900784 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800785 }
786
787 // [2] Add only the routes that have not previously been added.
788 if (newPrefixes != null && !newPrefixes.isEmpty()) {
789 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
790 if (mLastRaParams != null) {
791 addedPrefixes.removeAll(mLastRaParams.prefixes);
792 }
793
794 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900795 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800796 }
797 }
798 }
799
800 private void configureLocalIPv6Dns(
801 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
802 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
803 if (mNetd == null) {
804 if (newDnses != null) newDnses.clear();
805 mLog.e("No netd service instance available; not setting local IPv6 addresses");
806 return;
807 }
808
809 // [1] Remove deprecated local DNS IP addresses.
810 if (!deprecatedDnses.isEmpty()) {
811 for (Inet6Address dns : deprecatedDnses) {
812 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
813 mLog.e("Failed to remove local dns IP " + dns);
814 }
815
816 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
817 }
818 }
819
820 // [2] Add only the local DNS IP addresses that have not previously been added.
821 if (newDnses != null && !newDnses.isEmpty()) {
822 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
823 if (mLastRaParams != null) {
824 addedDnses.removeAll(mLastRaParams.dnses);
825 }
826
827 for (Inet6Address dns : addedDnses) {
828 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
829 mLog.e("Failed to add local dns IP " + dns);
830 newDnses.remove(dns);
831 }
832
833 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
834 }
835 }
836
837 try {
838 mNetd.tetherApplyDnsInterfaces();
839 } catch (ServiceSpecificException | RemoteException e) {
840 mLog.e("Failed to update local DNS caching server");
841 if (newDnses != null) newDnses.clear();
842 }
843 }
844
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900845 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800846 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
847 // offload is disabled. Add this check just in case.
848 // TODO: Perhaps remove this protection check.
849 if (!mUsingBpfOffload) return;
850
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900851 try {
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900852 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900853 mIpv6ForwardingRules.put(rule.address, rule);
854 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900855 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900856 }
857 }
858
859 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800860 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
861 // offload is disabled. Add this check just in case.
862 // TODO: Perhaps remove this protection check.
863 if (!mUsingBpfOffload) return;
864
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900865 try {
Lorenzo Colittibeb28402020-04-03 22:05:14 +0900866 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900867 if (removeFromMap) {
868 mIpv6ForwardingRules.remove(rule.address);
869 }
870 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900871 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900872 }
873 }
874
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900875 private void clearIpv6ForwardingRules() {
876 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
877 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
878 }
879 mIpv6ForwardingRules.clear();
880 }
881
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900882 // Convenience method to replace a rule with the same rule on a new upstream interface.
883 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
884 // Relies on the fact that rules are in a map indexed by IP address.
885 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
886 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
887 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
888 }
889
890 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
891 // changes or if a neighbor event is received.
892 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
893 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900894 // If we no longer have an upstream, clear forwarding rules and do nothing else.
895 if (upstreamIfindex == 0) {
896 clearIpv6ForwardingRules();
897 return;
898 }
899
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900900 // If the upstream interface has changed, remove all rules and re-add them with the new
901 // upstream interface.
902 if (prevUpstreamIfindex != upstreamIfindex) {
903 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
904 updateIpv6ForwardingRule(rule, upstreamIfindex);
905 }
906 }
907
908 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900909 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900910 if (e == null) return;
911 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
912 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
913 return;
914 }
915
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900916 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
917 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
918 // add rules with a null MAC, only delete them.
919 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900920 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900921 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900922 if (e.isValid()) {
923 addIpv6ForwardingRule(rule);
924 } else {
925 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
926 }
927 }
928
929 private void handleNeighborEvent(NeighborEvent e) {
930 if (mInterfaceParams != null
931 && mInterfaceParams.index == e.ifindex
932 && mInterfaceParams.hasMacAddress) {
933 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
934 }
935 }
936
Xiao Ma4455d6b2020-04-09 10:13:44 +0900937 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
938 if (!currentPrefix.contains(mIpv4Address.getAddress())
939 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
940 Log.e(TAG, "Invalid prefix: " + currentPrefix);
941 return;
942 }
943
944 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchienc9daba32020-02-12 00:19:21 +0800945 mIpv4Address = requestIpv4Address();
946 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900947 mLog.e("Fail to request a new downstream prefix");
948 return;
949 }
markchienc9daba32020-02-12 00:19:21 +0800950 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +0900951
952 // Add new IPv4 address on the interface.
953 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
954 mLog.e("Failed to add new IP " + srvAddr);
955 return;
956 }
957
958 // Remove deprecated routes from local network.
959 removeRoutesFromLocalNetwork(
960 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
961 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
962
963 // Add new routes to local network.
964 addRoutesToLocalNetwork(
965 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
966 mLinkProperties.addLinkAddress(mIpv4Address);
967
968 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
969 // listen on the interface configured with new IPv4 address, that results DNS validation
970 // failure of downstream client even if appropriate routes have been configured.
971 try {
972 mNetd.tetherApplyDnsInterfaces();
973 } catch (ServiceSpecificException | RemoteException e) {
974 mLog.e("Failed to update local DNS caching server");
975 return;
976 }
977 sendLinkProperties();
978
979 // Notify DHCP server that new prefix/route has been applied on IpServer.
980 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
981 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
982 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
983 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
984 try {
985 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
986 @Override
987 public void callback(int statusCode) {
988 if (statusCode != STATUS_SUCCESS) {
989 mLog.e("Error updating DHCP serving params: " + statusCode);
990 }
991 }
992 });
993 } catch (RemoteException e) {
994 mLog.e("Error updating DHCP serving params", e);
995 }
996 }
997
markchiend63c4f32020-05-21 17:38:28 +0800998 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +0800999 try {
1000 int upstreamHopLimit = Integer.parseUnsignedInt(
1001 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001002 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001003 // Cap the hop limit to 255.
1004 return (byte) Integer.min(upstreamHopLimit, 255);
1005 } catch (Exception e) {
1006 mLog.e("Failed to find upstream interface hop limit", e);
1007 }
1008 return RaParams.DEFAULT_HOPLIMIT;
1009 }
1010
1011 private void setRaParams(RaParams newParams) {
1012 if (mRaDaemon != null) {
1013 final RaParams deprecatedParams =
1014 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1015
1016 configureLocalIPv6Routes(deprecatedParams.prefixes,
1017 (newParams != null) ? newParams.prefixes : null);
1018
1019 configureLocalIPv6Dns(deprecatedParams.dnses,
1020 (newParams != null) ? newParams.dnses : null);
1021
1022 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1023 }
1024
1025 mLastRaParams = newParams;
1026 }
1027
1028 private void logMessage(State state, int what) {
1029 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
1030 }
1031
1032 private void sendInterfaceState(int newInterfaceState) {
1033 mServingMode = newInterfaceState;
1034 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1035 sendLinkProperties();
1036 }
1037
1038 private void sendLinkProperties() {
1039 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1040 }
1041
1042 private void resetLinkProperties() {
1043 mLinkProperties.clear();
1044 mLinkProperties.setInterfaceName(mIfaceName);
1045 }
1046
markchienf053e4b2020-03-16 21:49:48 +08001047 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001048 // Ignore static address configuration if they are invalid or null. In theory, static
1049 // addresses should not be invalid here because TetheringManager do not allow caller to
1050 // specify invalid static address configuration.
1051 if (request == null || request.localIPv4Address == null
1052 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1053 request.localIPv4Address, request.staticClientAddress)) {
1054 return;
1055 }
markchienf053e4b2020-03-16 21:49:48 +08001056
1057 mStaticIpv4ServerAddr = request.localIPv4Address;
1058 mStaticIpv4ClientAddr = request.staticClientAddress;
1059 }
1060
markchien74a4fa92019-09-09 20:50:49 +08001061 class InitialState extends State {
1062 @Override
1063 public void enter() {
1064 sendInterfaceState(STATE_AVAILABLE);
1065 }
1066
1067 @Override
1068 public boolean processMessage(Message message) {
1069 logMessage(this, message.what);
1070 switch (message.what) {
1071 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001072 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001073 switch (message.arg1) {
1074 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001075 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001076 transitionTo(mLocalHotspotState);
1077 break;
1078 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001079 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001080 transitionTo(mTetheredState);
1081 break;
1082 default:
1083 mLog.e("Invalid tethering interface serving state specified.");
1084 }
1085 break;
1086 case CMD_INTERFACE_DOWN:
1087 transitionTo(mUnavailableState);
1088 break;
1089 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001090 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001091 break;
1092 default:
1093 return NOT_HANDLED;
1094 }
1095 return HANDLED;
1096 }
1097 }
1098
1099 class BaseServingState extends State {
1100 @Override
1101 public void enter() {
1102 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001103 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001104 return;
1105 }
1106
1107 try {
markchienc9daba32020-02-12 00:19:21 +08001108 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001109 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001110 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001111 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001112 return;
1113 }
1114
1115 if (!startIPv6()) {
1116 mLog.e("Failed to startIPv6");
1117 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1118 return;
1119 }
1120 }
1121
1122 @Override
1123 public void exit() {
1124 // Note that at this point, we're leaving the tethered state. We can fail any
1125 // of these operations, but it doesn't really change that we have to try them
1126 // all in sequence.
1127 stopIPv6();
1128
1129 try {
markchien12c5bb82020-01-07 14:43:17 +08001130 NetdUtils.untetherInterface(mNetd, mIfaceName);
1131 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001132 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001133 mLog.e("Failed to untether interface: " + e);
1134 }
1135
1136 stopIPv4();
1137
1138 resetLinkProperties();
1139 }
1140
1141 @Override
1142 public boolean processMessage(Message message) {
1143 logMessage(this, message.what);
1144 switch (message.what) {
1145 case CMD_TETHER_UNREQUESTED:
1146 transitionTo(mInitialState);
1147 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1148 break;
1149 case CMD_INTERFACE_DOWN:
1150 transitionTo(mUnavailableState);
1151 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1152 break;
1153 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001154 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001155 sendLinkProperties();
1156 break;
1157 case CMD_IP_FORWARDING_ENABLE_ERROR:
1158 case CMD_IP_FORWARDING_DISABLE_ERROR:
1159 case CMD_START_TETHERING_ERROR:
1160 case CMD_STOP_TETHERING_ERROR:
1161 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001162 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001163 transitionTo(mInitialState);
1164 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001165 case CMD_NEW_PREFIX_REQUEST:
1166 handleNewPrefixRequest((IpPrefix) message.obj);
1167 break;
markchienc9daba32020-02-12 00:19:21 +08001168 case CMD_NOTIFY_PREFIX_CONFLICT:
1169 mLog.i("restart tethering: " + mInterfaceType);
1170 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1171 transitionTo(mWaitingForRestartState);
1172 break;
markchien74a4fa92019-09-09 20:50:49 +08001173 default:
1174 return false;
1175 }
1176 return true;
1177 }
1178 }
1179
1180 // Handling errors in BaseServingState.enter() by transitioning is
1181 // problematic because transitioning during a multi-state jump yields
1182 // a Log.wtf(). Ultimately, there should be only one ServingState,
1183 // and forwarding and NAT rules should be handled by a coordinating
1184 // functional element outside of IpServer.
1185 class LocalHotspotState extends BaseServingState {
1186 @Override
1187 public void enter() {
1188 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001189 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001190 transitionTo(mInitialState);
1191 }
1192
1193 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1194 sendInterfaceState(STATE_LOCAL_ONLY);
1195 }
1196
1197 @Override
1198 public boolean processMessage(Message message) {
1199 if (super.processMessage(message)) return true;
1200
1201 logMessage(this, message.what);
1202 switch (message.what) {
1203 case CMD_TETHER_REQUESTED:
1204 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1205 break;
1206 case CMD_TETHER_CONNECTION_CHANGED:
1207 // Ignored in local hotspot state.
1208 break;
1209 default:
1210 return false;
1211 }
1212 return true;
1213 }
1214 }
1215
1216 // Handling errors in BaseServingState.enter() by transitioning is
1217 // problematic because transitioning during a multi-state jump yields
1218 // a Log.wtf(). Ultimately, there should be only one ServingState,
1219 // and forwarding and NAT rules should be handled by a coordinating
1220 // functional element outside of IpServer.
1221 class TetheredState extends BaseServingState {
1222 @Override
1223 public void enter() {
1224 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001225 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001226 transitionTo(mInitialState);
1227 }
1228
1229 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1230 sendInterfaceState(STATE_TETHERED);
1231 }
1232
1233 @Override
1234 public void exit() {
1235 cleanupUpstream();
1236 super.exit();
1237 }
1238
1239 private void cleanupUpstream() {
1240 if (mUpstreamIfaceSet == null) return;
1241
1242 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1243 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001244 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001245 }
1246
1247 private void cleanupUpstreamInterface(String upstreamIface) {
1248 // Note that we don't care about errors here.
1249 // Sometimes interfaces are gone before we get
1250 // to remove their rules, which generates errors.
1251 // Just do the best we can.
1252 try {
markchien12c5bb82020-01-07 14:43:17 +08001253 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1254 } catch (RemoteException | ServiceSpecificException e) {
1255 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001256 }
1257 try {
markchien12c5bb82020-01-07 14:43:17 +08001258 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1259 } catch (RemoteException | ServiceSpecificException e) {
1260 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001261 }
1262 }
1263
1264 @Override
1265 public boolean processMessage(Message message) {
1266 if (super.processMessage(message)) return true;
1267
1268 logMessage(this, message.what);
1269 switch (message.what) {
1270 case CMD_TETHER_REQUESTED:
1271 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1272 break;
1273 case CMD_TETHER_CONNECTION_CHANGED:
1274 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1275 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1276 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1277 break;
1278 }
1279
1280 if (newUpstreamIfaceSet == null) {
1281 cleanupUpstream();
1282 break;
1283 }
1284
1285 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1286 cleanupUpstreamInterface(removed);
1287 }
1288
1289 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1290 // This makes the call to cleanupUpstream() in the error
1291 // path for any interface neatly cleanup all the interfaces.
1292 mUpstreamIfaceSet = newUpstreamIfaceSet;
1293
1294 for (String ifname : added) {
1295 try {
markchien12c5bb82020-01-07 14:43:17 +08001296 mNetd.tetherAddForward(mIfaceName, ifname);
1297 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1298 } catch (RemoteException | ServiceSpecificException e) {
1299 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001300 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001301 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001302 transitionTo(mInitialState);
1303 return true;
1304 }
1305 }
1306 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001307 case CMD_NEIGHBOR_EVENT:
1308 handleNeighborEvent((NeighborEvent) message.obj);
1309 break;
markchien74a4fa92019-09-09 20:50:49 +08001310 default:
1311 return false;
1312 }
1313 return true;
1314 }
1315
1316 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1317 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1318 if (mUpstreamIfaceSet != null && newIfaces != null) {
1319 return mUpstreamIfaceSet.equals(newIfaces);
1320 }
1321 return false;
1322 }
1323
1324 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1325 if (mUpstreamIfaceSet == null) return new HashSet<>();
1326
1327 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1328 removed.removeAll(newIfaces.ifnames);
1329 return removed;
1330 }
1331
1332 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1333 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1334 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1335 return added;
1336 }
1337 }
1338
1339 /**
1340 * This state is terminal for the per interface state machine. At this
1341 * point, the master state machine should have removed this interface
1342 * specific state machine from its list of possible recipients of
1343 * tethering requests. The state machine itself will hang around until
1344 * the garbage collector finds it.
1345 */
1346 class UnavailableState extends State {
1347 @Override
1348 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001349 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001350 sendInterfaceState(STATE_UNAVAILABLE);
1351 }
1352 }
1353
markchienc9daba32020-02-12 00:19:21 +08001354 class WaitingForRestartState extends State {
1355 @Override
1356 public boolean processMessage(Message message) {
1357 logMessage(this, message.what);
1358 switch (message.what) {
1359 case CMD_TETHER_UNREQUESTED:
1360 transitionTo(mInitialState);
1361 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1362 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1363 break;
1364 case CMD_INTERFACE_DOWN:
1365 transitionTo(mUnavailableState);
1366 mLog.i("Untethered (interface down) and restarting" + mIfaceName);
1367 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1368 break;
1369 default:
1370 return false;
1371 }
1372 return true;
1373 }
1374 }
1375
markchien74a4fa92019-09-09 20:50:49 +08001376 // Accumulate routes representing "prefixes to be assigned to the local
1377 // interface", for subsequent modification of local_network routing.
1378 private static ArrayList<RouteInfo> getLocalRoutesFor(
1379 String ifname, HashSet<IpPrefix> prefixes) {
1380 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1381 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001382 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001383 }
1384 return localRoutes;
1385 }
1386
1387 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1388 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1389 final byte[] dnsBytes = localPrefix.getRawAddress();
1390 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1391 try {
1392 return Inet6Address.getByAddress(null, dnsBytes, 0);
1393 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001394 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001395 return null;
1396 }
1397 }
1398
1399 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1400 final byte random = (byte) (new Random()).nextInt();
1401 for (int value : excluded) {
1402 if (random == value) return dflt;
1403 }
1404 return random;
1405 }
1406}