blob: 5f182a9cc0db76e6755637182668d77188e3cfe3 [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;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090022import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH;
markchien74a4fa92019-09-09 20:50:49 +080023import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
24import static android.net.util.NetworkConstants.asByte;
Mark Chien2ecd3332020-05-29 22:07:37 +000025import static android.net.util.PrefixUtils.asIpPrefix;
markchien6cf0e552019-12-06 15:24:53 +080026import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Automerger Merge Worker0010ca02020-03-16 04:06:46 +000027import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080028
markchien74a4fa92019-09-09 20:50:49 +080029import android.net.INetd;
30import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080031import android.net.IpPrefix;
32import android.net.LinkAddress;
33import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090034import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080035import android.net.RouteInfo;
Lorenzo Colittie6107d22020-04-06 09:19:57 +000036import android.net.TetherOffloadRuleParcel;
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;
Mark Chien2ecd3332020-05-29 22:07:37 +000069import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +080070
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090071import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080072import java.net.Inet4Address;
73import java.net.Inet6Address;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090074import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080075import java.net.UnknownHostException;
76import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090077import java.util.Arrays;
78import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080079import java.util.HashSet;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090080import java.util.LinkedHashMap;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090081import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080082import java.util.Objects;
83import java.util.Random;
84import java.util.Set;
85
86/**
87 * Provides the interface to IP-layer serving functionality for a given network
88 * interface, e.g. for tethering or "local-only hotspot" mode.
89 *
90 * @hide
91 */
92public class IpServer extends StateMachine {
93 public static final int STATE_UNAVAILABLE = 0;
94 public static final int STATE_AVAILABLE = 1;
95 public static final int STATE_TETHERED = 2;
96 public static final int STATE_LOCAL_ONLY = 3;
97
98 /** Get string name of |state|.*/
99 public static String getStateString(int state) {
100 switch (state) {
101 case STATE_UNAVAILABLE: return "UNAVAILABLE";
102 case STATE_AVAILABLE: return "AVAILABLE";
103 case STATE_TETHERED: return "TETHERED";
104 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
105 }
106 return "UNKNOWN: " + state;
107 }
108
109 private static final byte DOUG_ADAMS = (byte) 42;
110
markchien74a4fa92019-09-09 20:50:49 +0800111 // TODO: have PanService use some visible version of this constant
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
275 static class Ipv6ForwardingRule {
276 public final int upstreamIfindex;
277 public final int downstreamIfindex;
278 public final Inet6Address address;
279 public final MacAddress srcMac;
280 public final MacAddress dstMac;
281
282 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
283 MacAddress srcMac, MacAddress dstMac) {
284 this.upstreamIfindex = upstreamIfindex;
285 this.downstreamIfindex = downstreamIfIndex;
286 this.address = address;
287 this.srcMac = srcMac;
288 this.dstMac = dstMac;
289 }
290
291 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
292 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
293 dstMac);
294 }
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000295
296 // Don't manipulate TetherOffloadRuleParcel directly because implementing onNewUpstream()
297 // would be error-prone due to generated stable AIDL classes not having a copy constructor.
298 public TetherOffloadRuleParcel toTetherOffloadRuleParcel() {
299 final TetherOffloadRuleParcel parcel = new TetherOffloadRuleParcel();
300 parcel.inputInterfaceIndex = upstreamIfindex;
301 parcel.outputInterfaceIndex = downstreamIfindex;
302 parcel.destination = address.getAddress();
303 parcel.prefixLength = 128;
304 parcel.srcL2Address = srcMac.toByteArray();
305 parcel.dstL2Address = dstMac.toByteArray();
306 return parcel;
307 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900308 }
309 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
310 new LinkedHashMap<>();
311
312 private final IpNeighborMonitor mIpNeighborMonitor;
313
Mark Chien2ecd3332020-05-29 22:07:37 +0000314 private LinkAddress mIpv4Address;
315
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000316 // TODO: Add a dependency object to pass the data members or variables from the tethering
317 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800318 public IpServer(
319 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chend50f53b2020-06-02 00:13:26 +0000320 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
321 boolean usingLegacyDhcp, boolean usingBpfOffload,
Mark Chien2ecd3332020-05-29 22:07:37 +0000322 PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800323 super(ifaceName, looper);
324 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800325 mNetd = netd;
Hungming Chend50f53b2020-06-02 00:13:26 +0000326 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800327 mCallback = callback;
328 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
329 mIfaceName = ifaceName;
330 mInterfaceType = interfaceType;
331 mLinkProperties = new LinkProperties();
332 mUsingLegacyDhcp = usingLegacyDhcp;
Nucca Chen0bbfe122020-05-12 11:34:28 +0000333 mUsingBpfOffload = usingBpfOffload;
Mark Chien2ecd3332020-05-29 22:07:37 +0000334 mPrivateAddressCoordinator = addressCoordinator;
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();
Mark Chien2ecd3332020-05-29 22:07:37 +0000355 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800356 addState(mInitialState);
357 addState(mLocalHotspotState);
358 addState(mTetheredState);
Mark Chien2ecd3332020-05-29 22:07:37 +0000359 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800360 addState(mUnavailableState);
361
362 setInitialState(mInitialState);
363 }
364
365 /** Interface name which IpServer served.*/
366 public String interfaceName() {
367 return mIfaceName;
368 }
369
370 /**
markchien9b4d7572019-12-25 19:40:32 +0800371 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800372 */
373 public int interfaceType() {
374 return mInterfaceType;
375 }
376
377 /** Last error from this IpServer. */
378 public int lastError() {
379 return mLastError;
380 }
381
382 /** Serving mode is the current state of IpServer state machine. */
383 public int servingMode() {
384 return mServingMode;
385 }
386
387 /** The properties of the network link which IpServer is serving. */
388 public LinkProperties linkProperties() {
389 return new LinkProperties(mLinkProperties);
390 }
391
Mark Chien2ecd3332020-05-29 22:07:37 +0000392 /** The address which IpServer is using. */
393 public LinkAddress getAddress() {
394 return mIpv4Address;
395 }
396
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900397 /**
398 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
399 * thread.
400 */
401 public List<TetheredClient> getAllLeases() {
402 return Collections.unmodifiableList(mDhcpLeases);
403 }
404
markchien74a4fa92019-09-09 20:50:49 +0800405 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
406 public void stop() {
407 sendMessage(CMD_INTERFACE_DOWN);
408 }
409
410 /**
411 * Tethering is canceled. IpServer state machine will be available and wait for
412 * next tethering request.
413 */
414 public void unwanted() {
415 sendMessage(CMD_TETHER_UNREQUESTED);
416 }
417
418 /** Internals. */
419
420 private boolean startIPv4() {
421 return configureIPv4(true);
422 }
423
424 /**
425 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
426 * handler.
427 *
428 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
429 * with different implementations of the callback, to differentiate handling of success/error in
430 * each call.
431 */
432 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
433 @Override
434 public void onStatusAvailable(int statusCode) {
435 getHandler().post(() -> callback(statusCode));
436 }
437
438 public abstract void callback(int statusCode);
439
440 @Override
441 public int getInterfaceVersion() {
442 return this.VERSION;
443 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900444
445 @Override
446 public String getInterfaceHash() {
447 return this.HASH;
448 }
markchien74a4fa92019-09-09 20:50:49 +0800449 }
450
451 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
452 private final int mStartIndex;
453
454 private DhcpServerCallbacksImpl(int startIndex) {
455 mStartIndex = startIndex;
456 }
457
458 @Override
459 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
460 getHandler().post(() -> {
461 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
462 if (mStartIndex != mDhcpServerStartIndex) {
463 // This start request is obsolete. When the |server| binder token goes out of
464 // scope, the garbage collector will finalize it, which causes the network stack
465 // process garbage collector to collect the server itself.
466 return;
467 }
468
469 if (statusCode != STATUS_SUCCESS) {
470 mLog.e("Error obtaining DHCP server: " + statusCode);
471 handleError();
472 return;
473 }
474
475 mDhcpServer = server;
476 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900477 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800478 @Override
479 public void callback(int startStatusCode) {
480 if (startStatusCode != STATUS_SUCCESS) {
481 mLog.e("Error starting DHCP server: " + startStatusCode);
482 handleError();
483 }
484 }
Xiao Ma65401342020-05-14 06:52:59 +0000485 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800486 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800487 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800488 }
489 });
490 }
491
492 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800493 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800494 transitionTo(mInitialState);
495 }
496 }
497
Xiao Ma65401342020-05-14 06:52:59 +0000498 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900499 @Override
500 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
501 final ArrayList<TetheredClient> leases = new ArrayList<>();
502 for (DhcpLeaseParcelable lease : leaseParcelables) {
503 final LinkAddress address = new LinkAddress(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000504 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
505 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
506 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900507
508 final MacAddress macAddress;
509 try {
510 macAddress = MacAddress.fromBytes(lease.hwAddr);
511 } catch (IllegalArgumentException e) {
512 Log.wtf(TAG, "Invalid address received from DhcpServer: "
513 + Arrays.toString(lease.hwAddr));
514 return;
515 }
516
517 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000518 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900519 leases.add(new TetheredClient(
520 macAddress,
521 Collections.singletonList(addressInfo),
522 mInterfaceType));
523 }
524
525 getHandler().post(() -> {
526 mDhcpLeases = leases;
527 mCallback.dhcpLeasesChanged();
528 });
529 }
530
531 @Override
Xiao Ma65401342020-05-14 06:52:59 +0000532 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
533 Objects.requireNonNull(currentPrefix);
534 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma06c8ba02020-04-06 11:24:48 +0000535 }
536
537 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900538 public int getInterfaceVersion() {
539 return this.VERSION;
540 }
541
542 @Override
543 public String getInterfaceHash() throws RemoteException {
544 return this.HASH;
545 }
546 }
547
Xiao Ma65401342020-05-14 06:52:59 +0000548 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
549 Objects.requireNonNull(ipv4Address);
550 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
551 }
552
553 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
554 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
555 @Nullable Inet4Address clientAddr) {
556 final boolean changePrefixOnDecline =
557 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
558 return new DhcpServingParamsParcelExt()
559 .setDefaultRouters(defaultRouter)
560 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
561 .setDnsServers(dnsServer)
562 .setServerAddr(serverAddr)
563 .setMetered(true)
564 .setSingleClientAddr(clientAddr)
565 .setChangePrefixOnDecline(changePrefixOnDecline);
566 // TODO: also advertise link MTU
567 }
568
Treehugger Robot5da10702020-03-30 04:23:55 +0000569 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800570 if (mUsingLegacyDhcp) {
571 return true;
572 }
Treehugger Robot5da10702020-03-30 04:23:55 +0000573
574 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
Treehugger Robot5da10702020-03-30 04:23:55 +0000575 final Inet4Address clientAddr = clientLinkAddr == null ? null :
576 (Inet4Address) clientLinkAddr.getAddress();
577
Xiao Ma65401342020-05-14 06:52:59 +0000578 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
579 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800580 mDhcpServerStartIndex++;
581 mDeps.makeDhcpServer(
582 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
583 return true;
584 }
585
586 private void stopDhcp() {
587 // Make all previous start requests obsolete so servers are not started later
588 mDhcpServerStartIndex++;
589
590 if (mDhcpServer != null) {
591 try {
592 mDhcpServer.stop(new OnHandlerStatusCallback() {
593 @Override
594 public void callback(int statusCode) {
595 if (statusCode != STATUS_SUCCESS) {
596 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800597 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800598 // Not much more we can do here
599 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900600 mDhcpLeases.clear();
601 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800602 }
603 });
604 mDhcpServer = null;
605 } catch (RemoteException e) {
Xiao Ma65401342020-05-14 06:52:59 +0000606 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800607 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800608 }
609 }
610 }
611
Treehugger Robot5da10702020-03-30 04:23:55 +0000612 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
613 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800614 if (enable) {
Treehugger Robot5da10702020-03-30 04:23:55 +0000615 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800616 } else {
617 stopDhcp();
618 return true;
619 }
620 }
621
622 private void stopIPv4() {
623 configureIPv4(false);
624 // NOTE: All of configureIPv4() will be refactored out of existence
625 // into calls to InterfaceController, shared with startIPv4().
626 mInterfaceCtrl.clearIPv4Address();
Mark Chien2ecd3332020-05-29 22:07:37 +0000627 mPrivateAddressCoordinator.releaseDownstream(this);
markchien12c5bb82020-01-07 14:43:17 +0800628 mIpv4Address = null;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000629 mStaticIpv4ServerAddr = null;
630 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800631 }
632
markchien74a4fa92019-09-09 20:50:49 +0800633 private boolean configureIPv4(boolean enabled) {
634 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
635
Mark Chien2ecd3332020-05-29 22:07:37 +0000636 if (enabled) {
637 mIpv4Address = requestIpv4Address();
638 }
639
640 if (mIpv4Address == null) {
641 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800642 return false;
markchien74a4fa92019-09-09 20:50:49 +0800643 }
644
Mark Chien2ecd3332020-05-29 22:07:37 +0000645 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
646 // BT configures the interface elsewhere: only start DHCP.
647 // TODO: make all tethering types behave the same way, and delete the bluetooth
648 // code that calls into NetworkManagementService directly.
649 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
650 }
651
652 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
653
markchien12c5bb82020-01-07 14:43:17 +0800654 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800655 if (mInterfaceType == TetheringManager.TETHERING_WIFI
656 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800657 // The WiFi stack has ownership of the interface up/down state.
658 // It is unclear whether the Bluetooth or USB stacks will manage their own
659 // state.
660 setIfaceUp = null;
661 } else {
662 setIfaceUp = enabled;
663 }
664 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
665 mLog.e("Error configuring interface");
666 if (!enabled) stopDhcp();
667 return false;
668 }
markchien74a4fa92019-09-09 20:50:49 +0800669
markchien74a4fa92019-09-09 20:50:49 +0800670 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800671 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma65401342020-05-14 06:52:59 +0000672 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800673 } else {
markchien12c5bb82020-01-07 14:43:17 +0800674 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma65401342020-05-14 06:52:59 +0000675 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800676 }
Treehugger Robot5da10702020-03-30 04:23:55 +0000677 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800678 }
679
Mark Chien2ecd3332020-05-29 22:07:37 +0000680 private LinkAddress requestIpv4Address() {
681 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800682
Mark Chien2ecd3332020-05-29 22:07:37 +0000683 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
684 return new LinkAddress(BLUETOOTH_IFACE_ADDR);
685 }
686
687 return mPrivateAddressCoordinator.requestDownstreamAddress(this);
Xiao Ma65401342020-05-14 06:52:59 +0000688 }
689
markchien74a4fa92019-09-09 20:50:49 +0800690 private boolean startIPv6() {
691 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
692 if (mInterfaceParams == null) {
693 mLog.e("Failed to find InterfaceParams");
694 stopIPv6();
695 return false;
696 }
697
698 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
699 if (!mRaDaemon.start()) {
700 stopIPv6();
701 return false;
702 }
703
704 return true;
705 }
706
707 private void stopIPv6() {
708 mInterfaceParams = null;
709 setRaParams(null);
710
711 if (mRaDaemon != null) {
712 mRaDaemon.stop();
713 mRaDaemon = null;
714 }
715 }
716
717 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
718 // LinkProperties. These have extraneous data filtered out and only the
719 // necessary prefixes included (per its prefix distribution policy).
720 //
721 // TODO: Evaluate using a data structure than is more directly suited to
722 // communicating only the relevant information.
Mark Chiencd309132020-05-25 02:04:59 +0000723 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800724 if (mRaDaemon == null) return;
725
726 // Avoid unnecessary work on spurious updates.
727 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
728 return;
729 }
730
731 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900732 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800733
734 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900735 final String upstreamIface = v6only.getInterfaceName();
736
markchien74a4fa92019-09-09 20:50:49 +0800737 params = new RaParams();
Maciej Żenczykowskib5898ad2020-05-28 03:21:31 -0700738 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800739 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
740
Mark Chiencd309132020-05-25 02:04:59 +0000741 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800742
743 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
744 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
745
746 final IpPrefix prefix = new IpPrefix(
747 linkAddr.getAddress(), linkAddr.getPrefixLength());
748 params.prefixes.add(prefix);
749
750 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
751 if (dnsServer != null) {
752 params.dnses.add(dnsServer);
753 }
754 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900755
756 upstreamIfindex = mDeps.getIfindex(upstreamIface);
Hungming Chend50f53b2020-06-02 00:13:26 +0000757
758 // Add upstream index to name mapping for the tether stats usage in the coordinator.
759 // Although this mapping could be added by both class Tethering and IpServer, adding
760 // mapping from IpServer guarantees that the mapping is added before the adding
761 // forwarding rules. That is because there are different state machines in both
762 // classes. It is hard to guarantee the link property update order between multiple
763 // state machines.
764 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfindex, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800765 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900766
markchien74a4fa92019-09-09 20:50:49 +0800767 // If v6only is null, we pass in null to setRaParams(), which handles
768 // deprecation of any existing RA data.
769
770 setRaParams(params);
771 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900772
773 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
774 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800775 }
776
Xiao Ma65401342020-05-14 06:52:59 +0000777 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
778 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
779 mNetd, toBeRemoved);
780 if (removalFailures > 0) {
781 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
782 removalFailures));
783 }
784
785 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
786 }
787
788 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
789 try {
790 // It's safe to call networkAddInterface() even if
791 // the interface is already in the local_network.
792 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
793 try {
794 // Add routes from local network. Note that adding routes that
795 // already exist does not cause an error (EEXIST is silently ignored).
796 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
797 } catch (IllegalStateException e) {
798 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
799 return;
800 }
801 } catch (ServiceSpecificException | RemoteException e) {
802 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
803 return;
804 }
805
806 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
807 }
808
markchien74a4fa92019-09-09 20:50:49 +0800809 private void configureLocalIPv6Routes(
810 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
811 // [1] Remove the routes that are deprecated.
812 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma65401342020-05-14 06:52:59 +0000813 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800814 }
815
816 // [2] Add only the routes that have not previously been added.
817 if (newPrefixes != null && !newPrefixes.isEmpty()) {
818 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
819 if (mLastRaParams != null) {
820 addedPrefixes.removeAll(mLastRaParams.prefixes);
821 }
822
823 if (!addedPrefixes.isEmpty()) {
Xiao Ma65401342020-05-14 06:52:59 +0000824 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800825 }
826 }
827 }
828
829 private void configureLocalIPv6Dns(
830 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
831 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
832 if (mNetd == null) {
833 if (newDnses != null) newDnses.clear();
834 mLog.e("No netd service instance available; not setting local IPv6 addresses");
835 return;
836 }
837
838 // [1] Remove deprecated local DNS IP addresses.
839 if (!deprecatedDnses.isEmpty()) {
840 for (Inet6Address dns : deprecatedDnses) {
841 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
842 mLog.e("Failed to remove local dns IP " + dns);
843 }
844
845 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
846 }
847 }
848
849 // [2] Add only the local DNS IP addresses that have not previously been added.
850 if (newDnses != null && !newDnses.isEmpty()) {
851 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
852 if (mLastRaParams != null) {
853 addedDnses.removeAll(mLastRaParams.dnses);
854 }
855
856 for (Inet6Address dns : addedDnses) {
857 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
858 mLog.e("Failed to add local dns IP " + dns);
859 newDnses.remove(dns);
860 }
861
862 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
863 }
864 }
865
866 try {
867 mNetd.tetherApplyDnsInterfaces();
868 } catch (ServiceSpecificException | RemoteException e) {
869 mLog.e("Failed to update local DNS caching server");
870 if (newDnses != null) newDnses.clear();
871 }
872 }
873
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900874 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Nucca Chen0bbfe122020-05-12 11:34:28 +0000875 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
876 // offload is disabled. Add this check just in case.
877 // TODO: Perhaps remove this protection check.
878 if (!mUsingBpfOffload) return;
879
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900880 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000881 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900882 mIpv6ForwardingRules.put(rule.address, rule);
883 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000884 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900885 }
886 }
887
888 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
Nucca Chen0bbfe122020-05-12 11:34:28 +0000889 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
890 // offload is disabled. Add this check just in case.
891 // TODO: Perhaps remove this protection check.
892 if (!mUsingBpfOffload) return;
893
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900894 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000895 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900896 if (removeFromMap) {
897 mIpv6ForwardingRules.remove(rule.address);
898 }
899 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000900 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900901 }
902 }
903
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000904 private void clearIpv6ForwardingRules() {
905 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
906 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
907 }
908 mIpv6ForwardingRules.clear();
909 }
910
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900911 // Convenience method to replace a rule with the same rule on a new upstream interface.
912 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
913 // Relies on the fact that rules are in a map indexed by IP address.
914 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
915 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
916 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
917 }
918
919 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
920 // changes or if a neighbor event is received.
921 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
922 NeighborEvent e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000923 // If we no longer have an upstream, clear forwarding rules and do nothing else.
924 if (upstreamIfindex == 0) {
925 clearIpv6ForwardingRules();
926 return;
927 }
928
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900929 // If the upstream interface has changed, remove all rules and re-add them with the new
930 // upstream interface.
931 if (prevUpstreamIfindex != upstreamIfindex) {
932 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
933 updateIpv6ForwardingRule(rule, upstreamIfindex);
934 }
935 }
936
937 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000938 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900939 if (e == null) return;
940 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
941 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
942 return;
943 }
944
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000945 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
946 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
947 // add rules with a null MAC, only delete them.
948 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000949 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000950 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900951 if (e.isValid()) {
952 addIpv6ForwardingRule(rule);
953 } else {
954 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
955 }
956 }
957
958 private void handleNeighborEvent(NeighborEvent e) {
959 if (mInterfaceParams != null
960 && mInterfaceParams.index == e.ifindex
961 && mInterfaceParams.hasMacAddress) {
962 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
963 }
964 }
965
Xiao Ma65401342020-05-14 06:52:59 +0000966 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
967 if (!currentPrefix.contains(mIpv4Address.getAddress())
968 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
969 Log.e(TAG, "Invalid prefix: " + currentPrefix);
970 return;
971 }
972
973 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark Chien2ecd3332020-05-29 22:07:37 +0000974 mIpv4Address = requestIpv4Address();
975 if (mIpv4Address == null) {
Xiao Ma65401342020-05-14 06:52:59 +0000976 mLog.e("Fail to request a new downstream prefix");
977 return;
978 }
Mark Chien2ecd3332020-05-29 22:07:37 +0000979 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma65401342020-05-14 06:52:59 +0000980
981 // Add new IPv4 address on the interface.
982 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
983 mLog.e("Failed to add new IP " + srvAddr);
984 return;
985 }
986
987 // Remove deprecated routes from local network.
988 removeRoutesFromLocalNetwork(
989 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
990 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
991
992 // Add new routes to local network.
993 addRoutesToLocalNetwork(
994 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
995 mLinkProperties.addLinkAddress(mIpv4Address);
996
997 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
998 // listen on the interface configured with new IPv4 address, that results DNS validation
999 // failure of downstream client even if appropriate routes have been configured.
1000 try {
1001 mNetd.tetherApplyDnsInterfaces();
1002 } catch (ServiceSpecificException | RemoteException e) {
1003 mLog.e("Failed to update local DNS caching server");
1004 return;
1005 }
1006 sendLinkProperties();
1007
1008 // Notify DHCP server that new prefix/route has been applied on IpServer.
1009 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1010 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1011 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1012 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1013 try {
1014 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1015 @Override
1016 public void callback(int statusCode) {
1017 if (statusCode != STATUS_SUCCESS) {
1018 mLog.e("Error updating DHCP serving params: " + statusCode);
1019 }
1020 }
1021 });
1022 } catch (RemoteException e) {
1023 mLog.e("Error updating DHCP serving params", e);
1024 }
1025 }
1026
Mark Chiencd309132020-05-25 02:04:59 +00001027 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001028 try {
1029 int upstreamHopLimit = Integer.parseUnsignedInt(
1030 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
Mark Chiencd309132020-05-25 02:04:59 +00001031 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001032 // Cap the hop limit to 255.
1033 return (byte) Integer.min(upstreamHopLimit, 255);
1034 } catch (Exception e) {
1035 mLog.e("Failed to find upstream interface hop limit", e);
1036 }
1037 return RaParams.DEFAULT_HOPLIMIT;
1038 }
1039
1040 private void setRaParams(RaParams newParams) {
1041 if (mRaDaemon != null) {
1042 final RaParams deprecatedParams =
1043 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1044
1045 configureLocalIPv6Routes(deprecatedParams.prefixes,
1046 (newParams != null) ? newParams.prefixes : null);
1047
1048 configureLocalIPv6Dns(deprecatedParams.dnses,
1049 (newParams != null) ? newParams.dnses : null);
1050
1051 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1052 }
1053
1054 mLastRaParams = newParams;
1055 }
1056
1057 private void logMessage(State state, int what) {
1058 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
1059 }
1060
1061 private void sendInterfaceState(int newInterfaceState) {
1062 mServingMode = newInterfaceState;
1063 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1064 sendLinkProperties();
1065 }
1066
1067 private void sendLinkProperties() {
1068 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1069 }
1070
1071 private void resetLinkProperties() {
1072 mLinkProperties.clear();
1073 mLinkProperties.setInterfaceName(mIfaceName);
1074 }
1075
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001076 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
Treehugger Robot5da10702020-03-30 04:23:55 +00001077 // Ignore static address configuration if they are invalid or null. In theory, static
1078 // addresses should not be invalid here because TetheringManager do not allow caller to
1079 // specify invalid static address configuration.
1080 if (request == null || request.localIPv4Address == null
1081 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1082 request.localIPv4Address, request.staticClientAddress)) {
1083 return;
1084 }
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001085
1086 mStaticIpv4ServerAddr = request.localIPv4Address;
1087 mStaticIpv4ClientAddr = request.staticClientAddress;
1088 }
1089
markchien74a4fa92019-09-09 20:50:49 +08001090 class InitialState extends State {
1091 @Override
1092 public void enter() {
1093 sendInterfaceState(STATE_AVAILABLE);
1094 }
1095
1096 @Override
1097 public boolean processMessage(Message message) {
1098 logMessage(this, message.what);
1099 switch (message.what) {
1100 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001101 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001102 switch (message.arg1) {
1103 case STATE_LOCAL_ONLY:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001104 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001105 transitionTo(mLocalHotspotState);
1106 break;
1107 case STATE_TETHERED:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001108 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001109 transitionTo(mTetheredState);
1110 break;
1111 default:
1112 mLog.e("Invalid tethering interface serving state specified.");
1113 }
1114 break;
1115 case CMD_INTERFACE_DOWN:
1116 transitionTo(mUnavailableState);
1117 break;
1118 case CMD_IPV6_TETHER_UPDATE:
Mark Chiencd309132020-05-25 02:04:59 +00001119 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001120 break;
1121 default:
1122 return NOT_HANDLED;
1123 }
1124 return HANDLED;
1125 }
1126 }
1127
1128 class BaseServingState extends State {
1129 @Override
1130 public void enter() {
1131 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001132 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001133 return;
1134 }
1135
1136 try {
Mark Chien2ecd3332020-05-29 22:07:37 +00001137 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001138 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma65401342020-05-14 06:52:59 +00001139 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001140 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001141 return;
1142 }
1143
1144 if (!startIPv6()) {
1145 mLog.e("Failed to startIPv6");
1146 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1147 return;
1148 }
1149 }
1150
1151 @Override
1152 public void exit() {
1153 // Note that at this point, we're leaving the tethered state. We can fail any
1154 // of these operations, but it doesn't really change that we have to try them
1155 // all in sequence.
1156 stopIPv6();
1157
1158 try {
markchien12c5bb82020-01-07 14:43:17 +08001159 NetdUtils.untetherInterface(mNetd, mIfaceName);
1160 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001161 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001162 mLog.e("Failed to untether interface: " + e);
1163 }
1164
1165 stopIPv4();
1166
1167 resetLinkProperties();
1168 }
1169
1170 @Override
1171 public boolean processMessage(Message message) {
1172 logMessage(this, message.what);
1173 switch (message.what) {
1174 case CMD_TETHER_UNREQUESTED:
1175 transitionTo(mInitialState);
1176 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1177 break;
1178 case CMD_INTERFACE_DOWN:
1179 transitionTo(mUnavailableState);
1180 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1181 break;
1182 case CMD_IPV6_TETHER_UPDATE:
Mark Chiencd309132020-05-25 02:04:59 +00001183 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001184 sendLinkProperties();
1185 break;
1186 case CMD_IP_FORWARDING_ENABLE_ERROR:
1187 case CMD_IP_FORWARDING_DISABLE_ERROR:
1188 case CMD_START_TETHERING_ERROR:
1189 case CMD_STOP_TETHERING_ERROR:
1190 case CMD_SET_DNS_FORWARDERS_ERROR:
markchienf1332572020-03-19 13:37:43 +08001191 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001192 transitionTo(mInitialState);
1193 break;
Xiao Ma65401342020-05-14 06:52:59 +00001194 case CMD_NEW_PREFIX_REQUEST:
1195 handleNewPrefixRequest((IpPrefix) message.obj);
1196 break;
Mark Chien2ecd3332020-05-29 22:07:37 +00001197 case CMD_NOTIFY_PREFIX_CONFLICT:
1198 mLog.i("restart tethering: " + mInterfaceType);
1199 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1200 transitionTo(mWaitingForRestartState);
1201 break;
markchien74a4fa92019-09-09 20:50:49 +08001202 default:
1203 return false;
1204 }
1205 return true;
1206 }
1207 }
1208
1209 // Handling errors in BaseServingState.enter() by transitioning is
1210 // problematic because transitioning during a multi-state jump yields
1211 // a Log.wtf(). Ultimately, there should be only one ServingState,
1212 // and forwarding and NAT rules should be handled by a coordinating
1213 // functional element outside of IpServer.
1214 class LocalHotspotState extends BaseServingState {
1215 @Override
1216 public void enter() {
1217 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001218 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001219 transitionTo(mInitialState);
1220 }
1221
1222 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1223 sendInterfaceState(STATE_LOCAL_ONLY);
1224 }
1225
1226 @Override
1227 public boolean processMessage(Message message) {
1228 if (super.processMessage(message)) return true;
1229
1230 logMessage(this, message.what);
1231 switch (message.what) {
1232 case CMD_TETHER_REQUESTED:
1233 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1234 break;
1235 case CMD_TETHER_CONNECTION_CHANGED:
1236 // Ignored in local hotspot state.
1237 break;
1238 default:
1239 return false;
1240 }
1241 return true;
1242 }
1243 }
1244
1245 // Handling errors in BaseServingState.enter() by transitioning is
1246 // problematic because transitioning during a multi-state jump yields
1247 // a Log.wtf(). Ultimately, there should be only one ServingState,
1248 // and forwarding and NAT rules should be handled by a coordinating
1249 // functional element outside of IpServer.
1250 class TetheredState extends BaseServingState {
1251 @Override
1252 public void enter() {
1253 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001254 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001255 transitionTo(mInitialState);
1256 }
1257
1258 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1259 sendInterfaceState(STATE_TETHERED);
1260 }
1261
1262 @Override
1263 public void exit() {
1264 cleanupUpstream();
1265 super.exit();
1266 }
1267
1268 private void cleanupUpstream() {
1269 if (mUpstreamIfaceSet == null) return;
1270
1271 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1272 mUpstreamIfaceSet = null;
Automerger Merge Workerf1194882020-02-25 04:04:44 +00001273 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001274 }
1275
1276 private void cleanupUpstreamInterface(String upstreamIface) {
1277 // Note that we don't care about errors here.
1278 // Sometimes interfaces are gone before we get
1279 // to remove their rules, which generates errors.
1280 // Just do the best we can.
1281 try {
markchien12c5bb82020-01-07 14:43:17 +08001282 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1283 } catch (RemoteException | ServiceSpecificException e) {
1284 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001285 }
1286 try {
markchien12c5bb82020-01-07 14:43:17 +08001287 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1288 } catch (RemoteException | ServiceSpecificException e) {
1289 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001290 }
1291 }
1292
1293 @Override
1294 public boolean processMessage(Message message) {
1295 if (super.processMessage(message)) return true;
1296
1297 logMessage(this, message.what);
1298 switch (message.what) {
1299 case CMD_TETHER_REQUESTED:
1300 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1301 break;
1302 case CMD_TETHER_CONNECTION_CHANGED:
1303 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1304 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1305 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1306 break;
1307 }
1308
1309 if (newUpstreamIfaceSet == null) {
1310 cleanupUpstream();
1311 break;
1312 }
1313
1314 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1315 cleanupUpstreamInterface(removed);
1316 }
1317
1318 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1319 // This makes the call to cleanupUpstream() in the error
1320 // path for any interface neatly cleanup all the interfaces.
1321 mUpstreamIfaceSet = newUpstreamIfaceSet;
1322
1323 for (String ifname : added) {
1324 try {
markchien12c5bb82020-01-07 14:43:17 +08001325 mNetd.tetherAddForward(mIfaceName, ifname);
1326 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1327 } catch (RemoteException | ServiceSpecificException e) {
1328 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001329 cleanupUpstream();
markchienf1332572020-03-19 13:37:43 +08001330 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001331 transitionTo(mInitialState);
1332 return true;
1333 }
1334 }
1335 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001336 case CMD_NEIGHBOR_EVENT:
1337 handleNeighborEvent((NeighborEvent) message.obj);
1338 break;
markchien74a4fa92019-09-09 20:50:49 +08001339 default:
1340 return false;
1341 }
1342 return true;
1343 }
1344
1345 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1346 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1347 if (mUpstreamIfaceSet != null && newIfaces != null) {
1348 return mUpstreamIfaceSet.equals(newIfaces);
1349 }
1350 return false;
1351 }
1352
1353 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1354 if (mUpstreamIfaceSet == null) return new HashSet<>();
1355
1356 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1357 removed.removeAll(newIfaces.ifnames);
1358 return removed;
1359 }
1360
1361 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1362 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1363 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1364 return added;
1365 }
1366 }
1367
1368 /**
1369 * This state is terminal for the per interface state machine. At this
1370 * point, the master state machine should have removed this interface
1371 * specific state machine from its list of possible recipients of
1372 * tethering requests. The state machine itself will hang around until
1373 * the garbage collector finds it.
1374 */
1375 class UnavailableState extends State {
1376 @Override
1377 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001378 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001379 sendInterfaceState(STATE_UNAVAILABLE);
1380 }
1381 }
1382
Mark Chien2ecd3332020-05-29 22:07:37 +00001383 class WaitingForRestartState extends State {
1384 @Override
1385 public boolean processMessage(Message message) {
1386 logMessage(this, message.what);
1387 switch (message.what) {
1388 case CMD_TETHER_UNREQUESTED:
1389 transitionTo(mInitialState);
1390 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1391 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1392 break;
1393 case CMD_INTERFACE_DOWN:
1394 transitionTo(mUnavailableState);
1395 mLog.i("Untethered (interface down) and restarting" + mIfaceName);
1396 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1397 break;
1398 default:
1399 return false;
1400 }
1401 return true;
1402 }
1403 }
1404
markchien74a4fa92019-09-09 20:50:49 +08001405 // Accumulate routes representing "prefixes to be assigned to the local
1406 // interface", for subsequent modification of local_network routing.
1407 private static ArrayList<RouteInfo> getLocalRoutesFor(
1408 String ifname, HashSet<IpPrefix> prefixes) {
1409 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1410 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001411 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001412 }
1413 return localRoutes;
1414 }
1415
1416 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1417 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1418 final byte[] dnsBytes = localPrefix.getRawAddress();
1419 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1420 try {
1421 return Inet6Address.getByAddress(null, dnsBytes, 0);
1422 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001423 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001424 return null;
1425 }
1426 }
1427
1428 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1429 final byte random = (byte) (new Random()).nextInt();
1430 for (int value : excluded) {
1431 if (random == value) return dflt;
1432 }
1433 return random;
1434 }
1435}