blob: 822bdf600195094272826e7ba65d16975d85027f [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 Chend71c06e2020-12-21 19:39:49 +080070import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
Hungming Chenb150b872020-05-23 22:54:49 +080071import com.android.networkstack.tethering.BpfCoordinator.Ipv6ForwardingRule;
markchienc9daba32020-02-12 00:19:21 +080072import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +080073
74import java.net.Inet4Address;
75import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080076import java.net.UnknownHostException;
77import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090078import java.util.Arrays;
79import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080080import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090081import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080082import java.util.Objects;
83import java.util.Random;
84import java.util.Set;
85
86/**
87 * Provides the interface to IP-layer serving functionality for a given network
88 * interface, e.g. for tethering or "local-only hotspot" mode.
89 *
90 * @hide
91 */
92public class IpServer extends StateMachine {
93 public static final int STATE_UNAVAILABLE = 0;
94 public static final int STATE_AVAILABLE = 1;
95 public static final int STATE_TETHERED = 2;
96 public static final int STATE_LOCAL_ONLY = 3;
97
98 /** Get string name of |state|.*/
99 public static String getStateString(int state) {
100 switch (state) {
101 case STATE_UNAVAILABLE: return "UNAVAILABLE";
102 case STATE_AVAILABLE: return "AVAILABLE";
103 case STATE_TETHERED: return "TETHERED";
104 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
105 }
106 return "UNKNOWN: " + state;
107 }
108
109 private static final byte DOUG_ADAMS = (byte) 42;
110
markchien74a4fa92019-09-09 20:50:49 +0800111 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800112 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800113
114 // TODO: have this configurable
115 private static final int DHCP_LEASE_TIME_SECS = 3600;
116
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900117 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
118
markchien74a4fa92019-09-09 20:50:49 +0800119 private static final String TAG = "IpServer";
120 private static final boolean DBG = false;
121 private static final boolean VDBG = false;
122 private static final Class[] sMessageClasses = {
123 IpServer.class
124 };
125 private static final SparseArray<String> sMagicDecoderRing =
126 MessageUtils.findMessageNames(sMessageClasses);
127
128 /** IpServer callback. */
129 public static class Callback {
130 /**
131 * Notify that |who| has changed its tethering state.
132 *
133 * @param who the calling instance of IpServer
134 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800135 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800136 */
markchien9d353822019-12-16 20:15:20 +0800137 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800138
139 /**
140 * Notify that |who| has new LinkProperties.
141 *
142 * @param who the calling instance of IpServer
143 * @param newLp the new LinkProperties to report
144 */
markchien9d353822019-12-16 20:15:20 +0800145 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900146
147 /**
148 * Notify that the DHCP leases changed in one of the IpServers.
149 */
150 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800151
152 /**
153 * Request Tethering change.
154 *
155 * @param tetheringType the downstream type of this IpServer.
156 * @param enabled enable or disable tethering.
157 */
158 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800159 }
160
161 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800162 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700163 /**
164 * Create a DadProxy instance to be used by IpServer.
165 * To support multiple tethered interfaces concurrently DAD Proxy
166 * needs to be supported per IpServer instead of per upstream.
167 */
168 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
169 return new DadProxy(handler, ifParams);
170 }
171
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900172 /** Create an IpNeighborMonitor to be used by this IpServer */
173 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
174 IpNeighborMonitor.NeighborEventConsumer consumer) {
175 return new IpNeighborMonitor(handler, log, consumer);
176 }
177
markchien74a4fa92019-09-09 20:50:49 +0800178 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
179 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
180 return new RouterAdvertisementDaemon(ifParams);
181 }
182
183 /** Get |ifName|'s interface information.*/
184 public InterfaceParams getInterfaceParams(String ifName) {
185 return InterfaceParams.getByName(ifName);
186 }
187
markchien9d353822019-12-16 20:15:20 +0800188 /** Create a DhcpServer instance to be used by IpServer. */
189 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
190 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800191 }
192
markchien74a4fa92019-09-09 20:50:49 +0800193 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800194 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800195 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800196 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800197 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800198 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800199 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
200 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800201 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800202 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
203 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800204 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800205 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
206 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800207 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800208 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800209 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800210 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
211 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800213 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800214 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800215 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800216 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900217 // new neighbor cache entry on our interface
218 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900219 // request from DHCP server that it wants to have a new prefix
220 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800221 // request from PrivateAddressCoordinator to restart tethering.
222 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800223
224 private final State mInitialState;
225 private final State mLocalHotspotState;
226 private final State mTetheredState;
227 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800228 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800229
230 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800231 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800232 @NonNull
233 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800234 private final Callback mCallback;
235 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800236 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800237
238 private final String mIfaceName;
239 private final int mInterfaceType;
240 private final LinkProperties mLinkProperties;
241 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800242 private final boolean mUsingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800243
244 private final Dependencies mDeps;
245
246 private int mLastError;
247 private int mServingMode;
248 private InterfaceSet mUpstreamIfaceSet; // may change over time
249 private InterfaceParams mInterfaceParams;
250 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
251 // properties are those selected by the IPv6TetheringCoordinator and relayed
252 // to us. By comparison, mLinkProperties contains the addresses and directly
253 // connected routes that have been formed from these properties iff. we have
254 // succeeded in configuring them and are able to announce them within Router
255 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
256 private LinkProperties mLastIPv6LinkProperties;
257 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700258 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800259
260 // To be accessed only on the handler thread
261 private int mDhcpServerStartIndex = 0;
262 private IDhcpServer mDhcpServer;
263 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800264
265 private LinkAddress mStaticIpv4ServerAddr;
266 private LinkAddress mStaticIpv4ClientAddr;
267
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900268 @NonNull
269 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800270
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900271 private int mLastIPv6UpstreamIfindex = 0;
272
273 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
274 public void accept(NeighborEvent e) {
275 sendMessage(CMD_NEIGHBOR_EVENT, e);
276 }
277 }
278
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900279 private final IpNeighborMonitor mIpNeighborMonitor;
280
markchienc9daba32020-02-12 00:19:21 +0800281 private LinkAddress mIpv4Address;
282
Hungming Chen5bc3af92020-05-12 19:15:24 +0800283 // TODO: Add a dependency object to pass the data members or variables from the tethering
284 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800285 public IpServer(
286 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800287 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
288 boolean usingLegacyDhcp, boolean usingBpfOffload,
markchienc9daba32020-02-12 00:19:21 +0800289 PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800290 super(ifaceName, looper);
291 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800292 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800293 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800294 mCallback = callback;
295 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
296 mIfaceName = ifaceName;
297 mInterfaceType = interfaceType;
298 mLinkProperties = new LinkProperties();
299 mUsingLegacyDhcp = usingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800300 mUsingBpfOffload = usingBpfOffload;
markchienc9daba32020-02-12 00:19:21 +0800301 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800302 mDeps = deps;
303 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800304 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800305 mServingMode = STATE_AVAILABLE;
306
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900307 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
308 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800309
Hungming Chen5bc3af92020-05-12 19:15:24 +0800310 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800311 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800312 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800313 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800314 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
315 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900316 }
317
markchien74a4fa92019-09-09 20:50:49 +0800318 mInitialState = new InitialState();
319 mLocalHotspotState = new LocalHotspotState();
320 mTetheredState = new TetheredState();
321 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800322 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800323 addState(mInitialState);
324 addState(mLocalHotspotState);
325 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800326 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800327 addState(mUnavailableState);
328
329 setInitialState(mInitialState);
330 }
331
332 /** Interface name which IpServer served.*/
333 public String interfaceName() {
334 return mIfaceName;
335 }
336
337 /**
markchien9b4d7572019-12-25 19:40:32 +0800338 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800339 */
340 public int interfaceType() {
341 return mInterfaceType;
342 }
343
344 /** Last error from this IpServer. */
345 public int lastError() {
346 return mLastError;
347 }
348
349 /** Serving mode is the current state of IpServer state machine. */
350 public int servingMode() {
351 return mServingMode;
352 }
353
354 /** The properties of the network link which IpServer is serving. */
355 public LinkProperties linkProperties() {
356 return new LinkProperties(mLinkProperties);
357 }
358
markchienc9daba32020-02-12 00:19:21 +0800359 /** The address which IpServer is using. */
360 public LinkAddress getAddress() {
361 return mIpv4Address;
362 }
363
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900364 /**
365 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
366 * thread.
367 */
368 public List<TetheredClient> getAllLeases() {
369 return Collections.unmodifiableList(mDhcpLeases);
370 }
371
markchien74a4fa92019-09-09 20:50:49 +0800372 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
373 public void stop() {
374 sendMessage(CMD_INTERFACE_DOWN);
375 }
376
377 /**
378 * Tethering is canceled. IpServer state machine will be available and wait for
379 * next tethering request.
380 */
381 public void unwanted() {
382 sendMessage(CMD_TETHER_UNREQUESTED);
383 }
384
385 /** Internals. */
386
387 private boolean startIPv4() {
388 return configureIPv4(true);
389 }
390
391 /**
392 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
393 * handler.
394 *
395 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
396 * with different implementations of the callback, to differentiate handling of success/error in
397 * each call.
398 */
399 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
400 @Override
401 public void onStatusAvailable(int statusCode) {
402 getHandler().post(() -> callback(statusCode));
403 }
404
405 public abstract void callback(int statusCode);
406
407 @Override
408 public int getInterfaceVersion() {
409 return this.VERSION;
410 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900411
412 @Override
413 public String getInterfaceHash() {
414 return this.HASH;
415 }
markchien74a4fa92019-09-09 20:50:49 +0800416 }
417
418 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
419 private final int mStartIndex;
420
421 private DhcpServerCallbacksImpl(int startIndex) {
422 mStartIndex = startIndex;
423 }
424
425 @Override
426 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
427 getHandler().post(() -> {
428 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
429 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800430 // This start request is obsolete. Explicitly stop the DHCP server to shut
431 // down its thread. When the |server| binder token goes out of scope, the
432 // garbage collector will finalize it, which causes the network stack process
433 // garbage collector to collect the server itself.
434 try {
435 server.stop(null);
436 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800437 return;
438 }
439
440 if (statusCode != STATUS_SUCCESS) {
441 mLog.e("Error obtaining DHCP server: " + statusCode);
442 handleError();
443 return;
444 }
445
446 mDhcpServer = server;
447 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900448 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800449 @Override
450 public void callback(int startStatusCode) {
451 if (startStatusCode != STATUS_SUCCESS) {
452 mLog.e("Error starting DHCP server: " + startStatusCode);
453 handleError();
454 }
455 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900456 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800457 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800458 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800459 }
460 });
461 }
462
463 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800464 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800465 transitionTo(mInitialState);
466 }
467 }
468
Xiao Ma4455d6b2020-04-09 10:13:44 +0900469 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900470 @Override
471 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
472 final ArrayList<TetheredClient> leases = new ArrayList<>();
473 for (DhcpLeaseParcelable lease : leaseParcelables) {
474 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900475 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
476 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
477 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900478
479 final MacAddress macAddress;
480 try {
481 macAddress = MacAddress.fromBytes(lease.hwAddr);
482 } catch (IllegalArgumentException e) {
483 Log.wtf(TAG, "Invalid address received from DhcpServer: "
484 + Arrays.toString(lease.hwAddr));
485 return;
486 }
487
488 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900489 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900490 leases.add(new TetheredClient(
491 macAddress,
492 Collections.singletonList(addressInfo),
493 mInterfaceType));
494 }
495
496 getHandler().post(() -> {
497 mDhcpLeases = leases;
498 mCallback.dhcpLeasesChanged();
499 });
500 }
501
502 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900503 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
504 Objects.requireNonNull(currentPrefix);
505 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900506 }
507
508 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900509 public int getInterfaceVersion() {
510 return this.VERSION;
511 }
512
513 @Override
514 public String getInterfaceHash() throws RemoteException {
515 return this.HASH;
516 }
517 }
518
Xiao Ma4455d6b2020-04-09 10:13:44 +0900519 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
520 Objects.requireNonNull(ipv4Address);
521 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
522 }
523
524 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
525 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
526 @Nullable Inet4Address clientAddr) {
527 final boolean changePrefixOnDecline =
528 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
529 return new DhcpServingParamsParcelExt()
530 .setDefaultRouters(defaultRouter)
531 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
532 .setDnsServers(dnsServer)
533 .setServerAddr(serverAddr)
534 .setMetered(true)
535 .setSingleClientAddr(clientAddr)
536 .setChangePrefixOnDecline(changePrefixOnDecline);
537 // TODO: also advertise link MTU
538 }
539
markchien245352e2020-02-27 20:27:18 +0800540 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800541 if (mUsingLegacyDhcp) {
542 return true;
543 }
markchien245352e2020-02-27 20:27:18 +0800544
545 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800546 final Inet4Address clientAddr = clientLinkAddr == null ? null :
547 (Inet4Address) clientLinkAddr.getAddress();
548
Xiao Ma4455d6b2020-04-09 10:13:44 +0900549 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
550 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800551 mDhcpServerStartIndex++;
552 mDeps.makeDhcpServer(
553 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
554 return true;
555 }
556
557 private void stopDhcp() {
558 // Make all previous start requests obsolete so servers are not started later
559 mDhcpServerStartIndex++;
560
561 if (mDhcpServer != null) {
562 try {
563 mDhcpServer.stop(new OnHandlerStatusCallback() {
564 @Override
565 public void callback(int statusCode) {
566 if (statusCode != STATUS_SUCCESS) {
567 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800568 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800569 // Not much more we can do here
570 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900571 mDhcpLeases.clear();
572 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800573 }
574 });
575 mDhcpServer = null;
576 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900577 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800578 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800579 }
580 }
581 }
582
markchien245352e2020-02-27 20:27:18 +0800583 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
584 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800585 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800586 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800587 } else {
588 stopDhcp();
589 return true;
590 }
591 }
592
593 private void stopIPv4() {
594 configureIPv4(false);
595 // NOTE: All of configureIPv4() will be refactored out of existence
596 // into calls to InterfaceController, shared with startIPv4().
597 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800598 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800599 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800600 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800601 mStaticIpv4ServerAddr = null;
602 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800603 }
604
markchien74a4fa92019-09-09 20:50:49 +0800605 private boolean configureIPv4(boolean enabled) {
606 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
607
markchienc9daba32020-02-12 00:19:21 +0800608 if (enabled) {
markchiena2ffad82020-09-22 15:50:43 +0800609 mIpv4Address = requestIpv4Address(true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800610 }
611
612 if (mIpv4Address == null) {
613 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800614 return false;
markchien74a4fa92019-09-09 20:50:49 +0800615 }
616
markchienc9daba32020-02-12 00:19:21 +0800617 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
618 // BT configures the interface elsewhere: only start DHCP.
619 // TODO: make all tethering types behave the same way, and delete the bluetooth
620 // code that calls into NetworkManagementService directly.
621 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
622 }
623
624 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
625
markchien12c5bb82020-01-07 14:43:17 +0800626 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800627 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900628 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200629 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
630 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900631 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800632 // It is unclear whether the Bluetooth or USB stacks will manage their own
633 // state.
634 setIfaceUp = null;
635 } else {
636 setIfaceUp = enabled;
637 }
638 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
639 mLog.e("Error configuring interface");
640 if (!enabled) stopDhcp();
641 return false;
642 }
markchien74a4fa92019-09-09 20:50:49 +0800643
markchien74a4fa92019-09-09 20:50:49 +0800644 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800645 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900646 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800647 } else {
markchien12c5bb82020-01-07 14:43:17 +0800648 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900649 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800650 }
markchien245352e2020-02-27 20:27:18 +0800651 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800652 }
653
markchiena2ffad82020-09-22 15:50:43 +0800654 private LinkAddress requestIpv4Address(final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800655 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800656
markchienc9daba32020-02-12 00:19:21 +0800657 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
658 return new LinkAddress(BLUETOOTH_IFACE_ADDR);
659 }
660
markchiena2ffad82020-09-22 15:50:43 +0800661 return mPrivateAddressCoordinator.requestDownstreamAddress(this, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900662 }
663
markchien74a4fa92019-09-09 20:50:49 +0800664 private boolean startIPv6() {
665 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
666 if (mInterfaceParams == null) {
667 mLog.e("Failed to find InterfaceParams");
668 stopIPv6();
669 return false;
670 }
671
672 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
673 if (!mRaDaemon.start()) {
674 stopIPv6();
675 return false;
676 }
677
Tyler Wear90e40632020-03-13 11:38:38 -0700678 // TODO: use ShimUtils instead of explicitly checking the version here.
679 if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R || "S".equals(Build.VERSION.CODENAME)
680 || "T".equals(Build.VERSION.CODENAME)) {
681 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
682 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
683 }
684
markchien74a4fa92019-09-09 20:50:49 +0800685 return true;
686 }
687
688 private void stopIPv6() {
689 mInterfaceParams = null;
690 setRaParams(null);
691
692 if (mRaDaemon != null) {
693 mRaDaemon.stop();
694 mRaDaemon = null;
695 }
Tyler Wear90e40632020-03-13 11:38:38 -0700696
697 if (mDadProxy != null) {
698 mDadProxy.stop();
699 mDadProxy = null;
700 }
markchien74a4fa92019-09-09 20:50:49 +0800701 }
702
703 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
704 // LinkProperties. These have extraneous data filtered out and only the
705 // necessary prefixes included (per its prefix distribution policy).
706 //
707 // TODO: Evaluate using a data structure than is more directly suited to
708 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800709 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800710 if (mRaDaemon == null) return;
711
712 // Avoid unnecessary work on spurious updates.
713 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
714 return;
715 }
716
717 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700718 String upstreamIface = null;
719 InterfaceParams upstreamIfaceParams = null;
720 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800721
722 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700723 upstreamIface = v6only.getInterfaceName();
724 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
725 if (upstreamIfaceParams != null) {
726 upstreamIfIndex = upstreamIfaceParams.index;
727 }
markchien74a4fa92019-09-09 20:50:49 +0800728 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700729 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800730 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
731
markchiend63c4f32020-05-21 17:38:28 +0800732 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800733
734 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
735 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
736
737 final IpPrefix prefix = new IpPrefix(
738 linkAddr.getAddress(), linkAddr.getPrefixLength());
739 params.prefixes.add(prefix);
740
741 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
742 if (dnsServer != null) {
743 params.dnses.add(dnsServer);
744 }
745 }
746 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900747
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900748 // Add upstream index to name mapping. See the comment of the interface mapping update in
749 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
750 // timing issue. It prevents that the IPv6 capability is updated later than
751 // CMD_TETHER_CONNECTION_CHANGED.
752 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
753
markchien74a4fa92019-09-09 20:50:49 +0800754 // If v6only is null, we pass in null to setRaParams(), which handles
755 // deprecation of any existing RA data.
756
757 setRaParams(params);
758 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900759
Tyler Wear90e40632020-03-13 11:38:38 -0700760 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, null);
761 mLastIPv6UpstreamIfindex = upstreamIfIndex;
762 if (mDadProxy != null) {
763 mDadProxy.setUpstreamIface(upstreamIfaceParams);
764 }
markchien74a4fa92019-09-09 20:50:49 +0800765 }
766
Xiao Ma4455d6b2020-04-09 10:13:44 +0900767 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
768 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
769 mNetd, toBeRemoved);
770 if (removalFailures > 0) {
771 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
772 removalFailures));
773 }
774
775 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
776 }
777
778 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
779 try {
780 // It's safe to call networkAddInterface() even if
781 // the interface is already in the local_network.
782 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
783 try {
784 // Add routes from local network. Note that adding routes that
785 // already exist does not cause an error (EEXIST is silently ignored).
786 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
787 } catch (IllegalStateException e) {
788 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
789 return;
790 }
791 } catch (ServiceSpecificException | RemoteException e) {
792 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
793 return;
794 }
795
796 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
797 }
798
markchien74a4fa92019-09-09 20:50:49 +0800799 private void configureLocalIPv6Routes(
800 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
801 // [1] Remove the routes that are deprecated.
802 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900803 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800804 }
805
806 // [2] Add only the routes that have not previously been added.
807 if (newPrefixes != null && !newPrefixes.isEmpty()) {
808 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
809 if (mLastRaParams != null) {
810 addedPrefixes.removeAll(mLastRaParams.prefixes);
811 }
812
813 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900814 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800815 }
816 }
817 }
818
819 private void configureLocalIPv6Dns(
820 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
821 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
822 if (mNetd == null) {
823 if (newDnses != null) newDnses.clear();
824 mLog.e("No netd service instance available; not setting local IPv6 addresses");
825 return;
826 }
827
828 // [1] Remove deprecated local DNS IP addresses.
829 if (!deprecatedDnses.isEmpty()) {
830 for (Inet6Address dns : deprecatedDnses) {
831 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
832 mLog.e("Failed to remove local dns IP " + dns);
833 }
834
835 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
836 }
837 }
838
839 // [2] Add only the local DNS IP addresses that have not previously been added.
840 if (newDnses != null && !newDnses.isEmpty()) {
841 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
842 if (mLastRaParams != null) {
843 addedDnses.removeAll(mLastRaParams.dnses);
844 }
845
846 for (Inet6Address dns : addedDnses) {
847 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
848 mLog.e("Failed to add local dns IP " + dns);
849 newDnses.remove(dns);
850 }
851
852 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
853 }
854 }
855
856 try {
857 mNetd.tetherApplyDnsInterfaces();
858 } catch (ServiceSpecificException | RemoteException e) {
859 mLog.e("Failed to update local DNS caching server");
860 if (newDnses != null) newDnses.clear();
861 }
862 }
863
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900864 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800865 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
866 // offload is disabled. Add this check just in case.
867 // TODO: Perhaps remove this protection check.
868 if (!mUsingBpfOffload) return;
869
Hungming Chen269c0882020-05-06 14:57:35 +0800870 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900871 }
872
Hungming Chen269c0882020-05-06 14:57:35 +0800873 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800874 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800875 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800876 if (!mUsingBpfOffload) return;
877
Hungming Chen269c0882020-05-06 14:57:35 +0800878 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900879 }
880
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900881 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800882 if (!mUsingBpfOffload) return;
883
884 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900885 }
886
Hungming Chen269c0882020-05-06 14:57:35 +0800887 private void updateIpv6ForwardingRule(int newIfindex) {
888 // TODO: Perhaps remove this protection check.
889 // See the related comment in #addIpv6ForwardingRule.
890 if (!mUsingBpfOffload) return;
891
892 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900893 }
894
895 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
896 // changes or if a neighbor event is received.
897 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
898 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900899 // If we no longer have an upstream, clear forwarding rules and do nothing else.
900 if (upstreamIfindex == 0) {
901 clearIpv6ForwardingRules();
902 return;
903 }
904
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900905 // If the upstream interface has changed, remove all rules and re-add them with the new
906 // upstream interface.
907 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800908 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900909 }
910
911 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900912 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900913 if (e == null) return;
914 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
915 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
916 return;
917 }
918
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900919 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
920 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
921 // add rules with a null MAC, only delete them.
922 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900923 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900924 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900925 if (e.isValid()) {
926 addIpv6ForwardingRule(rule);
927 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800928 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900929 }
930 }
931
Hungming Chend71c06e2020-12-21 19:39:49 +0800932 // TODO: consider moving into BpfCoordinator.
933 private void updateClientInfoIpv4(NeighborEvent e) {
934 // TODO: Perhaps remove this protection check.
935 // See the related comment in #addIpv6ForwardingRule.
936 if (!mUsingBpfOffload) return;
937
938 if (e == null) return;
939 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
940 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
941 return;
942 }
943
944 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
945 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
946 // IpServer never add clients with a null MAC, only delete them.
947 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
948 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
949 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
950 if (e.isValid()) {
951 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
952 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800953 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
954 }
955 }
956
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900957 private void handleNeighborEvent(NeighborEvent e) {
958 if (mInterfaceParams != null
959 && mInterfaceParams.index == e.ifindex
960 && mInterfaceParams.hasMacAddress) {
961 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800962 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900963 }
964 }
965
Xiao Ma4455d6b2020-04-09 10:13:44 +0900966 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;
markchiena2ffad82020-09-22 15:50:43 +0800974 mIpv4Address = requestIpv4Address(false);
markchienc9daba32020-02-12 00:19:21 +0800975 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900976 mLog.e("Fail to request a new downstream prefix");
977 return;
978 }
markchienc9daba32020-02-12 00:19:21 +0800979 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +0900980
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
markchiend63c4f32020-05-21 17:38:28 +08001027 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"));
markchiend63c4f32020-05-21 17:38:28 +08001031 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
markchien21021ef2021-06-01 10:58:04 +08001057 private void maybeLogMessage(State state, int what) {
1058 switch (what) {
1059 // Suppress some CMD_* to avoid log flooding.
1060 case CMD_IPV6_TETHER_UPDATE:
1061 case CMD_NEIGHBOR_EVENT:
1062 break;
1063 default:
1064 mLog.log(state.getName() + " got "
1065 + sMagicDecoderRing.get(what, Integer.toString(what)));
1066 }
markchien74a4fa92019-09-09 20:50:49 +08001067 }
1068
1069 private void sendInterfaceState(int newInterfaceState) {
1070 mServingMode = newInterfaceState;
1071 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1072 sendLinkProperties();
1073 }
1074
1075 private void sendLinkProperties() {
1076 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1077 }
1078
1079 private void resetLinkProperties() {
1080 mLinkProperties.clear();
1081 mLinkProperties.setInterfaceName(mIfaceName);
1082 }
1083
markchienf053e4b2020-03-16 21:49:48 +08001084 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001085 // Ignore static address configuration if they are invalid or null. In theory, static
1086 // addresses should not be invalid here because TetheringManager do not allow caller to
1087 // specify invalid static address configuration.
1088 if (request == null || request.localIPv4Address == null
1089 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1090 request.localIPv4Address, request.staticClientAddress)) {
1091 return;
1092 }
markchienf053e4b2020-03-16 21:49:48 +08001093
1094 mStaticIpv4ServerAddr = request.localIPv4Address;
1095 mStaticIpv4ClientAddr = request.staticClientAddress;
1096 }
1097
markchien74a4fa92019-09-09 20:50:49 +08001098 class InitialState extends State {
1099 @Override
1100 public void enter() {
1101 sendInterfaceState(STATE_AVAILABLE);
1102 }
1103
1104 @Override
1105 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001106 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001107 switch (message.what) {
1108 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001109 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001110 switch (message.arg1) {
1111 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001112 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001113 transitionTo(mLocalHotspotState);
1114 break;
1115 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001116 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001117 transitionTo(mTetheredState);
1118 break;
1119 default:
1120 mLog.e("Invalid tethering interface serving state specified.");
1121 }
1122 break;
1123 case CMD_INTERFACE_DOWN:
1124 transitionTo(mUnavailableState);
1125 break;
1126 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001127 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001128 break;
1129 default:
1130 return NOT_HANDLED;
1131 }
1132 return HANDLED;
1133 }
1134 }
1135
Hungming Chen46c30b12020-10-15 17:25:36 +08001136 private void startConntrackMonitoring() {
1137 mBpfCoordinator.startMonitoring(this);
1138 }
1139
1140 private void stopConntrackMonitoring() {
1141 mBpfCoordinator.stopMonitoring(this);
1142 }
1143
markchien74a4fa92019-09-09 20:50:49 +08001144 class BaseServingState extends State {
1145 @Override
1146 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001147 startConntrackMonitoring();
1148
markchien74a4fa92019-09-09 20:50:49 +08001149 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001150 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001151 return;
1152 }
1153
1154 try {
markchienc9daba32020-02-12 00:19:21 +08001155 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001156 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001157 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001158 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001159 return;
1160 }
1161
1162 if (!startIPv6()) {
1163 mLog.e("Failed to startIPv6");
1164 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1165 return;
1166 }
1167 }
1168
1169 @Override
1170 public void exit() {
1171 // Note that at this point, we're leaving the tethered state. We can fail any
1172 // of these operations, but it doesn't really change that we have to try them
1173 // all in sequence.
1174 stopIPv6();
1175
1176 try {
markchien12c5bb82020-01-07 14:43:17 +08001177 NetdUtils.untetherInterface(mNetd, mIfaceName);
1178 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001179 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001180 mLog.e("Failed to untether interface: " + e);
1181 }
1182
1183 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001184 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001185
1186 resetLinkProperties();
1187 }
1188
1189 @Override
1190 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001191 switch (message.what) {
1192 case CMD_TETHER_UNREQUESTED:
1193 transitionTo(mInitialState);
1194 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1195 break;
1196 case CMD_INTERFACE_DOWN:
1197 transitionTo(mUnavailableState);
1198 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1199 break;
1200 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001201 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001202 sendLinkProperties();
1203 break;
1204 case CMD_IP_FORWARDING_ENABLE_ERROR:
1205 case CMD_IP_FORWARDING_DISABLE_ERROR:
1206 case CMD_START_TETHERING_ERROR:
1207 case CMD_STOP_TETHERING_ERROR:
1208 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001209 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001210 transitionTo(mInitialState);
1211 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001212 case CMD_NEW_PREFIX_REQUEST:
1213 handleNewPrefixRequest((IpPrefix) message.obj);
1214 break;
markchienc9daba32020-02-12 00:19:21 +08001215 case CMD_NOTIFY_PREFIX_CONFLICT:
1216 mLog.i("restart tethering: " + mInterfaceType);
1217 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1218 transitionTo(mWaitingForRestartState);
1219 break;
markchien74a4fa92019-09-09 20:50:49 +08001220 default:
1221 return false;
1222 }
1223 return true;
1224 }
1225 }
1226
1227 // Handling errors in BaseServingState.enter() by transitioning is
1228 // problematic because transitioning during a multi-state jump yields
1229 // a Log.wtf(). Ultimately, there should be only one ServingState,
1230 // and forwarding and NAT rules should be handled by a coordinating
1231 // functional element outside of IpServer.
1232 class LocalHotspotState extends BaseServingState {
1233 @Override
1234 public void enter() {
1235 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001236 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001237 transitionTo(mInitialState);
1238 }
1239
1240 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1241 sendInterfaceState(STATE_LOCAL_ONLY);
1242 }
1243
1244 @Override
1245 public boolean processMessage(Message message) {
1246 if (super.processMessage(message)) return true;
1247
markchien21021ef2021-06-01 10:58:04 +08001248 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001249 switch (message.what) {
1250 case CMD_TETHER_REQUESTED:
1251 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1252 break;
1253 case CMD_TETHER_CONNECTION_CHANGED:
1254 // Ignored in local hotspot state.
1255 break;
1256 default:
1257 return false;
1258 }
1259 return true;
1260 }
1261 }
1262
1263 // Handling errors in BaseServingState.enter() by transitioning is
1264 // problematic because transitioning during a multi-state jump yields
1265 // a Log.wtf(). Ultimately, there should be only one ServingState,
1266 // and forwarding and NAT rules should be handled by a coordinating
1267 // functional element outside of IpServer.
1268 class TetheredState extends BaseServingState {
1269 @Override
1270 public void enter() {
1271 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001272 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001273 transitionTo(mInitialState);
1274 }
1275
1276 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1277 sendInterfaceState(STATE_TETHERED);
1278 }
1279
1280 @Override
1281 public void exit() {
1282 cleanupUpstream();
1283 super.exit();
1284 }
1285
Hungming Chena6e78692021-02-08 17:15:35 +08001286 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1287 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1288 // and behaviour. While upstream is switching from offload supported interface to
1289 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1290 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1291 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1292 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1293 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1294 // in the state machine. Once there is any case out whish is not covered by previous cases,
1295 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001296 private void cleanupUpstream() {
1297 if (mUpstreamIfaceSet == null) return;
1298
1299 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1300 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001301 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001302 }
1303
1304 private void cleanupUpstreamInterface(String upstreamIface) {
1305 // Note that we don't care about errors here.
1306 // Sometimes interfaces are gone before we get
1307 // to remove their rules, which generates errors.
1308 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001309 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001310 try {
markchien12c5bb82020-01-07 14:43:17 +08001311 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1312 } catch (RemoteException | ServiceSpecificException e) {
1313 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001314 }
1315 try {
markchien12c5bb82020-01-07 14:43:17 +08001316 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1317 } catch (RemoteException | ServiceSpecificException e) {
1318 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001319 }
1320 }
1321
1322 @Override
1323 public boolean processMessage(Message message) {
1324 if (super.processMessage(message)) return true;
1325
markchien21021ef2021-06-01 10:58:04 +08001326 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001327 switch (message.what) {
1328 case CMD_TETHER_REQUESTED:
1329 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1330 break;
1331 case CMD_TETHER_CONNECTION_CHANGED:
1332 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1333 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1334 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1335 break;
1336 }
1337
1338 if (newUpstreamIfaceSet == null) {
1339 cleanupUpstream();
1340 break;
1341 }
1342
1343 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1344 cleanupUpstreamInterface(removed);
1345 }
1346
1347 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1348 // This makes the call to cleanupUpstream() in the error
1349 // path for any interface neatly cleanup all the interfaces.
1350 mUpstreamIfaceSet = newUpstreamIfaceSet;
1351
1352 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001353 // Add upstream index to name mapping for the tether stats usage in the
1354 // coordinator. Although this mapping could be added by both class
1355 // Tethering and IpServer, adding mapping from IpServer guarantees that
1356 // the mapping is added before adding forwarding rules. That is because
1357 // there are different state machines in both classes. It is hard to
1358 // guarantee the link property update order between multiple state machines.
1359 // Note that both IPv4 and IPv6 interface may be added because
1360 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1361 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1362 // capability may be updated later. In that case, IPv6 interface mapping is
1363 // updated in updateUpstreamIPv6LinkProperties.
1364 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1365 final InterfaceParams upstreamIfaceParams =
1366 mDeps.getInterfaceParams(ifname);
1367 if (upstreamIfaceParams != null) {
1368 mBpfCoordinator.addUpstreamNameToLookupTable(
1369 upstreamIfaceParams.index, ifname);
1370 }
1371 }
1372
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001373 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001374 try {
markchien12c5bb82020-01-07 14:43:17 +08001375 mNetd.tetherAddForward(mIfaceName, ifname);
1376 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1377 } catch (RemoteException | ServiceSpecificException e) {
1378 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001379 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001380 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001381 transitionTo(mInitialState);
1382 return true;
1383 }
1384 }
1385 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001386 case CMD_NEIGHBOR_EVENT:
1387 handleNeighborEvent((NeighborEvent) message.obj);
1388 break;
markchien74a4fa92019-09-09 20:50:49 +08001389 default:
1390 return false;
1391 }
1392 return true;
1393 }
1394
1395 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1396 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1397 if (mUpstreamIfaceSet != null && newIfaces != null) {
1398 return mUpstreamIfaceSet.equals(newIfaces);
1399 }
1400 return false;
1401 }
1402
1403 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1404 if (mUpstreamIfaceSet == null) return new HashSet<>();
1405
1406 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1407 removed.removeAll(newIfaces.ifnames);
1408 return removed;
1409 }
1410
1411 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1412 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1413 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1414 return added;
1415 }
1416 }
1417
1418 /**
1419 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001420 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001421 * specific state machine from its list of possible recipients of
1422 * tethering requests. The state machine itself will hang around until
1423 * the garbage collector finds it.
1424 */
1425 class UnavailableState extends State {
1426 @Override
1427 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001428 mIpNeighborMonitor.stop();
markchien9b4d7572019-12-25 19:40:32 +08001429 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001430 sendInterfaceState(STATE_UNAVAILABLE);
1431 }
1432 }
1433
markchienc9daba32020-02-12 00:19:21 +08001434 class WaitingForRestartState extends State {
1435 @Override
1436 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001437 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001438 switch (message.what) {
1439 case CMD_TETHER_UNREQUESTED:
1440 transitionTo(mInitialState);
1441 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1442 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1443 break;
1444 case CMD_INTERFACE_DOWN:
1445 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001446 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001447 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1448 break;
1449 default:
1450 return false;
1451 }
1452 return true;
1453 }
1454 }
1455
markchien74a4fa92019-09-09 20:50:49 +08001456 // Accumulate routes representing "prefixes to be assigned to the local
1457 // interface", for subsequent modification of local_network routing.
1458 private static ArrayList<RouteInfo> getLocalRoutesFor(
1459 String ifname, HashSet<IpPrefix> prefixes) {
1460 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1461 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001462 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001463 }
1464 return localRoutes;
1465 }
1466
1467 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1468 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1469 final byte[] dnsBytes = localPrefix.getRawAddress();
1470 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1471 try {
1472 return Inet6Address.getByAddress(null, dnsBytes, 0);
1473 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001474 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001475 return null;
1476 }
1477 }
1478
1479 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1480 final byte random = (byte) (new Random()).nextInt();
1481 for (int value : excluded) {
1482 if (random == value) return dflt;
1483 }
1484 return random;
1485 }
1486}