blob: 9131317e8d70ef126e0ef1ce33cd8b6876a4bb9d [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;
Treehugger Robot5da10702020-03-30 04:23:55 +000020import 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;
Mark Chien2ecd3332020-05-29 22:07:37 +000024import static android.net.util.PrefixUtils.asIpPrefix;
markchien6cf0e552019-12-06 15:24:53 +080025import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Automerger Merge Worker0010ca02020-03-16 04:06:46 +000026import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080027
Remi NGUYEN VANe10b80d2020-06-08 15:40:06 +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;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +000039import 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 Ma06c8ba02020-04-06 11:24:48 +000044import 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 Ma65401342020-05-14 06:52:59 +000052import 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 Ma65401342020-05-14 06:52:59 +000063import 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 Chend50f53b2020-06-02 00:13:26 +000068import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chen810a3812020-06-02 00:13:45 +000069import com.android.networkstack.tethering.BpfCoordinator.Ipv6ForwardingRule;
Mark Chien2ecd3332020-05-29 22:07:37 +000070import 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
Mark Chien2ecd3332020-05-29 22:07:37 +0000112 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 Colitti6f532ba2020-04-14 09:21:19 +0000117 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() { }
Mark Chien2ecd3332020-05-29 22:07:37 +0000151
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 }
Mark Chien2ecd3332020-05-29 22:07:37 +0000188
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 Ma65401342020-05-14 06:52:59 +0000216 // request from DHCP server that it wants to have a new prefix
217 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
Mark Chien2ecd3332020-05-29 22:07:37 +0000218 // 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;
Mark Chien2ecd3332020-05-29 22:07:37 +0000225 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 Chend50f53b2020-06-02 00:13:26 +0000229 @NonNull
230 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800231 private final Callback mCallback;
232 private final InterfaceController mInterfaceCtrl;
Mark Chien2ecd3332020-05-29 22:07:37 +0000233 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;
Nucca Chen0bbfe122020-05-12 11:34:28 +0000239 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;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000260
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 IpNeighborMonitor mIpNeighborMonitor;
276
Mark Chien2ecd3332020-05-29 22:07:37 +0000277 private LinkAddress mIpv4Address;
278
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000279 // TODO: Add a dependency object to pass the data members or variables from the tethering
280 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800281 public IpServer(
282 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chend50f53b2020-06-02 00:13:26 +0000283 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
284 boolean usingLegacyDhcp, boolean usingBpfOffload,
Mark Chien2ecd3332020-05-29 22:07:37 +0000285 PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800286 super(ifaceName, looper);
287 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800288 mNetd = netd;
Hungming Chend50f53b2020-06-02 00:13:26 +0000289 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800290 mCallback = callback;
291 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
292 mIfaceName = ifaceName;
293 mInterfaceType = interfaceType;
294 mLinkProperties = new LinkProperties();
295 mUsingLegacyDhcp = usingLegacyDhcp;
Nucca Chen0bbfe122020-05-12 11:34:28 +0000296 mUsingBpfOffload = usingBpfOffload;
Mark Chien2ecd3332020-05-29 22:07:37 +0000297 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800298 mDeps = deps;
299 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800300 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800301 mServingMode = STATE_AVAILABLE;
302
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900303 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
304 new MyNeighborEventConsumer());
Nucca Chen0bbfe122020-05-12 11:34:28 +0000305
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000306 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Nucca Chen0bbfe122020-05-12 11:34:28 +0000307 // forwarding rules per client. If BPF offload is not supported, don't start listening
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000308 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Nucca Chen0bbfe122020-05-12 11:34:28 +0000309 // removeIpv6ForwardingRule.
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000310 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
311 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900312 }
313
markchien74a4fa92019-09-09 20:50:49 +0800314 mInitialState = new InitialState();
315 mLocalHotspotState = new LocalHotspotState();
316 mTetheredState = new TetheredState();
317 mUnavailableState = new UnavailableState();
Mark Chien2ecd3332020-05-29 22:07:37 +0000318 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800319 addState(mInitialState);
320 addState(mLocalHotspotState);
321 addState(mTetheredState);
Mark Chien2ecd3332020-05-29 22:07:37 +0000322 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800323 addState(mUnavailableState);
324
325 setInitialState(mInitialState);
326 }
327
328 /** Interface name which IpServer served.*/
329 public String interfaceName() {
330 return mIfaceName;
331 }
332
333 /**
markchien9b4d7572019-12-25 19:40:32 +0800334 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800335 */
336 public int interfaceType() {
337 return mInterfaceType;
338 }
339
340 /** Last error from this IpServer. */
341 public int lastError() {
342 return mLastError;
343 }
344
345 /** Serving mode is the current state of IpServer state machine. */
346 public int servingMode() {
347 return mServingMode;
348 }
349
350 /** The properties of the network link which IpServer is serving. */
351 public LinkProperties linkProperties() {
352 return new LinkProperties(mLinkProperties);
353 }
354
Mark Chien2ecd3332020-05-29 22:07:37 +0000355 /** The address which IpServer is using. */
356 public LinkAddress getAddress() {
357 return mIpv4Address;
358 }
359
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900360 /**
361 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
362 * thread.
363 */
364 public List<TetheredClient> getAllLeases() {
365 return Collections.unmodifiableList(mDhcpLeases);
366 }
367
markchien74a4fa92019-09-09 20:50:49 +0800368 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
369 public void stop() {
370 sendMessage(CMD_INTERFACE_DOWN);
371 }
372
373 /**
374 * Tethering is canceled. IpServer state machine will be available and wait for
375 * next tethering request.
376 */
377 public void unwanted() {
378 sendMessage(CMD_TETHER_UNREQUESTED);
379 }
380
381 /** Internals. */
382
383 private boolean startIPv4() {
384 return configureIPv4(true);
385 }
386
387 /**
388 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
389 * handler.
390 *
391 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
392 * with different implementations of the callback, to differentiate handling of success/error in
393 * each call.
394 */
395 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
396 @Override
397 public void onStatusAvailable(int statusCode) {
398 getHandler().post(() -> callback(statusCode));
399 }
400
401 public abstract void callback(int statusCode);
402
403 @Override
404 public int getInterfaceVersion() {
405 return this.VERSION;
406 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900407
408 @Override
409 public String getInterfaceHash() {
410 return this.HASH;
411 }
markchien74a4fa92019-09-09 20:50:49 +0800412 }
413
414 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
415 private final int mStartIndex;
416
417 private DhcpServerCallbacksImpl(int startIndex) {
418 mStartIndex = startIndex;
419 }
420
421 @Override
422 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
423 getHandler().post(() -> {
424 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
425 if (mStartIndex != mDhcpServerStartIndex) {
markchiena732b3a2020-07-22 21:28:48 +0800426 // This start request is obsolete. Explicitly stop the DHCP server to shut
427 // down its thread. When the |server| binder token goes out of scope, the
428 // garbage collector will finalize it, which causes the network stack process
429 // garbage collector to collect the server itself.
430 try {
431 server.stop(null);
432 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800433 return;
434 }
435
436 if (statusCode != STATUS_SUCCESS) {
437 mLog.e("Error obtaining DHCP server: " + statusCode);
438 handleError();
439 return;
440 }
441
442 mDhcpServer = server;
443 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900444 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800445 @Override
446 public void callback(int startStatusCode) {
447 if (startStatusCode != STATUS_SUCCESS) {
448 mLog.e("Error starting DHCP server: " + startStatusCode);
449 handleError();
450 }
451 }
Xiao Ma65401342020-05-14 06:52:59 +0000452 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800453 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800454 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800455 }
456 });
457 }
458
459 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800460 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800461 transitionTo(mInitialState);
462 }
463 }
464
Xiao Ma65401342020-05-14 06:52:59 +0000465 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900466 @Override
467 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
468 final ArrayList<TetheredClient> leases = new ArrayList<>();
469 for (DhcpLeaseParcelable lease : leaseParcelables) {
470 final LinkAddress address = new LinkAddress(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000471 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
472 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
473 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900474
475 final MacAddress macAddress;
476 try {
477 macAddress = MacAddress.fromBytes(lease.hwAddr);
478 } catch (IllegalArgumentException e) {
479 Log.wtf(TAG, "Invalid address received from DhcpServer: "
480 + Arrays.toString(lease.hwAddr));
481 return;
482 }
483
484 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000485 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900486 leases.add(new TetheredClient(
487 macAddress,
488 Collections.singletonList(addressInfo),
489 mInterfaceType));
490 }
491
492 getHandler().post(() -> {
493 mDhcpLeases = leases;
494 mCallback.dhcpLeasesChanged();
495 });
496 }
497
498 @Override
Xiao Ma65401342020-05-14 06:52:59 +0000499 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
500 Objects.requireNonNull(currentPrefix);
501 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma06c8ba02020-04-06 11:24:48 +0000502 }
503
504 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900505 public int getInterfaceVersion() {
506 return this.VERSION;
507 }
508
509 @Override
510 public String getInterfaceHash() throws RemoteException {
511 return this.HASH;
512 }
513 }
514
Xiao Ma65401342020-05-14 06:52:59 +0000515 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
516 Objects.requireNonNull(ipv4Address);
517 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
518 }
519
520 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
521 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
522 @Nullable Inet4Address clientAddr) {
523 final boolean changePrefixOnDecline =
524 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
525 return new DhcpServingParamsParcelExt()
526 .setDefaultRouters(defaultRouter)
527 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
528 .setDnsServers(dnsServer)
529 .setServerAddr(serverAddr)
530 .setMetered(true)
531 .setSingleClientAddr(clientAddr)
532 .setChangePrefixOnDecline(changePrefixOnDecline);
533 // TODO: also advertise link MTU
534 }
535
Treehugger Robot5da10702020-03-30 04:23:55 +0000536 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800537 if (mUsingLegacyDhcp) {
538 return true;
539 }
Treehugger Robot5da10702020-03-30 04:23:55 +0000540
541 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
Treehugger Robot5da10702020-03-30 04:23:55 +0000542 final Inet4Address clientAddr = clientLinkAddr == null ? null :
543 (Inet4Address) clientLinkAddr.getAddress();
544
Xiao Ma65401342020-05-14 06:52:59 +0000545 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
546 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800547 mDhcpServerStartIndex++;
548 mDeps.makeDhcpServer(
549 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
550 return true;
551 }
552
553 private void stopDhcp() {
554 // Make all previous start requests obsolete so servers are not started later
555 mDhcpServerStartIndex++;
556
557 if (mDhcpServer != null) {
558 try {
559 mDhcpServer.stop(new OnHandlerStatusCallback() {
560 @Override
561 public void callback(int statusCode) {
562 if (statusCode != STATUS_SUCCESS) {
563 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800564 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800565 // Not much more we can do here
566 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900567 mDhcpLeases.clear();
568 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800569 }
570 });
571 mDhcpServer = null;
572 } catch (RemoteException e) {
Xiao Ma65401342020-05-14 06:52:59 +0000573 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800574 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800575 }
576 }
577 }
578
Treehugger Robot5da10702020-03-30 04:23:55 +0000579 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
580 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800581 if (enable) {
Treehugger Robot5da10702020-03-30 04:23:55 +0000582 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800583 } else {
584 stopDhcp();
585 return true;
586 }
587 }
588
589 private void stopIPv4() {
590 configureIPv4(false);
591 // NOTE: All of configureIPv4() will be refactored out of existence
592 // into calls to InterfaceController, shared with startIPv4().
593 mInterfaceCtrl.clearIPv4Address();
Mark Chien2ecd3332020-05-29 22:07:37 +0000594 mPrivateAddressCoordinator.releaseDownstream(this);
markchien12c5bb82020-01-07 14:43:17 +0800595 mIpv4Address = null;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000596 mStaticIpv4ServerAddr = null;
597 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800598 }
599
markchien74a4fa92019-09-09 20:50:49 +0800600 private boolean configureIPv4(boolean enabled) {
601 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
602
Mark Chien2ecd3332020-05-29 22:07:37 +0000603 if (enabled) {
604 mIpv4Address = requestIpv4Address();
605 }
606
607 if (mIpv4Address == null) {
608 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800609 return false;
markchien74a4fa92019-09-09 20:50:49 +0800610 }
611
Mark Chien2ecd3332020-05-29 22:07:37 +0000612 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
613 // BT configures the interface elsewhere: only start DHCP.
614 // TODO: make all tethering types behave the same way, and delete the bluetooth
615 // code that calls into NetworkManagementService directly.
616 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
617 }
618
619 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
620
markchien12c5bb82020-01-07 14:43:17 +0800621 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800622 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Mark Chien67569722020-06-19 06:25:12 +0000623 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky4dd87aa2019-11-21 00:36:14 +0200624 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
625 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Mark Chien67569722020-06-19 06:25:12 +0000626 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800627 // It is unclear whether the Bluetooth or USB stacks will manage their own
628 // state.
629 setIfaceUp = null;
630 } else {
631 setIfaceUp = enabled;
632 }
633 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
634 mLog.e("Error configuring interface");
635 if (!enabled) stopDhcp();
636 return false;
637 }
markchien74a4fa92019-09-09 20:50:49 +0800638
markchien74a4fa92019-09-09 20:50:49 +0800639 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800640 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma65401342020-05-14 06:52:59 +0000641 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800642 } else {
markchien12c5bb82020-01-07 14:43:17 +0800643 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma65401342020-05-14 06:52:59 +0000644 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800645 }
Treehugger Robot5da10702020-03-30 04:23:55 +0000646 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800647 }
648
Mark Chien2ecd3332020-05-29 22:07:37 +0000649 private LinkAddress requestIpv4Address() {
650 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800651
Mark Chien2ecd3332020-05-29 22:07:37 +0000652 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
653 return new LinkAddress(BLUETOOTH_IFACE_ADDR);
654 }
655
656 return mPrivateAddressCoordinator.requestDownstreamAddress(this);
Xiao Ma65401342020-05-14 06:52:59 +0000657 }
658
markchien74a4fa92019-09-09 20:50:49 +0800659 private boolean startIPv6() {
660 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
661 if (mInterfaceParams == null) {
662 mLog.e("Failed to find InterfaceParams");
663 stopIPv6();
664 return false;
665 }
666
667 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
668 if (!mRaDaemon.start()) {
669 stopIPv6();
670 return false;
671 }
672
673 return true;
674 }
675
676 private void stopIPv6() {
677 mInterfaceParams = null;
678 setRaParams(null);
679
680 if (mRaDaemon != null) {
681 mRaDaemon.stop();
682 mRaDaemon = null;
683 }
684 }
685
686 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
687 // LinkProperties. These have extraneous data filtered out and only the
688 // necessary prefixes included (per its prefix distribution policy).
689 //
690 // TODO: Evaluate using a data structure than is more directly suited to
691 // communicating only the relevant information.
Mark Chiencd309132020-05-25 02:04:59 +0000692 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800693 if (mRaDaemon == null) return;
694
695 // Avoid unnecessary work on spurious updates.
696 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
697 return;
698 }
699
700 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900701 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800702
703 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900704 final String upstreamIface = v6only.getInterfaceName();
705
markchien74a4fa92019-09-09 20:50:49 +0800706 params = new RaParams();
Maciej Żenczykowskib5898ad2020-05-28 03:21:31 -0700707 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800708 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
709
Mark Chiencd309132020-05-25 02:04:59 +0000710 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800711
712 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
713 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
714
715 final IpPrefix prefix = new IpPrefix(
716 linkAddr.getAddress(), linkAddr.getPrefixLength());
717 params.prefixes.add(prefix);
718
719 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
720 if (dnsServer != null) {
721 params.dnses.add(dnsServer);
722 }
723 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900724
725 upstreamIfindex = mDeps.getIfindex(upstreamIface);
Hungming Chend50f53b2020-06-02 00:13:26 +0000726
727 // Add upstream index to name mapping for the tether stats usage in the coordinator.
728 // Although this mapping could be added by both class Tethering and IpServer, adding
729 // mapping from IpServer guarantees that the mapping is added before the adding
730 // forwarding rules. That is because there are different state machines in both
731 // classes. It is hard to guarantee the link property update order between multiple
732 // state machines.
733 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfindex, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800734 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900735
markchien74a4fa92019-09-09 20:50:49 +0800736 // If v6only is null, we pass in null to setRaParams(), which handles
737 // deprecation of any existing RA data.
738
739 setRaParams(params);
740 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900741
742 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
743 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800744 }
745
Xiao Ma65401342020-05-14 06:52:59 +0000746 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
747 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
748 mNetd, toBeRemoved);
749 if (removalFailures > 0) {
750 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
751 removalFailures));
752 }
753
754 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
755 }
756
757 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
758 try {
759 // It's safe to call networkAddInterface() even if
760 // the interface is already in the local_network.
761 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
762 try {
763 // Add routes from local network. Note that adding routes that
764 // already exist does not cause an error (EEXIST is silently ignored).
765 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
766 } catch (IllegalStateException e) {
767 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
768 return;
769 }
770 } catch (ServiceSpecificException | RemoteException e) {
771 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
772 return;
773 }
774
775 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
776 }
777
markchien74a4fa92019-09-09 20:50:49 +0800778 private void configureLocalIPv6Routes(
779 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
780 // [1] Remove the routes that are deprecated.
781 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma65401342020-05-14 06:52:59 +0000782 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800783 }
784
785 // [2] Add only the routes that have not previously been added.
786 if (newPrefixes != null && !newPrefixes.isEmpty()) {
787 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
788 if (mLastRaParams != null) {
789 addedPrefixes.removeAll(mLastRaParams.prefixes);
790 }
791
792 if (!addedPrefixes.isEmpty()) {
Xiao Ma65401342020-05-14 06:52:59 +0000793 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800794 }
795 }
796 }
797
798 private void configureLocalIPv6Dns(
799 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
800 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
801 if (mNetd == null) {
802 if (newDnses != null) newDnses.clear();
803 mLog.e("No netd service instance available; not setting local IPv6 addresses");
804 return;
805 }
806
807 // [1] Remove deprecated local DNS IP addresses.
808 if (!deprecatedDnses.isEmpty()) {
809 for (Inet6Address dns : deprecatedDnses) {
810 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
811 mLog.e("Failed to remove local dns IP " + dns);
812 }
813
814 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
815 }
816 }
817
818 // [2] Add only the local DNS IP addresses that have not previously been added.
819 if (newDnses != null && !newDnses.isEmpty()) {
820 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
821 if (mLastRaParams != null) {
822 addedDnses.removeAll(mLastRaParams.dnses);
823 }
824
825 for (Inet6Address dns : addedDnses) {
826 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
827 mLog.e("Failed to add local dns IP " + dns);
828 newDnses.remove(dns);
829 }
830
831 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
832 }
833 }
834
835 try {
836 mNetd.tetherApplyDnsInterfaces();
837 } catch (ServiceSpecificException | RemoteException e) {
838 mLog.e("Failed to update local DNS caching server");
839 if (newDnses != null) newDnses.clear();
840 }
841 }
842
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900843 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Nucca Chen0bbfe122020-05-12 11:34:28 +0000844 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
845 // offload is disabled. Add this check just in case.
846 // TODO: Perhaps remove this protection check.
847 if (!mUsingBpfOffload) return;
848
Treehugger Robot7c538fa2020-06-09 13:28:38 +0000849 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900850 }
851
Treehugger Robot7c538fa2020-06-09 13:28:38 +0000852 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Nucca Chen0bbfe122020-05-12 11:34:28 +0000853 // TODO: Perhaps remove this protection check.
Treehugger Robot7c538fa2020-06-09 13:28:38 +0000854 // See the related comment in #addIpv6ForwardingRule.
Nucca Chen0bbfe122020-05-12 11:34:28 +0000855 if (!mUsingBpfOffload) return;
856
Treehugger Robot7c538fa2020-06-09 13:28:38 +0000857 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900858 }
859
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000860 private void clearIpv6ForwardingRules() {
Treehugger Robot7c538fa2020-06-09 13:28:38 +0000861 if (!mUsingBpfOffload) return;
862
863 mBpfCoordinator.tetherOffloadRuleClear(this);
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000864 }
865
Treehugger Robot7c538fa2020-06-09 13:28:38 +0000866 private void updateIpv6ForwardingRule(int newIfindex) {
867 // TODO: Perhaps remove this protection check.
868 // See the related comment in #addIpv6ForwardingRule.
869 if (!mUsingBpfOffload) return;
870
871 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900872 }
873
874 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
875 // changes or if a neighbor event is received.
876 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
877 NeighborEvent e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000878 // If we no longer have an upstream, clear forwarding rules and do nothing else.
879 if (upstreamIfindex == 0) {
880 clearIpv6ForwardingRules();
881 return;
882 }
883
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900884 // If the upstream interface has changed, remove all rules and re-add them with the new
885 // upstream interface.
886 if (prevUpstreamIfindex != upstreamIfindex) {
Treehugger Robot7c538fa2020-06-09 13:28:38 +0000887 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900888 }
889
890 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000891 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900892 if (e == null) return;
893 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
894 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
895 return;
896 }
897
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000898 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
899 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
900 // add rules with a null MAC, only delete them.
901 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000902 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000903 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900904 if (e.isValid()) {
905 addIpv6ForwardingRule(rule);
906 } else {
Treehugger Robot7c538fa2020-06-09 13:28:38 +0000907 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900908 }
909 }
910
911 private void handleNeighborEvent(NeighborEvent e) {
912 if (mInterfaceParams != null
913 && mInterfaceParams.index == e.ifindex
914 && mInterfaceParams.hasMacAddress) {
915 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
916 }
917 }
918
Xiao Ma65401342020-05-14 06:52:59 +0000919 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
920 if (!currentPrefix.contains(mIpv4Address.getAddress())
921 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
922 Log.e(TAG, "Invalid prefix: " + currentPrefix);
923 return;
924 }
925
926 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark Chien2ecd3332020-05-29 22:07:37 +0000927 mIpv4Address = requestIpv4Address();
928 if (mIpv4Address == null) {
Xiao Ma65401342020-05-14 06:52:59 +0000929 mLog.e("Fail to request a new downstream prefix");
930 return;
931 }
Mark Chien2ecd3332020-05-29 22:07:37 +0000932 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma65401342020-05-14 06:52:59 +0000933
934 // Add new IPv4 address on the interface.
935 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
936 mLog.e("Failed to add new IP " + srvAddr);
937 return;
938 }
939
940 // Remove deprecated routes from local network.
941 removeRoutesFromLocalNetwork(
942 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
943 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
944
945 // Add new routes to local network.
946 addRoutesToLocalNetwork(
947 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
948 mLinkProperties.addLinkAddress(mIpv4Address);
949
950 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
951 // listen on the interface configured with new IPv4 address, that results DNS validation
952 // failure of downstream client even if appropriate routes have been configured.
953 try {
954 mNetd.tetherApplyDnsInterfaces();
955 } catch (ServiceSpecificException | RemoteException e) {
956 mLog.e("Failed to update local DNS caching server");
957 return;
958 }
959 sendLinkProperties();
960
961 // Notify DHCP server that new prefix/route has been applied on IpServer.
962 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
963 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
964 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
965 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
966 try {
967 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
968 @Override
969 public void callback(int statusCode) {
970 if (statusCode != STATUS_SUCCESS) {
971 mLog.e("Error updating DHCP serving params: " + statusCode);
972 }
973 }
974 });
975 } catch (RemoteException e) {
976 mLog.e("Error updating DHCP serving params", e);
977 }
978 }
979
Mark Chiencd309132020-05-25 02:04:59 +0000980 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +0800981 try {
982 int upstreamHopLimit = Integer.parseUnsignedInt(
983 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
Mark Chiencd309132020-05-25 02:04:59 +0000984 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +0800985 // Cap the hop limit to 255.
986 return (byte) Integer.min(upstreamHopLimit, 255);
987 } catch (Exception e) {
988 mLog.e("Failed to find upstream interface hop limit", e);
989 }
990 return RaParams.DEFAULT_HOPLIMIT;
991 }
992
993 private void setRaParams(RaParams newParams) {
994 if (mRaDaemon != null) {
995 final RaParams deprecatedParams =
996 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
997
998 configureLocalIPv6Routes(deprecatedParams.prefixes,
999 (newParams != null) ? newParams.prefixes : null);
1000
1001 configureLocalIPv6Dns(deprecatedParams.dnses,
1002 (newParams != null) ? newParams.dnses : null);
1003
1004 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1005 }
1006
1007 mLastRaParams = newParams;
1008 }
1009
1010 private void logMessage(State state, int what) {
1011 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
1012 }
1013
1014 private void sendInterfaceState(int newInterfaceState) {
1015 mServingMode = newInterfaceState;
1016 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1017 sendLinkProperties();
1018 }
1019
1020 private void sendLinkProperties() {
1021 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1022 }
1023
1024 private void resetLinkProperties() {
1025 mLinkProperties.clear();
1026 mLinkProperties.setInterfaceName(mIfaceName);
1027 }
1028
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001029 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
Treehugger Robot5da10702020-03-30 04:23:55 +00001030 // Ignore static address configuration if they are invalid or null. In theory, static
1031 // addresses should not be invalid here because TetheringManager do not allow caller to
1032 // specify invalid static address configuration.
1033 if (request == null || request.localIPv4Address == null
1034 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1035 request.localIPv4Address, request.staticClientAddress)) {
1036 return;
1037 }
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001038
1039 mStaticIpv4ServerAddr = request.localIPv4Address;
1040 mStaticIpv4ClientAddr = request.staticClientAddress;
1041 }
1042
markchien74a4fa92019-09-09 20:50:49 +08001043 class InitialState extends State {
1044 @Override
1045 public void enter() {
1046 sendInterfaceState(STATE_AVAILABLE);
1047 }
1048
1049 @Override
1050 public boolean processMessage(Message message) {
1051 logMessage(this, message.what);
1052 switch (message.what) {
1053 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001054 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001055 switch (message.arg1) {
1056 case STATE_LOCAL_ONLY:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001057 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001058 transitionTo(mLocalHotspotState);
1059 break;
1060 case STATE_TETHERED:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001061 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001062 transitionTo(mTetheredState);
1063 break;
1064 default:
1065 mLog.e("Invalid tethering interface serving state specified.");
1066 }
1067 break;
1068 case CMD_INTERFACE_DOWN:
1069 transitionTo(mUnavailableState);
1070 break;
1071 case CMD_IPV6_TETHER_UPDATE:
Mark Chiencd309132020-05-25 02:04:59 +00001072 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001073 break;
1074 default:
1075 return NOT_HANDLED;
1076 }
1077 return HANDLED;
1078 }
1079 }
1080
1081 class BaseServingState extends State {
1082 @Override
1083 public void enter() {
1084 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001085 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001086 return;
1087 }
1088
1089 try {
Mark Chien2ecd3332020-05-29 22:07:37 +00001090 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001091 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma65401342020-05-14 06:52:59 +00001092 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001093 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001094 return;
1095 }
1096
1097 if (!startIPv6()) {
1098 mLog.e("Failed to startIPv6");
1099 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1100 return;
1101 }
1102 }
1103
1104 @Override
1105 public void exit() {
1106 // Note that at this point, we're leaving the tethered state. We can fail any
1107 // of these operations, but it doesn't really change that we have to try them
1108 // all in sequence.
1109 stopIPv6();
1110
1111 try {
markchien12c5bb82020-01-07 14:43:17 +08001112 NetdUtils.untetherInterface(mNetd, mIfaceName);
1113 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001114 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001115 mLog.e("Failed to untether interface: " + e);
1116 }
1117
1118 stopIPv4();
1119
1120 resetLinkProperties();
1121 }
1122
1123 @Override
1124 public boolean processMessage(Message message) {
1125 logMessage(this, message.what);
1126 switch (message.what) {
1127 case CMD_TETHER_UNREQUESTED:
1128 transitionTo(mInitialState);
1129 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1130 break;
1131 case CMD_INTERFACE_DOWN:
1132 transitionTo(mUnavailableState);
1133 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1134 break;
1135 case CMD_IPV6_TETHER_UPDATE:
Mark Chiencd309132020-05-25 02:04:59 +00001136 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001137 sendLinkProperties();
1138 break;
1139 case CMD_IP_FORWARDING_ENABLE_ERROR:
1140 case CMD_IP_FORWARDING_DISABLE_ERROR:
1141 case CMD_START_TETHERING_ERROR:
1142 case CMD_STOP_TETHERING_ERROR:
1143 case CMD_SET_DNS_FORWARDERS_ERROR:
markchienf1332572020-03-19 13:37:43 +08001144 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001145 transitionTo(mInitialState);
1146 break;
Xiao Ma65401342020-05-14 06:52:59 +00001147 case CMD_NEW_PREFIX_REQUEST:
1148 handleNewPrefixRequest((IpPrefix) message.obj);
1149 break;
Mark Chien2ecd3332020-05-29 22:07:37 +00001150 case CMD_NOTIFY_PREFIX_CONFLICT:
1151 mLog.i("restart tethering: " + mInterfaceType);
1152 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1153 transitionTo(mWaitingForRestartState);
1154 break;
markchien74a4fa92019-09-09 20:50:49 +08001155 default:
1156 return false;
1157 }
1158 return true;
1159 }
1160 }
1161
1162 // Handling errors in BaseServingState.enter() by transitioning is
1163 // problematic because transitioning during a multi-state jump yields
1164 // a Log.wtf(). Ultimately, there should be only one ServingState,
1165 // and forwarding and NAT rules should be handled by a coordinating
1166 // functional element outside of IpServer.
1167 class LocalHotspotState extends BaseServingState {
1168 @Override
1169 public void enter() {
1170 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001171 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001172 transitionTo(mInitialState);
1173 }
1174
1175 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1176 sendInterfaceState(STATE_LOCAL_ONLY);
1177 }
1178
1179 @Override
1180 public boolean processMessage(Message message) {
1181 if (super.processMessage(message)) return true;
1182
1183 logMessage(this, message.what);
1184 switch (message.what) {
1185 case CMD_TETHER_REQUESTED:
1186 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1187 break;
1188 case CMD_TETHER_CONNECTION_CHANGED:
1189 // Ignored in local hotspot state.
1190 break;
1191 default:
1192 return false;
1193 }
1194 return true;
1195 }
1196 }
1197
1198 // Handling errors in BaseServingState.enter() by transitioning is
1199 // problematic because transitioning during a multi-state jump yields
1200 // a Log.wtf(). Ultimately, there should be only one ServingState,
1201 // and forwarding and NAT rules should be handled by a coordinating
1202 // functional element outside of IpServer.
1203 class TetheredState extends BaseServingState {
1204 @Override
1205 public void enter() {
1206 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001207 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001208 transitionTo(mInitialState);
1209 }
1210
1211 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1212 sendInterfaceState(STATE_TETHERED);
1213 }
1214
1215 @Override
1216 public void exit() {
1217 cleanupUpstream();
1218 super.exit();
1219 }
1220
1221 private void cleanupUpstream() {
1222 if (mUpstreamIfaceSet == null) return;
1223
1224 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1225 mUpstreamIfaceSet = null;
Automerger Merge Workerf1194882020-02-25 04:04:44 +00001226 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001227 }
1228
1229 private void cleanupUpstreamInterface(String upstreamIface) {
1230 // Note that we don't care about errors here.
1231 // Sometimes interfaces are gone before we get
1232 // to remove their rules, which generates errors.
1233 // Just do the best we can.
1234 try {
markchien12c5bb82020-01-07 14:43:17 +08001235 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1236 } catch (RemoteException | ServiceSpecificException e) {
1237 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001238 }
1239 try {
markchien12c5bb82020-01-07 14:43:17 +08001240 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1241 } catch (RemoteException | ServiceSpecificException e) {
1242 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001243 }
1244 }
1245
1246 @Override
1247 public boolean processMessage(Message message) {
1248 if (super.processMessage(message)) return true;
1249
1250 logMessage(this, message.what);
1251 switch (message.what) {
1252 case CMD_TETHER_REQUESTED:
1253 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1254 break;
1255 case CMD_TETHER_CONNECTION_CHANGED:
1256 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1257 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1258 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1259 break;
1260 }
1261
1262 if (newUpstreamIfaceSet == null) {
1263 cleanupUpstream();
1264 break;
1265 }
1266
1267 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1268 cleanupUpstreamInterface(removed);
1269 }
1270
1271 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1272 // This makes the call to cleanupUpstream() in the error
1273 // path for any interface neatly cleanup all the interfaces.
1274 mUpstreamIfaceSet = newUpstreamIfaceSet;
1275
1276 for (String ifname : added) {
1277 try {
markchien12c5bb82020-01-07 14:43:17 +08001278 mNetd.tetherAddForward(mIfaceName, ifname);
1279 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1280 } catch (RemoteException | ServiceSpecificException e) {
1281 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001282 cleanupUpstream();
markchienf1332572020-03-19 13:37:43 +08001283 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001284 transitionTo(mInitialState);
1285 return true;
1286 }
1287 }
1288 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001289 case CMD_NEIGHBOR_EVENT:
1290 handleNeighborEvent((NeighborEvent) message.obj);
1291 break;
markchien74a4fa92019-09-09 20:50:49 +08001292 default:
1293 return false;
1294 }
1295 return true;
1296 }
1297
1298 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1299 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1300 if (mUpstreamIfaceSet != null && newIfaces != null) {
1301 return mUpstreamIfaceSet.equals(newIfaces);
1302 }
1303 return false;
1304 }
1305
1306 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1307 if (mUpstreamIfaceSet == null) return new HashSet<>();
1308
1309 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1310 removed.removeAll(newIfaces.ifnames);
1311 return removed;
1312 }
1313
1314 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1315 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1316 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1317 return added;
1318 }
1319 }
1320
1321 /**
1322 * This state is terminal for the per interface state machine. At this
1323 * point, the master state machine should have removed this interface
1324 * specific state machine from its list of possible recipients of
1325 * tethering requests. The state machine itself will hang around until
1326 * the garbage collector finds it.
1327 */
1328 class UnavailableState extends State {
1329 @Override
1330 public void enter() {
Lorenzo Colitti93e59ee2020-06-18 16:36:32 +00001331 mIpNeighborMonitor.stop();
markchien9b4d7572019-12-25 19:40:32 +08001332 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001333 sendInterfaceState(STATE_UNAVAILABLE);
1334 }
1335 }
1336
Mark Chien2ecd3332020-05-29 22:07:37 +00001337 class WaitingForRestartState extends State {
1338 @Override
1339 public boolean processMessage(Message message) {
1340 logMessage(this, message.what);
1341 switch (message.what) {
1342 case CMD_TETHER_UNREQUESTED:
1343 transitionTo(mInitialState);
1344 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1345 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1346 break;
1347 case CMD_INTERFACE_DOWN:
1348 transitionTo(mUnavailableState);
1349 mLog.i("Untethered (interface down) and restarting" + mIfaceName);
1350 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1351 break;
1352 default:
1353 return false;
1354 }
1355 return true;
1356 }
1357 }
1358
markchien74a4fa92019-09-09 20:50:49 +08001359 // Accumulate routes representing "prefixes to be assigned to the local
1360 // interface", for subsequent modification of local_network routing.
1361 private static ArrayList<RouteInfo> getLocalRoutesFor(
1362 String ifname, HashSet<IpPrefix> prefixes) {
1363 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1364 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001365 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001366 }
1367 return localRoutes;
1368 }
1369
1370 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1371 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1372 final byte[] dnsBytes = localPrefix.getRawAddress();
1373 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1374 try {
1375 return Inet6Address.getByAddress(null, dnsBytes, 0);
1376 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001377 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001378 return null;
1379 }
1380 }
1381
1382 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1383 final byte random = (byte) (new Random()).nextInt();
1384 for (int value : excluded) {
1385 if (random == value) return dflt;
1386 }
1387 return random;
1388 }
1389}