blob: 659d344acfcd181784b2161d6c858766bd89414d [file] [log] [blame]
markchien74a4fa92019-09-09 20:50:49 +08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net.ip;
18
19import static android.net.InetAddresses.parseNumericAddress;
markchien6cf0e552019-12-06 15:24:53 +080020import static android.net.RouteInfo.RTN_UNICAST;
Treehugger Robot5da10702020-03-30 04:23:55 +000021import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080022import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090023import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH;
markchien74a4fa92019-09-09 20:50:49 +080024import static android.net.util.NetworkConstants.FF;
25import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
26import static android.net.util.NetworkConstants.asByte;
markchien6cf0e552019-12-06 15:24:53 +080027import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Automerger Merge Worker0010ca02020-03-16 04:06:46 +000028import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080029
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;
Lorenzo Colittie6107d22020-04-06 09:19:57 +000037import android.net.TetherOffloadRuleParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090038import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080039import android.net.TetheringManager;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +000040import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090041import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.dhcp.DhcpServerCallbacks;
43import android.net.dhcp.DhcpServingParamsParcel;
44import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma06c8ba02020-04-06 11:24:48 +000045import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090047import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080048import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080049import android.net.shared.NetdUtils;
50import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080051import android.net.util.InterfaceParams;
52import android.net.util.InterfaceSet;
Xiao Ma65401342020-05-14 06:52:59 +000053import android.net.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080054import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090055import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080056import android.os.Looper;
57import android.os.Message;
58import android.os.RemoteException;
59import android.os.ServiceSpecificException;
60import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080061import android.util.SparseArray;
62
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090063import androidx.annotation.NonNull;
Xiao Ma65401342020-05-14 06:52:59 +000064import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090065
markchien74a4fa92019-09-09 20:50:49 +080066import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080067import com.android.internal.util.State;
68import com.android.internal.util.StateMachine;
69
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090070import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080071import java.net.Inet4Address;
72import java.net.Inet6Address;
73import java.net.InetAddress;
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
111 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
112 private static final int USB_PREFIX_LENGTH = 24;
113 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
114 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
115 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
116 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900117 private static final String ETHERNET_IFACE_ADDR = "192.168.50.1";
118 private static final int ETHERNET_IFACE_PREFIX_LENGTH = 24;
markchien74a4fa92019-09-09 20:50:49 +0800119
Xiao Ma65401342020-05-14 06:52:59 +0000120 // TODO: remove this constant after introducing PrivateAddressCoordinator.
121 private static final List<IpPrefix> NCM_PREFIXES = Collections.unmodifiableList(
122 Arrays.asList(
123 new IpPrefix("192.168.42.0/24"),
124 new IpPrefix("192.168.51.0/24"),
125 new IpPrefix("192.168.52.0/24"),
126 new IpPrefix("192.168.53.0/24")
127 ));
128
markchien74a4fa92019-09-09 20:50:49 +0800129 // TODO: have PanService use some visible version of this constant
130 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
131 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
132
133 // TODO: have this configurable
134 private static final int DHCP_LEASE_TIME_SECS = 3600;
135
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000136 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
137
markchien74a4fa92019-09-09 20:50:49 +0800138 private static final String TAG = "IpServer";
139 private static final boolean DBG = false;
140 private static final boolean VDBG = false;
141 private static final Class[] sMessageClasses = {
142 IpServer.class
143 };
144 private static final SparseArray<String> sMagicDecoderRing =
145 MessageUtils.findMessageNames(sMessageClasses);
146
147 /** IpServer callback. */
148 public static class Callback {
149 /**
150 * Notify that |who| has changed its tethering state.
151 *
152 * @param who the calling instance of IpServer
153 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800154 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800155 */
markchien9d353822019-12-16 20:15:20 +0800156 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800157
158 /**
159 * Notify that |who| has new LinkProperties.
160 *
161 * @param who the calling instance of IpServer
162 * @param newLp the new LinkProperties to report
163 */
markchien9d353822019-12-16 20:15:20 +0800164 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900165
166 /**
167 * Notify that the DHCP leases changed in one of the IpServers.
168 */
169 public void dhcpLeasesChanged() { }
markchien74a4fa92019-09-09 20:50:49 +0800170 }
171
172 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800173 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900174 /** Create an IpNeighborMonitor to be used by this IpServer */
175 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
176 IpNeighborMonitor.NeighborEventConsumer consumer) {
177 return new IpNeighborMonitor(handler, log, consumer);
178 }
179
markchien74a4fa92019-09-09 20:50:49 +0800180 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
181 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
182 return new RouterAdvertisementDaemon(ifParams);
183 }
184
185 /** Get |ifName|'s interface information.*/
186 public InterfaceParams getInterfaceParams(String ifName) {
187 return InterfaceParams.getByName(ifName);
188 }
189
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900190 /** Get |ifName|'s interface index. */
191 public int getIfindex(String ifName) {
192 try {
193 return NetworkInterface.getByName(ifName).getIndex();
194 } catch (IOException | NullPointerException e) {
195 Log.e(TAG, "Can't determine interface index for interface " + ifName);
196 return 0;
197 }
198 }
markchien9d353822019-12-16 20:15:20 +0800199 /** Create a DhcpServer instance to be used by IpServer. */
200 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
201 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800202 }
203
markchien74a4fa92019-09-09 20:50:49 +0800204 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800205 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800206 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800207 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800208 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800209 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800210 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800211 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800212 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800213 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800214 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800215 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800216 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800217 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800218 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800219 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800220 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800221 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800222 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800223 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900224 // new neighbor cache entry on our interface
225 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma65401342020-05-14 06:52:59 +0000226 // request from DHCP server that it wants to have a new prefix
227 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchien74a4fa92019-09-09 20:50:49 +0800228
229 private final State mInitialState;
230 private final State mLocalHotspotState;
231 private final State mTetheredState;
232 private final State mUnavailableState;
233
234 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800235 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800236 private final Callback mCallback;
237 private final InterfaceController mInterfaceCtrl;
238
239 private final String mIfaceName;
240 private final int mInterfaceType;
241 private final LinkProperties mLinkProperties;
242 private final boolean mUsingLegacyDhcp;
Nucca Chen0bbfe122020-05-12 11:34:28 +0000243 private final boolean mUsingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800244
245 private final Dependencies mDeps;
246
247 private int mLastError;
248 private int mServingMode;
249 private InterfaceSet mUpstreamIfaceSet; // may change over time
250 private InterfaceParams mInterfaceParams;
251 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
252 // properties are those selected by the IPv6TetheringCoordinator and relayed
253 // to us. By comparison, mLinkProperties contains the addresses and directly
254 // connected routes that have been formed from these properties iff. we have
255 // succeeded in configuring them and are able to announce them within Router
256 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
257 private LinkProperties mLastIPv6LinkProperties;
258 private RouterAdvertisementDaemon mRaDaemon;
259
260 // To be accessed only on the handler thread
261 private int mDhcpServerStartIndex = 0;
262 private IDhcpServer mDhcpServer;
263 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800264 private LinkAddress mIpv4Address;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000265
266 private LinkAddress mStaticIpv4ServerAddr;
267 private LinkAddress mStaticIpv4ClientAddr;
268
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900269 @NonNull
270 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800271
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900272 private int mLastIPv6UpstreamIfindex = 0;
273
274 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
275 public void accept(NeighborEvent e) {
276 sendMessage(CMD_NEIGHBOR_EVENT, e);
277 }
278 }
279
280 static class Ipv6ForwardingRule {
281 public final int upstreamIfindex;
282 public final int downstreamIfindex;
283 public final Inet6Address address;
284 public final MacAddress srcMac;
285 public final MacAddress dstMac;
286
287 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
288 MacAddress srcMac, MacAddress dstMac) {
289 this.upstreamIfindex = upstreamIfindex;
290 this.downstreamIfindex = downstreamIfIndex;
291 this.address = address;
292 this.srcMac = srcMac;
293 this.dstMac = dstMac;
294 }
295
296 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
297 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
298 dstMac);
299 }
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000300
301 // Don't manipulate TetherOffloadRuleParcel directly because implementing onNewUpstream()
302 // would be error-prone due to generated stable AIDL classes not having a copy constructor.
303 public TetherOffloadRuleParcel toTetherOffloadRuleParcel() {
304 final TetherOffloadRuleParcel parcel = new TetherOffloadRuleParcel();
305 parcel.inputInterfaceIndex = upstreamIfindex;
306 parcel.outputInterfaceIndex = downstreamIfindex;
307 parcel.destination = address.getAddress();
308 parcel.prefixLength = 128;
309 parcel.srcL2Address = srcMac.toByteArray();
310 parcel.dstL2Address = dstMac.toByteArray();
311 return parcel;
312 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900313 }
314 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
315 new LinkedHashMap<>();
316
317 private final IpNeighborMonitor mIpNeighborMonitor;
318
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000319 // TODO: Add a dependency object to pass the data members or variables from the tethering
320 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800321 public IpServer(
322 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Nucca Chen0bbfe122020-05-12 11:34:28 +0000323 INetd netd, Callback callback, boolean usingLegacyDhcp, boolean usingBpfOffload,
324 Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800325 super(ifaceName, looper);
326 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800327 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800328 mCallback = callback;
329 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
330 mIfaceName = ifaceName;
331 mInterfaceType = interfaceType;
332 mLinkProperties = new LinkProperties();
333 mUsingLegacyDhcp = usingLegacyDhcp;
Nucca Chen0bbfe122020-05-12 11:34:28 +0000334 mUsingBpfOffload = usingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800335 mDeps = deps;
336 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800337 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800338 mServingMode = STATE_AVAILABLE;
339
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900340 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
341 new MyNeighborEventConsumer());
Nucca Chen0bbfe122020-05-12 11:34:28 +0000342
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000343 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Nucca Chen0bbfe122020-05-12 11:34:28 +0000344 // forwarding rules per client. If BPF offload is not supported, don't start listening
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000345 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Nucca Chen0bbfe122020-05-12 11:34:28 +0000346 // removeIpv6ForwardingRule.
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000347 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
348 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900349 }
350
markchien74a4fa92019-09-09 20:50:49 +0800351 mInitialState = new InitialState();
352 mLocalHotspotState = new LocalHotspotState();
353 mTetheredState = new TetheredState();
354 mUnavailableState = new UnavailableState();
355 addState(mInitialState);
356 addState(mLocalHotspotState);
357 addState(mTetheredState);
358 addState(mUnavailableState);
359
360 setInitialState(mInitialState);
361 }
362
363 /** Interface name which IpServer served.*/
364 public String interfaceName() {
365 return mIfaceName;
366 }
367
368 /**
markchien9b4d7572019-12-25 19:40:32 +0800369 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800370 */
371 public int interfaceType() {
372 return mInterfaceType;
373 }
374
375 /** Last error from this IpServer. */
376 public int lastError() {
377 return mLastError;
378 }
379
380 /** Serving mode is the current state of IpServer state machine. */
381 public int servingMode() {
382 return mServingMode;
383 }
384
385 /** The properties of the network link which IpServer is serving. */
386 public LinkProperties linkProperties() {
387 return new LinkProperties(mLinkProperties);
388 }
389
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900390 /**
391 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
392 * thread.
393 */
394 public List<TetheredClient> getAllLeases() {
395 return Collections.unmodifiableList(mDhcpLeases);
396 }
397
markchien74a4fa92019-09-09 20:50:49 +0800398 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
399 public void stop() {
400 sendMessage(CMD_INTERFACE_DOWN);
401 }
402
403 /**
404 * Tethering is canceled. IpServer state machine will be available and wait for
405 * next tethering request.
406 */
407 public void unwanted() {
408 sendMessage(CMD_TETHER_UNREQUESTED);
409 }
410
411 /** Internals. */
412
413 private boolean startIPv4() {
414 return configureIPv4(true);
415 }
416
417 /**
418 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
419 * handler.
420 *
421 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
422 * with different implementations of the callback, to differentiate handling of success/error in
423 * each call.
424 */
425 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
426 @Override
427 public void onStatusAvailable(int statusCode) {
428 getHandler().post(() -> callback(statusCode));
429 }
430
431 public abstract void callback(int statusCode);
432
433 @Override
434 public int getInterfaceVersion() {
435 return this.VERSION;
436 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900437
438 @Override
439 public String getInterfaceHash() {
440 return this.HASH;
441 }
markchien74a4fa92019-09-09 20:50:49 +0800442 }
443
444 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
445 private final int mStartIndex;
446
447 private DhcpServerCallbacksImpl(int startIndex) {
448 mStartIndex = startIndex;
449 }
450
451 @Override
452 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
453 getHandler().post(() -> {
454 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
455 if (mStartIndex != mDhcpServerStartIndex) {
456 // This start request is obsolete. When the |server| binder token goes out of
457 // scope, the garbage collector will finalize it, which causes the network stack
458 // process garbage collector to collect the server itself.
459 return;
460 }
461
462 if (statusCode != STATUS_SUCCESS) {
463 mLog.e("Error obtaining DHCP server: " + statusCode);
464 handleError();
465 return;
466 }
467
468 mDhcpServer = server;
469 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900470 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800471 @Override
472 public void callback(int startStatusCode) {
473 if (startStatusCode != STATUS_SUCCESS) {
474 mLog.e("Error starting DHCP server: " + startStatusCode);
475 handleError();
476 }
477 }
Xiao Ma65401342020-05-14 06:52:59 +0000478 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800479 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800480 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800481 }
482 });
483 }
484
485 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800486 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800487 transitionTo(mInitialState);
488 }
489 }
490
Xiao Ma65401342020-05-14 06:52:59 +0000491 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900492 @Override
493 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
494 final ArrayList<TetheredClient> leases = new ArrayList<>();
495 for (DhcpLeaseParcelable lease : leaseParcelables) {
496 final LinkAddress address = new LinkAddress(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000497 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
498 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
499 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900500
501 final MacAddress macAddress;
502 try {
503 macAddress = MacAddress.fromBytes(lease.hwAddr);
504 } catch (IllegalArgumentException e) {
505 Log.wtf(TAG, "Invalid address received from DhcpServer: "
506 + Arrays.toString(lease.hwAddr));
507 return;
508 }
509
510 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000511 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900512 leases.add(new TetheredClient(
513 macAddress,
514 Collections.singletonList(addressInfo),
515 mInterfaceType));
516 }
517
518 getHandler().post(() -> {
519 mDhcpLeases = leases;
520 mCallback.dhcpLeasesChanged();
521 });
522 }
523
524 @Override
Xiao Ma65401342020-05-14 06:52:59 +0000525 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
526 Objects.requireNonNull(currentPrefix);
527 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma06c8ba02020-04-06 11:24:48 +0000528 }
529
530 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900531 public int getInterfaceVersion() {
532 return this.VERSION;
533 }
534
535 @Override
536 public String getInterfaceHash() throws RemoteException {
537 return this.HASH;
538 }
539 }
540
Xiao Ma65401342020-05-14 06:52:59 +0000541 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
542 Objects.requireNonNull(ipv4Address);
543 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
544 }
545
546 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
547 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
548 @Nullable Inet4Address clientAddr) {
549 final boolean changePrefixOnDecline =
550 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
551 return new DhcpServingParamsParcelExt()
552 .setDefaultRouters(defaultRouter)
553 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
554 .setDnsServers(dnsServer)
555 .setServerAddr(serverAddr)
556 .setMetered(true)
557 .setSingleClientAddr(clientAddr)
558 .setChangePrefixOnDecline(changePrefixOnDecline);
559 // TODO: also advertise link MTU
560 }
561
Treehugger Robot5da10702020-03-30 04:23:55 +0000562 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800563 if (mUsingLegacyDhcp) {
564 return true;
565 }
Treehugger Robot5da10702020-03-30 04:23:55 +0000566
567 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
Treehugger Robot5da10702020-03-30 04:23:55 +0000568 final Inet4Address clientAddr = clientLinkAddr == null ? null :
569 (Inet4Address) clientLinkAddr.getAddress();
570
Xiao Ma65401342020-05-14 06:52:59 +0000571 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
572 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800573 mDhcpServerStartIndex++;
574 mDeps.makeDhcpServer(
575 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
576 return true;
577 }
578
579 private void stopDhcp() {
580 // Make all previous start requests obsolete so servers are not started later
581 mDhcpServerStartIndex++;
582
583 if (mDhcpServer != null) {
584 try {
585 mDhcpServer.stop(new OnHandlerStatusCallback() {
586 @Override
587 public void callback(int statusCode) {
588 if (statusCode != STATUS_SUCCESS) {
589 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800590 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800591 // Not much more we can do here
592 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900593 mDhcpLeases.clear();
594 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800595 }
596 });
597 mDhcpServer = null;
598 } catch (RemoteException e) {
Xiao Ma65401342020-05-14 06:52:59 +0000599 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800600 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800601 }
602 }
603 }
604
Treehugger Robot5da10702020-03-30 04:23:55 +0000605 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
606 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800607 if (enable) {
Treehugger Robot5da10702020-03-30 04:23:55 +0000608 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800609 } else {
610 stopDhcp();
611 return true;
612 }
613 }
614
615 private void stopIPv4() {
616 configureIPv4(false);
617 // NOTE: All of configureIPv4() will be refactored out of existence
618 // into calls to InterfaceController, shared with startIPv4().
619 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800620 mIpv4Address = null;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000621 mStaticIpv4ServerAddr = null;
622 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800623 }
624
markchien74a4fa92019-09-09 20:50:49 +0800625 private boolean configureIPv4(boolean enabled) {
626 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
627
628 // TODO: Replace this hard-coded information with dynamically selected
629 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800630 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800631 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800632 try {
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000633 if (mStaticIpv4ServerAddr != null) {
634 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
635 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
636 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900637 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800638 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
639 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800640 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800641 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
642 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800643 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800644 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
645 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900646 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
647 // TODO: randomize address for tethering too, similarly to wifi
648 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
649 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800650 } else {
651 // BT configures the interface elsewhere: only start DHCP.
652 // TODO: make all tethering types behave the same way, and delete the bluetooth
653 // code that calls into NetworkManagementService directly.
654 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
655 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
Treehugger Robot5da10702020-03-30 04:23:55 +0000656 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
markchien12c5bb82020-01-07 14:43:17 +0800657 }
658 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
659 } catch (IllegalArgumentException e) {
660 mLog.e("Error selecting ipv4 address", e);
661 if (!enabled) stopDhcp();
662 return false;
markchien74a4fa92019-09-09 20:50:49 +0800663 }
664
markchien12c5bb82020-01-07 14:43:17 +0800665 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800666 if (mInterfaceType == TetheringManager.TETHERING_WIFI
667 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800668 // The WiFi stack has ownership of the interface up/down state.
669 // It is unclear whether the Bluetooth or USB stacks will manage their own
670 // state.
671 setIfaceUp = null;
672 } else {
673 setIfaceUp = enabled;
674 }
675 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
676 mLog.e("Error configuring interface");
677 if (!enabled) stopDhcp();
678 return false;
679 }
markchien74a4fa92019-09-09 20:50:49 +0800680
markchien74a4fa92019-09-09 20:50:49 +0800681 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800682 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma65401342020-05-14 06:52:59 +0000683 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800684 } else {
markchien12c5bb82020-01-07 14:43:17 +0800685 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma65401342020-05-14 06:52:59 +0000686 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800687 }
Treehugger Robot5da10702020-03-30 04:23:55 +0000688 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800689 }
690
Xiao Ma65401342020-05-14 06:52:59 +0000691 private Inet4Address getRandomIPv4Address(@NonNull final byte[] rawAddr) {
692 final byte[] ipv4Addr = rawAddr;
693 ipv4Addr[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
markchien74a4fa92019-09-09 20:50:49 +0800694 try {
Xiao Ma65401342020-05-14 06:52:59 +0000695 return (Inet4Address) InetAddress.getByAddress(ipv4Addr);
696 } catch (UnknownHostException e) {
697 mLog.e("Failed to construct Inet4Address from raw IPv4 addr");
698 return null;
markchien74a4fa92019-09-09 20:50:49 +0800699 }
700 }
701
Xiao Ma65401342020-05-14 06:52:59 +0000702 private String getRandomWifiIPv4Address() {
703 final Inet4Address ipv4Addr =
704 getRandomIPv4Address(parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress());
705 return ipv4Addr != null ? ipv4Addr.getHostAddress() : WIFI_HOST_IFACE_ADDR;
706 }
707
markchien74a4fa92019-09-09 20:50:49 +0800708 private boolean startIPv6() {
709 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
710 if (mInterfaceParams == null) {
711 mLog.e("Failed to find InterfaceParams");
712 stopIPv6();
713 return false;
714 }
715
716 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
717 if (!mRaDaemon.start()) {
718 stopIPv6();
719 return false;
720 }
721
722 return true;
723 }
724
725 private void stopIPv6() {
726 mInterfaceParams = null;
727 setRaParams(null);
728
729 if (mRaDaemon != null) {
730 mRaDaemon.stop();
731 mRaDaemon = null;
732 }
733 }
734
735 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
736 // LinkProperties. These have extraneous data filtered out and only the
737 // necessary prefixes included (per its prefix distribution policy).
738 //
739 // TODO: Evaluate using a data structure than is more directly suited to
740 // communicating only the relevant information.
Mark Chiencd309132020-05-25 02:04:59 +0000741 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800742 if (mRaDaemon == null) return;
743
744 // Avoid unnecessary work on spurious updates.
745 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
746 return;
747 }
748
749 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900750 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800751
752 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900753 final String upstreamIface = v6only.getInterfaceName();
754
markchien74a4fa92019-09-09 20:50:49 +0800755 params = new RaParams();
Nucca Chen0bbfe122020-05-12 11:34:28 +0000756 // When BPF offload is enabled, we advertise an mtu lower by 16, which is the closest
757 // multiple of 8 >= 14, the ethernet header size. This makes kernel ebpf tethering
758 // offload happy. This hack should be reverted once we have the kernel fixed up.
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800759 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
760 // see RouterAdvertisementDaemon.java putMtu()
Nucca Chen0bbfe122020-05-12 11:34:28 +0000761 params.mtu = mUsingBpfOffload ? v6only.getMtu() - 16 : v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800762 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
763
Mark Chiencd309132020-05-25 02:04:59 +0000764 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800765
766 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
767 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
768
769 final IpPrefix prefix = new IpPrefix(
770 linkAddr.getAddress(), linkAddr.getPrefixLength());
771 params.prefixes.add(prefix);
772
773 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
774 if (dnsServer != null) {
775 params.dnses.add(dnsServer);
776 }
777 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900778
779 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800780 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900781
markchien74a4fa92019-09-09 20:50:49 +0800782 // If v6only is null, we pass in null to setRaParams(), which handles
783 // deprecation of any existing RA data.
784
785 setRaParams(params);
786 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900787
788 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
789 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800790 }
791
Xiao Ma65401342020-05-14 06:52:59 +0000792 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
793 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
794 mNetd, toBeRemoved);
795 if (removalFailures > 0) {
796 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
797 removalFailures));
798 }
799
800 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
801 }
802
803 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
804 try {
805 // It's safe to call networkAddInterface() even if
806 // the interface is already in the local_network.
807 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
808 try {
809 // Add routes from local network. Note that adding routes that
810 // already exist does not cause an error (EEXIST is silently ignored).
811 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
812 } catch (IllegalStateException e) {
813 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
814 return;
815 }
816 } catch (ServiceSpecificException | RemoteException e) {
817 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
818 return;
819 }
820
821 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
822 }
823
markchien74a4fa92019-09-09 20:50:49 +0800824 private void configureLocalIPv6Routes(
825 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
826 // [1] Remove the routes that are deprecated.
827 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma65401342020-05-14 06:52:59 +0000828 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800829 }
830
831 // [2] Add only the routes that have not previously been added.
832 if (newPrefixes != null && !newPrefixes.isEmpty()) {
833 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
834 if (mLastRaParams != null) {
835 addedPrefixes.removeAll(mLastRaParams.prefixes);
836 }
837
838 if (!addedPrefixes.isEmpty()) {
Xiao Ma65401342020-05-14 06:52:59 +0000839 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800840 }
841 }
842 }
843
844 private void configureLocalIPv6Dns(
845 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
846 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
847 if (mNetd == null) {
848 if (newDnses != null) newDnses.clear();
849 mLog.e("No netd service instance available; not setting local IPv6 addresses");
850 return;
851 }
852
853 // [1] Remove deprecated local DNS IP addresses.
854 if (!deprecatedDnses.isEmpty()) {
855 for (Inet6Address dns : deprecatedDnses) {
856 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
857 mLog.e("Failed to remove local dns IP " + dns);
858 }
859
860 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
861 }
862 }
863
864 // [2] Add only the local DNS IP addresses that have not previously been added.
865 if (newDnses != null && !newDnses.isEmpty()) {
866 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
867 if (mLastRaParams != null) {
868 addedDnses.removeAll(mLastRaParams.dnses);
869 }
870
871 for (Inet6Address dns : addedDnses) {
872 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
873 mLog.e("Failed to add local dns IP " + dns);
874 newDnses.remove(dns);
875 }
876
877 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
878 }
879 }
880
881 try {
882 mNetd.tetherApplyDnsInterfaces();
883 } catch (ServiceSpecificException | RemoteException e) {
884 mLog.e("Failed to update local DNS caching server");
885 if (newDnses != null) newDnses.clear();
886 }
887 }
888
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900889 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Nucca Chen0bbfe122020-05-12 11:34:28 +0000890 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
891 // offload is disabled. Add this check just in case.
892 // TODO: Perhaps remove this protection check.
893 if (!mUsingBpfOffload) return;
894
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900895 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000896 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900897 mIpv6ForwardingRules.put(rule.address, rule);
898 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000899 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900900 }
901 }
902
903 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
Nucca Chen0bbfe122020-05-12 11:34:28 +0000904 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
905 // offload is disabled. Add this check just in case.
906 // TODO: Perhaps remove this protection check.
907 if (!mUsingBpfOffload) return;
908
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900909 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000910 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900911 if (removeFromMap) {
912 mIpv6ForwardingRules.remove(rule.address);
913 }
914 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000915 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900916 }
917 }
918
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000919 private void clearIpv6ForwardingRules() {
920 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
921 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
922 }
923 mIpv6ForwardingRules.clear();
924 }
925
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900926 // Convenience method to replace a rule with the same rule on a new upstream interface.
927 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
928 // Relies on the fact that rules are in a map indexed by IP address.
929 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
930 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
931 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
932 }
933
934 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
935 // changes or if a neighbor event is received.
936 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
937 NeighborEvent e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000938 // If we no longer have an upstream, clear forwarding rules and do nothing else.
939 if (upstreamIfindex == 0) {
940 clearIpv6ForwardingRules();
941 return;
942 }
943
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900944 // If the upstream interface has changed, remove all rules and re-add them with the new
945 // upstream interface.
946 if (prevUpstreamIfindex != upstreamIfindex) {
947 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
948 updateIpv6ForwardingRule(rule, upstreamIfindex);
949 }
950 }
951
952 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000953 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900954 if (e == null) return;
955 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
956 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
957 return;
958 }
959
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000960 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
961 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
962 // add rules with a null MAC, only delete them.
963 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000964 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000965 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900966 if (e.isValid()) {
967 addIpv6ForwardingRule(rule);
968 } else {
969 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
970 }
971 }
972
973 private void handleNeighborEvent(NeighborEvent e) {
974 if (mInterfaceParams != null
975 && mInterfaceParams.index == e.ifindex
976 && mInterfaceParams.hasMacAddress) {
977 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
978 }
979 }
980
Xiao Ma65401342020-05-14 06:52:59 +0000981 // TODO: call PrivateAddressCoordinator.requestDownstreamAddress instead of this temporary
982 // logic.
983 private Inet4Address requestDownstreamAddress(@NonNull final IpPrefix currentPrefix) {
984 final int oldIndex = NCM_PREFIXES.indexOf(currentPrefix);
985 if (oldIndex == -1) {
986 mLog.e("current prefix isn't supported for NCM link: " + currentPrefix);
987 return null;
988 }
989
990 final IpPrefix newPrefix = NCM_PREFIXES.get((oldIndex + 1) % NCM_PREFIXES.size());
991 return getRandomIPv4Address(newPrefix.getRawAddress());
992 }
993
994 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
995 if (!currentPrefix.contains(mIpv4Address.getAddress())
996 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
997 Log.e(TAG, "Invalid prefix: " + currentPrefix);
998 return;
999 }
1000
1001 final LinkAddress deprecatedLinkAddress = mIpv4Address;
1002 final Inet4Address srvAddr = requestDownstreamAddress(currentPrefix);
1003 if (srvAddr == null) {
1004 mLog.e("Fail to request a new downstream prefix");
1005 return;
1006 }
1007 mIpv4Address = new LinkAddress(srvAddr, currentPrefix.getPrefixLength());
1008
1009 // Add new IPv4 address on the interface.
1010 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1011 mLog.e("Failed to add new IP " + srvAddr);
1012 return;
1013 }
1014
1015 // Remove deprecated routes from local network.
1016 removeRoutesFromLocalNetwork(
1017 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1018 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1019
1020 // Add new routes to local network.
1021 addRoutesToLocalNetwork(
1022 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1023 mLinkProperties.addLinkAddress(mIpv4Address);
1024
1025 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1026 // listen on the interface configured with new IPv4 address, that results DNS validation
1027 // failure of downstream client even if appropriate routes have been configured.
1028 try {
1029 mNetd.tetherApplyDnsInterfaces();
1030 } catch (ServiceSpecificException | RemoteException e) {
1031 mLog.e("Failed to update local DNS caching server");
1032 return;
1033 }
1034 sendLinkProperties();
1035
1036 // Notify DHCP server that new prefix/route has been applied on IpServer.
1037 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1038 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1039 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1040 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1041 try {
1042 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1043 @Override
1044 public void callback(int statusCode) {
1045 if (statusCode != STATUS_SUCCESS) {
1046 mLog.e("Error updating DHCP serving params: " + statusCode);
1047 }
1048 }
1049 });
1050 } catch (RemoteException e) {
1051 mLog.e("Error updating DHCP serving params", e);
1052 }
1053 }
1054
Mark Chiencd309132020-05-25 02:04:59 +00001055 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001056 try {
1057 int upstreamHopLimit = Integer.parseUnsignedInt(
1058 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
Mark Chiencd309132020-05-25 02:04:59 +00001059 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001060 // Cap the hop limit to 255.
1061 return (byte) Integer.min(upstreamHopLimit, 255);
1062 } catch (Exception e) {
1063 mLog.e("Failed to find upstream interface hop limit", e);
1064 }
1065 return RaParams.DEFAULT_HOPLIMIT;
1066 }
1067
1068 private void setRaParams(RaParams newParams) {
1069 if (mRaDaemon != null) {
1070 final RaParams deprecatedParams =
1071 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1072
1073 configureLocalIPv6Routes(deprecatedParams.prefixes,
1074 (newParams != null) ? newParams.prefixes : null);
1075
1076 configureLocalIPv6Dns(deprecatedParams.dnses,
1077 (newParams != null) ? newParams.dnses : null);
1078
1079 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1080 }
1081
1082 mLastRaParams = newParams;
1083 }
1084
1085 private void logMessage(State state, int what) {
1086 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
1087 }
1088
1089 private void sendInterfaceState(int newInterfaceState) {
1090 mServingMode = newInterfaceState;
1091 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1092 sendLinkProperties();
1093 }
1094
1095 private void sendLinkProperties() {
1096 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1097 }
1098
1099 private void resetLinkProperties() {
1100 mLinkProperties.clear();
1101 mLinkProperties.setInterfaceName(mIfaceName);
1102 }
1103
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001104 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
Treehugger Robot5da10702020-03-30 04:23:55 +00001105 // Ignore static address configuration if they are invalid or null. In theory, static
1106 // addresses should not be invalid here because TetheringManager do not allow caller to
1107 // specify invalid static address configuration.
1108 if (request == null || request.localIPv4Address == null
1109 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1110 request.localIPv4Address, request.staticClientAddress)) {
1111 return;
1112 }
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001113
1114 mStaticIpv4ServerAddr = request.localIPv4Address;
1115 mStaticIpv4ClientAddr = request.staticClientAddress;
1116 }
1117
markchien74a4fa92019-09-09 20:50:49 +08001118 class InitialState extends State {
1119 @Override
1120 public void enter() {
1121 sendInterfaceState(STATE_AVAILABLE);
1122 }
1123
1124 @Override
1125 public boolean processMessage(Message message) {
1126 logMessage(this, message.what);
1127 switch (message.what) {
1128 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001129 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001130 switch (message.arg1) {
1131 case STATE_LOCAL_ONLY:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001132 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001133 transitionTo(mLocalHotspotState);
1134 break;
1135 case STATE_TETHERED:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001136 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001137 transitionTo(mTetheredState);
1138 break;
1139 default:
1140 mLog.e("Invalid tethering interface serving state specified.");
1141 }
1142 break;
1143 case CMD_INTERFACE_DOWN:
1144 transitionTo(mUnavailableState);
1145 break;
1146 case CMD_IPV6_TETHER_UPDATE:
Mark Chiencd309132020-05-25 02:04:59 +00001147 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001148 break;
1149 default:
1150 return NOT_HANDLED;
1151 }
1152 return HANDLED;
1153 }
1154 }
1155
1156 class BaseServingState extends State {
1157 @Override
1158 public void enter() {
1159 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001160 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001161 return;
1162 }
1163
1164 try {
Xiao Ma65401342020-05-14 06:52:59 +00001165 NetdUtils.tetherInterface(mNetd, mIfaceName, PrefixUtils.asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001166 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma65401342020-05-14 06:52:59 +00001167 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001168 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001169 return;
1170 }
1171
1172 if (!startIPv6()) {
1173 mLog.e("Failed to startIPv6");
1174 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1175 return;
1176 }
1177 }
1178
1179 @Override
1180 public void exit() {
1181 // Note that at this point, we're leaving the tethered state. We can fail any
1182 // of these operations, but it doesn't really change that we have to try them
1183 // all in sequence.
1184 stopIPv6();
1185
1186 try {
markchien12c5bb82020-01-07 14:43:17 +08001187 NetdUtils.untetherInterface(mNetd, mIfaceName);
1188 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001189 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001190 mLog.e("Failed to untether interface: " + e);
1191 }
1192
1193 stopIPv4();
1194
1195 resetLinkProperties();
1196 }
1197
1198 @Override
1199 public boolean processMessage(Message message) {
1200 logMessage(this, message.what);
1201 switch (message.what) {
1202 case CMD_TETHER_UNREQUESTED:
1203 transitionTo(mInitialState);
1204 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1205 break;
1206 case CMD_INTERFACE_DOWN:
1207 transitionTo(mUnavailableState);
1208 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1209 break;
1210 case CMD_IPV6_TETHER_UPDATE:
Mark Chiencd309132020-05-25 02:04:59 +00001211 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001212 sendLinkProperties();
1213 break;
1214 case CMD_IP_FORWARDING_ENABLE_ERROR:
1215 case CMD_IP_FORWARDING_DISABLE_ERROR:
1216 case CMD_START_TETHERING_ERROR:
1217 case CMD_STOP_TETHERING_ERROR:
1218 case CMD_SET_DNS_FORWARDERS_ERROR:
markchienf1332572020-03-19 13:37:43 +08001219 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001220 transitionTo(mInitialState);
1221 break;
Xiao Ma65401342020-05-14 06:52:59 +00001222 case CMD_NEW_PREFIX_REQUEST:
1223 handleNewPrefixRequest((IpPrefix) message.obj);
1224 break;
markchien74a4fa92019-09-09 20:50:49 +08001225 default:
1226 return false;
1227 }
1228 return true;
1229 }
1230 }
1231
1232 // Handling errors in BaseServingState.enter() by transitioning is
1233 // problematic because transitioning during a multi-state jump yields
1234 // a Log.wtf(). Ultimately, there should be only one ServingState,
1235 // and forwarding and NAT rules should be handled by a coordinating
1236 // functional element outside of IpServer.
1237 class LocalHotspotState extends BaseServingState {
1238 @Override
1239 public void enter() {
1240 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001241 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001242 transitionTo(mInitialState);
1243 }
1244
1245 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1246 sendInterfaceState(STATE_LOCAL_ONLY);
1247 }
1248
1249 @Override
1250 public boolean processMessage(Message message) {
1251 if (super.processMessage(message)) return true;
1252
1253 logMessage(this, message.what);
1254 switch (message.what) {
1255 case CMD_TETHER_REQUESTED:
1256 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1257 break;
1258 case CMD_TETHER_CONNECTION_CHANGED:
1259 // Ignored in local hotspot state.
1260 break;
1261 default:
1262 return false;
1263 }
1264 return true;
1265 }
1266 }
1267
1268 // Handling errors in BaseServingState.enter() by transitioning is
1269 // problematic because transitioning during a multi-state jump yields
1270 // a Log.wtf(). Ultimately, there should be only one ServingState,
1271 // and forwarding and NAT rules should be handled by a coordinating
1272 // functional element outside of IpServer.
1273 class TetheredState extends BaseServingState {
1274 @Override
1275 public void enter() {
1276 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001277 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001278 transitionTo(mInitialState);
1279 }
1280
1281 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1282 sendInterfaceState(STATE_TETHERED);
1283 }
1284
1285 @Override
1286 public void exit() {
1287 cleanupUpstream();
1288 super.exit();
1289 }
1290
1291 private void cleanupUpstream() {
1292 if (mUpstreamIfaceSet == null) return;
1293
1294 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1295 mUpstreamIfaceSet = null;
Automerger Merge Workerf1194882020-02-25 04:04:44 +00001296 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001297 }
1298
1299 private void cleanupUpstreamInterface(String upstreamIface) {
1300 // Note that we don't care about errors here.
1301 // Sometimes interfaces are gone before we get
1302 // to remove their rules, which generates errors.
1303 // Just do the best we can.
1304 try {
markchien12c5bb82020-01-07 14:43:17 +08001305 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1306 } catch (RemoteException | ServiceSpecificException e) {
1307 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001308 }
1309 try {
markchien12c5bb82020-01-07 14:43:17 +08001310 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1311 } catch (RemoteException | ServiceSpecificException e) {
1312 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001313 }
1314 }
1315
1316 @Override
1317 public boolean processMessage(Message message) {
1318 if (super.processMessage(message)) return true;
1319
1320 logMessage(this, message.what);
1321 switch (message.what) {
1322 case CMD_TETHER_REQUESTED:
1323 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1324 break;
1325 case CMD_TETHER_CONNECTION_CHANGED:
1326 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1327 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1328 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1329 break;
1330 }
1331
1332 if (newUpstreamIfaceSet == null) {
1333 cleanupUpstream();
1334 break;
1335 }
1336
1337 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1338 cleanupUpstreamInterface(removed);
1339 }
1340
1341 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1342 // This makes the call to cleanupUpstream() in the error
1343 // path for any interface neatly cleanup all the interfaces.
1344 mUpstreamIfaceSet = newUpstreamIfaceSet;
1345
1346 for (String ifname : added) {
1347 try {
markchien12c5bb82020-01-07 14:43:17 +08001348 mNetd.tetherAddForward(mIfaceName, ifname);
1349 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1350 } catch (RemoteException | ServiceSpecificException e) {
1351 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001352 cleanupUpstream();
markchienf1332572020-03-19 13:37:43 +08001353 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001354 transitionTo(mInitialState);
1355 return true;
1356 }
1357 }
1358 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001359 case CMD_NEIGHBOR_EVENT:
1360 handleNeighborEvent((NeighborEvent) message.obj);
1361 break;
markchien74a4fa92019-09-09 20:50:49 +08001362 default:
1363 return false;
1364 }
1365 return true;
1366 }
1367
1368 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1369 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1370 if (mUpstreamIfaceSet != null && newIfaces != null) {
1371 return mUpstreamIfaceSet.equals(newIfaces);
1372 }
1373 return false;
1374 }
1375
1376 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1377 if (mUpstreamIfaceSet == null) return new HashSet<>();
1378
1379 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1380 removed.removeAll(newIfaces.ifnames);
1381 return removed;
1382 }
1383
1384 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1385 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1386 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1387 return added;
1388 }
1389 }
1390
1391 /**
1392 * This state is terminal for the per interface state machine. At this
1393 * point, the master state machine should have removed this interface
1394 * specific state machine from its list of possible recipients of
1395 * tethering requests. The state machine itself will hang around until
1396 * the garbage collector finds it.
1397 */
1398 class UnavailableState extends State {
1399 @Override
1400 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001401 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001402 sendInterfaceState(STATE_UNAVAILABLE);
1403 }
1404 }
1405
1406 // Accumulate routes representing "prefixes to be assigned to the local
1407 // interface", for subsequent modification of local_network routing.
1408 private static ArrayList<RouteInfo> getLocalRoutesFor(
1409 String ifname, HashSet<IpPrefix> prefixes) {
1410 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1411 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001412 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001413 }
1414 return localRoutes;
1415 }
1416
1417 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1418 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1419 final byte[] dnsBytes = localPrefix.getRawAddress();
1420 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1421 try {
1422 return Inet6Address.getByAddress(null, dnsBytes, 0);
1423 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001424 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001425 return null;
1426 }
1427 }
1428
1429 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1430 final byte random = (byte) (new Random()).nextInt();
1431 for (int value : excluded) {
1432 if (random == value) return dflt;
1433 }
1434 return random;
1435 }
1436}