blob: d993306b171aaad0fad901639097b291ad46cd81 [file] [log] [blame]
Christopher Wileyd2896662016-05-19 11:54:54 -07001/*
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
Erik Kline7a4ccc62018-08-27 17:26:47 +090017package android.net.ip;
Christopher Wileyd2896662016-05-19 11:54:54 -070018
markchien08cc0302019-09-09 20:50:49 +080019import static android.net.InetAddresses.parseNumericAddress;
markchien986750b2019-12-06 15:24:53 +080020import static android.net.RouteInfo.RTN_UNICAST;
Treehugger Robot86d212b2020-03-30 04:23:55 +000021import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +090022import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +090023import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH;
Erik Kline0f27eed2018-05-29 19:24:43 +090024import static android.net.util.NetworkConstants.FF;
Erik Kline94ae4c92017-06-13 21:32:10 +090025import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +090026import static android.net.util.NetworkConstants.asByte;
markchien986750b2019-12-06 15:24:53 +080027import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Automerger Merge Worker3d330ff2020-03-16 04:06:46 +000028import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
Erik Kline94ae4c92017-06-13 21:32:10 +090029
Erik Kline94ae4c92017-06-13 21:32:10 +090030import android.net.INetd;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +090031import android.net.INetworkStackStatusCallback;
Erik Kline94ae4c92017-06-13 21:32:10 +090032import android.net.IpPrefix;
Christopher Wileyd2896662016-05-19 11:54:54 -070033import android.net.LinkAddress;
Erik Kline1eb8c692016-07-08 17:21:26 +090034import android.net.LinkProperties;
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +090035import android.net.MacAddress;
Erik Kline94ae4c92017-06-13 21:32:10 +090036import android.net.RouteInfo;
Lorenzo Colitti0fb584b2020-04-06 09:19:57 +000037import android.net.TetherOffloadRuleParcel;
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +090038import android.net.TetheredClient;
markchien9e44cde2019-12-25 19:40:32 +080039import android.net.TetheringManager;
Automerger Merge Worker37a22752020-03-17 16:59:57 +000040import android.net.TetheringRequestParcel;
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +090041import android.net.dhcp.DhcpLeaseParcelable;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +090042import android.net.dhcp.DhcpServerCallbacks;
43import android.net.dhcp.DhcpServingParamsParcel;
44import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma3eab4922020-04-06 11:24:48 +000045import android.net.dhcp.IDhcpEventCallbacks;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +090046import android.net.dhcp.IDhcpServer;
Lorenzo Colittifb19f492020-02-14 01:06:35 +090047import android.net.ip.IpNeighborMonitor.NeighborEvent;
Erik Kline94ae4c92017-06-13 21:32:10 +090048import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien92b8e7f2020-01-07 14:43:17 +080049import android.net.shared.NetdUtils;
50import android.net.shared.RouteUtils;
Erik Kline8bd00d52017-12-08 17:47:50 +090051import android.net.util.InterfaceParams;
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +090052import android.net.util.InterfaceSet;
Erik Kline7747fd42017-05-12 16:52:48 +090053import android.net.util.SharedLog;
Lorenzo Colittifb19f492020-02-14 01:06:35 +090054import android.os.Handler;
Christopher Wileyd2896662016-05-19 11:54:54 -070055import android.os.Looper;
56import android.os.Message;
Erik Kline94ae4c92017-06-13 21:32:10 +090057import android.os.RemoteException;
58import android.os.ServiceSpecificException;
Christopher Wileyd2896662016-05-19 11:54:54 -070059import android.util.Log;
60import android.util.SparseArray;
61
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +090062import androidx.annotation.NonNull;
63
Christopher Wileyd2896662016-05-19 11:54:54 -070064import com.android.internal.util.MessageUtils;
Christopher Wileyd2896662016-05-19 11:54:54 -070065import com.android.internal.util.State;
66import com.android.internal.util.StateMachine;
67
Lorenzo Colittifb19f492020-02-14 01:06:35 +090068import java.io.IOException;
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +090069import java.net.Inet4Address;
Erik Kline94ae4c92017-06-13 21:32:10 +090070import java.net.Inet6Address;
Christopher Wileyd2896662016-05-19 11:54:54 -070071import java.net.InetAddress;
Lorenzo Colittifb19f492020-02-14 01:06:35 +090072import java.net.NetworkInterface;
Erik Kline94ae4c92017-06-13 21:32:10 +090073import java.net.UnknownHostException;
74import java.util.ArrayList;
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +090075import java.util.Arrays;
76import java.util.Collections;
Erik Kline94ae4c92017-06-13 21:32:10 +090077import java.util.HashSet;
Lorenzo Colittifb19f492020-02-14 01:06:35 +090078import java.util.LinkedHashMap;
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +090079import java.util.List;
Erik Kline94ae4c92017-06-13 21:32:10 +090080import java.util.Objects;
81import java.util.Random;
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +090082import java.util.Set;
Christopher Wileyd2896662016-05-19 11:54:54 -070083
84/**
Erik Klinedd4d5822017-06-12 18:20:08 +090085 * Provides the interface to IP-layer serving functionality for a given network
86 * interface, e.g. for tethering or "local-only hotspot" mode.
Christopher Wileyd2896662016-05-19 11:54:54 -070087 *
Erik Klinedd4d5822017-06-12 18:20:08 +090088 * @hide
Christopher Wileyd2896662016-05-19 11:54:54 -070089 */
Erik Kline7a4ccc62018-08-27 17:26:47 +090090public class IpServer extends StateMachine {
91 public static final int STATE_UNAVAILABLE = 0;
92 public static final int STATE_AVAILABLE = 1;
93 public static final int STATE_TETHERED = 2;
94 public static final int STATE_LOCAL_ONLY = 3;
95
markchien08cc0302019-09-09 20:50:49 +080096 /** Get string name of |state|.*/
Erik Kline7a4ccc62018-08-27 17:26:47 +090097 public static String getStateString(int state) {
98 switch (state) {
99 case STATE_UNAVAILABLE: return "UNAVAILABLE";
100 case STATE_AVAILABLE: return "AVAILABLE";
101 case STATE_TETHERED: return "TETHERED";
102 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
103 }
104 return "UNKNOWN: " + state;
105 }
106
Erik Kline0f27eed2018-05-29 19:24:43 +0900107 private static final byte DOUG_ADAMS = (byte) 42;
Erik Kline94ae4c92017-06-13 21:32:10 +0900108
Christopher Wileyd2896662016-05-19 11:54:54 -0700109 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
110 private static final int USB_PREFIX_LENGTH = 24;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700111 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
112 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
Jimmy Chenbcd86d02019-07-15 18:03:23 +0800113 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
114 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
Remi NGUYEN VANf2f3f3e2020-01-24 22:57:09 +0900115 private static final String ETHERNET_IFACE_ADDR = "192.168.50.1";
116 private static final int ETHERNET_IFACE_PREFIX_LENGTH = 24;
Christopher Wileyd2896662016-05-19 11:54:54 -0700117
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900118 // TODO: have PanService use some visible version of this constant
119 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
120 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
121
122 // TODO: have this configurable
123 private static final int DHCP_LEASE_TIME_SECS = 3600;
124
Lorenzo Colitti8bc1e542020-04-14 09:21:19 +0000125 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
126
markchien08cc0302019-09-09 20:50:49 +0800127 private static final String TAG = "IpServer";
128 private static final boolean DBG = false;
129 private static final boolean VDBG = false;
130 private static final Class[] sMessageClasses = {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900131 IpServer.class
Christopher Wileyd2896662016-05-19 11:54:54 -0700132 };
133 private static final SparseArray<String> sMagicDecoderRing =
markchien08cc0302019-09-09 20:50:49 +0800134 MessageUtils.findMessageNames(sMessageClasses);
Christopher Wileyd2896662016-05-19 11:54:54 -0700135
markchien08cc0302019-09-09 20:50:49 +0800136 /** IpServer callback. */
Erik Kline7a4ccc62018-08-27 17:26:47 +0900137 public static class Callback {
138 /**
139 * Notify that |who| has changed its tethering state.
140 *
141 * @param who the calling instance of IpServer
142 * @param state one of STATE_*
markchien9e44cde2019-12-25 19:40:32 +0800143 * @param lastError one of TetheringManager.TETHER_ERROR_*
Erik Kline7a4ccc62018-08-27 17:26:47 +0900144 */
markchien6d06f6d2019-12-16 20:15:20 +0800145 public void updateInterfaceState(IpServer who, int state, int lastError) { }
Erik Kline7a4ccc62018-08-27 17:26:47 +0900146
147 /**
148 * Notify that |who| has new LinkProperties.
149 *
150 * @param who the calling instance of IpServer
151 * @param newLp the new LinkProperties to report
152 */
markchien6d06f6d2019-12-16 20:15:20 +0800153 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900154
155 /**
156 * Notify that the DHCP leases changed in one of the IpServers.
157 */
158 public void dhcpLeasesChanged() { }
Erik Kline7a4ccc62018-08-27 17:26:47 +0900159 }
160
markchien08cc0302019-09-09 20:50:49 +0800161 /** Capture IpServer dependencies, for injection. */
markchien6d06f6d2019-12-16 20:15:20 +0800162 public abstract static class Dependencies {
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900163 /** Create an IpNeighborMonitor to be used by this IpServer */
164 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
165 IpNeighborMonitor.NeighborEventConsumer consumer) {
166 return new IpNeighborMonitor(handler, log, consumer);
167 }
168
markchien08cc0302019-09-09 20:50:49 +0800169 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
Erik Kline7a4ccc62018-08-27 17:26:47 +0900170 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
171 return new RouterAdvertisementDaemon(ifParams);
172 }
173
markchien08cc0302019-09-09 20:50:49 +0800174 /** Get |ifName|'s interface information.*/
Erik Kline7a4ccc62018-08-27 17:26:47 +0900175 public InterfaceParams getInterfaceParams(String ifName) {
176 return InterfaceParams.getByName(ifName);
177 }
178
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900179 /** Get |ifName|'s interface index. */
180 public int getIfindex(String ifName) {
181 try {
182 return NetworkInterface.getByName(ifName).getIndex();
183 } catch (IOException | NullPointerException e) {
184 Log.e(TAG, "Can't determine interface index for interface " + ifName);
185 return 0;
186 }
187 }
markchien6d06f6d2019-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);
Erik Kline7a4ccc62018-08-27 17:26:47 +0900191 }
192
Christopher Wileyd2896662016-05-19 11:54:54 -0700193 // request from the user that it wants to tether
markchien986750b2019-12-06 15:24:53 +0800194 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
Christopher Wileyd2896662016-05-19 11:54:54 -0700195 // request from the user that it wants to untether
markchien986750b2019-12-06 15:24:53 +0800196 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
Christopher Wileyd2896662016-05-19 11:54:54 -0700197 // notification that this interface is down
markchien986750b2019-12-06 15:24:53 +0800198 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Christopher Wileyd2896662016-05-19 11:54:54 -0700199 // notification from the master SM that it had trouble enabling IP Forwarding
markchien986750b2019-12-06 15:24:53 +0800200 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Christopher Wileyd2896662016-05-19 11:54:54 -0700201 // notification from the master SM that it had trouble disabling IP Forwarding
markchien986750b2019-12-06 15:24:53 +0800202 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Christopher Wileyd2896662016-05-19 11:54:54 -0700203 // notification from the master SM that it had trouble starting tethering
markchien986750b2019-12-06 15:24:53 +0800204 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Christopher Wileyd2896662016-05-19 11:54:54 -0700205 // notification from the master SM that it had trouble stopping tethering
markchien986750b2019-12-06 15:24:53 +0800206 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Christopher Wileyd2896662016-05-19 11:54:54 -0700207 // notification from the master SM that it had trouble setting the DNS forwarders
markchien986750b2019-12-06 15:24:53 +0800208 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
Christopher Wileyd2896662016-05-19 11:54:54 -0700209 // the upstream connection has changed
markchien986750b2019-12-06 15:24:53 +0800210 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
Erik Kline1eb8c692016-07-08 17:21:26 +0900211 // new IPv6 tethering parameters need to be processed
markchien986750b2019-12-06 15:24:53 +0800212 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900213 // new neighbor cache entry on our interface
214 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Christopher Wileyd2896662016-05-19 11:54:54 -0700215
216 private final State mInitialState;
Erik Klineea9cc482017-03-10 19:35:34 +0900217 private final State mLocalHotspotState;
Christopher Wileyd2896662016-05-19 11:54:54 -0700218 private final State mTetheredState;
219 private final State mUnavailableState;
220
Erik Kline7747fd42017-05-12 16:52:48 +0900221 private final SharedLog mLog;
Erik Klined3c0b5e2017-09-03 20:38:29 +0900222 private final INetd mNetd;
Erik Kline7a4ccc62018-08-27 17:26:47 +0900223 private final Callback mCallback;
Erik Klined3c0b5e2017-09-03 20:38:29 +0900224 private final InterfaceController mInterfaceCtrl;
Christopher Wileyd2896662016-05-19 11:54:54 -0700225
Christopher Wileyd2896662016-05-19 11:54:54 -0700226 private final String mIfaceName;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700227 private final int mInterfaceType;
Erik Klineab6439b2017-06-06 19:24:21 +0900228 private final LinkProperties mLinkProperties;
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900229 private final boolean mUsingLegacyDhcp;
Nucca Chen95e0bac2020-05-12 11:34:28 +0000230 private final boolean mUsingBpfOffload;
Christopher Wileyd2896662016-05-19 11:54:54 -0700231
Erik Kline7a4ccc62018-08-27 17:26:47 +0900232 private final Dependencies mDeps;
Remi NGUYEN VANa911e842018-03-15 11:57:14 +0900233
Christopher Wileyd2896662016-05-19 11:54:54 -0700234 private int mLastError;
Erik Klineb3bb26e2017-07-06 19:49:35 +0900235 private int mServingMode;
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +0900236 private InterfaceSet mUpstreamIfaceSet; // may change over time
Erik Kline8bd00d52017-12-08 17:47:50 +0900237 private InterfaceParams mInterfaceParams;
Erik Klinedd4d5822017-06-12 18:20:08 +0900238 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
239 // properties are those selected by the IPv6TetheringCoordinator and relayed
240 // to us. By comparison, mLinkProperties contains the addresses and directly
241 // connected routes that have been formed from these properties iff. we have
242 // succeeded in configuring them and are able to announce them within Router
243 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
Erik Kline94ae4c92017-06-13 21:32:10 +0900244 private LinkProperties mLastIPv6LinkProperties;
245 private RouterAdvertisementDaemon mRaDaemon;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900246
247 // To be accessed only on the handler thread
248 private int mDhcpServerStartIndex = 0;
249 private IDhcpServer mDhcpServer;
Erik Kline94ae4c92017-06-13 21:32:10 +0900250 private RaParams mLastRaParams;
markchien92b8e7f2020-01-07 14:43:17 +0800251 private LinkAddress mIpv4Address;
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000252
253 private LinkAddress mStaticIpv4ServerAddr;
254 private LinkAddress mStaticIpv4ClientAddr;
255
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900256 @NonNull
257 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
Christopher Wileyd2896662016-05-19 11:54:54 -0700258
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900259 private int mLastIPv6UpstreamIfindex = 0;
260
261 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
262 public void accept(NeighborEvent e) {
263 sendMessage(CMD_NEIGHBOR_EVENT, e);
264 }
265 }
266
267 static class Ipv6ForwardingRule {
268 public final int upstreamIfindex;
269 public final int downstreamIfindex;
270 public final Inet6Address address;
271 public final MacAddress srcMac;
272 public final MacAddress dstMac;
273
274 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
275 MacAddress srcMac, MacAddress dstMac) {
276 this.upstreamIfindex = upstreamIfindex;
277 this.downstreamIfindex = downstreamIfIndex;
278 this.address = address;
279 this.srcMac = srcMac;
280 this.dstMac = dstMac;
281 }
282
283 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
284 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
285 dstMac);
286 }
Lorenzo Colitti0fb584b2020-04-06 09:19:57 +0000287
288 // Don't manipulate TetherOffloadRuleParcel directly because implementing onNewUpstream()
289 // would be error-prone due to generated stable AIDL classes not having a copy constructor.
290 public TetherOffloadRuleParcel toTetherOffloadRuleParcel() {
291 final TetherOffloadRuleParcel parcel = new TetherOffloadRuleParcel();
292 parcel.inputInterfaceIndex = upstreamIfindex;
293 parcel.outputInterfaceIndex = downstreamIfindex;
294 parcel.destination = address.getAddress();
295 parcel.prefixLength = 128;
296 parcel.srcL2Address = srcMac.toByteArray();
297 parcel.dstL2Address = dstMac.toByteArray();
298 return parcel;
299 }
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900300 }
301 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
302 new LinkedHashMap<>();
303
304 private final IpNeighborMonitor mIpNeighborMonitor;
305
Maciej Żenczykowski61d59a72020-05-12 19:04:39 +0000306 // TODO: Add a dependency object to pass the data members or variables from the tethering
307 // object. It helps to reduce the arguments of the constructor.
Erik Kline7a4ccc62018-08-27 17:26:47 +0900308 public IpServer(
Erik Kline7747fd42017-05-12 16:52:48 +0900309 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Nucca Chen95e0bac2020-05-12 11:34:28 +0000310 INetd netd, Callback callback, boolean usingLegacyDhcp, boolean usingBpfOffload,
311 Dependencies deps) {
Christopher Wileyd2896662016-05-19 11:54:54 -0700312 super(ifaceName, looper);
Erik Kline7747fd42017-05-12 16:52:48 +0900313 mLog = log.forSubComponent(ifaceName);
markchien92b8e7f2020-01-07 14:43:17 +0800314 mNetd = netd;
Erik Kline7a4ccc62018-08-27 17:26:47 +0900315 mCallback = callback;
Remi NGUYEN VANd1b51a32019-01-22 16:13:57 +0900316 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
Christopher Wileyd2896662016-05-19 11:54:54 -0700317 mIfaceName = ifaceName;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700318 mInterfaceType = interfaceType;
Erik Klineab6439b2017-06-06 19:24:21 +0900319 mLinkProperties = new LinkProperties();
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900320 mUsingLegacyDhcp = usingLegacyDhcp;
Nucca Chen95e0bac2020-05-12 11:34:28 +0000321 mUsingBpfOffload = usingBpfOffload;
Remi NGUYEN VANa911e842018-03-15 11:57:14 +0900322 mDeps = deps;
Erik Klinedd4d5822017-06-12 18:20:08 +0900323 resetLinkProperties();
markchien9e44cde2019-12-25 19:40:32 +0800324 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
Erik Kline7a4ccc62018-08-27 17:26:47 +0900325 mServingMode = STATE_AVAILABLE;
Christopher Wileyd2896662016-05-19 11:54:54 -0700326
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900327 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
328 new MyNeighborEventConsumer());
Nucca Chen95e0bac2020-05-12 11:34:28 +0000329
Maciej Żenczykowski61d59a72020-05-12 19:04:39 +0000330 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Nucca Chen95e0bac2020-05-12 11:34:28 +0000331 // forwarding rules per client. If BPF offload is not supported, don't start listening
Maciej Żenczykowski61d59a72020-05-12 19:04:39 +0000332 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Nucca Chen95e0bac2020-05-12 11:34:28 +0000333 // removeIpv6ForwardingRule.
Maciej Żenczykowski61d59a72020-05-12 19:04:39 +0000334 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
335 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900336 }
337
Christopher Wileyd2896662016-05-19 11:54:54 -0700338 mInitialState = new InitialState();
Erik Klineea9cc482017-03-10 19:35:34 +0900339 mLocalHotspotState = new LocalHotspotState();
Christopher Wileyd2896662016-05-19 11:54:54 -0700340 mTetheredState = new TetheredState();
Christopher Wileyd2896662016-05-19 11:54:54 -0700341 mUnavailableState = new UnavailableState();
Erik Klineea9cc482017-03-10 19:35:34 +0900342 addState(mInitialState);
Erik Klinef79a34d2017-04-13 22:54:34 +0900343 addState(mLocalHotspotState);
344 addState(mTetheredState);
Christopher Wileyd2896662016-05-19 11:54:54 -0700345 addState(mUnavailableState);
346
347 setInitialState(mInitialState);
348 }
349
markchien08cc0302019-09-09 20:50:49 +0800350 /** Interface name which IpServer served.*/
351 public String interfaceName() {
352 return mIfaceName;
353 }
Erik Kline218c2262017-06-09 16:36:29 +0900354
Erik Kline94ae4c92017-06-13 21:32:10 +0900355 /**
markchien9e44cde2019-12-25 19:40:32 +0800356 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
Erik Kline94ae4c92017-06-13 21:32:10 +0900357 */
markchien08cc0302019-09-09 20:50:49 +0800358 public int interfaceType() {
359 return mInterfaceType;
360 }
Erik Kline94ae4c92017-06-13 21:32:10 +0900361
markchien08cc0302019-09-09 20:50:49 +0800362 /** Last error from this IpServer. */
363 public int lastError() {
364 return mLastError;
365 }
366
367 /** Serving mode is the current state of IpServer state machine. */
368 public int servingMode() {
369 return mServingMode;
370 }
371
372 /** The properties of the network link which IpServer is serving. */
373 public LinkProperties linkProperties() {
374 return new LinkProperties(mLinkProperties);
375 }
376
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900377 /**
378 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
379 * thread.
380 */
381 public List<TetheredClient> getAllLeases() {
382 return Collections.unmodifiableList(mDhcpLeases);
383 }
384
markchien08cc0302019-09-09 20:50:49 +0800385 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
386 public void stop() {
387 sendMessage(CMD_INTERFACE_DOWN);
388 }
389
390 /**
391 * Tethering is canceled. IpServer state machine will be available and wait for
392 * next tethering request.
393 */
394 public void unwanted() {
395 sendMessage(CMD_TETHER_UNREQUESTED);
396 }
397
398 /** Internals. */
399
400 private boolean startIPv4() {
401 return configureIPv4(true);
402 }
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700403
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900404 /**
405 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
406 * handler.
407 *
408 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
409 * with different implementations of the callback, to differentiate handling of success/error in
410 * each call.
411 */
412 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
413 @Override
414 public void onStatusAvailable(int statusCode) {
415 getHandler().post(() -> callback(statusCode));
416 }
417
418 public abstract void callback(int statusCode);
Remi NGUYEN VAN1232fe32019-04-05 15:15:48 +0900419
420 @Override
421 public int getInterfaceVersion() {
422 return this.VERSION;
423 }
Paul Trautrime01ea252020-01-23 14:55:57 +0900424
425 @Override
426 public String getInterfaceHash() {
427 return this.HASH;
428 }
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900429 }
430
431 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
432 private final int mStartIndex;
433
434 private DhcpServerCallbacksImpl(int startIndex) {
435 mStartIndex = startIndex;
436 }
437
438 @Override
439 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
440 getHandler().post(() -> {
441 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
442 if (mStartIndex != mDhcpServerStartIndex) {
443 // This start request is obsolete. When the |server| binder token goes out of
444 // scope, the garbage collector will finalize it, which causes the network stack
445 // process garbage collector to collect the server itself.
446 return;
447 }
448
449 if (statusCode != STATUS_SUCCESS) {
450 mLog.e("Error obtaining DHCP server: " + statusCode);
451 handleError();
452 return;
453 }
454
455 mDhcpServer = server;
456 try {
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900457 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900458 @Override
459 public void callback(int startStatusCode) {
460 if (startStatusCode != STATUS_SUCCESS) {
461 mLog.e("Error starting DHCP server: " + startStatusCode);
462 handleError();
463 }
464 }
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900465 }, new DhcpLeaseCallback());
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900466 } catch (RemoteException e) {
markchien92b8e7f2020-01-07 14:43:17 +0800467 throw new IllegalStateException(e);
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900468 }
469 });
470 }
471
472 private void handleError() {
markchien9e44cde2019-12-25 19:40:32 +0800473 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900474 transitionTo(mInitialState);
475 }
476 }
477
Xiao Ma3eab4922020-04-06 11:24:48 +0000478 private class DhcpLeaseCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900479 @Override
480 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
481 final ArrayList<TetheredClient> leases = new ArrayList<>();
482 for (DhcpLeaseParcelable lease : leaseParcelables) {
483 final LinkAddress address = new LinkAddress(
Automerger Merge Worker3d330ff2020-03-16 04:06:46 +0000484 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
485 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
486 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900487
488 final MacAddress macAddress;
489 try {
490 macAddress = MacAddress.fromBytes(lease.hwAddr);
491 } catch (IllegalArgumentException e) {
492 Log.wtf(TAG, "Invalid address received from DhcpServer: "
493 + Arrays.toString(lease.hwAddr));
494 return;
495 }
496
497 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Automerger Merge Worker3d330ff2020-03-16 04:06:46 +0000498 address, lease.hostname);
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900499 leases.add(new TetheredClient(
500 macAddress,
501 Collections.singletonList(addressInfo),
502 mInterfaceType));
503 }
504
505 getHandler().post(() -> {
506 mDhcpLeases = leases;
507 mCallback.dhcpLeasesChanged();
508 });
509 }
510
511 @Override
Xiao Ma3eab4922020-04-06 11:24:48 +0000512 public void onNewPrefixRequest(IpPrefix currentPrefix) {
513 //TODO: add specific implementation.
514 }
515
516 @Override
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900517 public int getInterfaceVersion() {
518 return this.VERSION;
519 }
520
521 @Override
522 public String getInterfaceHash() throws RemoteException {
523 return this.HASH;
524 }
525 }
526
Treehugger Robot86d212b2020-03-30 04:23:55 +0000527 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900528 if (mUsingLegacyDhcp) {
529 return true;
530 }
Treehugger Robot86d212b2020-03-30 04:23:55 +0000531
532 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
533 final int prefixLen = serverLinkAddr.getPrefixLength();
534 final Inet4Address clientAddr = clientLinkAddr == null ? null :
535 (Inet4Address) clientLinkAddr.getAddress();
536
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900537 final DhcpServingParamsParcel params;
538 params = new DhcpServingParamsParcelExt()
539 .setDefaultRouters(addr)
540 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
541 .setDnsServers(addr)
Treehugger Robot86d212b2020-03-30 04:23:55 +0000542 .setServerAddr(serverLinkAddr)
543 .setMetered(true)
544 .setSingleClientAddr(clientAddr);
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900545 // TODO: also advertise link MTU
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900546
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900547 mDhcpServerStartIndex++;
548 mDeps.makeDhcpServer(
549 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900550 return true;
551 }
552
553 private void stopDhcp() {
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900554 // Make all previous start requests obsolete so servers are not started later
555 mDhcpServerStartIndex++;
556
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900557 if (mDhcpServer != null) {
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900558 try {
559 mDhcpServer.stop(new OnHandlerStatusCallback() {
560 @Override
561 public void callback(int statusCode) {
562 if (statusCode != STATUS_SUCCESS) {
563 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9e44cde2019-12-25 19:40:32 +0800564 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900565 // Not much more we can do here
566 }
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900567 mDhcpLeases.clear();
568 getHandler().post(mCallback::dhcpLeasesChanged);
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900569 }
570 });
571 mDhcpServer = null;
572 } catch (RemoteException e) {
markchien92b8e7f2020-01-07 14:43:17 +0800573 mLog.e("Error stopping DHCP", e);
574 // Not much more we can do here
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900575 }
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900576 }
577 }
578
Treehugger Robot86d212b2020-03-30 04:23:55 +0000579 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
580 final LinkAddress clientAddr) {
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900581 if (enable) {
Treehugger Robot86d212b2020-03-30 04:23:55 +0000582 return startDhcp(serverAddr, clientAddr);
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900583 } else {
584 stopDhcp();
585 return true;
586 }
587 }
588
Erik Klinef8bba5b2018-05-18 16:09:24 +0900589 private void stopIPv4() {
590 configureIPv4(false);
591 // NOTE: All of configureIPv4() will be refactored out of existence
592 // into calls to InterfaceController, shared with startIPv4().
593 mInterfaceCtrl.clearIPv4Address();
markchien92b8e7f2020-01-07 14:43:17 +0800594 mIpv4Address = null;
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000595 mStaticIpv4ServerAddr = null;
596 mStaticIpv4ClientAddr = null;
Erik Klinef8bba5b2018-05-18 16:09:24 +0900597 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900598
599 private boolean configureIPv4(boolean enabled) {
600 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
601
602 // TODO: Replace this hard-coded information with dynamically selected
603 // config passed down to us by a higher layer IP-coordinating element.
markchien92b8e7f2020-01-07 14:43:17 +0800604 final Inet4Address srvAddr;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700605 int prefixLen = 0;
markchien92b8e7f2020-01-07 14:43:17 +0800606 try {
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000607 if (mStaticIpv4ServerAddr != null) {
608 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
609 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
610 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee58527ba2019-10-17 05:02:33 +0900611 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien92b8e7f2020-01-07 14:43:17 +0800612 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
613 prefixLen = USB_PREFIX_LENGTH;
markchien9e44cde2019-12-25 19:40:32 +0800614 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien92b8e7f2020-01-07 14:43:17 +0800615 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
616 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9e44cde2019-12-25 19:40:32 +0800617 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien92b8e7f2020-01-07 14:43:17 +0800618 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
619 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VANf2f3f3e2020-01-24 22:57:09 +0900620 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
621 // TODO: randomize address for tethering too, similarly to wifi
622 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
623 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien92b8e7f2020-01-07 14:43:17 +0800624 } else {
625 // BT configures the interface elsewhere: only start DHCP.
626 // TODO: make all tethering types behave the same way, and delete the bluetooth
627 // code that calls into NetworkManagementService directly.
628 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
629 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
Treehugger Robot86d212b2020-03-30 04:23:55 +0000630 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
markchien92b8e7f2020-01-07 14:43:17 +0800631 }
632 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
633 } catch (IllegalArgumentException e) {
634 mLog.e("Error selecting ipv4 address", e);
635 if (!enabled) stopDhcp();
636 return false;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700637 }
Christopher Wileyd2896662016-05-19 11:54:54 -0700638
markchien92b8e7f2020-01-07 14:43:17 +0800639 final Boolean setIfaceUp;
Jimmy Chen151384d2019-12-03 11:37:09 +0800640 if (mInterfaceType == TetheringManager.TETHERING_WIFI
641 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien92b8e7f2020-01-07 14:43:17 +0800642 // The WiFi stack has ownership of the interface up/down state.
643 // 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 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900654
Erik Klinedd4d5822017-06-12 18:20:08 +0900655 // Directly-connected route.
markchien92b8e7f2020-01-07 14:43:17 +0800656 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
657 mIpv4Address.getPrefixLength());
markchien986750b2019-12-06 15:24:53 +0800658 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
Erik Klinedd4d5822017-06-12 18:20:08 +0900659 if (enabled) {
markchien92b8e7f2020-01-07 14:43:17 +0800660 mLinkProperties.addLinkAddress(mIpv4Address);
Erik Klinedd4d5822017-06-12 18:20:08 +0900661 mLinkProperties.addRoute(route);
662 } else {
markchien92b8e7f2020-01-07 14:43:17 +0800663 mLinkProperties.removeLinkAddress(mIpv4Address);
Erik Klinedd4d5822017-06-12 18:20:08 +0900664 mLinkProperties.removeRoute(route);
665 }
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000666
Treehugger Robot86d212b2020-03-30 04:23:55 +0000667 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
Christopher Wileyd2896662016-05-19 11:54:54 -0700668 }
669
Erik Kline0f27eed2018-05-29 19:24:43 +0900670 private String getRandomWifiIPv4Address() {
671 try {
markchien08cc0302019-09-09 20:50:49 +0800672 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
Erik Kline0f27eed2018-05-29 19:24:43 +0900673 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
674 return InetAddress.getByAddress(bytes).getHostAddress();
675 } catch (Exception e) {
676 return WIFI_HOST_IFACE_ADDR;
677 }
678 }
679
Erik Kline94ae4c92017-06-13 21:32:10 +0900680 private boolean startIPv6() {
Remi NGUYEN VANa911e842018-03-15 11:57:14 +0900681 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
Erik Kline8bd00d52017-12-08 17:47:50 +0900682 if (mInterfaceParams == null) {
683 mLog.e("Failed to find InterfaceParams");
Erik Kline94ae4c92017-06-13 21:32:10 +0900684 stopIPv6();
685 return false;
686 }
687
Remi NGUYEN VANa911e842018-03-15 11:57:14 +0900688 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
Erik Kline94ae4c92017-06-13 21:32:10 +0900689 if (!mRaDaemon.start()) {
690 stopIPv6();
691 return false;
692 }
693
694 return true;
695 }
696
697 private void stopIPv6() {
Erik Kline8bd00d52017-12-08 17:47:50 +0900698 mInterfaceParams = null;
Erik Kline94ae4c92017-06-13 21:32:10 +0900699 setRaParams(null);
700
701 if (mRaDaemon != null) {
702 mRaDaemon.stop();
703 mRaDaemon = null;
704 }
705 }
706
707 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
708 // LinkProperties. These have extraneous data filtered out and only the
709 // necessary prefixes included (per its prefix distribution policy).
710 //
711 // TODO: Evaluate using a data structure than is more directly suited to
712 // communicating only the relevant information.
713 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
714 if (mRaDaemon == null) return;
715
716 // Avoid unnecessary work on spurious updates.
717 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
718 return;
719 }
720
721 RaParams params = null;
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900722 int upstreamIfindex = 0;
Erik Kline94ae4c92017-06-13 21:32:10 +0900723
724 if (v6only != null) {
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900725 final String upstreamIface = v6only.getInterfaceName();
726
Erik Kline94ae4c92017-06-13 21:32:10 +0900727 params = new RaParams();
Nucca Chen95e0bac2020-05-12 11:34:28 +0000728 // When BPF offload is enabled, we advertise an mtu lower by 16, which is the closest
729 // multiple of 8 >= 14, the ethernet header size. This makes kernel ebpf tethering
730 // offload happy. This hack should be reverted once we have the kernel fixed up.
Maciej Żenczykowski34d43612020-02-19 01:24:39 -0800731 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
732 // see RouterAdvertisementDaemon.java putMtu()
Nucca Chen95e0bac2020-05-12 11:34:28 +0000733 params.mtu = mUsingBpfOffload ? v6only.getMtu() - 16 : v6only.getMtu();
paulhud9736de2019-03-08 16:35:20 +0800734 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
Erik Kline94ae4c92017-06-13 21:32:10 +0900735
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900736 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
Erik Kline8e492f82018-09-14 16:25:54 +0900737
Erik Kline94ae4c92017-06-13 21:32:10 +0900738 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
739 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
740
741 final IpPrefix prefix = new IpPrefix(
742 linkAddr.getAddress(), linkAddr.getPrefixLength());
743 params.prefixes.add(prefix);
744
745 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
746 if (dnsServer != null) {
747 params.dnses.add(dnsServer);
748 }
749 }
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900750
751 upstreamIfindex = mDeps.getIfindex(upstreamIface);
Erik Kline94ae4c92017-06-13 21:32:10 +0900752 }
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900753
Erik Kline94ae4c92017-06-13 21:32:10 +0900754 // 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 Colittifb19f492020-02-14 01:06:35 +0900759
760 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
761 mLastIPv6UpstreamIfindex = upstreamIfindex;
Erik Kline94ae4c92017-06-13 21:32:10 +0900762 }
763
Erik Klinedd4d5822017-06-12 18:20:08 +0900764 private void configureLocalIPv6Routes(
Erik Kline94ae4c92017-06-13 21:32:10 +0900765 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
766 // [1] Remove the routes that are deprecated.
767 if (!deprecatedPrefixes.isEmpty()) {
768 final ArrayList<RouteInfo> toBeRemoved =
769 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien92b8e7f2020-01-07 14:43:17 +0800770 // Remove routes from local network.
771 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
772 mNetd, toBeRemoved);
773 if (removalFailures > 0) {
774 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
775 removalFailures));
Erik Kline94ae4c92017-06-13 21:32:10 +0900776 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900777
778 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
Erik Kline94ae4c92017-06-13 21:32:10 +0900779 }
780
781 // [2] Add only the routes that have not previously been added.
782 if (newPrefixes != null && !newPrefixes.isEmpty()) {
783 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
784 if (mLastRaParams != null) {
785 addedPrefixes.removeAll(mLastRaParams.prefixes);
786 }
787
Erik Kline94ae4c92017-06-13 21:32:10 +0900788 if (!addedPrefixes.isEmpty()) {
789 final ArrayList<RouteInfo> toBeAdded =
790 getLocalRoutesFor(mIfaceName, addedPrefixes);
791 try {
markchien92b8e7f2020-01-07 14:43:17 +0800792 // It's safe to call networkAddInterface() even if
793 // the interface is already in the local_network.
794 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
795 try {
796 // Add routes from local network. Note that adding routes that
797 // already exist does not cause an error (EEXIST is silently ignored).
798 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
799 } catch (IllegalStateException e) {
800 mLog.e("Failed to add IPv6 routes to local table: " + e);
801 }
802 } catch (ServiceSpecificException | RemoteException e) {
803 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
Erik Kline94ae4c92017-06-13 21:32:10 +0900804 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900805
806 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
Erik Kline94ae4c92017-06-13 21:32:10 +0900807 }
808 }
809 }
810
Erik Klinedd4d5822017-06-12 18:20:08 +0900811 private void configureLocalIPv6Dns(
Erik Kline94ae4c92017-06-13 21:32:10 +0900812 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
Erik Klined3c0b5e2017-09-03 20:38:29 +0900813 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
814 if (mNetd == null) {
Erik Kline94ae4c92017-06-13 21:32:10 +0900815 if (newDnses != null) newDnses.clear();
816 mLog.e("No netd service instance available; not setting local IPv6 addresses");
817 return;
818 }
819
820 // [1] Remove deprecated local DNS IP addresses.
821 if (!deprecatedDnses.isEmpty()) {
822 for (Inet6Address dns : deprecatedDnses) {
Erik Klined3c0b5e2017-09-03 20:38:29 +0900823 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
824 mLog.e("Failed to remove local dns IP " + dns);
Erik Kline94ae4c92017-06-13 21:32:10 +0900825 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900826
827 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
Erik Kline94ae4c92017-06-13 21:32:10 +0900828 }
829 }
830
831 // [2] Add only the local DNS IP addresses that have not previously been added.
832 if (newDnses != null && !newDnses.isEmpty()) {
833 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
834 if (mLastRaParams != null) {
835 addedDnses.removeAll(mLastRaParams.dnses);
836 }
837
838 for (Inet6Address dns : addedDnses) {
Erik Klined3c0b5e2017-09-03 20:38:29 +0900839 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
840 mLog.e("Failed to add local dns IP " + dns);
Erik Kline94ae4c92017-06-13 21:32:10 +0900841 newDnses.remove(dns);
842 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900843
844 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
Erik Kline94ae4c92017-06-13 21:32:10 +0900845 }
846 }
847
848 try {
Erik Klined3c0b5e2017-09-03 20:38:29 +0900849 mNetd.tetherApplyDnsInterfaces();
Erik Kline94ae4c92017-06-13 21:32:10 +0900850 } catch (ServiceSpecificException | RemoteException e) {
851 mLog.e("Failed to update local DNS caching server");
852 if (newDnses != null) newDnses.clear();
853 }
854 }
855
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900856 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Nucca Chen95e0bac2020-05-12 11:34:28 +0000857 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
858 // offload is disabled. Add this check just in case.
859 // TODO: Perhaps remove this protection check.
860 if (!mUsingBpfOffload) return;
861
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900862 try {
Lorenzo Colitti0fb584b2020-04-06 09:19:57 +0000863 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900864 mIpv6ForwardingRules.put(rule.address, rule);
865 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000866 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900867 }
868 }
869
870 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
Nucca Chen95e0bac2020-05-12 11:34:28 +0000871 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
872 // offload is disabled. Add this check just in case.
873 // TODO: Perhaps remove this protection check.
874 if (!mUsingBpfOffload) return;
875
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900876 try {
Lorenzo Colitti0fb584b2020-04-06 09:19:57 +0000877 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900878 if (removeFromMap) {
879 mIpv6ForwardingRules.remove(rule.address);
880 }
881 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000882 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900883 }
884 }
885
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000886 private void clearIpv6ForwardingRules() {
887 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
888 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
889 }
890 mIpv6ForwardingRules.clear();
891 }
892
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900893 // Convenience method to replace a rule with the same rule on a new upstream interface.
894 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
895 // Relies on the fact that rules are in a map indexed by IP address.
896 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
897 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
898 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
899 }
900
901 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
902 // changes or if a neighbor event is received.
903 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
904 NeighborEvent e) {
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000905 // If we no longer have an upstream, clear forwarding rules and do nothing else.
906 if (upstreamIfindex == 0) {
907 clearIpv6ForwardingRules();
908 return;
909 }
910
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900911 // If the upstream interface has changed, remove all rules and re-add them with the new
912 // upstream interface.
913 if (prevUpstreamIfindex != upstreamIfindex) {
914 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
915 updateIpv6ForwardingRule(rule, upstreamIfindex);
916 }
917 }
918
919 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000920 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900921 if (e == null) return;
922 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
923 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
924 return;
925 }
926
Lorenzo Colitti8bc1e542020-04-14 09:21:19 +0000927 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
928 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
929 // add rules with a null MAC, only delete them.
930 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000931 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti8bc1e542020-04-14 09:21:19 +0000932 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900933 if (e.isValid()) {
934 addIpv6ForwardingRule(rule);
935 } else {
936 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
937 }
938 }
939
940 private void handleNeighborEvent(NeighborEvent e) {
941 if (mInterfaceParams != null
942 && mInterfaceParams.index == e.ifindex
943 && mInterfaceParams.hasMacAddress) {
944 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
945 }
946 }
947
Erik Kline8e492f82018-09-14 16:25:54 +0900948 private byte getHopLimit(String upstreamIface) {
949 try {
950 int upstreamHopLimit = Integer.parseUnsignedInt(
951 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
952 // Add one hop to account for this forwarding device
953 upstreamHopLimit++;
954 // Cap the hop limit to 255.
955 return (byte) Integer.min(upstreamHopLimit, 255);
956 } catch (Exception e) {
957 mLog.e("Failed to find upstream interface hop limit", e);
958 }
959 return RaParams.DEFAULT_HOPLIMIT;
960 }
961
Erik Kline94ae4c92017-06-13 21:32:10 +0900962 private void setRaParams(RaParams newParams) {
963 if (mRaDaemon != null) {
964 final RaParams deprecatedParams =
965 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
966
Erik Klinedd4d5822017-06-12 18:20:08 +0900967 configureLocalIPv6Routes(deprecatedParams.prefixes,
Erik Kline94ae4c92017-06-13 21:32:10 +0900968 (newParams != null) ? newParams.prefixes : null);
969
Erik Klinedd4d5822017-06-12 18:20:08 +0900970 configureLocalIPv6Dns(deprecatedParams.dnses,
Erik Kline94ae4c92017-06-13 21:32:10 +0900971 (newParams != null) ? newParams.dnses : null);
972
973 mRaDaemon.buildNewRa(deprecatedParams, newParams);
974 }
975
976 mLastRaParams = newParams;
977 }
978
Erik Klineb4df3f42017-07-06 16:40:06 +0900979 private void logMessage(State state, int what) {
980 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
Christopher Wileyd2896662016-05-19 11:54:54 -0700981 }
982
Erik Klineea9cc482017-03-10 19:35:34 +0900983 private void sendInterfaceState(int newInterfaceState) {
Erik Klineb3bb26e2017-07-06 19:49:35 +0900984 mServingMode = newInterfaceState;
Erik Kline7a4ccc62018-08-27 17:26:47 +0900985 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
Erik Klinedd4d5822017-06-12 18:20:08 +0900986 sendLinkProperties();
987 }
988
989 private void sendLinkProperties() {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900990 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
Erik Klineea9cc482017-03-10 19:35:34 +0900991 }
992
Erik Klinedd4d5822017-06-12 18:20:08 +0900993 private void resetLinkProperties() {
994 mLinkProperties.clear();
995 mLinkProperties.setInterfaceName(mIfaceName);
996 }
997
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000998 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
Treehugger Robot86d212b2020-03-30 04:23:55 +0000999 // Ignore static address configuration if they are invalid or null. In theory, static
1000 // addresses should not be invalid here because TetheringManager do not allow caller to
1001 // specify invalid static address configuration.
1002 if (request == null || request.localIPv4Address == null
1003 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1004 request.localIPv4Address, request.staticClientAddress)) {
1005 return;
1006 }
Automerger Merge Worker37a22752020-03-17 16:59:57 +00001007
1008 mStaticIpv4ServerAddr = request.localIPv4Address;
1009 mStaticIpv4ClientAddr = request.staticClientAddress;
1010 }
1011
Christopher Wileyd2896662016-05-19 11:54:54 -07001012 class InitialState extends State {
1013 @Override
1014 public void enter() {
Erik Kline7a4ccc62018-08-27 17:26:47 +09001015 sendInterfaceState(STATE_AVAILABLE);
Christopher Wileyd2896662016-05-19 11:54:54 -07001016 }
1017
1018 @Override
1019 public boolean processMessage(Message message) {
Erik Klineb4df3f42017-07-06 16:40:06 +09001020 logMessage(this, message.what);
Christopher Wileyd2896662016-05-19 11:54:54 -07001021 switch (message.what) {
1022 case CMD_TETHER_REQUESTED:
markchien9e44cde2019-12-25 19:40:32 +08001023 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
Erik Klineea9cc482017-03-10 19:35:34 +09001024 switch (message.arg1) {
Erik Kline7a4ccc62018-08-27 17:26:47 +09001025 case STATE_LOCAL_ONLY:
Automerger Merge Worker37a22752020-03-17 16:59:57 +00001026 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
Erik Klineea9cc482017-03-10 19:35:34 +09001027 transitionTo(mLocalHotspotState);
1028 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001029 case STATE_TETHERED:
Automerger Merge Worker37a22752020-03-17 16:59:57 +00001030 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
Erik Klineea9cc482017-03-10 19:35:34 +09001031 transitionTo(mTetheredState);
1032 break;
1033 default:
Erik Kline7747fd42017-05-12 16:52:48 +09001034 mLog.e("Invalid tethering interface serving state specified.");
Erik Klineea9cc482017-03-10 19:35:34 +09001035 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001036 break;
1037 case CMD_INTERFACE_DOWN:
1038 transitionTo(mUnavailableState);
1039 break;
Erik Kline1eb8c692016-07-08 17:21:26 +09001040 case CMD_IPV6_TETHER_UPDATE:
Erik Kline94ae4c92017-06-13 21:32:10 +09001041 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
Erik Kline1eb8c692016-07-08 17:21:26 +09001042 break;
Christopher Wileyd2896662016-05-19 11:54:54 -07001043 default:
Erik Klineab6439b2017-06-06 19:24:21 +09001044 return NOT_HANDLED;
Christopher Wileyd2896662016-05-19 11:54:54 -07001045 }
Erik Klineab6439b2017-06-06 19:24:21 +09001046 return HANDLED;
Christopher Wileyd2896662016-05-19 11:54:54 -07001047 }
1048 }
1049
Erik Klinef79a34d2017-04-13 22:54:34 +09001050 class BaseServingState extends State {
Christopher Wileyd2896662016-05-19 11:54:54 -07001051 @Override
1052 public void enter() {
Erik Klinedd4d5822017-06-12 18:20:08 +09001053 if (!startIPv4()) {
markchien9e44cde2019-12-25 19:40:32 +08001054 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -07001055 return;
Christopher Wileyd2896662016-05-19 11:54:54 -07001056 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001057
Christopher Wileyd2896662016-05-19 11:54:54 -07001058 try {
markchien92b8e7f2020-01-07 14:43:17 +08001059 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1060 mIpv4Address.getPrefixLength());
1061 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchiend72cf2c2020-02-15 11:35:00 +08001062 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Erik Kline7747fd42017-05-12 16:52:48 +09001063 mLog.e("Error Tethering: " + e);
markchien9e44cde2019-12-25 19:40:32 +08001064 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
Christopher Wileyd2896662016-05-19 11:54:54 -07001065 return;
1066 }
Erik Kline1eb8c692016-07-08 17:21:26 +09001067
Erik Kline94ae4c92017-06-13 21:32:10 +09001068 if (!startIPv6()) {
1069 mLog.e("Failed to startIPv6");
Erik Klinef79a34d2017-04-13 22:54:34 +09001070 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1071 return;
Erik Kline1eb8c692016-07-08 17:21:26 +09001072 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001073 }
1074
Christopher Wileye10bfc02016-05-23 16:17:30 -07001075 @Override
1076 public void exit() {
Christopher Wileye10bfc02016-05-23 16:17:30 -07001077 // Note that at this point, we're leaving the tethered state. We can fail any
1078 // of these operations, but it doesn't really change that we have to try them
1079 // all in sequence.
Erik Kline94ae4c92017-06-13 21:32:10 +09001080 stopIPv6();
Christopher Wileye10bfc02016-05-23 16:17:30 -07001081
1082 try {
markchien92b8e7f2020-01-07 14:43:17 +08001083 NetdUtils.untetherInterface(mNetd, mIfaceName);
1084 } catch (RemoteException | ServiceSpecificException e) {
markchien9e44cde2019-12-25 19:40:32 +08001085 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
Erik Kline7747fd42017-05-12 16:52:48 +09001086 mLog.e("Failed to untether interface: " + e);
Christopher Wileye10bfc02016-05-23 16:17:30 -07001087 }
1088
Erik Klinedd4d5822017-06-12 18:20:08 +09001089 stopIPv4();
1090
1091 resetLinkProperties();
Christopher Wileye10bfc02016-05-23 16:17:30 -07001092 }
1093
Erik Klineea9cc482017-03-10 19:35:34 +09001094 @Override
1095 public boolean processMessage(Message message) {
Erik Klineb4df3f42017-07-06 16:40:06 +09001096 logMessage(this, message.what);
Erik Klineea9cc482017-03-10 19:35:34 +09001097 switch (message.what) {
1098 case CMD_TETHER_UNREQUESTED:
1099 transitionTo(mInitialState);
1100 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1101 break;
1102 case CMD_INTERFACE_DOWN:
1103 transitionTo(mUnavailableState);
1104 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1105 break;
1106 case CMD_IPV6_TETHER_UPDATE:
Erik Kline94ae4c92017-06-13 21:32:10 +09001107 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
Erik Klinedd4d5822017-06-12 18:20:08 +09001108 sendLinkProperties();
Erik Klineea9cc482017-03-10 19:35:34 +09001109 break;
1110 case CMD_IP_FORWARDING_ENABLE_ERROR:
1111 case CMD_IP_FORWARDING_DISABLE_ERROR:
1112 case CMD_START_TETHERING_ERROR:
1113 case CMD_STOP_TETHERING_ERROR:
1114 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien62a625d2020-03-19 13:37:43 +08001115 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
Erik Klineea9cc482017-03-10 19:35:34 +09001116 transitionTo(mInitialState);
1117 break;
1118 default:
1119 return false;
1120 }
1121 return true;
1122 }
1123 }
1124
Erik Klinef79a34d2017-04-13 22:54:34 +09001125 // Handling errors in BaseServingState.enter() by transitioning is
1126 // problematic because transitioning during a multi-state jump yields
1127 // a Log.wtf(). Ultimately, there should be only one ServingState,
1128 // and forwarding and NAT rules should be handled by a coordinating
Erik Kline7a4ccc62018-08-27 17:26:47 +09001129 // functional element outside of IpServer.
Erik Klinef79a34d2017-04-13 22:54:34 +09001130 class LocalHotspotState extends BaseServingState {
Erik Klineea9cc482017-03-10 19:35:34 +09001131 @Override
1132 public void enter() {
Erik Klinef79a34d2017-04-13 22:54:34 +09001133 super.enter();
markchien9e44cde2019-12-25 19:40:32 +08001134 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
Erik Klinef79a34d2017-04-13 22:54:34 +09001135 transitionTo(mInitialState);
1136 }
1137
Erik Klineea9cc482017-03-10 19:35:34 +09001138 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001139 sendInterfaceState(STATE_LOCAL_ONLY);
Erik Klineea9cc482017-03-10 19:35:34 +09001140 }
1141
1142 @Override
1143 public boolean processMessage(Message message) {
Erik Klinef79a34d2017-04-13 22:54:34 +09001144 if (super.processMessage(message)) return true;
1145
Erik Klineb4df3f42017-07-06 16:40:06 +09001146 logMessage(this, message.what);
Erik Klineea9cc482017-03-10 19:35:34 +09001147 switch (message.what) {
1148 case CMD_TETHER_REQUESTED:
Erik Kline7747fd42017-05-12 16:52:48 +09001149 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
Erik Klineea9cc482017-03-10 19:35:34 +09001150 break;
1151 case CMD_TETHER_CONNECTION_CHANGED:
1152 // Ignored in local hotspot state.
1153 break;
1154 default:
1155 return false;
1156 }
1157 return true;
1158 }
1159 }
1160
Erik Klinef79a34d2017-04-13 22:54:34 +09001161 // Handling errors in BaseServingState.enter() by transitioning is
1162 // problematic because transitioning during a multi-state jump yields
1163 // a Log.wtf(). Ultimately, there should be only one ServingState,
1164 // and forwarding and NAT rules should be handled by a coordinating
Erik Kline7a4ccc62018-08-27 17:26:47 +09001165 // functional element outside of IpServer.
Erik Klinef79a34d2017-04-13 22:54:34 +09001166 class TetheredState extends BaseServingState {
Erik Klineea9cc482017-03-10 19:35:34 +09001167 @Override
1168 public void enter() {
Erik Klinef79a34d2017-04-13 22:54:34 +09001169 super.enter();
markchien9e44cde2019-12-25 19:40:32 +08001170 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
Erik Klinef79a34d2017-04-13 22:54:34 +09001171 transitionTo(mInitialState);
1172 }
1173
Erik Klineea9cc482017-03-10 19:35:34 +09001174 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001175 sendInterfaceState(STATE_TETHERED);
Erik Klineea9cc482017-03-10 19:35:34 +09001176 }
1177
1178 @Override
1179 public void exit() {
1180 cleanupUpstream();
Erik Klinef79a34d2017-04-13 22:54:34 +09001181 super.exit();
Erik Klineea9cc482017-03-10 19:35:34 +09001182 }
1183
Christopher Wileyd2896662016-05-19 11:54:54 -07001184 private void cleanupUpstream() {
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001185 if (mUpstreamIfaceSet == null) return;
Erik Kline8ea45482017-02-13 17:28:53 +09001186
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001187 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1188 mUpstreamIfaceSet = null;
Automerger Merge Worker43c671d2020-02-25 04:04:44 +00001189 clearIpv6ForwardingRules();
Erik Kline8ea45482017-02-13 17:28:53 +09001190 }
1191
1192 private void cleanupUpstreamInterface(String upstreamIface) {
1193 // Note that we don't care about errors here.
1194 // Sometimes interfaces are gone before we get
1195 // to remove their rules, which generates errors.
1196 // Just do the best we can.
1197 try {
markchien92b8e7f2020-01-07 14:43:17 +08001198 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1199 } catch (RemoteException | ServiceSpecificException e) {
1200 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
Erik Kline8ea45482017-02-13 17:28:53 +09001201 }
1202 try {
markchien92b8e7f2020-01-07 14:43:17 +08001203 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1204 } catch (RemoteException | ServiceSpecificException e) {
1205 mLog.e("Exception in disableNat: " + e.toString());
Erik Kline8ea45482017-02-13 17:28:53 +09001206 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001207 }
1208
1209 @Override
1210 public boolean processMessage(Message message) {
Erik Klinef79a34d2017-04-13 22:54:34 +09001211 if (super.processMessage(message)) return true;
1212
Erik Klineb4df3f42017-07-06 16:40:06 +09001213 logMessage(this, message.what);
Christopher Wileyd2896662016-05-19 11:54:54 -07001214 switch (message.what) {
Erik Klineea9cc482017-03-10 19:35:34 +09001215 case CMD_TETHER_REQUESTED:
Erik Kline7747fd42017-05-12 16:52:48 +09001216 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
Christopher Wileyd2896662016-05-19 11:54:54 -07001217 break;
1218 case CMD_TETHER_CONNECTION_CHANGED:
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001219 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1220 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
Christopher Wileyd2896662016-05-19 11:54:54 -07001221 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1222 break;
1223 }
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001224
1225 if (newUpstreamIfaceSet == null) {
1226 cleanupUpstream();
1227 break;
1228 }
1229
1230 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1231 cleanupUpstreamInterface(removed);
1232 }
1233
1234 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1235 // This makes the call to cleanupUpstream() in the error
1236 // path for any interface neatly cleanup all the interfaces.
1237 mUpstreamIfaceSet = newUpstreamIfaceSet;
1238
1239 for (String ifname : added) {
Christopher Wileyd2896662016-05-19 11:54:54 -07001240 try {
markchien92b8e7f2020-01-07 14:43:17 +08001241 mNetd.tetherAddForward(mIfaceName, ifname);
1242 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1243 } catch (RemoteException | ServiceSpecificException e) {
1244 mLog.e("Exception enabling NAT: " + e.toString());
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001245 cleanupUpstream();
markchien62a625d2020-03-19 13:37:43 +08001246 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
Christopher Wileyd2896662016-05-19 11:54:54 -07001247 transitionTo(mInitialState);
1248 return true;
1249 }
1250 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001251 break;
Lorenzo Colittifb19f492020-02-14 01:06:35 +09001252 case CMD_NEIGHBOR_EVENT:
1253 handleNeighborEvent((NeighborEvent) message.obj);
1254 break;
Christopher Wileyd2896662016-05-19 11:54:54 -07001255 default:
Erik Klinedd4d5822017-06-12 18:20:08 +09001256 return false;
Christopher Wileyd2896662016-05-19 11:54:54 -07001257 }
Erik Klinedd4d5822017-06-12 18:20:08 +09001258 return true;
Christopher Wileyd2896662016-05-19 11:54:54 -07001259 }
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001260
1261 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1262 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1263 if (mUpstreamIfaceSet != null && newIfaces != null) {
1264 return mUpstreamIfaceSet.equals(newIfaces);
1265 }
1266 return false;
1267 }
1268
1269 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1270 if (mUpstreamIfaceSet == null) return new HashSet<>();
1271
1272 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1273 removed.removeAll(newIfaces.ifnames);
1274 return removed;
1275 }
1276
1277 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1278 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1279 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1280 return added;
1281 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001282 }
1283
Christopher Wiley9ad83ab2016-05-20 17:51:27 -07001284 /**
1285 * This state is terminal for the per interface state machine. At this
1286 * point, the master state machine should have removed this interface
1287 * specific state machine from its list of possible recipients of
1288 * tethering requests. The state machine itself will hang around until
1289 * the garbage collector finds it.
1290 */
Christopher Wileyd2896662016-05-19 11:54:54 -07001291 class UnavailableState extends State {
1292 @Override
1293 public void enter() {
markchien9e44cde2019-12-25 19:40:32 +08001294 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001295 sendInterfaceState(STATE_UNAVAILABLE);
Christopher Wileyd2896662016-05-19 11:54:54 -07001296 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001297 }
Erik Kline94ae4c92017-06-13 21:32:10 +09001298
1299 // Accumulate routes representing "prefixes to be assigned to the local
1300 // interface", for subsequent modification of local_network routing.
1301 private static ArrayList<RouteInfo> getLocalRoutesFor(
1302 String ifname, HashSet<IpPrefix> prefixes) {
1303 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1304 for (IpPrefix ipp : prefixes) {
markchien986750b2019-12-06 15:24:53 +08001305 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
Erik Kline94ae4c92017-06-13 21:32:10 +09001306 }
1307 return localRoutes;
1308 }
1309
1310 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1311 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1312 final byte[] dnsBytes = localPrefix.getRawAddress();
Erik Kline0f27eed2018-05-29 19:24:43 +09001313 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
Erik Kline94ae4c92017-06-13 21:32:10 +09001314 try {
1315 return Inet6Address.getByAddress(null, dnsBytes, 0);
1316 } catch (UnknownHostException e) {
markchien986750b2019-12-06 15:24:53 +08001317 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
Erik Kline94ae4c92017-06-13 21:32:10 +09001318 return null;
1319 }
1320 }
1321
Erik Kline0f27eed2018-05-29 19:24:43 +09001322 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
Erik Kline94ae4c92017-06-13 21:32:10 +09001323 final byte random = (byte) (new Random()).nextInt();
Erik Kline0f27eed2018-05-29 19:24:43 +09001324 for (int value : excluded) {
1325 if (random == value) return dflt;
1326 }
1327 return random;
Erik Kline94ae4c92017-06-13 21:32:10 +09001328 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001329}