blob: 336124dc1b906872d797263a512ad3a77b095933 [file] [log] [blame]
markchien74a4fa92019-09-09 20:50:49 +08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net.ip;
18
markchien6cf0e552019-12-06 15:24:53 +080019import static android.net.RouteInfo.RTN_UNICAST;
markchien245352e2020-02-27 20:27:18 +080020import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080021import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
markchien74a4fa92019-09-09 20:50:49 +080022import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
23import static android.net.util.NetworkConstants.asByte;
markchienc9daba32020-02-12 00:19:21 +080024import static android.net.util.PrefixUtils.asIpPrefix;
markchien6cf0e552019-12-06 15:24:53 +080025import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090026import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080027
Chalard Jean78701642020-07-31 20:00:30 +090028import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
29
markchien74a4fa92019-09-09 20:50:49 +080030import android.net.INetd;
31import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080032import android.net.IpPrefix;
33import android.net.LinkAddress;
34import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090035import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080036import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090037import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080038import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080039import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090040import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080041import android.net.dhcp.DhcpServerCallbacks;
42import android.net.dhcp.DhcpServingParamsParcel;
43import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090044import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080045import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090046import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080047import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080048import android.net.shared.NetdUtils;
49import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080050import android.net.util.InterfaceParams;
51import android.net.util.InterfaceSet;
Xiao Ma4455d6b2020-04-09 10:13:44 +090052import android.net.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080053import android.net.util.SharedLog;
Tyler Wear90e40632020-03-13 11:38:38 -070054import android.os.Build;
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 Ma4455d6b2020-04-09 10:13:44 +090064import 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;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080069import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chenb150b872020-05-23 22:54:49 +080070import com.android.networkstack.tethering.BpfCoordinator.Ipv6ForwardingRule;
markchienc9daba32020-02-12 00:19:21 +080071import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +080072
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090073import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080074import java.net.Inet4Address;
75import java.net.Inet6Address;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090076import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080077import java.net.UnknownHostException;
78import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090079import java.util.Arrays;
80import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080081import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090082import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080083import java.util.Objects;
84import java.util.Random;
85import java.util.Set;
86
87/**
88 * Provides the interface to IP-layer serving functionality for a given network
89 * interface, e.g. for tethering or "local-only hotspot" mode.
90 *
91 * @hide
92 */
93public class IpServer extends StateMachine {
94 public static final int STATE_UNAVAILABLE = 0;
95 public static final int STATE_AVAILABLE = 1;
96 public static final int STATE_TETHERED = 2;
97 public static final int STATE_LOCAL_ONLY = 3;
98
99 /** Get string name of |state|.*/
100 public static String getStateString(int state) {
101 switch (state) {
102 case STATE_UNAVAILABLE: return "UNAVAILABLE";
103 case STATE_AVAILABLE: return "AVAILABLE";
104 case STATE_TETHERED: return "TETHERED";
105 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
106 }
107 return "UNKNOWN: " + state;
108 }
109
110 private static final byte DOUG_ADAMS = (byte) 42;
111
markchien74a4fa92019-09-09 20:50:49 +0800112 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800113 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800114
115 // TODO: have this configurable
116 private static final int DHCP_LEASE_TIME_SECS = 3600;
117
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900118 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
119
markchien74a4fa92019-09-09 20:50:49 +0800120 private static final String TAG = "IpServer";
121 private static final boolean DBG = false;
122 private static final boolean VDBG = false;
123 private static final Class[] sMessageClasses = {
124 IpServer.class
125 };
126 private static final SparseArray<String> sMagicDecoderRing =
127 MessageUtils.findMessageNames(sMessageClasses);
128
129 /** IpServer callback. */
130 public static class Callback {
131 /**
132 * Notify that |who| has changed its tethering state.
133 *
134 * @param who the calling instance of IpServer
135 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800136 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800137 */
markchien9d353822019-12-16 20:15:20 +0800138 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800139
140 /**
141 * Notify that |who| has new LinkProperties.
142 *
143 * @param who the calling instance of IpServer
144 * @param newLp the new LinkProperties to report
145 */
markchien9d353822019-12-16 20:15:20 +0800146 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900147
148 /**
149 * Notify that the DHCP leases changed in one of the IpServers.
150 */
151 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800152
153 /**
154 * Request Tethering change.
155 *
156 * @param tetheringType the downstream type of this IpServer.
157 * @param enabled enable or disable tethering.
158 */
159 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800160 }
161
162 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800163 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700164 /**
165 * Create a DadProxy instance to be used by IpServer.
166 * To support multiple tethered interfaces concurrently DAD Proxy
167 * needs to be supported per IpServer instead of per upstream.
168 */
169 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
170 return new DadProxy(handler, ifParams);
171 }
172
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900173 /** Create an IpNeighborMonitor to be used by this IpServer */
174 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
175 IpNeighborMonitor.NeighborEventConsumer consumer) {
176 return new IpNeighborMonitor(handler, log, consumer);
177 }
178
markchien74a4fa92019-09-09 20:50:49 +0800179 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
180 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
181 return new RouterAdvertisementDaemon(ifParams);
182 }
183
184 /** Get |ifName|'s interface information.*/
185 public InterfaceParams getInterfaceParams(String ifName) {
186 return InterfaceParams.getByName(ifName);
187 }
188
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900189 /** Get |ifName|'s interface index. */
190 public int getIfindex(String ifName) {
191 try {
192 return NetworkInterface.getByName(ifName).getIndex();
193 } catch (IOException | NullPointerException e) {
194 Log.e(TAG, "Can't determine interface index for interface " + ifName);
195 return 0;
196 }
197 }
markchienc9daba32020-02-12 00:19:21 +0800198
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;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800210 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
211 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800213 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
214 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800215 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800216 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
217 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800218 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800219 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800220 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800221 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
222 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800223 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800224 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800225 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800226 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800227 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900228 // new neighbor cache entry on our interface
229 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900230 // request from DHCP server that it wants to have a new prefix
231 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800232 // request from PrivateAddressCoordinator to restart tethering.
233 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800234
235 private final State mInitialState;
236 private final State mLocalHotspotState;
237 private final State mTetheredState;
238 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800239 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800240
241 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800242 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800243 @NonNull
244 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800245 private final Callback mCallback;
246 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800247 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800248
249 private final String mIfaceName;
250 private final int mInterfaceType;
251 private final LinkProperties mLinkProperties;
252 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800253 private final boolean mUsingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800254
255 private final Dependencies mDeps;
256
257 private int mLastError;
258 private int mServingMode;
259 private InterfaceSet mUpstreamIfaceSet; // may change over time
260 private InterfaceParams mInterfaceParams;
261 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
262 // properties are those selected by the IPv6TetheringCoordinator and relayed
263 // to us. By comparison, mLinkProperties contains the addresses and directly
264 // connected routes that have been formed from these properties iff. we have
265 // succeeded in configuring them and are able to announce them within Router
266 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
267 private LinkProperties mLastIPv6LinkProperties;
268 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700269 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800270
271 // To be accessed only on the handler thread
272 private int mDhcpServerStartIndex = 0;
273 private IDhcpServer mDhcpServer;
274 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800275
276 private LinkAddress mStaticIpv4ServerAddr;
277 private LinkAddress mStaticIpv4ClientAddr;
278
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900279 @NonNull
280 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800281
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900282 private int mLastIPv6UpstreamIfindex = 0;
283
284 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
285 public void accept(NeighborEvent e) {
286 sendMessage(CMD_NEIGHBOR_EVENT, e);
287 }
288 }
289
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900290 private final IpNeighborMonitor mIpNeighborMonitor;
291
markchienc9daba32020-02-12 00:19:21 +0800292 private LinkAddress mIpv4Address;
293
Hungming Chen5bc3af92020-05-12 19:15:24 +0800294 // TODO: Add a dependency object to pass the data members or variables from the tethering
295 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800296 public IpServer(
297 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800298 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
299 boolean usingLegacyDhcp, boolean usingBpfOffload,
markchienc9daba32020-02-12 00:19:21 +0800300 PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800301 super(ifaceName, looper);
302 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800303 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800304 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800305 mCallback = callback;
306 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
307 mIfaceName = ifaceName;
308 mInterfaceType = interfaceType;
309 mLinkProperties = new LinkProperties();
310 mUsingLegacyDhcp = usingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800311 mUsingBpfOffload = usingBpfOffload;
markchienc9daba32020-02-12 00:19:21 +0800312 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800313 mDeps = deps;
314 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800315 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800316 mServingMode = STATE_AVAILABLE;
317
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900318 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
319 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800320
Hungming Chen5bc3af92020-05-12 19:15:24 +0800321 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800322 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800323 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800324 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800325 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
326 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900327 }
328
markchien74a4fa92019-09-09 20:50:49 +0800329 mInitialState = new InitialState();
330 mLocalHotspotState = new LocalHotspotState();
331 mTetheredState = new TetheredState();
332 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800333 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800334 addState(mInitialState);
335 addState(mLocalHotspotState);
336 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800337 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800338 addState(mUnavailableState);
339
340 setInitialState(mInitialState);
341 }
342
343 /** Interface name which IpServer served.*/
344 public String interfaceName() {
345 return mIfaceName;
346 }
347
348 /**
markchien9b4d7572019-12-25 19:40:32 +0800349 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800350 */
351 public int interfaceType() {
352 return mInterfaceType;
353 }
354
355 /** Last error from this IpServer. */
356 public int lastError() {
357 return mLastError;
358 }
359
360 /** Serving mode is the current state of IpServer state machine. */
361 public int servingMode() {
362 return mServingMode;
363 }
364
365 /** The properties of the network link which IpServer is serving. */
366 public LinkProperties linkProperties() {
367 return new LinkProperties(mLinkProperties);
368 }
369
markchienc9daba32020-02-12 00:19:21 +0800370 /** The address which IpServer is using. */
371 public LinkAddress getAddress() {
372 return mIpv4Address;
373 }
374
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900375 /**
376 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
377 * thread.
378 */
379 public List<TetheredClient> getAllLeases() {
380 return Collections.unmodifiableList(mDhcpLeases);
381 }
382
markchien74a4fa92019-09-09 20:50:49 +0800383 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
384 public void stop() {
385 sendMessage(CMD_INTERFACE_DOWN);
386 }
387
388 /**
389 * Tethering is canceled. IpServer state machine will be available and wait for
390 * next tethering request.
391 */
392 public void unwanted() {
393 sendMessage(CMD_TETHER_UNREQUESTED);
394 }
395
396 /** Internals. */
397
398 private boolean startIPv4() {
399 return configureIPv4(true);
400 }
401
402 /**
403 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
404 * handler.
405 *
406 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
407 * with different implementations of the callback, to differentiate handling of success/error in
408 * each call.
409 */
410 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
411 @Override
412 public void onStatusAvailable(int statusCode) {
413 getHandler().post(() -> callback(statusCode));
414 }
415
416 public abstract void callback(int statusCode);
417
418 @Override
419 public int getInterfaceVersion() {
420 return this.VERSION;
421 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900422
423 @Override
424 public String getInterfaceHash() {
425 return this.HASH;
426 }
markchien74a4fa92019-09-09 20:50:49 +0800427 }
428
429 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
430 private final int mStartIndex;
431
432 private DhcpServerCallbacksImpl(int startIndex) {
433 mStartIndex = startIndex;
434 }
435
436 @Override
437 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
438 getHandler().post(() -> {
439 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
440 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800441 // This start request is obsolete. Explicitly stop the DHCP server to shut
442 // down its thread. When the |server| binder token goes out of scope, the
443 // garbage collector will finalize it, which causes the network stack process
444 // garbage collector to collect the server itself.
445 try {
446 server.stop(null);
447 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800448 return;
449 }
450
451 if (statusCode != STATUS_SUCCESS) {
452 mLog.e("Error obtaining DHCP server: " + statusCode);
453 handleError();
454 return;
455 }
456
457 mDhcpServer = server;
458 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900459 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800460 @Override
461 public void callback(int startStatusCode) {
462 if (startStatusCode != STATUS_SUCCESS) {
463 mLog.e("Error starting DHCP server: " + startStatusCode);
464 handleError();
465 }
466 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900467 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800468 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800469 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800470 }
471 });
472 }
473
474 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800475 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800476 transitionTo(mInitialState);
477 }
478 }
479
Xiao Ma4455d6b2020-04-09 10:13:44 +0900480 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900481 @Override
482 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
483 final ArrayList<TetheredClient> leases = new ArrayList<>();
484 for (DhcpLeaseParcelable lease : leaseParcelables) {
485 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900486 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
487 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
488 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900489
490 final MacAddress macAddress;
491 try {
492 macAddress = MacAddress.fromBytes(lease.hwAddr);
493 } catch (IllegalArgumentException e) {
494 Log.wtf(TAG, "Invalid address received from DhcpServer: "
495 + Arrays.toString(lease.hwAddr));
496 return;
497 }
498
499 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900500 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900501 leases.add(new TetheredClient(
502 macAddress,
503 Collections.singletonList(addressInfo),
504 mInterfaceType));
505 }
506
507 getHandler().post(() -> {
508 mDhcpLeases = leases;
509 mCallback.dhcpLeasesChanged();
510 });
511 }
512
513 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900514 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
515 Objects.requireNonNull(currentPrefix);
516 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900517 }
518
519 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900520 public int getInterfaceVersion() {
521 return this.VERSION;
522 }
523
524 @Override
525 public String getInterfaceHash() throws RemoteException {
526 return this.HASH;
527 }
528 }
529
Xiao Ma4455d6b2020-04-09 10:13:44 +0900530 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
531 Objects.requireNonNull(ipv4Address);
532 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
533 }
534
535 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
536 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
537 @Nullable Inet4Address clientAddr) {
538 final boolean changePrefixOnDecline =
539 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
540 return new DhcpServingParamsParcelExt()
541 .setDefaultRouters(defaultRouter)
542 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
543 .setDnsServers(dnsServer)
544 .setServerAddr(serverAddr)
545 .setMetered(true)
546 .setSingleClientAddr(clientAddr)
547 .setChangePrefixOnDecline(changePrefixOnDecline);
548 // TODO: also advertise link MTU
549 }
550
markchien245352e2020-02-27 20:27:18 +0800551 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800552 if (mUsingLegacyDhcp) {
553 return true;
554 }
markchien245352e2020-02-27 20:27:18 +0800555
556 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800557 final Inet4Address clientAddr = clientLinkAddr == null ? null :
558 (Inet4Address) clientLinkAddr.getAddress();
559
Xiao Ma4455d6b2020-04-09 10:13:44 +0900560 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
561 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800562 mDhcpServerStartIndex++;
563 mDeps.makeDhcpServer(
564 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
565 return true;
566 }
567
568 private void stopDhcp() {
569 // Make all previous start requests obsolete so servers are not started later
570 mDhcpServerStartIndex++;
571
572 if (mDhcpServer != null) {
573 try {
574 mDhcpServer.stop(new OnHandlerStatusCallback() {
575 @Override
576 public void callback(int statusCode) {
577 if (statusCode != STATUS_SUCCESS) {
578 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800579 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800580 // Not much more we can do here
581 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900582 mDhcpLeases.clear();
583 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800584 }
585 });
586 mDhcpServer = null;
587 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900588 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800589 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800590 }
591 }
592 }
593
markchien245352e2020-02-27 20:27:18 +0800594 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
595 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800596 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800597 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800598 } else {
599 stopDhcp();
600 return true;
601 }
602 }
603
604 private void stopIPv4() {
605 configureIPv4(false);
606 // NOTE: All of configureIPv4() will be refactored out of existence
607 // into calls to InterfaceController, shared with startIPv4().
608 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800609 mPrivateAddressCoordinator.releaseDownstream(this);
markchien12c5bb82020-01-07 14:43:17 +0800610 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800611 mStaticIpv4ServerAddr = null;
612 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800613 }
614
markchien74a4fa92019-09-09 20:50:49 +0800615 private boolean configureIPv4(boolean enabled) {
616 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
617
markchienc9daba32020-02-12 00:19:21 +0800618 if (enabled) {
619 mIpv4Address = requestIpv4Address();
620 }
621
622 if (mIpv4Address == null) {
623 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800624 return false;
markchien74a4fa92019-09-09 20:50:49 +0800625 }
626
markchienc9daba32020-02-12 00:19:21 +0800627 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
628 // BT configures the interface elsewhere: only start DHCP.
629 // TODO: make all tethering types behave the same way, and delete the bluetooth
630 // code that calls into NetworkManagementService directly.
631 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
632 }
633
634 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
635
markchien12c5bb82020-01-07 14:43:17 +0800636 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800637 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900638 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200639 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
640 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900641 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800642 // It is unclear whether the Bluetooth or USB stacks will manage their own
643 // state.
644 setIfaceUp = null;
645 } else {
646 setIfaceUp = enabled;
647 }
648 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
649 mLog.e("Error configuring interface");
650 if (!enabled) stopDhcp();
651 return false;
652 }
markchien74a4fa92019-09-09 20:50:49 +0800653
markchien74a4fa92019-09-09 20:50:49 +0800654 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800655 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900656 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800657 } else {
markchien12c5bb82020-01-07 14:43:17 +0800658 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900659 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800660 }
markchien245352e2020-02-27 20:27:18 +0800661 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800662 }
663
markchienc9daba32020-02-12 00:19:21 +0800664 private LinkAddress requestIpv4Address() {
665 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800666
markchienc9daba32020-02-12 00:19:21 +0800667 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
668 return new LinkAddress(BLUETOOTH_IFACE_ADDR);
669 }
670
671 return mPrivateAddressCoordinator.requestDownstreamAddress(this);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900672 }
673
markchien74a4fa92019-09-09 20:50:49 +0800674 private boolean startIPv6() {
675 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
676 if (mInterfaceParams == null) {
677 mLog.e("Failed to find InterfaceParams");
678 stopIPv6();
679 return false;
680 }
681
682 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
683 if (!mRaDaemon.start()) {
684 stopIPv6();
685 return false;
686 }
687
Tyler Wear90e40632020-03-13 11:38:38 -0700688 // TODO: use ShimUtils instead of explicitly checking the version here.
689 if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R || "S".equals(Build.VERSION.CODENAME)
690 || "T".equals(Build.VERSION.CODENAME)) {
691 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
692 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
693 }
694
markchien74a4fa92019-09-09 20:50:49 +0800695 return true;
696 }
697
698 private void stopIPv6() {
699 mInterfaceParams = null;
700 setRaParams(null);
701
702 if (mRaDaemon != null) {
703 mRaDaemon.stop();
704 mRaDaemon = null;
705 }
Tyler Wear90e40632020-03-13 11:38:38 -0700706
707 if (mDadProxy != null) {
708 mDadProxy.stop();
709 mDadProxy = null;
710 }
markchien74a4fa92019-09-09 20:50:49 +0800711 }
712
713 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
714 // LinkProperties. These have extraneous data filtered out and only the
715 // necessary prefixes included (per its prefix distribution policy).
716 //
717 // TODO: Evaluate using a data structure than is more directly suited to
718 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800719 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800720 if (mRaDaemon == null) return;
721
722 // Avoid unnecessary work on spurious updates.
723 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
724 return;
725 }
726
727 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700728 String upstreamIface = null;
729 InterfaceParams upstreamIfaceParams = null;
730 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800731
732 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700733 upstreamIface = v6only.getInterfaceName();
734 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
735 if (upstreamIfaceParams != null) {
736 upstreamIfIndex = upstreamIfaceParams.index;
737 }
markchien74a4fa92019-09-09 20:50:49 +0800738 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700739 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800740 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
741
markchiend63c4f32020-05-21 17:38:28 +0800742 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800743
744 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
745 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
746
747 final IpPrefix prefix = new IpPrefix(
748 linkAddr.getAddress(), linkAddr.getPrefixLength());
749 params.prefixes.add(prefix);
750
751 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
752 if (dnsServer != null) {
753 params.dnses.add(dnsServer);
754 }
755 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900756
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800757 // Add upstream index to name mapping for the tether stats usage in the coordinator.
758 // Although this mapping could be added by both class Tethering and IpServer, adding
759 // mapping from IpServer guarantees that the mapping is added before the adding
760 // forwarding rules. That is because there are different state machines in both
761 // classes. It is hard to guarantee the link property update order between multiple
762 // state machines.
Tyler Wear90e40632020-03-13 11:38:38 -0700763 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800764 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900765
markchien74a4fa92019-09-09 20:50:49 +0800766 // If v6only is null, we pass in null to setRaParams(), which handles
767 // deprecation of any existing RA data.
768
769 setRaParams(params);
770 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900771
Tyler Wear90e40632020-03-13 11:38:38 -0700772 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, null);
773 mLastIPv6UpstreamIfindex = upstreamIfIndex;
774 if (mDadProxy != null) {
775 mDadProxy.setUpstreamIface(upstreamIfaceParams);
776 }
markchien74a4fa92019-09-09 20:50:49 +0800777 }
778
Xiao Ma4455d6b2020-04-09 10:13:44 +0900779 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
780 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
781 mNetd, toBeRemoved);
782 if (removalFailures > 0) {
783 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
784 removalFailures));
785 }
786
787 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
788 }
789
790 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
791 try {
792 // It's safe to call networkAddInterface() even if
793 // the interface is already in the local_network.
794 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
795 try {
796 // Add routes from local network. Note that adding routes that
797 // already exist does not cause an error (EEXIST is silently ignored).
798 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
799 } catch (IllegalStateException e) {
800 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
801 return;
802 }
803 } catch (ServiceSpecificException | RemoteException e) {
804 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
805 return;
806 }
807
808 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
809 }
810
markchien74a4fa92019-09-09 20:50:49 +0800811 private void configureLocalIPv6Routes(
812 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
813 // [1] Remove the routes that are deprecated.
814 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900815 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800816 }
817
818 // [2] Add only the routes that have not previously been added.
819 if (newPrefixes != null && !newPrefixes.isEmpty()) {
820 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
821 if (mLastRaParams != null) {
822 addedPrefixes.removeAll(mLastRaParams.prefixes);
823 }
824
825 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900826 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800827 }
828 }
829 }
830
831 private void configureLocalIPv6Dns(
832 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
833 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
834 if (mNetd == null) {
835 if (newDnses != null) newDnses.clear();
836 mLog.e("No netd service instance available; not setting local IPv6 addresses");
837 return;
838 }
839
840 // [1] Remove deprecated local DNS IP addresses.
841 if (!deprecatedDnses.isEmpty()) {
842 for (Inet6Address dns : deprecatedDnses) {
843 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
844 mLog.e("Failed to remove local dns IP " + dns);
845 }
846
847 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
848 }
849 }
850
851 // [2] Add only the local DNS IP addresses that have not previously been added.
852 if (newDnses != null && !newDnses.isEmpty()) {
853 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
854 if (mLastRaParams != null) {
855 addedDnses.removeAll(mLastRaParams.dnses);
856 }
857
858 for (Inet6Address dns : addedDnses) {
859 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
860 mLog.e("Failed to add local dns IP " + dns);
861 newDnses.remove(dns);
862 }
863
864 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
865 }
866 }
867
868 try {
869 mNetd.tetherApplyDnsInterfaces();
870 } catch (ServiceSpecificException | RemoteException e) {
871 mLog.e("Failed to update local DNS caching server");
872 if (newDnses != null) newDnses.clear();
873 }
874 }
875
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900876 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800877 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
878 // offload is disabled. Add this check just in case.
879 // TODO: Perhaps remove this protection check.
880 if (!mUsingBpfOffload) return;
881
Hungming Chen269c0882020-05-06 14:57:35 +0800882 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900883 }
884
Hungming Chen269c0882020-05-06 14:57:35 +0800885 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800886 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800887 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800888 if (!mUsingBpfOffload) return;
889
Hungming Chen269c0882020-05-06 14:57:35 +0800890 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900891 }
892
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900893 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800894 if (!mUsingBpfOffload) return;
895
896 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900897 }
898
Hungming Chen269c0882020-05-06 14:57:35 +0800899 private void updateIpv6ForwardingRule(int newIfindex) {
900 // TODO: Perhaps remove this protection check.
901 // See the related comment in #addIpv6ForwardingRule.
902 if (!mUsingBpfOffload) return;
903
904 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900905 }
906
907 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
908 // changes or if a neighbor event is received.
909 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
910 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900911 // If we no longer have an upstream, clear forwarding rules and do nothing else.
912 if (upstreamIfindex == 0) {
913 clearIpv6ForwardingRules();
914 return;
915 }
916
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900917 // If the upstream interface has changed, remove all rules and re-add them with the new
918 // upstream interface.
919 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800920 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900921 }
922
923 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900924 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900925 if (e == null) return;
926 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
927 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
928 return;
929 }
930
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900931 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
932 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
933 // add rules with a null MAC, only delete them.
934 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900935 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900936 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900937 if (e.isValid()) {
938 addIpv6ForwardingRule(rule);
939 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800940 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900941 }
942 }
943
944 private void handleNeighborEvent(NeighborEvent e) {
945 if (mInterfaceParams != null
946 && mInterfaceParams.index == e.ifindex
947 && mInterfaceParams.hasMacAddress) {
948 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
949 }
950 }
951
Xiao Ma4455d6b2020-04-09 10:13:44 +0900952 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
953 if (!currentPrefix.contains(mIpv4Address.getAddress())
954 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
955 Log.e(TAG, "Invalid prefix: " + currentPrefix);
956 return;
957 }
958
959 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchienc9daba32020-02-12 00:19:21 +0800960 mIpv4Address = requestIpv4Address();
961 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900962 mLog.e("Fail to request a new downstream prefix");
963 return;
964 }
markchienc9daba32020-02-12 00:19:21 +0800965 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +0900966
967 // Add new IPv4 address on the interface.
968 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
969 mLog.e("Failed to add new IP " + srvAddr);
970 return;
971 }
972
973 // Remove deprecated routes from local network.
974 removeRoutesFromLocalNetwork(
975 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
976 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
977
978 // Add new routes to local network.
979 addRoutesToLocalNetwork(
980 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
981 mLinkProperties.addLinkAddress(mIpv4Address);
982
983 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
984 // listen on the interface configured with new IPv4 address, that results DNS validation
985 // failure of downstream client even if appropriate routes have been configured.
986 try {
987 mNetd.tetherApplyDnsInterfaces();
988 } catch (ServiceSpecificException | RemoteException e) {
989 mLog.e("Failed to update local DNS caching server");
990 return;
991 }
992 sendLinkProperties();
993
994 // Notify DHCP server that new prefix/route has been applied on IpServer.
995 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
996 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
997 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
998 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
999 try {
1000 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1001 @Override
1002 public void callback(int statusCode) {
1003 if (statusCode != STATUS_SUCCESS) {
1004 mLog.e("Error updating DHCP serving params: " + statusCode);
1005 }
1006 }
1007 });
1008 } catch (RemoteException e) {
1009 mLog.e("Error updating DHCP serving params", e);
1010 }
1011 }
1012
markchiend63c4f32020-05-21 17:38:28 +08001013 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001014 try {
1015 int upstreamHopLimit = Integer.parseUnsignedInt(
1016 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001017 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001018 // Cap the hop limit to 255.
1019 return (byte) Integer.min(upstreamHopLimit, 255);
1020 } catch (Exception e) {
1021 mLog.e("Failed to find upstream interface hop limit", e);
1022 }
1023 return RaParams.DEFAULT_HOPLIMIT;
1024 }
1025
1026 private void setRaParams(RaParams newParams) {
1027 if (mRaDaemon != null) {
1028 final RaParams deprecatedParams =
1029 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1030
1031 configureLocalIPv6Routes(deprecatedParams.prefixes,
1032 (newParams != null) ? newParams.prefixes : null);
1033
1034 configureLocalIPv6Dns(deprecatedParams.dnses,
1035 (newParams != null) ? newParams.dnses : null);
1036
1037 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1038 }
1039
1040 mLastRaParams = newParams;
1041 }
1042
1043 private void logMessage(State state, int what) {
1044 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
1045 }
1046
1047 private void sendInterfaceState(int newInterfaceState) {
1048 mServingMode = newInterfaceState;
1049 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1050 sendLinkProperties();
1051 }
1052
1053 private void sendLinkProperties() {
1054 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1055 }
1056
1057 private void resetLinkProperties() {
1058 mLinkProperties.clear();
1059 mLinkProperties.setInterfaceName(mIfaceName);
1060 }
1061
markchienf053e4b2020-03-16 21:49:48 +08001062 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001063 // Ignore static address configuration if they are invalid or null. In theory, static
1064 // addresses should not be invalid here because TetheringManager do not allow caller to
1065 // specify invalid static address configuration.
1066 if (request == null || request.localIPv4Address == null
1067 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1068 request.localIPv4Address, request.staticClientAddress)) {
1069 return;
1070 }
markchienf053e4b2020-03-16 21:49:48 +08001071
1072 mStaticIpv4ServerAddr = request.localIPv4Address;
1073 mStaticIpv4ClientAddr = request.staticClientAddress;
1074 }
1075
markchien74a4fa92019-09-09 20:50:49 +08001076 class InitialState extends State {
1077 @Override
1078 public void enter() {
1079 sendInterfaceState(STATE_AVAILABLE);
1080 }
1081
1082 @Override
1083 public boolean processMessage(Message message) {
1084 logMessage(this, message.what);
1085 switch (message.what) {
1086 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001087 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001088 switch (message.arg1) {
1089 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001090 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001091 transitionTo(mLocalHotspotState);
1092 break;
1093 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001094 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001095 transitionTo(mTetheredState);
1096 break;
1097 default:
1098 mLog.e("Invalid tethering interface serving state specified.");
1099 }
1100 break;
1101 case CMD_INTERFACE_DOWN:
1102 transitionTo(mUnavailableState);
1103 break;
1104 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001105 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001106 break;
1107 default:
1108 return NOT_HANDLED;
1109 }
1110 return HANDLED;
1111 }
1112 }
1113
1114 class BaseServingState extends State {
1115 @Override
1116 public void enter() {
1117 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001118 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001119 return;
1120 }
1121
1122 try {
markchienc9daba32020-02-12 00:19:21 +08001123 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001124 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001125 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001126 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001127 return;
1128 }
1129
1130 if (!startIPv6()) {
1131 mLog.e("Failed to startIPv6");
1132 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1133 return;
1134 }
1135 }
1136
1137 @Override
1138 public void exit() {
1139 // Note that at this point, we're leaving the tethered state. We can fail any
1140 // of these operations, but it doesn't really change that we have to try them
1141 // all in sequence.
1142 stopIPv6();
1143
1144 try {
markchien12c5bb82020-01-07 14:43:17 +08001145 NetdUtils.untetherInterface(mNetd, mIfaceName);
1146 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001147 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001148 mLog.e("Failed to untether interface: " + e);
1149 }
1150
1151 stopIPv4();
1152
1153 resetLinkProperties();
1154 }
1155
1156 @Override
1157 public boolean processMessage(Message message) {
1158 logMessage(this, message.what);
1159 switch (message.what) {
1160 case CMD_TETHER_UNREQUESTED:
1161 transitionTo(mInitialState);
1162 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1163 break;
1164 case CMD_INTERFACE_DOWN:
1165 transitionTo(mUnavailableState);
1166 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1167 break;
1168 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001169 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001170 sendLinkProperties();
1171 break;
1172 case CMD_IP_FORWARDING_ENABLE_ERROR:
1173 case CMD_IP_FORWARDING_DISABLE_ERROR:
1174 case CMD_START_TETHERING_ERROR:
1175 case CMD_STOP_TETHERING_ERROR:
1176 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001177 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001178 transitionTo(mInitialState);
1179 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001180 case CMD_NEW_PREFIX_REQUEST:
1181 handleNewPrefixRequest((IpPrefix) message.obj);
1182 break;
markchienc9daba32020-02-12 00:19:21 +08001183 case CMD_NOTIFY_PREFIX_CONFLICT:
1184 mLog.i("restart tethering: " + mInterfaceType);
1185 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1186 transitionTo(mWaitingForRestartState);
1187 break;
markchien74a4fa92019-09-09 20:50:49 +08001188 default:
1189 return false;
1190 }
1191 return true;
1192 }
1193 }
1194
1195 // Handling errors in BaseServingState.enter() by transitioning is
1196 // problematic because transitioning during a multi-state jump yields
1197 // a Log.wtf(). Ultimately, there should be only one ServingState,
1198 // and forwarding and NAT rules should be handled by a coordinating
1199 // functional element outside of IpServer.
1200 class LocalHotspotState extends BaseServingState {
1201 @Override
1202 public void enter() {
1203 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001204 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001205 transitionTo(mInitialState);
1206 }
1207
1208 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1209 sendInterfaceState(STATE_LOCAL_ONLY);
1210 }
1211
1212 @Override
1213 public boolean processMessage(Message message) {
1214 if (super.processMessage(message)) return true;
1215
1216 logMessage(this, message.what);
1217 switch (message.what) {
1218 case CMD_TETHER_REQUESTED:
1219 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1220 break;
1221 case CMD_TETHER_CONNECTION_CHANGED:
1222 // Ignored in local hotspot state.
1223 break;
1224 default:
1225 return false;
1226 }
1227 return true;
1228 }
1229 }
1230
1231 // Handling errors in BaseServingState.enter() by transitioning is
1232 // problematic because transitioning during a multi-state jump yields
1233 // a Log.wtf(). Ultimately, there should be only one ServingState,
1234 // and forwarding and NAT rules should be handled by a coordinating
1235 // functional element outside of IpServer.
1236 class TetheredState extends BaseServingState {
1237 @Override
1238 public void enter() {
1239 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001240 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001241 transitionTo(mInitialState);
1242 }
1243
1244 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1245 sendInterfaceState(STATE_TETHERED);
1246 }
1247
1248 @Override
1249 public void exit() {
1250 cleanupUpstream();
1251 super.exit();
1252 }
1253
1254 private void cleanupUpstream() {
1255 if (mUpstreamIfaceSet == null) return;
1256
1257 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1258 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001259 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001260 }
1261
1262 private void cleanupUpstreamInterface(String upstreamIface) {
1263 // Note that we don't care about errors here.
1264 // Sometimes interfaces are gone before we get
1265 // to remove their rules, which generates errors.
1266 // Just do the best we can.
1267 try {
markchien12c5bb82020-01-07 14:43:17 +08001268 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1269 } catch (RemoteException | ServiceSpecificException e) {
1270 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001271 }
1272 try {
markchien12c5bb82020-01-07 14:43:17 +08001273 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1274 } catch (RemoteException | ServiceSpecificException e) {
1275 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001276 }
1277 }
1278
1279 @Override
1280 public boolean processMessage(Message message) {
1281 if (super.processMessage(message)) return true;
1282
1283 logMessage(this, message.what);
1284 switch (message.what) {
1285 case CMD_TETHER_REQUESTED:
1286 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1287 break;
1288 case CMD_TETHER_CONNECTION_CHANGED:
1289 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1290 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1291 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1292 break;
1293 }
1294
1295 if (newUpstreamIfaceSet == null) {
1296 cleanupUpstream();
1297 break;
1298 }
1299
1300 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1301 cleanupUpstreamInterface(removed);
1302 }
1303
1304 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1305 // This makes the call to cleanupUpstream() in the error
1306 // path for any interface neatly cleanup all the interfaces.
1307 mUpstreamIfaceSet = newUpstreamIfaceSet;
1308
1309 for (String ifname : added) {
1310 try {
markchien12c5bb82020-01-07 14:43:17 +08001311 mNetd.tetherAddForward(mIfaceName, ifname);
1312 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1313 } catch (RemoteException | ServiceSpecificException e) {
1314 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001315 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001316 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001317 transitionTo(mInitialState);
1318 return true;
1319 }
1320 }
1321 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001322 case CMD_NEIGHBOR_EVENT:
1323 handleNeighborEvent((NeighborEvent) message.obj);
1324 break;
markchien74a4fa92019-09-09 20:50:49 +08001325 default:
1326 return false;
1327 }
1328 return true;
1329 }
1330
1331 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1332 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1333 if (mUpstreamIfaceSet != null && newIfaces != null) {
1334 return mUpstreamIfaceSet.equals(newIfaces);
1335 }
1336 return false;
1337 }
1338
1339 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1340 if (mUpstreamIfaceSet == null) return new HashSet<>();
1341
1342 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1343 removed.removeAll(newIfaces.ifnames);
1344 return removed;
1345 }
1346
1347 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1348 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1349 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1350 return added;
1351 }
1352 }
1353
1354 /**
1355 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001356 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001357 * specific state machine from its list of possible recipients of
1358 * tethering requests. The state machine itself will hang around until
1359 * the garbage collector finds it.
1360 */
1361 class UnavailableState extends State {
1362 @Override
1363 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001364 mIpNeighborMonitor.stop();
markchien9b4d7572019-12-25 19:40:32 +08001365 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001366 sendInterfaceState(STATE_UNAVAILABLE);
1367 }
1368 }
1369
markchienc9daba32020-02-12 00:19:21 +08001370 class WaitingForRestartState extends State {
1371 @Override
1372 public boolean processMessage(Message message) {
1373 logMessage(this, message.what);
1374 switch (message.what) {
1375 case CMD_TETHER_UNREQUESTED:
1376 transitionTo(mInitialState);
1377 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1378 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1379 break;
1380 case CMD_INTERFACE_DOWN:
1381 transitionTo(mUnavailableState);
1382 mLog.i("Untethered (interface down) and restarting" + mIfaceName);
1383 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1384 break;
1385 default:
1386 return false;
1387 }
1388 return true;
1389 }
1390 }
1391
markchien74a4fa92019-09-09 20:50:49 +08001392 // Accumulate routes representing "prefixes to be assigned to the local
1393 // interface", for subsequent modification of local_network routing.
1394 private static ArrayList<RouteInfo> getLocalRoutesFor(
1395 String ifname, HashSet<IpPrefix> prefixes) {
1396 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1397 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001398 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001399 }
1400 return localRoutes;
1401 }
1402
1403 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1404 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1405 final byte[] dnsBytes = localPrefix.getRawAddress();
1406 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1407 try {
1408 return Inet6Address.getByAddress(null, dnsBytes, 0);
1409 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001410 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001411 return null;
1412 }
1413 }
1414
1415 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1416 final byte random = (byte) (new Random()).nextInt();
1417 for (int value : excluded) {
1418 if (random == value) return dflt;
1419 }
1420 return random;
1421 }
1422}