blob: 7f3e80fb271fcb126746da95ce98ff9498f649b8 [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
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090074import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080075import java.net.Inet4Address;
76import java.net.Inet6Address;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090077import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080078import java.net.UnknownHostException;
79import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090080import java.util.Arrays;
81import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080082import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090083import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080084import java.util.Objects;
85import java.util.Random;
86import java.util.Set;
87
88/**
89 * Provides the interface to IP-layer serving functionality for a given network
90 * interface, e.g. for tethering or "local-only hotspot" mode.
91 *
92 * @hide
93 */
94public class IpServer extends StateMachine {
95 public static final int STATE_UNAVAILABLE = 0;
96 public static final int STATE_AVAILABLE = 1;
97 public static final int STATE_TETHERED = 2;
98 public static final int STATE_LOCAL_ONLY = 3;
99
100 /** Get string name of |state|.*/
101 public static String getStateString(int state) {
102 switch (state) {
103 case STATE_UNAVAILABLE: return "UNAVAILABLE";
104 case STATE_AVAILABLE: return "AVAILABLE";
105 case STATE_TETHERED: return "TETHERED";
106 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
107 }
108 return "UNKNOWN: " + state;
109 }
110
111 private static final byte DOUG_ADAMS = (byte) 42;
112
markchien74a4fa92019-09-09 20:50:49 +0800113 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800114 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800115
116 // TODO: have this configurable
117 private static final int DHCP_LEASE_TIME_SECS = 3600;
118
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900119 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
120
markchien74a4fa92019-09-09 20:50:49 +0800121 private static final String TAG = "IpServer";
122 private static final boolean DBG = false;
123 private static final boolean VDBG = false;
124 private static final Class[] sMessageClasses = {
125 IpServer.class
126 };
127 private static final SparseArray<String> sMagicDecoderRing =
128 MessageUtils.findMessageNames(sMessageClasses);
129
130 /** IpServer callback. */
131 public static class Callback {
132 /**
133 * Notify that |who| has changed its tethering state.
134 *
135 * @param who the calling instance of IpServer
136 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800137 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800138 */
markchien9d353822019-12-16 20:15:20 +0800139 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800140
141 /**
142 * Notify that |who| has new LinkProperties.
143 *
144 * @param who the calling instance of IpServer
145 * @param newLp the new LinkProperties to report
146 */
markchien9d353822019-12-16 20:15:20 +0800147 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900148
149 /**
150 * Notify that the DHCP leases changed in one of the IpServers.
151 */
152 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800153
154 /**
155 * Request Tethering change.
156 *
157 * @param tetheringType the downstream type of this IpServer.
158 * @param enabled enable or disable tethering.
159 */
160 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800161 }
162
163 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800164 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700165 /**
166 * Create a DadProxy instance to be used by IpServer.
167 * To support multiple tethered interfaces concurrently DAD Proxy
168 * needs to be supported per IpServer instead of per upstream.
169 */
170 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
171 return new DadProxy(handler, ifParams);
172 }
173
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900174 /** Create an IpNeighborMonitor to be used by this IpServer */
175 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
176 IpNeighborMonitor.NeighborEventConsumer consumer) {
177 return new IpNeighborMonitor(handler, log, consumer);
178 }
179
markchien74a4fa92019-09-09 20:50:49 +0800180 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
181 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
182 return new RouterAdvertisementDaemon(ifParams);
183 }
184
185 /** Get |ifName|'s interface information.*/
186 public InterfaceParams getInterfaceParams(String ifName) {
187 return InterfaceParams.getByName(ifName);
188 }
189
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900190 /** Get |ifName|'s interface index. */
191 public int getIfindex(String ifName) {
192 try {
193 return NetworkInterface.getByName(ifName).getIndex();
194 } catch (IOException | NullPointerException e) {
195 Log.e(TAG, "Can't determine interface index for interface " + ifName);
196 return 0;
197 }
198 }
markchienc9daba32020-02-12 00:19:21 +0800199
markchien9d353822019-12-16 20:15:20 +0800200 /** Create a DhcpServer instance to be used by IpServer. */
201 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
202 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800203 }
204
markchien74a4fa92019-09-09 20:50:49 +0800205 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800206 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800207 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800209 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800211 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
212 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800213 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800214 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
215 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800216 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800217 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
218 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800219 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800220 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800221 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800222 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
223 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800224 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800225 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800226 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800227 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800228 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900229 // new neighbor cache entry on our interface
230 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900231 // request from DHCP server that it wants to have a new prefix
232 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800233 // request from PrivateAddressCoordinator to restart tethering.
234 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800235
236 private final State mInitialState;
237 private final State mLocalHotspotState;
238 private final State mTetheredState;
239 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800240 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800241
242 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800243 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800244 @NonNull
245 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800246 private final Callback mCallback;
247 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800248 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800249
250 private final String mIfaceName;
251 private final int mInterfaceType;
252 private final LinkProperties mLinkProperties;
253 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800254 private final boolean mUsingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800255
256 private final Dependencies mDeps;
257
258 private int mLastError;
259 private int mServingMode;
260 private InterfaceSet mUpstreamIfaceSet; // may change over time
261 private InterfaceParams mInterfaceParams;
262 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
263 // properties are those selected by the IPv6TetheringCoordinator and relayed
264 // to us. By comparison, mLinkProperties contains the addresses and directly
265 // connected routes that have been formed from these properties iff. we have
266 // succeeded in configuring them and are able to announce them within Router
267 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
268 private LinkProperties mLastIPv6LinkProperties;
269 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700270 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800271
272 // To be accessed only on the handler thread
273 private int mDhcpServerStartIndex = 0;
274 private IDhcpServer mDhcpServer;
275 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800276
277 private LinkAddress mStaticIpv4ServerAddr;
278 private LinkAddress mStaticIpv4ClientAddr;
279
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900280 @NonNull
281 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800282
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900283 private int mLastIPv6UpstreamIfindex = 0;
284
285 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
286 public void accept(NeighborEvent e) {
287 sendMessage(CMD_NEIGHBOR_EVENT, e);
288 }
289 }
290
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900291 private final IpNeighborMonitor mIpNeighborMonitor;
292
markchienc9daba32020-02-12 00:19:21 +0800293 private LinkAddress mIpv4Address;
294
Hungming Chen5bc3af92020-05-12 19:15:24 +0800295 // TODO: Add a dependency object to pass the data members or variables from the tethering
296 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800297 public IpServer(
298 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800299 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
300 boolean usingLegacyDhcp, boolean usingBpfOffload,
markchienc9daba32020-02-12 00:19:21 +0800301 PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800302 super(ifaceName, looper);
303 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800304 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800305 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800306 mCallback = callback;
307 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
308 mIfaceName = ifaceName;
309 mInterfaceType = interfaceType;
310 mLinkProperties = new LinkProperties();
311 mUsingLegacyDhcp = usingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800312 mUsingBpfOffload = usingBpfOffload;
markchienc9daba32020-02-12 00:19:21 +0800313 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800314 mDeps = deps;
315 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800316 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800317 mServingMode = STATE_AVAILABLE;
318
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900319 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
320 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800321
Hungming Chen5bc3af92020-05-12 19:15:24 +0800322 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800323 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800324 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800325 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800326 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
327 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900328 }
329
markchien74a4fa92019-09-09 20:50:49 +0800330 mInitialState = new InitialState();
331 mLocalHotspotState = new LocalHotspotState();
332 mTetheredState = new TetheredState();
333 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800334 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800335 addState(mInitialState);
336 addState(mLocalHotspotState);
337 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800338 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800339 addState(mUnavailableState);
340
341 setInitialState(mInitialState);
342 }
343
344 /** Interface name which IpServer served.*/
345 public String interfaceName() {
346 return mIfaceName;
347 }
348
349 /**
markchien9b4d7572019-12-25 19:40:32 +0800350 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800351 */
352 public int interfaceType() {
353 return mInterfaceType;
354 }
355
356 /** Last error from this IpServer. */
357 public int lastError() {
358 return mLastError;
359 }
360
361 /** Serving mode is the current state of IpServer state machine. */
362 public int servingMode() {
363 return mServingMode;
364 }
365
366 /** The properties of the network link which IpServer is serving. */
367 public LinkProperties linkProperties() {
368 return new LinkProperties(mLinkProperties);
369 }
370
markchienc9daba32020-02-12 00:19:21 +0800371 /** The address which IpServer is using. */
372 public LinkAddress getAddress() {
373 return mIpv4Address;
374 }
375
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900376 /**
377 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
378 * thread.
379 */
380 public List<TetheredClient> getAllLeases() {
381 return Collections.unmodifiableList(mDhcpLeases);
382 }
383
markchien74a4fa92019-09-09 20:50:49 +0800384 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
385 public void stop() {
386 sendMessage(CMD_INTERFACE_DOWN);
387 }
388
389 /**
390 * Tethering is canceled. IpServer state machine will be available and wait for
391 * next tethering request.
392 */
393 public void unwanted() {
394 sendMessage(CMD_TETHER_UNREQUESTED);
395 }
396
397 /** Internals. */
398
399 private boolean startIPv4() {
400 return configureIPv4(true);
401 }
402
403 /**
404 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
405 * handler.
406 *
407 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
408 * with different implementations of the callback, to differentiate handling of success/error in
409 * each call.
410 */
411 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
412 @Override
413 public void onStatusAvailable(int statusCode) {
414 getHandler().post(() -> callback(statusCode));
415 }
416
417 public abstract void callback(int statusCode);
418
419 @Override
420 public int getInterfaceVersion() {
421 return this.VERSION;
422 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900423
424 @Override
425 public String getInterfaceHash() {
426 return this.HASH;
427 }
markchien74a4fa92019-09-09 20:50:49 +0800428 }
429
430 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
431 private final int mStartIndex;
432
433 private DhcpServerCallbacksImpl(int startIndex) {
434 mStartIndex = startIndex;
435 }
436
437 @Override
438 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
439 getHandler().post(() -> {
440 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
441 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800442 // This start request is obsolete. Explicitly stop the DHCP server to shut
443 // down its thread. When the |server| binder token goes out of scope, the
444 // garbage collector will finalize it, which causes the network stack process
445 // garbage collector to collect the server itself.
446 try {
447 server.stop(null);
448 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800449 return;
450 }
451
452 if (statusCode != STATUS_SUCCESS) {
453 mLog.e("Error obtaining DHCP server: " + statusCode);
454 handleError();
455 return;
456 }
457
458 mDhcpServer = server;
459 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900460 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800461 @Override
462 public void callback(int startStatusCode) {
463 if (startStatusCode != STATUS_SUCCESS) {
464 mLog.e("Error starting DHCP server: " + startStatusCode);
465 handleError();
466 }
467 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900468 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800469 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800470 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800471 }
472 });
473 }
474
475 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800476 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800477 transitionTo(mInitialState);
478 }
479 }
480
Xiao Ma4455d6b2020-04-09 10:13:44 +0900481 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900482 @Override
483 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
484 final ArrayList<TetheredClient> leases = new ArrayList<>();
485 for (DhcpLeaseParcelable lease : leaseParcelables) {
486 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900487 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
488 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
489 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900490
491 final MacAddress macAddress;
492 try {
493 macAddress = MacAddress.fromBytes(lease.hwAddr);
494 } catch (IllegalArgumentException e) {
495 Log.wtf(TAG, "Invalid address received from DhcpServer: "
496 + Arrays.toString(lease.hwAddr));
497 return;
498 }
499
500 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900501 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900502 leases.add(new TetheredClient(
503 macAddress,
504 Collections.singletonList(addressInfo),
505 mInterfaceType));
506 }
507
508 getHandler().post(() -> {
509 mDhcpLeases = leases;
510 mCallback.dhcpLeasesChanged();
511 });
512 }
513
514 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900515 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
516 Objects.requireNonNull(currentPrefix);
517 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900518 }
519
520 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900521 public int getInterfaceVersion() {
522 return this.VERSION;
523 }
524
525 @Override
526 public String getInterfaceHash() throws RemoteException {
527 return this.HASH;
528 }
529 }
530
Xiao Ma4455d6b2020-04-09 10:13:44 +0900531 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
532 Objects.requireNonNull(ipv4Address);
533 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
534 }
535
536 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
537 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
538 @Nullable Inet4Address clientAddr) {
539 final boolean changePrefixOnDecline =
540 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
541 return new DhcpServingParamsParcelExt()
542 .setDefaultRouters(defaultRouter)
543 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
544 .setDnsServers(dnsServer)
545 .setServerAddr(serverAddr)
546 .setMetered(true)
547 .setSingleClientAddr(clientAddr)
548 .setChangePrefixOnDecline(changePrefixOnDecline);
549 // TODO: also advertise link MTU
550 }
551
markchien245352e2020-02-27 20:27:18 +0800552 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800553 if (mUsingLegacyDhcp) {
554 return true;
555 }
markchien245352e2020-02-27 20:27:18 +0800556
557 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800558 final Inet4Address clientAddr = clientLinkAddr == null ? null :
559 (Inet4Address) clientLinkAddr.getAddress();
560
Xiao Ma4455d6b2020-04-09 10:13:44 +0900561 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
562 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800563 mDhcpServerStartIndex++;
564 mDeps.makeDhcpServer(
565 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
566 return true;
567 }
568
569 private void stopDhcp() {
570 // Make all previous start requests obsolete so servers are not started later
571 mDhcpServerStartIndex++;
572
573 if (mDhcpServer != null) {
574 try {
575 mDhcpServer.stop(new OnHandlerStatusCallback() {
576 @Override
577 public void callback(int statusCode) {
578 if (statusCode != STATUS_SUCCESS) {
579 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800580 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800581 // Not much more we can do here
582 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900583 mDhcpLeases.clear();
584 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800585 }
586 });
587 mDhcpServer = null;
588 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900589 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800590 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800591 }
592 }
593 }
594
markchien245352e2020-02-27 20:27:18 +0800595 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
596 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800597 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800598 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800599 } else {
600 stopDhcp();
601 return true;
602 }
603 }
604
605 private void stopIPv4() {
606 configureIPv4(false);
607 // NOTE: All of configureIPv4() will be refactored out of existence
608 // into calls to InterfaceController, shared with startIPv4().
609 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800610 mPrivateAddressCoordinator.releaseDownstream(this);
markchien12c5bb82020-01-07 14:43:17 +0800611 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800612 mStaticIpv4ServerAddr = null;
613 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800614 }
615
markchien74a4fa92019-09-09 20:50:49 +0800616 private boolean configureIPv4(boolean enabled) {
617 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
618
markchienc9daba32020-02-12 00:19:21 +0800619 if (enabled) {
markchiena2ffad82020-09-22 15:50:43 +0800620 mIpv4Address = requestIpv4Address(true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800621 }
622
623 if (mIpv4Address == null) {
624 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800625 return false;
markchien74a4fa92019-09-09 20:50:49 +0800626 }
627
markchienc9daba32020-02-12 00:19:21 +0800628 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
629 // BT configures the interface elsewhere: only start DHCP.
630 // TODO: make all tethering types behave the same way, and delete the bluetooth
631 // code that calls into NetworkManagementService directly.
632 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
633 }
634
635 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
636
markchien12c5bb82020-01-07 14:43:17 +0800637 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800638 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900639 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200640 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
641 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900642 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800643 // It is unclear whether the Bluetooth or USB stacks will manage their own
644 // state.
645 setIfaceUp = null;
646 } else {
647 setIfaceUp = enabled;
648 }
649 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
650 mLog.e("Error configuring interface");
651 if (!enabled) stopDhcp();
652 return false;
653 }
markchien74a4fa92019-09-09 20:50:49 +0800654
markchien74a4fa92019-09-09 20:50:49 +0800655 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800656 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900657 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800658 } else {
markchien12c5bb82020-01-07 14:43:17 +0800659 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900660 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800661 }
markchien245352e2020-02-27 20:27:18 +0800662 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800663 }
664
markchiena2ffad82020-09-22 15:50:43 +0800665 private LinkAddress requestIpv4Address(final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800666 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800667
markchienc9daba32020-02-12 00:19:21 +0800668 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
669 return new LinkAddress(BLUETOOTH_IFACE_ADDR);
670 }
671
markchiena2ffad82020-09-22 15:50:43 +0800672 return mPrivateAddressCoordinator.requestDownstreamAddress(this, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900673 }
674
markchien74a4fa92019-09-09 20:50:49 +0800675 private boolean startIPv6() {
676 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
677 if (mInterfaceParams == null) {
678 mLog.e("Failed to find InterfaceParams");
679 stopIPv6();
680 return false;
681 }
682
683 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
684 if (!mRaDaemon.start()) {
685 stopIPv6();
686 return false;
687 }
688
Tyler Wear90e40632020-03-13 11:38:38 -0700689 // TODO: use ShimUtils instead of explicitly checking the version here.
690 if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R || "S".equals(Build.VERSION.CODENAME)
691 || "T".equals(Build.VERSION.CODENAME)) {
692 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
693 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
694 }
695
markchien74a4fa92019-09-09 20:50:49 +0800696 return true;
697 }
698
699 private void stopIPv6() {
700 mInterfaceParams = null;
701 setRaParams(null);
702
703 if (mRaDaemon != null) {
704 mRaDaemon.stop();
705 mRaDaemon = null;
706 }
Tyler Wear90e40632020-03-13 11:38:38 -0700707
708 if (mDadProxy != null) {
709 mDadProxy.stop();
710 mDadProxy = null;
711 }
markchien74a4fa92019-09-09 20:50:49 +0800712 }
713
714 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
715 // LinkProperties. These have extraneous data filtered out and only the
716 // necessary prefixes included (per its prefix distribution policy).
717 //
718 // TODO: Evaluate using a data structure than is more directly suited to
719 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800720 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800721 if (mRaDaemon == null) return;
722
723 // Avoid unnecessary work on spurious updates.
724 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
725 return;
726 }
727
728 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700729 String upstreamIface = null;
730 InterfaceParams upstreamIfaceParams = null;
731 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800732
733 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700734 upstreamIface = v6only.getInterfaceName();
735 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
736 if (upstreamIfaceParams != null) {
737 upstreamIfIndex = upstreamIfaceParams.index;
738 }
markchien74a4fa92019-09-09 20:50:49 +0800739 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700740 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800741 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
742
markchiend63c4f32020-05-21 17:38:28 +0800743 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800744
745 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
746 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
747
748 final IpPrefix prefix = new IpPrefix(
749 linkAddr.getAddress(), linkAddr.getPrefixLength());
750 params.prefixes.add(prefix);
751
752 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
753 if (dnsServer != null) {
754 params.dnses.add(dnsServer);
755 }
756 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900757
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800758 // Add upstream index to name mapping for the tether stats usage in the coordinator.
759 // Although this mapping could be added by both class Tethering and IpServer, adding
760 // mapping from IpServer guarantees that the mapping is added before the adding
761 // forwarding rules. That is because there are different state machines in both
762 // classes. It is hard to guarantee the link property update order between multiple
763 // state machines.
Tyler Wear90e40632020-03-13 11:38:38 -0700764 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800765 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900766
markchien74a4fa92019-09-09 20:50:49 +0800767 // If v6only is null, we pass in null to setRaParams(), which handles
768 // deprecation of any existing RA data.
769
770 setRaParams(params);
771 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900772
Tyler Wear90e40632020-03-13 11:38:38 -0700773 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, null);
774 mLastIPv6UpstreamIfindex = upstreamIfIndex;
775 if (mDadProxy != null) {
776 mDadProxy.setUpstreamIface(upstreamIfaceParams);
777 }
markchien74a4fa92019-09-09 20:50:49 +0800778 }
779
Xiao Ma4455d6b2020-04-09 10:13:44 +0900780 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
781 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
782 mNetd, toBeRemoved);
783 if (removalFailures > 0) {
784 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
785 removalFailures));
786 }
787
788 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
789 }
790
791 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
792 try {
793 // It's safe to call networkAddInterface() even if
794 // the interface is already in the local_network.
795 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
796 try {
797 // Add routes from local network. Note that adding routes that
798 // already exist does not cause an error (EEXIST is silently ignored).
799 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
800 } catch (IllegalStateException e) {
801 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
802 return;
803 }
804 } catch (ServiceSpecificException | RemoteException e) {
805 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
806 return;
807 }
808
809 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
810 }
811
markchien74a4fa92019-09-09 20:50:49 +0800812 private void configureLocalIPv6Routes(
813 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
814 // [1] Remove the routes that are deprecated.
815 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900816 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800817 }
818
819 // [2] Add only the routes that have not previously been added.
820 if (newPrefixes != null && !newPrefixes.isEmpty()) {
821 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
822 if (mLastRaParams != null) {
823 addedPrefixes.removeAll(mLastRaParams.prefixes);
824 }
825
826 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900827 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800828 }
829 }
830 }
831
832 private void configureLocalIPv6Dns(
833 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
834 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
835 if (mNetd == null) {
836 if (newDnses != null) newDnses.clear();
837 mLog.e("No netd service instance available; not setting local IPv6 addresses");
838 return;
839 }
840
841 // [1] Remove deprecated local DNS IP addresses.
842 if (!deprecatedDnses.isEmpty()) {
843 for (Inet6Address dns : deprecatedDnses) {
844 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
845 mLog.e("Failed to remove local dns IP " + dns);
846 }
847
848 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
849 }
850 }
851
852 // [2] Add only the local DNS IP addresses that have not previously been added.
853 if (newDnses != null && !newDnses.isEmpty()) {
854 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
855 if (mLastRaParams != null) {
856 addedDnses.removeAll(mLastRaParams.dnses);
857 }
858
859 for (Inet6Address dns : addedDnses) {
860 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
861 mLog.e("Failed to add local dns IP " + dns);
862 newDnses.remove(dns);
863 }
864
865 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
866 }
867 }
868
869 try {
870 mNetd.tetherApplyDnsInterfaces();
871 } catch (ServiceSpecificException | RemoteException e) {
872 mLog.e("Failed to update local DNS caching server");
873 if (newDnses != null) newDnses.clear();
874 }
875 }
876
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900877 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800878 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
879 // offload is disabled. Add this check just in case.
880 // TODO: Perhaps remove this protection check.
881 if (!mUsingBpfOffload) return;
882
Hungming Chen269c0882020-05-06 14:57:35 +0800883 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900884 }
885
Hungming Chen269c0882020-05-06 14:57:35 +0800886 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800887 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800888 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800889 if (!mUsingBpfOffload) return;
890
Hungming Chen269c0882020-05-06 14:57:35 +0800891 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900892 }
893
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900894 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800895 if (!mUsingBpfOffload) return;
896
897 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900898 }
899
Hungming Chen269c0882020-05-06 14:57:35 +0800900 private void updateIpv6ForwardingRule(int newIfindex) {
901 // TODO: Perhaps remove this protection check.
902 // See the related comment in #addIpv6ForwardingRule.
903 if (!mUsingBpfOffload) return;
904
905 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900906 }
907
908 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
909 // changes or if a neighbor event is received.
910 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
911 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900912 // If we no longer have an upstream, clear forwarding rules and do nothing else.
913 if (upstreamIfindex == 0) {
914 clearIpv6ForwardingRules();
915 return;
916 }
917
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900918 // If the upstream interface has changed, remove all rules and re-add them with the new
919 // upstream interface.
920 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800921 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900922 }
923
924 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900925 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900926 if (e == null) return;
927 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
928 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
929 return;
930 }
931
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900932 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
933 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
934 // add rules with a null MAC, only delete them.
935 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900936 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900937 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900938 if (e.isValid()) {
939 addIpv6ForwardingRule(rule);
940 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800941 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900942 }
943 }
944
Hungming Chend71c06e2020-12-21 19:39:49 +0800945 // TODO: consider moving into BpfCoordinator.
946 private void updateClientInfoIpv4(NeighborEvent e) {
947 // TODO: Perhaps remove this protection check.
948 // See the related comment in #addIpv6ForwardingRule.
949 if (!mUsingBpfOffload) return;
950
951 if (e == null) return;
952 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
953 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
954 return;
955 }
956
957 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
958 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
959 // IpServer never add clients with a null MAC, only delete them.
960 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
961 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
962 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
963 if (e.isValid()) {
964 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
965 } else {
966 // TODO: Delete all related offload rules which are using this client.
967 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
968 }
969 }
970
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900971 private void handleNeighborEvent(NeighborEvent e) {
972 if (mInterfaceParams != null
973 && mInterfaceParams.index == e.ifindex
974 && mInterfaceParams.hasMacAddress) {
975 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800976 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900977 }
978 }
979
Xiao Ma4455d6b2020-04-09 10:13:44 +0900980 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
981 if (!currentPrefix.contains(mIpv4Address.getAddress())
982 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
983 Log.e(TAG, "Invalid prefix: " + currentPrefix);
984 return;
985 }
986
987 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchiena2ffad82020-09-22 15:50:43 +0800988 mIpv4Address = requestIpv4Address(false);
markchienc9daba32020-02-12 00:19:21 +0800989 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900990 mLog.e("Fail to request a new downstream prefix");
991 return;
992 }
markchienc9daba32020-02-12 00:19:21 +0800993 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +0900994
995 // Add new IPv4 address on the interface.
996 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
997 mLog.e("Failed to add new IP " + srvAddr);
998 return;
999 }
1000
1001 // Remove deprecated routes from local network.
1002 removeRoutesFromLocalNetwork(
1003 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1004 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1005
1006 // Add new routes to local network.
1007 addRoutesToLocalNetwork(
1008 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1009 mLinkProperties.addLinkAddress(mIpv4Address);
1010
1011 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1012 // listen on the interface configured with new IPv4 address, that results DNS validation
1013 // failure of downstream client even if appropriate routes have been configured.
1014 try {
1015 mNetd.tetherApplyDnsInterfaces();
1016 } catch (ServiceSpecificException | RemoteException e) {
1017 mLog.e("Failed to update local DNS caching server");
1018 return;
1019 }
1020 sendLinkProperties();
1021
1022 // Notify DHCP server that new prefix/route has been applied on IpServer.
1023 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1024 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1025 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1026 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1027 try {
1028 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1029 @Override
1030 public void callback(int statusCode) {
1031 if (statusCode != STATUS_SUCCESS) {
1032 mLog.e("Error updating DHCP serving params: " + statusCode);
1033 }
1034 }
1035 });
1036 } catch (RemoteException e) {
1037 mLog.e("Error updating DHCP serving params", e);
1038 }
1039 }
1040
markchiend63c4f32020-05-21 17:38:28 +08001041 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001042 try {
1043 int upstreamHopLimit = Integer.parseUnsignedInt(
1044 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001045 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001046 // Cap the hop limit to 255.
1047 return (byte) Integer.min(upstreamHopLimit, 255);
1048 } catch (Exception e) {
1049 mLog.e("Failed to find upstream interface hop limit", e);
1050 }
1051 return RaParams.DEFAULT_HOPLIMIT;
1052 }
1053
1054 private void setRaParams(RaParams newParams) {
1055 if (mRaDaemon != null) {
1056 final RaParams deprecatedParams =
1057 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1058
1059 configureLocalIPv6Routes(deprecatedParams.prefixes,
1060 (newParams != null) ? newParams.prefixes : null);
1061
1062 configureLocalIPv6Dns(deprecatedParams.dnses,
1063 (newParams != null) ? newParams.dnses : null);
1064
1065 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1066 }
1067
1068 mLastRaParams = newParams;
1069 }
1070
1071 private void logMessage(State state, int what) {
1072 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
1073 }
1074
1075 private void sendInterfaceState(int newInterfaceState) {
1076 mServingMode = newInterfaceState;
1077 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1078 sendLinkProperties();
1079 }
1080
1081 private void sendLinkProperties() {
1082 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1083 }
1084
1085 private void resetLinkProperties() {
1086 mLinkProperties.clear();
1087 mLinkProperties.setInterfaceName(mIfaceName);
1088 }
1089
markchienf053e4b2020-03-16 21:49:48 +08001090 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001091 // Ignore static address configuration if they are invalid or null. In theory, static
1092 // addresses should not be invalid here because TetheringManager do not allow caller to
1093 // specify invalid static address configuration.
1094 if (request == null || request.localIPv4Address == null
1095 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1096 request.localIPv4Address, request.staticClientAddress)) {
1097 return;
1098 }
markchienf053e4b2020-03-16 21:49:48 +08001099
1100 mStaticIpv4ServerAddr = request.localIPv4Address;
1101 mStaticIpv4ClientAddr = request.staticClientAddress;
1102 }
1103
markchien74a4fa92019-09-09 20:50:49 +08001104 class InitialState extends State {
1105 @Override
1106 public void enter() {
1107 sendInterfaceState(STATE_AVAILABLE);
1108 }
1109
1110 @Override
1111 public boolean processMessage(Message message) {
1112 logMessage(this, message.what);
1113 switch (message.what) {
1114 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001115 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001116 switch (message.arg1) {
1117 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001118 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001119 transitionTo(mLocalHotspotState);
1120 break;
1121 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001122 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001123 transitionTo(mTetheredState);
1124 break;
1125 default:
1126 mLog.e("Invalid tethering interface serving state specified.");
1127 }
1128 break;
1129 case CMD_INTERFACE_DOWN:
1130 transitionTo(mUnavailableState);
1131 break;
1132 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001133 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001134 break;
1135 default:
1136 return NOT_HANDLED;
1137 }
1138 return HANDLED;
1139 }
1140 }
1141
Hungming Chen46c30b12020-10-15 17:25:36 +08001142 private void startConntrackMonitoring() {
1143 mBpfCoordinator.startMonitoring(this);
1144 }
1145
1146 private void stopConntrackMonitoring() {
1147 mBpfCoordinator.stopMonitoring(this);
1148 }
1149
markchien74a4fa92019-09-09 20:50:49 +08001150 class BaseServingState extends State {
1151 @Override
1152 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001153 startConntrackMonitoring();
1154
markchien74a4fa92019-09-09 20:50:49 +08001155 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001156 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001157 return;
1158 }
1159
1160 try {
markchienc9daba32020-02-12 00:19:21 +08001161 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001162 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001163 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001164 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001165 return;
1166 }
1167
1168 if (!startIPv6()) {
1169 mLog.e("Failed to startIPv6");
1170 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1171 return;
1172 }
1173 }
1174
1175 @Override
1176 public void exit() {
1177 // Note that at this point, we're leaving the tethered state. We can fail any
1178 // of these operations, but it doesn't really change that we have to try them
1179 // all in sequence.
1180 stopIPv6();
1181
1182 try {
markchien12c5bb82020-01-07 14:43:17 +08001183 NetdUtils.untetherInterface(mNetd, mIfaceName);
1184 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001185 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001186 mLog.e("Failed to untether interface: " + e);
1187 }
1188
1189 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001190 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001191
1192 resetLinkProperties();
1193 }
1194
1195 @Override
1196 public boolean processMessage(Message message) {
1197 logMessage(this, message.what);
1198 switch (message.what) {
1199 case CMD_TETHER_UNREQUESTED:
1200 transitionTo(mInitialState);
1201 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1202 break;
1203 case CMD_INTERFACE_DOWN:
1204 transitionTo(mUnavailableState);
1205 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1206 break;
1207 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001208 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001209 sendLinkProperties();
1210 break;
1211 case CMD_IP_FORWARDING_ENABLE_ERROR:
1212 case CMD_IP_FORWARDING_DISABLE_ERROR:
1213 case CMD_START_TETHERING_ERROR:
1214 case CMD_STOP_TETHERING_ERROR:
1215 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001216 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001217 transitionTo(mInitialState);
1218 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001219 case CMD_NEW_PREFIX_REQUEST:
1220 handleNewPrefixRequest((IpPrefix) message.obj);
1221 break;
markchienc9daba32020-02-12 00:19:21 +08001222 case CMD_NOTIFY_PREFIX_CONFLICT:
1223 mLog.i("restart tethering: " + mInterfaceType);
1224 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1225 transitionTo(mWaitingForRestartState);
1226 break;
markchien74a4fa92019-09-09 20:50:49 +08001227 default:
1228 return false;
1229 }
1230 return true;
1231 }
1232 }
1233
1234 // Handling errors in BaseServingState.enter() by transitioning is
1235 // problematic because transitioning during a multi-state jump yields
1236 // a Log.wtf(). Ultimately, there should be only one ServingState,
1237 // and forwarding and NAT rules should be handled by a coordinating
1238 // functional element outside of IpServer.
1239 class LocalHotspotState extends BaseServingState {
1240 @Override
1241 public void enter() {
1242 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001243 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001244 transitionTo(mInitialState);
1245 }
1246
1247 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1248 sendInterfaceState(STATE_LOCAL_ONLY);
1249 }
1250
1251 @Override
1252 public boolean processMessage(Message message) {
1253 if (super.processMessage(message)) return true;
1254
1255 logMessage(this, message.what);
1256 switch (message.what) {
1257 case CMD_TETHER_REQUESTED:
1258 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1259 break;
1260 case CMD_TETHER_CONNECTION_CHANGED:
1261 // Ignored in local hotspot state.
1262 break;
1263 default:
1264 return false;
1265 }
1266 return true;
1267 }
1268 }
1269
1270 // Handling errors in BaseServingState.enter() by transitioning is
1271 // problematic because transitioning during a multi-state jump yields
1272 // a Log.wtf(). Ultimately, there should be only one ServingState,
1273 // and forwarding and NAT rules should be handled by a coordinating
1274 // functional element outside of IpServer.
1275 class TetheredState extends BaseServingState {
1276 @Override
1277 public void enter() {
1278 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001279 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001280 transitionTo(mInitialState);
1281 }
1282
1283 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1284 sendInterfaceState(STATE_TETHERED);
1285 }
1286
1287 @Override
1288 public void exit() {
1289 cleanupUpstream();
1290 super.exit();
1291 }
1292
1293 private void cleanupUpstream() {
1294 if (mUpstreamIfaceSet == null) return;
1295
1296 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1297 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001298 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001299 }
1300
1301 private void cleanupUpstreamInterface(String upstreamIface) {
1302 // Note that we don't care about errors here.
1303 // Sometimes interfaces are gone before we get
1304 // to remove their rules, which generates errors.
1305 // Just do the best we can.
1306 try {
markchien12c5bb82020-01-07 14:43:17 +08001307 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1308 } catch (RemoteException | ServiceSpecificException e) {
1309 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001310 }
1311 try {
markchien12c5bb82020-01-07 14:43:17 +08001312 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1313 } catch (RemoteException | ServiceSpecificException e) {
1314 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001315 }
1316 }
1317
1318 @Override
1319 public boolean processMessage(Message message) {
1320 if (super.processMessage(message)) return true;
1321
1322 logMessage(this, message.what);
1323 switch (message.what) {
1324 case CMD_TETHER_REQUESTED:
1325 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1326 break;
1327 case CMD_TETHER_CONNECTION_CHANGED:
1328 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1329 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1330 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1331 break;
1332 }
1333
1334 if (newUpstreamIfaceSet == null) {
1335 cleanupUpstream();
1336 break;
1337 }
1338
1339 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1340 cleanupUpstreamInterface(removed);
1341 }
1342
1343 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1344 // This makes the call to cleanupUpstream() in the error
1345 // path for any interface neatly cleanup all the interfaces.
1346 mUpstreamIfaceSet = newUpstreamIfaceSet;
1347
1348 for (String ifname : added) {
1349 try {
markchien12c5bb82020-01-07 14:43:17 +08001350 mNetd.tetherAddForward(mIfaceName, ifname);
1351 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1352 } catch (RemoteException | ServiceSpecificException e) {
1353 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001354 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001355 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001356 transitionTo(mInitialState);
1357 return true;
1358 }
1359 }
1360 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001361 case CMD_NEIGHBOR_EVENT:
1362 handleNeighborEvent((NeighborEvent) message.obj);
1363 break;
markchien74a4fa92019-09-09 20:50:49 +08001364 default:
1365 return false;
1366 }
1367 return true;
1368 }
1369
1370 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1371 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1372 if (mUpstreamIfaceSet != null && newIfaces != null) {
1373 return mUpstreamIfaceSet.equals(newIfaces);
1374 }
1375 return false;
1376 }
1377
1378 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1379 if (mUpstreamIfaceSet == null) return new HashSet<>();
1380
1381 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1382 removed.removeAll(newIfaces.ifnames);
1383 return removed;
1384 }
1385
1386 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1387 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1388 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1389 return added;
1390 }
1391 }
1392
1393 /**
1394 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001395 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001396 * specific state machine from its list of possible recipients of
1397 * tethering requests. The state machine itself will hang around until
1398 * the garbage collector finds it.
1399 */
1400 class UnavailableState extends State {
1401 @Override
1402 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001403 mIpNeighborMonitor.stop();
markchien9b4d7572019-12-25 19:40:32 +08001404 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001405 sendInterfaceState(STATE_UNAVAILABLE);
1406 }
1407 }
1408
markchienc9daba32020-02-12 00:19:21 +08001409 class WaitingForRestartState extends State {
1410 @Override
1411 public boolean processMessage(Message message) {
1412 logMessage(this, message.what);
1413 switch (message.what) {
1414 case CMD_TETHER_UNREQUESTED:
1415 transitionTo(mInitialState);
1416 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1417 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1418 break;
1419 case CMD_INTERFACE_DOWN:
1420 transitionTo(mUnavailableState);
1421 mLog.i("Untethered (interface down) and restarting" + mIfaceName);
1422 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1423 break;
1424 default:
1425 return false;
1426 }
1427 return true;
1428 }
1429 }
1430
markchien74a4fa92019-09-09 20:50:49 +08001431 // Accumulate routes representing "prefixes to be assigned to the local
1432 // interface", for subsequent modification of local_network routing.
1433 private static ArrayList<RouteInfo> getLocalRoutesFor(
1434 String ifname, HashSet<IpPrefix> prefixes) {
1435 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1436 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001437 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001438 }
1439 return localRoutes;
1440 }
1441
1442 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1443 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1444 final byte[] dnsBytes = localPrefix.getRawAddress();
1445 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1446 try {
1447 return Inet6Address.getByAddress(null, dnsBytes, 0);
1448 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001449 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001450 return null;
1451 }
1452 }
1453
1454 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1455 final byte random = (byte) (new Random()).nextInt();
1456 for (int value : excluded) {
1457 if (random == value) return dflt;
1458 }
1459 return random;
1460 }
1461}