blob: 83727bcdc67e5377ec89ff4a8e39c803f83fd11c [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;
Christopher Wileyd2896662016-05-19 11:54:54 -0700230
Erik Kline7a4ccc62018-08-27 17:26:47 +0900231 private final Dependencies mDeps;
Remi NGUYEN VANa911e842018-03-15 11:57:14 +0900232
Christopher Wileyd2896662016-05-19 11:54:54 -0700233 private int mLastError;
Erik Klineb3bb26e2017-07-06 19:49:35 +0900234 private int mServingMode;
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +0900235 private InterfaceSet mUpstreamIfaceSet; // may change over time
Erik Kline8bd00d52017-12-08 17:47:50 +0900236 private InterfaceParams mInterfaceParams;
Erik Klinedd4d5822017-06-12 18:20:08 +0900237 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
238 // properties are those selected by the IPv6TetheringCoordinator and relayed
239 // to us. By comparison, mLinkProperties contains the addresses and directly
240 // connected routes that have been formed from these properties iff. we have
241 // succeeded in configuring them and are able to announce them within Router
242 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
Erik Kline94ae4c92017-06-13 21:32:10 +0900243 private LinkProperties mLastIPv6LinkProperties;
244 private RouterAdvertisementDaemon mRaDaemon;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900245
246 // To be accessed only on the handler thread
247 private int mDhcpServerStartIndex = 0;
248 private IDhcpServer mDhcpServer;
Erik Kline94ae4c92017-06-13 21:32:10 +0900249 private RaParams mLastRaParams;
markchien92b8e7f2020-01-07 14:43:17 +0800250 private LinkAddress mIpv4Address;
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000251
252 private LinkAddress mStaticIpv4ServerAddr;
253 private LinkAddress mStaticIpv4ClientAddr;
254
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900255 @NonNull
256 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
Christopher Wileyd2896662016-05-19 11:54:54 -0700257
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900258 private int mLastIPv6UpstreamIfindex = 0;
259
260 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
261 public void accept(NeighborEvent e) {
262 sendMessage(CMD_NEIGHBOR_EVENT, e);
263 }
264 }
265
266 static class Ipv6ForwardingRule {
267 public final int upstreamIfindex;
268 public final int downstreamIfindex;
269 public final Inet6Address address;
270 public final MacAddress srcMac;
271 public final MacAddress dstMac;
272
273 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
274 MacAddress srcMac, MacAddress dstMac) {
275 this.upstreamIfindex = upstreamIfindex;
276 this.downstreamIfindex = downstreamIfIndex;
277 this.address = address;
278 this.srcMac = srcMac;
279 this.dstMac = dstMac;
280 }
281
282 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
283 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
284 dstMac);
285 }
Lorenzo Colitti0fb584b2020-04-06 09:19:57 +0000286
287 // Don't manipulate TetherOffloadRuleParcel directly because implementing onNewUpstream()
288 // would be error-prone due to generated stable AIDL classes not having a copy constructor.
289 public TetherOffloadRuleParcel toTetherOffloadRuleParcel() {
290 final TetherOffloadRuleParcel parcel = new TetherOffloadRuleParcel();
291 parcel.inputInterfaceIndex = upstreamIfindex;
292 parcel.outputInterfaceIndex = downstreamIfindex;
293 parcel.destination = address.getAddress();
294 parcel.prefixLength = 128;
295 parcel.srcL2Address = srcMac.toByteArray();
296 parcel.dstL2Address = dstMac.toByteArray();
297 return parcel;
298 }
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900299 }
300 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
301 new LinkedHashMap<>();
302
303 private final IpNeighborMonitor mIpNeighborMonitor;
304
Erik Kline7a4ccc62018-08-27 17:26:47 +0900305 public IpServer(
Erik Kline7747fd42017-05-12 16:52:48 +0900306 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulaie3f41432019-12-03 14:34:13 +0800307 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
Christopher Wileyd2896662016-05-19 11:54:54 -0700308 super(ifaceName, looper);
Erik Kline7747fd42017-05-12 16:52:48 +0900309 mLog = log.forSubComponent(ifaceName);
markchien92b8e7f2020-01-07 14:43:17 +0800310 mNetd = netd;
Erik Kline7a4ccc62018-08-27 17:26:47 +0900311 mCallback = callback;
Remi NGUYEN VANd1b51a32019-01-22 16:13:57 +0900312 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
Christopher Wileyd2896662016-05-19 11:54:54 -0700313 mIfaceName = ifaceName;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700314 mInterfaceType = interfaceType;
Erik Klineab6439b2017-06-06 19:24:21 +0900315 mLinkProperties = new LinkProperties();
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900316 mUsingLegacyDhcp = usingLegacyDhcp;
Remi NGUYEN VANa911e842018-03-15 11:57:14 +0900317 mDeps = deps;
Erik Klinedd4d5822017-06-12 18:20:08 +0900318 resetLinkProperties();
markchien9e44cde2019-12-25 19:40:32 +0800319 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
Erik Kline7a4ccc62018-08-27 17:26:47 +0900320 mServingMode = STATE_AVAILABLE;
Christopher Wileyd2896662016-05-19 11:54:54 -0700321
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900322 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
323 new MyNeighborEventConsumer());
324 if (!mIpNeighborMonitor.start()) {
325 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
326 }
327
Christopher Wileyd2896662016-05-19 11:54:54 -0700328 mInitialState = new InitialState();
Erik Klineea9cc482017-03-10 19:35:34 +0900329 mLocalHotspotState = new LocalHotspotState();
Christopher Wileyd2896662016-05-19 11:54:54 -0700330 mTetheredState = new TetheredState();
Christopher Wileyd2896662016-05-19 11:54:54 -0700331 mUnavailableState = new UnavailableState();
Erik Klineea9cc482017-03-10 19:35:34 +0900332 addState(mInitialState);
Erik Klinef79a34d2017-04-13 22:54:34 +0900333 addState(mLocalHotspotState);
334 addState(mTetheredState);
Christopher Wileyd2896662016-05-19 11:54:54 -0700335 addState(mUnavailableState);
336
337 setInitialState(mInitialState);
338 }
339
markchien08cc0302019-09-09 20:50:49 +0800340 /** Interface name which IpServer served.*/
341 public String interfaceName() {
342 return mIfaceName;
343 }
Erik Kline218c2262017-06-09 16:36:29 +0900344
Erik Kline94ae4c92017-06-13 21:32:10 +0900345 /**
markchien9e44cde2019-12-25 19:40:32 +0800346 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
Erik Kline94ae4c92017-06-13 21:32:10 +0900347 */
markchien08cc0302019-09-09 20:50:49 +0800348 public int interfaceType() {
349 return mInterfaceType;
350 }
Erik Kline94ae4c92017-06-13 21:32:10 +0900351
markchien08cc0302019-09-09 20:50:49 +0800352 /** Last error from this IpServer. */
353 public int lastError() {
354 return mLastError;
355 }
356
357 /** Serving mode is the current state of IpServer state machine. */
358 public int servingMode() {
359 return mServingMode;
360 }
361
362 /** The properties of the network link which IpServer is serving. */
363 public LinkProperties linkProperties() {
364 return new LinkProperties(mLinkProperties);
365 }
366
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900367 /**
368 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
369 * thread.
370 */
371 public List<TetheredClient> getAllLeases() {
372 return Collections.unmodifiableList(mDhcpLeases);
373 }
374
markchien08cc0302019-09-09 20:50:49 +0800375 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
376 public void stop() {
377 sendMessage(CMD_INTERFACE_DOWN);
378 }
379
380 /**
381 * Tethering is canceled. IpServer state machine will be available and wait for
382 * next tethering request.
383 */
384 public void unwanted() {
385 sendMessage(CMD_TETHER_UNREQUESTED);
386 }
387
388 /** Internals. */
389
390 private boolean startIPv4() {
391 return configureIPv4(true);
392 }
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700393
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900394 /**
395 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
396 * handler.
397 *
398 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
399 * with different implementations of the callback, to differentiate handling of success/error in
400 * each call.
401 */
402 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
403 @Override
404 public void onStatusAvailable(int statusCode) {
405 getHandler().post(() -> callback(statusCode));
406 }
407
408 public abstract void callback(int statusCode);
Remi NGUYEN VAN1232fe32019-04-05 15:15:48 +0900409
410 @Override
411 public int getInterfaceVersion() {
412 return this.VERSION;
413 }
Paul Trautrime01ea252020-01-23 14:55:57 +0900414
415 @Override
416 public String getInterfaceHash() {
417 return this.HASH;
418 }
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900419 }
420
421 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
422 private final int mStartIndex;
423
424 private DhcpServerCallbacksImpl(int startIndex) {
425 mStartIndex = startIndex;
426 }
427
428 @Override
429 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
430 getHandler().post(() -> {
431 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
432 if (mStartIndex != mDhcpServerStartIndex) {
433 // This start request is obsolete. When the |server| binder token goes out of
434 // scope, the garbage collector will finalize it, which causes the network stack
435 // process garbage collector to collect the server itself.
436 return;
437 }
438
439 if (statusCode != STATUS_SUCCESS) {
440 mLog.e("Error obtaining DHCP server: " + statusCode);
441 handleError();
442 return;
443 }
444
445 mDhcpServer = server;
446 try {
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900447 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900448 @Override
449 public void callback(int startStatusCode) {
450 if (startStatusCode != STATUS_SUCCESS) {
451 mLog.e("Error starting DHCP server: " + startStatusCode);
452 handleError();
453 }
454 }
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900455 }, new DhcpLeaseCallback());
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900456 } catch (RemoteException e) {
markchien92b8e7f2020-01-07 14:43:17 +0800457 throw new IllegalStateException(e);
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900458 }
459 });
460 }
461
462 private void handleError() {
markchien9e44cde2019-12-25 19:40:32 +0800463 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900464 transitionTo(mInitialState);
465 }
466 }
467
Xiao Ma3eab4922020-04-06 11:24:48 +0000468 private class DhcpLeaseCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900469 @Override
470 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
471 final ArrayList<TetheredClient> leases = new ArrayList<>();
472 for (DhcpLeaseParcelable lease : leaseParcelables) {
473 final LinkAddress address = new LinkAddress(
Automerger Merge Worker3d330ff2020-03-16 04:06:46 +0000474 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
475 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
476 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900477
478 final MacAddress macAddress;
479 try {
480 macAddress = MacAddress.fromBytes(lease.hwAddr);
481 } catch (IllegalArgumentException e) {
482 Log.wtf(TAG, "Invalid address received from DhcpServer: "
483 + Arrays.toString(lease.hwAddr));
484 return;
485 }
486
487 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Automerger Merge Worker3d330ff2020-03-16 04:06:46 +0000488 address, lease.hostname);
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900489 leases.add(new TetheredClient(
490 macAddress,
491 Collections.singletonList(addressInfo),
492 mInterfaceType));
493 }
494
495 getHandler().post(() -> {
496 mDhcpLeases = leases;
497 mCallback.dhcpLeasesChanged();
498 });
499 }
500
501 @Override
Xiao Ma3eab4922020-04-06 11:24:48 +0000502 public void onNewPrefixRequest(IpPrefix currentPrefix) {
503 //TODO: add specific implementation.
504 }
505
506 @Override
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900507 public int getInterfaceVersion() {
508 return this.VERSION;
509 }
510
511 @Override
512 public String getInterfaceHash() throws RemoteException {
513 return this.HASH;
514 }
515 }
516
Treehugger Robot86d212b2020-03-30 04:23:55 +0000517 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900518 if (mUsingLegacyDhcp) {
519 return true;
520 }
Treehugger Robot86d212b2020-03-30 04:23:55 +0000521
522 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
523 final int prefixLen = serverLinkAddr.getPrefixLength();
524 final Inet4Address clientAddr = clientLinkAddr == null ? null :
525 (Inet4Address) clientLinkAddr.getAddress();
526
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900527 final DhcpServingParamsParcel params;
528 params = new DhcpServingParamsParcelExt()
529 .setDefaultRouters(addr)
530 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
531 .setDnsServers(addr)
Treehugger Robot86d212b2020-03-30 04:23:55 +0000532 .setServerAddr(serverLinkAddr)
533 .setMetered(true)
534 .setSingleClientAddr(clientAddr);
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900535 // TODO: also advertise link MTU
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900536
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900537 mDhcpServerStartIndex++;
538 mDeps.makeDhcpServer(
539 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900540 return true;
541 }
542
543 private void stopDhcp() {
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900544 // Make all previous start requests obsolete so servers are not started later
545 mDhcpServerStartIndex++;
546
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900547 if (mDhcpServer != null) {
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900548 try {
549 mDhcpServer.stop(new OnHandlerStatusCallback() {
550 @Override
551 public void callback(int statusCode) {
552 if (statusCode != STATUS_SUCCESS) {
553 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9e44cde2019-12-25 19:40:32 +0800554 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900555 // Not much more we can do here
556 }
Remi NGUYEN VANdb5594d2020-02-13 09:16:19 +0900557 mDhcpLeases.clear();
558 getHandler().post(mCallback::dhcpLeasesChanged);
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900559 }
560 });
561 mDhcpServer = null;
562 } catch (RemoteException e) {
markchien92b8e7f2020-01-07 14:43:17 +0800563 mLog.e("Error stopping DHCP", e);
564 // Not much more we can do here
Remi NGUYEN VAN0e3d09232018-12-04 12:13:09 +0900565 }
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900566 }
567 }
568
Treehugger Robot86d212b2020-03-30 04:23:55 +0000569 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
570 final LinkAddress clientAddr) {
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900571 if (enable) {
Treehugger Robot86d212b2020-03-30 04:23:55 +0000572 return startDhcp(serverAddr, clientAddr);
Remi NGUYEN VANe3bb5c52018-06-12 15:57:04 +0900573 } else {
574 stopDhcp();
575 return true;
576 }
577 }
578
Erik Klinef8bba5b2018-05-18 16:09:24 +0900579 private void stopIPv4() {
580 configureIPv4(false);
581 // NOTE: All of configureIPv4() will be refactored out of existence
582 // into calls to InterfaceController, shared with startIPv4().
583 mInterfaceCtrl.clearIPv4Address();
markchien92b8e7f2020-01-07 14:43:17 +0800584 mIpv4Address = null;
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000585 mStaticIpv4ServerAddr = null;
586 mStaticIpv4ClientAddr = null;
Erik Klinef8bba5b2018-05-18 16:09:24 +0900587 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900588
589 private boolean configureIPv4(boolean enabled) {
590 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
591
592 // TODO: Replace this hard-coded information with dynamically selected
593 // config passed down to us by a higher layer IP-coordinating element.
markchien92b8e7f2020-01-07 14:43:17 +0800594 final Inet4Address srvAddr;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700595 int prefixLen = 0;
markchien92b8e7f2020-01-07 14:43:17 +0800596 try {
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000597 if (mStaticIpv4ServerAddr != null) {
598 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
599 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
600 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee58527ba2019-10-17 05:02:33 +0900601 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien92b8e7f2020-01-07 14:43:17 +0800602 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
603 prefixLen = USB_PREFIX_LENGTH;
markchien9e44cde2019-12-25 19:40:32 +0800604 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien92b8e7f2020-01-07 14:43:17 +0800605 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
606 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9e44cde2019-12-25 19:40:32 +0800607 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien92b8e7f2020-01-07 14:43:17 +0800608 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
609 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VANf2f3f3e2020-01-24 22:57:09 +0900610 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
611 // TODO: randomize address for tethering too, similarly to wifi
612 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
613 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien92b8e7f2020-01-07 14:43:17 +0800614 } else {
615 // BT configures the interface elsewhere: only start DHCP.
616 // TODO: make all tethering types behave the same way, and delete the bluetooth
617 // code that calls into NetworkManagementService directly.
618 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
619 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
Treehugger Robot86d212b2020-03-30 04:23:55 +0000620 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
markchien92b8e7f2020-01-07 14:43:17 +0800621 }
622 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
623 } catch (IllegalArgumentException e) {
624 mLog.e("Error selecting ipv4 address", e);
625 if (!enabled) stopDhcp();
626 return false;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -0700627 }
Christopher Wileyd2896662016-05-19 11:54:54 -0700628
markchien92b8e7f2020-01-07 14:43:17 +0800629 final Boolean setIfaceUp;
Jimmy Chen151384d2019-12-03 11:37:09 +0800630 if (mInterfaceType == TetheringManager.TETHERING_WIFI
631 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien92b8e7f2020-01-07 14:43:17 +0800632 // The WiFi stack has ownership of the interface up/down state.
633 // It is unclear whether the Bluetooth or USB stacks will manage their own
634 // state.
635 setIfaceUp = null;
636 } else {
637 setIfaceUp = enabled;
638 }
639 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
640 mLog.e("Error configuring interface");
641 if (!enabled) stopDhcp();
642 return false;
643 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900644
Erik Klinedd4d5822017-06-12 18:20:08 +0900645 // Directly-connected route.
markchien92b8e7f2020-01-07 14:43:17 +0800646 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
647 mIpv4Address.getPrefixLength());
markchien986750b2019-12-06 15:24:53 +0800648 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
Erik Klinedd4d5822017-06-12 18:20:08 +0900649 if (enabled) {
markchien92b8e7f2020-01-07 14:43:17 +0800650 mLinkProperties.addLinkAddress(mIpv4Address);
Erik Klinedd4d5822017-06-12 18:20:08 +0900651 mLinkProperties.addRoute(route);
652 } else {
markchien92b8e7f2020-01-07 14:43:17 +0800653 mLinkProperties.removeLinkAddress(mIpv4Address);
Erik Klinedd4d5822017-06-12 18:20:08 +0900654 mLinkProperties.removeRoute(route);
655 }
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000656
Treehugger Robot86d212b2020-03-30 04:23:55 +0000657 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
Christopher Wileyd2896662016-05-19 11:54:54 -0700658 }
659
Erik Kline0f27eed2018-05-29 19:24:43 +0900660 private String getRandomWifiIPv4Address() {
661 try {
markchien08cc0302019-09-09 20:50:49 +0800662 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
Erik Kline0f27eed2018-05-29 19:24:43 +0900663 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
664 return InetAddress.getByAddress(bytes).getHostAddress();
665 } catch (Exception e) {
666 return WIFI_HOST_IFACE_ADDR;
667 }
668 }
669
Erik Kline94ae4c92017-06-13 21:32:10 +0900670 private boolean startIPv6() {
Remi NGUYEN VANa911e842018-03-15 11:57:14 +0900671 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
Erik Kline8bd00d52017-12-08 17:47:50 +0900672 if (mInterfaceParams == null) {
673 mLog.e("Failed to find InterfaceParams");
Erik Kline94ae4c92017-06-13 21:32:10 +0900674 stopIPv6();
675 return false;
676 }
677
Remi NGUYEN VANa911e842018-03-15 11:57:14 +0900678 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
Erik Kline94ae4c92017-06-13 21:32:10 +0900679 if (!mRaDaemon.start()) {
680 stopIPv6();
681 return false;
682 }
683
684 return true;
685 }
686
687 private void stopIPv6() {
Erik Kline8bd00d52017-12-08 17:47:50 +0900688 mInterfaceParams = null;
Erik Kline94ae4c92017-06-13 21:32:10 +0900689 setRaParams(null);
690
691 if (mRaDaemon != null) {
692 mRaDaemon.stop();
693 mRaDaemon = null;
694 }
695 }
696
697 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
698 // LinkProperties. These have extraneous data filtered out and only the
699 // necessary prefixes included (per its prefix distribution policy).
700 //
701 // TODO: Evaluate using a data structure than is more directly suited to
702 // communicating only the relevant information.
703 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
704 if (mRaDaemon == null) return;
705
706 // Avoid unnecessary work on spurious updates.
707 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
708 return;
709 }
710
711 RaParams params = null;
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900712 int upstreamIfindex = 0;
Erik Kline94ae4c92017-06-13 21:32:10 +0900713
714 if (v6only != null) {
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900715 final String upstreamIface = v6only.getInterfaceName();
716
Erik Kline94ae4c92017-06-13 21:32:10 +0900717 params = new RaParams();
Maciej Żenczykowski34d43612020-02-19 01:24:39 -0800718 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
719 // the ethernet header size. This makes kernel ebpf tethering offload happy.
720 // This hack should be reverted once we have the kernel fixed up.
721 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
722 // see RouterAdvertisementDaemon.java putMtu()
723 params.mtu = v6only.getMtu() - 16;
paulhud9736de2019-03-08 16:35:20 +0800724 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
Erik Kline94ae4c92017-06-13 21:32:10 +0900725
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900726 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
Erik Kline8e492f82018-09-14 16:25:54 +0900727
Erik Kline94ae4c92017-06-13 21:32:10 +0900728 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
729 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
730
731 final IpPrefix prefix = new IpPrefix(
732 linkAddr.getAddress(), linkAddr.getPrefixLength());
733 params.prefixes.add(prefix);
734
735 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
736 if (dnsServer != null) {
737 params.dnses.add(dnsServer);
738 }
739 }
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900740
741 upstreamIfindex = mDeps.getIfindex(upstreamIface);
Erik Kline94ae4c92017-06-13 21:32:10 +0900742 }
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900743
Erik Kline94ae4c92017-06-13 21:32:10 +0900744 // If v6only is null, we pass in null to setRaParams(), which handles
745 // deprecation of any existing RA data.
746
747 setRaParams(params);
748 mLastIPv6LinkProperties = v6only;
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900749
750 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
751 mLastIPv6UpstreamIfindex = upstreamIfindex;
Erik Kline94ae4c92017-06-13 21:32:10 +0900752 }
753
Erik Klinedd4d5822017-06-12 18:20:08 +0900754 private void configureLocalIPv6Routes(
Erik Kline94ae4c92017-06-13 21:32:10 +0900755 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
756 // [1] Remove the routes that are deprecated.
757 if (!deprecatedPrefixes.isEmpty()) {
758 final ArrayList<RouteInfo> toBeRemoved =
759 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien92b8e7f2020-01-07 14:43:17 +0800760 // Remove routes from local network.
761 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
762 mNetd, toBeRemoved);
763 if (removalFailures > 0) {
764 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
765 removalFailures));
Erik Kline94ae4c92017-06-13 21:32:10 +0900766 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900767
768 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
Erik Kline94ae4c92017-06-13 21:32:10 +0900769 }
770
771 // [2] Add only the routes that have not previously been added.
772 if (newPrefixes != null && !newPrefixes.isEmpty()) {
773 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
774 if (mLastRaParams != null) {
775 addedPrefixes.removeAll(mLastRaParams.prefixes);
776 }
777
Erik Kline94ae4c92017-06-13 21:32:10 +0900778 if (!addedPrefixes.isEmpty()) {
779 final ArrayList<RouteInfo> toBeAdded =
780 getLocalRoutesFor(mIfaceName, addedPrefixes);
781 try {
markchien92b8e7f2020-01-07 14:43:17 +0800782 // It's safe to call networkAddInterface() even if
783 // the interface is already in the local_network.
784 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
785 try {
786 // Add routes from local network. Note that adding routes that
787 // already exist does not cause an error (EEXIST is silently ignored).
788 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
789 } catch (IllegalStateException e) {
790 mLog.e("Failed to add IPv6 routes to local table: " + e);
791 }
792 } catch (ServiceSpecificException | RemoteException e) {
793 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
Erik Kline94ae4c92017-06-13 21:32:10 +0900794 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900795
796 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
Erik Kline94ae4c92017-06-13 21:32:10 +0900797 }
798 }
799 }
800
Erik Klinedd4d5822017-06-12 18:20:08 +0900801 private void configureLocalIPv6Dns(
Erik Kline94ae4c92017-06-13 21:32:10 +0900802 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
Erik Klined3c0b5e2017-09-03 20:38:29 +0900803 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
804 if (mNetd == null) {
Erik Kline94ae4c92017-06-13 21:32:10 +0900805 if (newDnses != null) newDnses.clear();
806 mLog.e("No netd service instance available; not setting local IPv6 addresses");
807 return;
808 }
809
810 // [1] Remove deprecated local DNS IP addresses.
811 if (!deprecatedDnses.isEmpty()) {
812 for (Inet6Address dns : deprecatedDnses) {
Erik Klined3c0b5e2017-09-03 20:38:29 +0900813 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
814 mLog.e("Failed to remove local dns IP " + dns);
Erik Kline94ae4c92017-06-13 21:32:10 +0900815 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900816
817 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
Erik Kline94ae4c92017-06-13 21:32:10 +0900818 }
819 }
820
821 // [2] Add only the local DNS IP addresses that have not previously been added.
822 if (newDnses != null && !newDnses.isEmpty()) {
823 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
824 if (mLastRaParams != null) {
825 addedDnses.removeAll(mLastRaParams.dnses);
826 }
827
828 for (Inet6Address dns : addedDnses) {
Erik Klined3c0b5e2017-09-03 20:38:29 +0900829 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
830 mLog.e("Failed to add local dns IP " + dns);
Erik Kline94ae4c92017-06-13 21:32:10 +0900831 newDnses.remove(dns);
832 }
Erik Klinedd4d5822017-06-12 18:20:08 +0900833
834 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
Erik Kline94ae4c92017-06-13 21:32:10 +0900835 }
836 }
837
838 try {
Erik Klined3c0b5e2017-09-03 20:38:29 +0900839 mNetd.tetherApplyDnsInterfaces();
Erik Kline94ae4c92017-06-13 21:32:10 +0900840 } catch (ServiceSpecificException | RemoteException e) {
841 mLog.e("Failed to update local DNS caching server");
842 if (newDnses != null) newDnses.clear();
843 }
844 }
845
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900846 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
847 try {
Lorenzo Colitti0fb584b2020-04-06 09:19:57 +0000848 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900849 mIpv6ForwardingRules.put(rule.address, rule);
850 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000851 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900852 }
853 }
854
855 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
856 try {
Lorenzo Colitti0fb584b2020-04-06 09:19:57 +0000857 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900858 if (removeFromMap) {
859 mIpv6ForwardingRules.remove(rule.address);
860 }
861 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000862 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900863 }
864 }
865
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000866 private void clearIpv6ForwardingRules() {
867 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
868 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
869 }
870 mIpv6ForwardingRules.clear();
871 }
872
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900873 // Convenience method to replace a rule with the same rule on a new upstream interface.
874 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
875 // Relies on the fact that rules are in a map indexed by IP address.
876 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
877 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
878 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
879 }
880
881 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
882 // changes or if a neighbor event is received.
883 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
884 NeighborEvent e) {
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000885 // If we no longer have an upstream, clear forwarding rules and do nothing else.
886 if (upstreamIfindex == 0) {
887 clearIpv6ForwardingRules();
888 return;
889 }
890
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900891 // If the upstream interface has changed, remove all rules and re-add them with the new
892 // upstream interface.
893 if (prevUpstreamIfindex != upstreamIfindex) {
894 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
895 updateIpv6ForwardingRule(rule, upstreamIfindex);
896 }
897 }
898
899 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000900 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900901 if (e == null) return;
902 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
903 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
904 return;
905 }
906
Lorenzo Colitti8bc1e542020-04-14 09:21:19 +0000907 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
908 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
909 // add rules with a null MAC, only delete them.
910 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Automerger Merge Worker43c671d2020-02-25 04:04:44 +0000911 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti8bc1e542020-04-14 09:21:19 +0000912 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colittifb19f492020-02-14 01:06:35 +0900913 if (e.isValid()) {
914 addIpv6ForwardingRule(rule);
915 } else {
916 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
917 }
918 }
919
920 private void handleNeighborEvent(NeighborEvent e) {
921 if (mInterfaceParams != null
922 && mInterfaceParams.index == e.ifindex
923 && mInterfaceParams.hasMacAddress) {
924 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
925 }
926 }
927
Erik Kline8e492f82018-09-14 16:25:54 +0900928 private byte getHopLimit(String upstreamIface) {
929 try {
930 int upstreamHopLimit = Integer.parseUnsignedInt(
931 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
932 // Add one hop to account for this forwarding device
933 upstreamHopLimit++;
934 // Cap the hop limit to 255.
935 return (byte) Integer.min(upstreamHopLimit, 255);
936 } catch (Exception e) {
937 mLog.e("Failed to find upstream interface hop limit", e);
938 }
939 return RaParams.DEFAULT_HOPLIMIT;
940 }
941
Erik Kline94ae4c92017-06-13 21:32:10 +0900942 private void setRaParams(RaParams newParams) {
943 if (mRaDaemon != null) {
944 final RaParams deprecatedParams =
945 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
946
Erik Klinedd4d5822017-06-12 18:20:08 +0900947 configureLocalIPv6Routes(deprecatedParams.prefixes,
Erik Kline94ae4c92017-06-13 21:32:10 +0900948 (newParams != null) ? newParams.prefixes : null);
949
Erik Klinedd4d5822017-06-12 18:20:08 +0900950 configureLocalIPv6Dns(deprecatedParams.dnses,
Erik Kline94ae4c92017-06-13 21:32:10 +0900951 (newParams != null) ? newParams.dnses : null);
952
953 mRaDaemon.buildNewRa(deprecatedParams, newParams);
954 }
955
956 mLastRaParams = newParams;
957 }
958
Erik Klineb4df3f42017-07-06 16:40:06 +0900959 private void logMessage(State state, int what) {
960 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
Christopher Wileyd2896662016-05-19 11:54:54 -0700961 }
962
Erik Klineea9cc482017-03-10 19:35:34 +0900963 private void sendInterfaceState(int newInterfaceState) {
Erik Klineb3bb26e2017-07-06 19:49:35 +0900964 mServingMode = newInterfaceState;
Erik Kline7a4ccc62018-08-27 17:26:47 +0900965 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
Erik Klinedd4d5822017-06-12 18:20:08 +0900966 sendLinkProperties();
967 }
968
969 private void sendLinkProperties() {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900970 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
Erik Klineea9cc482017-03-10 19:35:34 +0900971 }
972
Erik Klinedd4d5822017-06-12 18:20:08 +0900973 private void resetLinkProperties() {
974 mLinkProperties.clear();
975 mLinkProperties.setInterfaceName(mIfaceName);
976 }
977
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000978 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
Treehugger Robot86d212b2020-03-30 04:23:55 +0000979 // Ignore static address configuration if they are invalid or null. In theory, static
980 // addresses should not be invalid here because TetheringManager do not allow caller to
981 // specify invalid static address configuration.
982 if (request == null || request.localIPv4Address == null
983 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
984 request.localIPv4Address, request.staticClientAddress)) {
985 return;
986 }
Automerger Merge Worker37a22752020-03-17 16:59:57 +0000987
988 mStaticIpv4ServerAddr = request.localIPv4Address;
989 mStaticIpv4ClientAddr = request.staticClientAddress;
990 }
991
Christopher Wileyd2896662016-05-19 11:54:54 -0700992 class InitialState extends State {
993 @Override
994 public void enter() {
Erik Kline7a4ccc62018-08-27 17:26:47 +0900995 sendInterfaceState(STATE_AVAILABLE);
Christopher Wileyd2896662016-05-19 11:54:54 -0700996 }
997
998 @Override
999 public boolean processMessage(Message message) {
Erik Klineb4df3f42017-07-06 16:40:06 +09001000 logMessage(this, message.what);
Christopher Wileyd2896662016-05-19 11:54:54 -07001001 switch (message.what) {
1002 case CMD_TETHER_REQUESTED:
markchien9e44cde2019-12-25 19:40:32 +08001003 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
Erik Klineea9cc482017-03-10 19:35:34 +09001004 switch (message.arg1) {
Erik Kline7a4ccc62018-08-27 17:26:47 +09001005 case STATE_LOCAL_ONLY:
Automerger Merge Worker37a22752020-03-17 16:59:57 +00001006 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
Erik Klineea9cc482017-03-10 19:35:34 +09001007 transitionTo(mLocalHotspotState);
1008 break;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001009 case STATE_TETHERED:
Automerger Merge Worker37a22752020-03-17 16:59:57 +00001010 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
Erik Klineea9cc482017-03-10 19:35:34 +09001011 transitionTo(mTetheredState);
1012 break;
1013 default:
Erik Kline7747fd42017-05-12 16:52:48 +09001014 mLog.e("Invalid tethering interface serving state specified.");
Erik Klineea9cc482017-03-10 19:35:34 +09001015 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001016 break;
1017 case CMD_INTERFACE_DOWN:
1018 transitionTo(mUnavailableState);
1019 break;
Erik Kline1eb8c692016-07-08 17:21:26 +09001020 case CMD_IPV6_TETHER_UPDATE:
Erik Kline94ae4c92017-06-13 21:32:10 +09001021 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
Erik Kline1eb8c692016-07-08 17:21:26 +09001022 break;
Christopher Wileyd2896662016-05-19 11:54:54 -07001023 default:
Erik Klineab6439b2017-06-06 19:24:21 +09001024 return NOT_HANDLED;
Christopher Wileyd2896662016-05-19 11:54:54 -07001025 }
Erik Klineab6439b2017-06-06 19:24:21 +09001026 return HANDLED;
Christopher Wileyd2896662016-05-19 11:54:54 -07001027 }
1028 }
1029
Erik Klinef79a34d2017-04-13 22:54:34 +09001030 class BaseServingState extends State {
Christopher Wileyd2896662016-05-19 11:54:54 -07001031 @Override
1032 public void enter() {
Erik Klinedd4d5822017-06-12 18:20:08 +09001033 if (!startIPv4()) {
markchien9e44cde2019-12-25 19:40:32 +08001034 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
Christopher Wiley5c0b10a2016-05-31 14:43:08 -07001035 return;
Christopher Wileyd2896662016-05-19 11:54:54 -07001036 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001037
Christopher Wileyd2896662016-05-19 11:54:54 -07001038 try {
markchien92b8e7f2020-01-07 14:43:17 +08001039 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1040 mIpv4Address.getPrefixLength());
1041 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchiend72cf2c2020-02-15 11:35:00 +08001042 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Erik Kline7747fd42017-05-12 16:52:48 +09001043 mLog.e("Error Tethering: " + e);
markchien9e44cde2019-12-25 19:40:32 +08001044 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
Christopher Wileyd2896662016-05-19 11:54:54 -07001045 return;
1046 }
Erik Kline1eb8c692016-07-08 17:21:26 +09001047
Erik Kline94ae4c92017-06-13 21:32:10 +09001048 if (!startIPv6()) {
1049 mLog.e("Failed to startIPv6");
Erik Klinef79a34d2017-04-13 22:54:34 +09001050 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1051 return;
Erik Kline1eb8c692016-07-08 17:21:26 +09001052 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001053 }
1054
Christopher Wileye10bfc02016-05-23 16:17:30 -07001055 @Override
1056 public void exit() {
Christopher Wileye10bfc02016-05-23 16:17:30 -07001057 // Note that at this point, we're leaving the tethered state. We can fail any
1058 // of these operations, but it doesn't really change that we have to try them
1059 // all in sequence.
Erik Kline94ae4c92017-06-13 21:32:10 +09001060 stopIPv6();
Christopher Wileye10bfc02016-05-23 16:17:30 -07001061
1062 try {
markchien92b8e7f2020-01-07 14:43:17 +08001063 NetdUtils.untetherInterface(mNetd, mIfaceName);
1064 } catch (RemoteException | ServiceSpecificException e) {
markchien9e44cde2019-12-25 19:40:32 +08001065 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
Erik Kline7747fd42017-05-12 16:52:48 +09001066 mLog.e("Failed to untether interface: " + e);
Christopher Wileye10bfc02016-05-23 16:17:30 -07001067 }
1068
Erik Klinedd4d5822017-06-12 18:20:08 +09001069 stopIPv4();
1070
1071 resetLinkProperties();
Christopher Wileye10bfc02016-05-23 16:17:30 -07001072 }
1073
Erik Klineea9cc482017-03-10 19:35:34 +09001074 @Override
1075 public boolean processMessage(Message message) {
Erik Klineb4df3f42017-07-06 16:40:06 +09001076 logMessage(this, message.what);
Erik Klineea9cc482017-03-10 19:35:34 +09001077 switch (message.what) {
1078 case CMD_TETHER_UNREQUESTED:
1079 transitionTo(mInitialState);
1080 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1081 break;
1082 case CMD_INTERFACE_DOWN:
1083 transitionTo(mUnavailableState);
1084 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1085 break;
1086 case CMD_IPV6_TETHER_UPDATE:
Erik Kline94ae4c92017-06-13 21:32:10 +09001087 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
Erik Klinedd4d5822017-06-12 18:20:08 +09001088 sendLinkProperties();
Erik Klineea9cc482017-03-10 19:35:34 +09001089 break;
1090 case CMD_IP_FORWARDING_ENABLE_ERROR:
1091 case CMD_IP_FORWARDING_DISABLE_ERROR:
1092 case CMD_START_TETHERING_ERROR:
1093 case CMD_STOP_TETHERING_ERROR:
1094 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien62a625d2020-03-19 13:37:43 +08001095 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
Erik Klineea9cc482017-03-10 19:35:34 +09001096 transitionTo(mInitialState);
1097 break;
1098 default:
1099 return false;
1100 }
1101 return true;
1102 }
1103 }
1104
Erik Klinef79a34d2017-04-13 22:54:34 +09001105 // Handling errors in BaseServingState.enter() by transitioning is
1106 // problematic because transitioning during a multi-state jump yields
1107 // a Log.wtf(). Ultimately, there should be only one ServingState,
1108 // and forwarding and NAT rules should be handled by a coordinating
Erik Kline7a4ccc62018-08-27 17:26:47 +09001109 // functional element outside of IpServer.
Erik Klinef79a34d2017-04-13 22:54:34 +09001110 class LocalHotspotState extends BaseServingState {
Erik Klineea9cc482017-03-10 19:35:34 +09001111 @Override
1112 public void enter() {
Erik Klinef79a34d2017-04-13 22:54:34 +09001113 super.enter();
markchien9e44cde2019-12-25 19:40:32 +08001114 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
Erik Klinef79a34d2017-04-13 22:54:34 +09001115 transitionTo(mInitialState);
1116 }
1117
Erik Klineea9cc482017-03-10 19:35:34 +09001118 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001119 sendInterfaceState(STATE_LOCAL_ONLY);
Erik Klineea9cc482017-03-10 19:35:34 +09001120 }
1121
1122 @Override
1123 public boolean processMessage(Message message) {
Erik Klinef79a34d2017-04-13 22:54:34 +09001124 if (super.processMessage(message)) return true;
1125
Erik Klineb4df3f42017-07-06 16:40:06 +09001126 logMessage(this, message.what);
Erik Klineea9cc482017-03-10 19:35:34 +09001127 switch (message.what) {
1128 case CMD_TETHER_REQUESTED:
Erik Kline7747fd42017-05-12 16:52:48 +09001129 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
Erik Klineea9cc482017-03-10 19:35:34 +09001130 break;
1131 case CMD_TETHER_CONNECTION_CHANGED:
1132 // Ignored in local hotspot state.
1133 break;
1134 default:
1135 return false;
1136 }
1137 return true;
1138 }
1139 }
1140
Erik Klinef79a34d2017-04-13 22:54:34 +09001141 // Handling errors in BaseServingState.enter() by transitioning is
1142 // problematic because transitioning during a multi-state jump yields
1143 // a Log.wtf(). Ultimately, there should be only one ServingState,
1144 // and forwarding and NAT rules should be handled by a coordinating
Erik Kline7a4ccc62018-08-27 17:26:47 +09001145 // functional element outside of IpServer.
Erik Klinef79a34d2017-04-13 22:54:34 +09001146 class TetheredState extends BaseServingState {
Erik Klineea9cc482017-03-10 19:35:34 +09001147 @Override
1148 public void enter() {
Erik Klinef79a34d2017-04-13 22:54:34 +09001149 super.enter();
markchien9e44cde2019-12-25 19:40:32 +08001150 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
Erik Klinef79a34d2017-04-13 22:54:34 +09001151 transitionTo(mInitialState);
1152 }
1153
Erik Klineea9cc482017-03-10 19:35:34 +09001154 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
Erik Kline7a4ccc62018-08-27 17:26:47 +09001155 sendInterfaceState(STATE_TETHERED);
Erik Klineea9cc482017-03-10 19:35:34 +09001156 }
1157
1158 @Override
1159 public void exit() {
1160 cleanupUpstream();
Erik Klinef79a34d2017-04-13 22:54:34 +09001161 super.exit();
Erik Klineea9cc482017-03-10 19:35:34 +09001162 }
1163
Christopher Wileyd2896662016-05-19 11:54:54 -07001164 private void cleanupUpstream() {
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001165 if (mUpstreamIfaceSet == null) return;
Erik Kline8ea45482017-02-13 17:28:53 +09001166
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001167 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1168 mUpstreamIfaceSet = null;
Automerger Merge Worker43c671d2020-02-25 04:04:44 +00001169 clearIpv6ForwardingRules();
Erik Kline8ea45482017-02-13 17:28:53 +09001170 }
1171
1172 private void cleanupUpstreamInterface(String upstreamIface) {
1173 // Note that we don't care about errors here.
1174 // Sometimes interfaces are gone before we get
1175 // to remove their rules, which generates errors.
1176 // Just do the best we can.
1177 try {
markchien92b8e7f2020-01-07 14:43:17 +08001178 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1179 } catch (RemoteException | ServiceSpecificException e) {
1180 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
Erik Kline8ea45482017-02-13 17:28:53 +09001181 }
1182 try {
markchien92b8e7f2020-01-07 14:43:17 +08001183 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1184 } catch (RemoteException | ServiceSpecificException e) {
1185 mLog.e("Exception in disableNat: " + e.toString());
Erik Kline8ea45482017-02-13 17:28:53 +09001186 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001187 }
1188
1189 @Override
1190 public boolean processMessage(Message message) {
Erik Klinef79a34d2017-04-13 22:54:34 +09001191 if (super.processMessage(message)) return true;
1192
Erik Klineb4df3f42017-07-06 16:40:06 +09001193 logMessage(this, message.what);
Christopher Wileyd2896662016-05-19 11:54:54 -07001194 switch (message.what) {
Erik Klineea9cc482017-03-10 19:35:34 +09001195 case CMD_TETHER_REQUESTED:
Erik Kline7747fd42017-05-12 16:52:48 +09001196 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
Christopher Wileyd2896662016-05-19 11:54:54 -07001197 break;
1198 case CMD_TETHER_CONNECTION_CHANGED:
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001199 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1200 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
Christopher Wileyd2896662016-05-19 11:54:54 -07001201 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1202 break;
1203 }
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001204
1205 if (newUpstreamIfaceSet == null) {
1206 cleanupUpstream();
1207 break;
1208 }
1209
1210 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1211 cleanupUpstreamInterface(removed);
1212 }
1213
1214 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1215 // This makes the call to cleanupUpstream() in the error
1216 // path for any interface neatly cleanup all the interfaces.
1217 mUpstreamIfaceSet = newUpstreamIfaceSet;
1218
1219 for (String ifname : added) {
Christopher Wileyd2896662016-05-19 11:54:54 -07001220 try {
markchien92b8e7f2020-01-07 14:43:17 +08001221 mNetd.tetherAddForward(mIfaceName, ifname);
1222 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1223 } catch (RemoteException | ServiceSpecificException e) {
1224 mLog.e("Exception enabling NAT: " + e.toString());
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001225 cleanupUpstream();
markchien62a625d2020-03-19 13:37:43 +08001226 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
Christopher Wileyd2896662016-05-19 11:54:54 -07001227 transitionTo(mInitialState);
1228 return true;
1229 }
1230 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001231 break;
Lorenzo Colittifb19f492020-02-14 01:06:35 +09001232 case CMD_NEIGHBOR_EVENT:
1233 handleNeighborEvent((NeighborEvent) message.obj);
1234 break;
Christopher Wileyd2896662016-05-19 11:54:54 -07001235 default:
Erik Klinedd4d5822017-06-12 18:20:08 +09001236 return false;
Christopher Wileyd2896662016-05-19 11:54:54 -07001237 }
Erik Klinedd4d5822017-06-12 18:20:08 +09001238 return true;
Christopher Wileyd2896662016-05-19 11:54:54 -07001239 }
Remi NGUYEN VAN25a7e4f2018-03-09 14:07:18 +09001240
1241 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1242 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1243 if (mUpstreamIfaceSet != null && newIfaces != null) {
1244 return mUpstreamIfaceSet.equals(newIfaces);
1245 }
1246 return false;
1247 }
1248
1249 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1250 if (mUpstreamIfaceSet == null) return new HashSet<>();
1251
1252 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1253 removed.removeAll(newIfaces.ifnames);
1254 return removed;
1255 }
1256
1257 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1258 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1259 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1260 return added;
1261 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001262 }
1263
Christopher Wiley9ad83ab2016-05-20 17:51:27 -07001264 /**
1265 * This state is terminal for the per interface state machine. At this
1266 * point, the master state machine should have removed this interface
1267 * specific state machine from its list of possible recipients of
1268 * tethering requests. The state machine itself will hang around until
1269 * the garbage collector finds it.
1270 */
Christopher Wileyd2896662016-05-19 11:54:54 -07001271 class UnavailableState extends State {
1272 @Override
1273 public void enter() {
markchien9e44cde2019-12-25 19:40:32 +08001274 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
Erik Kline7a4ccc62018-08-27 17:26:47 +09001275 sendInterfaceState(STATE_UNAVAILABLE);
Christopher Wileyd2896662016-05-19 11:54:54 -07001276 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001277 }
Erik Kline94ae4c92017-06-13 21:32:10 +09001278
1279 // Accumulate routes representing "prefixes to be assigned to the local
1280 // interface", for subsequent modification of local_network routing.
1281 private static ArrayList<RouteInfo> getLocalRoutesFor(
1282 String ifname, HashSet<IpPrefix> prefixes) {
1283 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1284 for (IpPrefix ipp : prefixes) {
markchien986750b2019-12-06 15:24:53 +08001285 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
Erik Kline94ae4c92017-06-13 21:32:10 +09001286 }
1287 return localRoutes;
1288 }
1289
1290 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1291 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1292 final byte[] dnsBytes = localPrefix.getRawAddress();
Erik Kline0f27eed2018-05-29 19:24:43 +09001293 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
Erik Kline94ae4c92017-06-13 21:32:10 +09001294 try {
1295 return Inet6Address.getByAddress(null, dnsBytes, 0);
1296 } catch (UnknownHostException e) {
markchien986750b2019-12-06 15:24:53 +08001297 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
Erik Kline94ae4c92017-06-13 21:32:10 +09001298 return null;
1299 }
1300 }
1301
Erik Kline0f27eed2018-05-29 19:24:43 +09001302 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
Erik Kline94ae4c92017-06-13 21:32:10 +09001303 final byte random = (byte) (new Random()).nextInt();
Erik Kline0f27eed2018-05-29 19:24:43 +09001304 for (int value : excluded) {
1305 if (random == value) return dflt;
1306 }
1307 return random;
Erik Kline94ae4c92017-06-13 21:32:10 +09001308 }
Christopher Wileyd2896662016-05-19 11:54:54 -07001309}