blob: f08429bb06969ec9f0512ac2827b652bc92f5b13 [file] [log] [blame]
markchien74a4fa92019-09-09 20:50:49 +08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net.ip;
18
markchien6cf0e552019-12-06 15:24:53 +080019import static android.net.RouteInfo.RTN_UNICAST;
Treehugger Robot5da10702020-03-30 04:23:55 +000020import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080021import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090022import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH;
markchien74a4fa92019-09-09 20:50:49 +080023import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
24import static android.net.util.NetworkConstants.asByte;
Mark Chien2ecd3332020-05-29 22:07:37 +000025import static android.net.util.PrefixUtils.asIpPrefix;
markchien6cf0e552019-12-06 15:24:53 +080026import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Automerger Merge Worker0010ca02020-03-16 04:06:46 +000027import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080028
markchien74a4fa92019-09-09 20:50:49 +080029import android.net.INetd;
30import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080031import android.net.IpPrefix;
32import android.net.LinkAddress;
33import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090034import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080035import android.net.RouteInfo;
Lorenzo Colittie6107d22020-04-06 09:19:57 +000036import android.net.TetherOffloadRuleParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090037import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080038import android.net.TetheringManager;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +000039import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090040import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080041import android.net.dhcp.DhcpServerCallbacks;
42import android.net.dhcp.DhcpServingParamsParcel;
43import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma06c8ba02020-04-06 11:24:48 +000044import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080045import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090046import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080047import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080048import android.net.shared.NetdUtils;
49import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080050import android.net.util.InterfaceParams;
51import android.net.util.InterfaceSet;
Xiao Ma65401342020-05-14 06:52:59 +000052import android.net.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080053import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090054import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080055import android.os.Looper;
56import android.os.Message;
57import android.os.RemoteException;
58import android.os.ServiceSpecificException;
59import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080060import android.util.SparseArray;
61
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090062import androidx.annotation.NonNull;
Xiao Ma65401342020-05-14 06:52:59 +000063import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090064
markchien74a4fa92019-09-09 20:50:49 +080065import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080066import com.android.internal.util.State;
67import com.android.internal.util.StateMachine;
Mark Chien2ecd3332020-05-29 22:07:37 +000068import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +080069
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090070import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080071import java.net.Inet4Address;
72import java.net.Inet6Address;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090073import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080074import java.net.UnknownHostException;
75import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090076import java.util.Arrays;
77import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080078import java.util.HashSet;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090079import java.util.LinkedHashMap;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090080import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080081import java.util.Objects;
82import java.util.Random;
83import java.util.Set;
84
85/**
86 * Provides the interface to IP-layer serving functionality for a given network
87 * interface, e.g. for tethering or "local-only hotspot" mode.
88 *
89 * @hide
90 */
91public class IpServer extends StateMachine {
92 public static final int STATE_UNAVAILABLE = 0;
93 public static final int STATE_AVAILABLE = 1;
94 public static final int STATE_TETHERED = 2;
95 public static final int STATE_LOCAL_ONLY = 3;
96
97 /** Get string name of |state|.*/
98 public static String getStateString(int state) {
99 switch (state) {
100 case STATE_UNAVAILABLE: return "UNAVAILABLE";
101 case STATE_AVAILABLE: return "AVAILABLE";
102 case STATE_TETHERED: return "TETHERED";
103 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
104 }
105 return "UNKNOWN: " + state;
106 }
107
108 private static final byte DOUG_ADAMS = (byte) 42;
109
markchien74a4fa92019-09-09 20:50:49 +0800110 // TODO: have PanService use some visible version of this constant
Mark Chien2ecd3332020-05-29 22:07:37 +0000111 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800112
113 // TODO: have this configurable
114 private static final int DHCP_LEASE_TIME_SECS = 3600;
115
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000116 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
117
markchien74a4fa92019-09-09 20:50:49 +0800118 private static final String TAG = "IpServer";
119 private static final boolean DBG = false;
120 private static final boolean VDBG = false;
121 private static final Class[] sMessageClasses = {
122 IpServer.class
123 };
124 private static final SparseArray<String> sMagicDecoderRing =
125 MessageUtils.findMessageNames(sMessageClasses);
126
127 /** IpServer callback. */
128 public static class Callback {
129 /**
130 * Notify that |who| has changed its tethering state.
131 *
132 * @param who the calling instance of IpServer
133 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800134 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800135 */
markchien9d353822019-12-16 20:15:20 +0800136 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800137
138 /**
139 * Notify that |who| has new LinkProperties.
140 *
141 * @param who the calling instance of IpServer
142 * @param newLp the new LinkProperties to report
143 */
markchien9d353822019-12-16 20:15:20 +0800144 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900145
146 /**
147 * Notify that the DHCP leases changed in one of the IpServers.
148 */
149 public void dhcpLeasesChanged() { }
Mark Chien2ecd3332020-05-29 22:07:37 +0000150
151 /**
152 * Request Tethering change.
153 *
154 * @param tetheringType the downstream type of this IpServer.
155 * @param enabled enable or disable tethering.
156 */
157 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800158 }
159
160 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800161 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900162 /** Create an IpNeighborMonitor to be used by this IpServer */
163 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
164 IpNeighborMonitor.NeighborEventConsumer consumer) {
165 return new IpNeighborMonitor(handler, log, consumer);
166 }
167
markchien74a4fa92019-09-09 20:50:49 +0800168 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
169 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
170 return new RouterAdvertisementDaemon(ifParams);
171 }
172
173 /** Get |ifName|'s interface information.*/
174 public InterfaceParams getInterfaceParams(String ifName) {
175 return InterfaceParams.getByName(ifName);
176 }
177
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900178 /** Get |ifName|'s interface index. */
179 public int getIfindex(String ifName) {
180 try {
181 return NetworkInterface.getByName(ifName).getIndex();
182 } catch (IOException | NullPointerException e) {
183 Log.e(TAG, "Can't determine interface index for interface " + ifName);
184 return 0;
185 }
186 }
Mark Chien2ecd3332020-05-29 22:07:37 +0000187
markchien9d353822019-12-16 20:15:20 +0800188 /** Create a DhcpServer instance to be used by IpServer. */
189 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
190 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800191 }
192
markchien74a4fa92019-09-09 20:50:49 +0800193 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800194 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800195 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800196 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800197 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800198 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800199 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800200 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800201 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800202 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800203 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800204 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800205 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800206 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800207 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800209 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800211 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900213 // new neighbor cache entry on our interface
214 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma65401342020-05-14 06:52:59 +0000215 // request from DHCP server that it wants to have a new prefix
216 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
Mark Chien2ecd3332020-05-29 22:07:37 +0000217 // request from PrivateAddressCoordinator to restart tethering.
218 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800219
220 private final State mInitialState;
221 private final State mLocalHotspotState;
222 private final State mTetheredState;
223 private final State mUnavailableState;
Mark Chien2ecd3332020-05-29 22:07:37 +0000224 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800225
226 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800227 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800228 private final Callback mCallback;
229 private final InterfaceController mInterfaceCtrl;
Mark Chien2ecd3332020-05-29 22:07:37 +0000230 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800231
232 private final String mIfaceName;
233 private final int mInterfaceType;
234 private final LinkProperties mLinkProperties;
235 private final boolean mUsingLegacyDhcp;
Nucca Chen0bbfe122020-05-12 11:34:28 +0000236 private final boolean mUsingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800237
238 private final Dependencies mDeps;
239
240 private int mLastError;
241 private int mServingMode;
242 private InterfaceSet mUpstreamIfaceSet; // may change over time
243 private InterfaceParams mInterfaceParams;
244 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
245 // properties are those selected by the IPv6TetheringCoordinator and relayed
246 // to us. By comparison, mLinkProperties contains the addresses and directly
247 // connected routes that have been formed from these properties iff. we have
248 // succeeded in configuring them and are able to announce them within Router
249 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
250 private LinkProperties mLastIPv6LinkProperties;
251 private RouterAdvertisementDaemon mRaDaemon;
252
253 // To be accessed only on the handler thread
254 private int mDhcpServerStartIndex = 0;
255 private IDhcpServer mDhcpServer;
256 private RaParams mLastRaParams;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000257
258 private LinkAddress mStaticIpv4ServerAddr;
259 private LinkAddress mStaticIpv4ClientAddr;
260
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900261 @NonNull
262 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800263
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900264 private int mLastIPv6UpstreamIfindex = 0;
265
266 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
267 public void accept(NeighborEvent e) {
268 sendMessage(CMD_NEIGHBOR_EVENT, e);
269 }
270 }
271
272 static class Ipv6ForwardingRule {
273 public final int upstreamIfindex;
274 public final int downstreamIfindex;
275 public final Inet6Address address;
276 public final MacAddress srcMac;
277 public final MacAddress dstMac;
278
279 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
280 MacAddress srcMac, MacAddress dstMac) {
281 this.upstreamIfindex = upstreamIfindex;
282 this.downstreamIfindex = downstreamIfIndex;
283 this.address = address;
284 this.srcMac = srcMac;
285 this.dstMac = dstMac;
286 }
287
288 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
289 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
290 dstMac);
291 }
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000292
293 // Don't manipulate TetherOffloadRuleParcel directly because implementing onNewUpstream()
294 // would be error-prone due to generated stable AIDL classes not having a copy constructor.
295 public TetherOffloadRuleParcel toTetherOffloadRuleParcel() {
296 final TetherOffloadRuleParcel parcel = new TetherOffloadRuleParcel();
297 parcel.inputInterfaceIndex = upstreamIfindex;
298 parcel.outputInterfaceIndex = downstreamIfindex;
299 parcel.destination = address.getAddress();
300 parcel.prefixLength = 128;
301 parcel.srcL2Address = srcMac.toByteArray();
302 parcel.dstL2Address = dstMac.toByteArray();
303 return parcel;
304 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900305 }
306 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
307 new LinkedHashMap<>();
308
309 private final IpNeighborMonitor mIpNeighborMonitor;
310
Mark Chien2ecd3332020-05-29 22:07:37 +0000311 private LinkAddress mIpv4Address;
312
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000313 // TODO: Add a dependency object to pass the data members or variables from the tethering
314 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800315 public IpServer(
316 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Nucca Chen0bbfe122020-05-12 11:34:28 +0000317 INetd netd, Callback callback, boolean usingLegacyDhcp, boolean usingBpfOffload,
Mark Chien2ecd3332020-05-29 22:07:37 +0000318 PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800319 super(ifaceName, looper);
320 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800321 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800322 mCallback = callback;
323 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
324 mIfaceName = ifaceName;
325 mInterfaceType = interfaceType;
326 mLinkProperties = new LinkProperties();
327 mUsingLegacyDhcp = usingLegacyDhcp;
Nucca Chen0bbfe122020-05-12 11:34:28 +0000328 mUsingBpfOffload = usingBpfOffload;
Mark Chien2ecd3332020-05-29 22:07:37 +0000329 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800330 mDeps = deps;
331 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800332 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800333 mServingMode = STATE_AVAILABLE;
334
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900335 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
336 new MyNeighborEventConsumer());
Nucca Chen0bbfe122020-05-12 11:34:28 +0000337
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000338 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Nucca Chen0bbfe122020-05-12 11:34:28 +0000339 // forwarding rules per client. If BPF offload is not supported, don't start listening
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000340 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Nucca Chen0bbfe122020-05-12 11:34:28 +0000341 // removeIpv6ForwardingRule.
Maciej Żenczykowskifd8b4bb2020-05-12 19:04:39 +0000342 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
343 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900344 }
345
markchien74a4fa92019-09-09 20:50:49 +0800346 mInitialState = new InitialState();
347 mLocalHotspotState = new LocalHotspotState();
348 mTetheredState = new TetheredState();
349 mUnavailableState = new UnavailableState();
Mark Chien2ecd3332020-05-29 22:07:37 +0000350 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800351 addState(mInitialState);
352 addState(mLocalHotspotState);
353 addState(mTetheredState);
Mark Chien2ecd3332020-05-29 22:07:37 +0000354 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800355 addState(mUnavailableState);
356
357 setInitialState(mInitialState);
358 }
359
360 /** Interface name which IpServer served.*/
361 public String interfaceName() {
362 return mIfaceName;
363 }
364
365 /**
markchien9b4d7572019-12-25 19:40:32 +0800366 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800367 */
368 public int interfaceType() {
369 return mInterfaceType;
370 }
371
372 /** Last error from this IpServer. */
373 public int lastError() {
374 return mLastError;
375 }
376
377 /** Serving mode is the current state of IpServer state machine. */
378 public int servingMode() {
379 return mServingMode;
380 }
381
382 /** The properties of the network link which IpServer is serving. */
383 public LinkProperties linkProperties() {
384 return new LinkProperties(mLinkProperties);
385 }
386
Mark Chien2ecd3332020-05-29 22:07:37 +0000387 /** The address which IpServer is using. */
388 public LinkAddress getAddress() {
389 return mIpv4Address;
390 }
391
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900392 /**
393 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
394 * thread.
395 */
396 public List<TetheredClient> getAllLeases() {
397 return Collections.unmodifiableList(mDhcpLeases);
398 }
399
markchien74a4fa92019-09-09 20:50:49 +0800400 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
401 public void stop() {
402 sendMessage(CMD_INTERFACE_DOWN);
403 }
404
405 /**
406 * Tethering is canceled. IpServer state machine will be available and wait for
407 * next tethering request.
408 */
409 public void unwanted() {
410 sendMessage(CMD_TETHER_UNREQUESTED);
411 }
412
413 /** Internals. */
414
415 private boolean startIPv4() {
416 return configureIPv4(true);
417 }
418
419 /**
420 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
421 * handler.
422 *
423 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
424 * with different implementations of the callback, to differentiate handling of success/error in
425 * each call.
426 */
427 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
428 @Override
429 public void onStatusAvailable(int statusCode) {
430 getHandler().post(() -> callback(statusCode));
431 }
432
433 public abstract void callback(int statusCode);
434
435 @Override
436 public int getInterfaceVersion() {
437 return this.VERSION;
438 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900439
440 @Override
441 public String getInterfaceHash() {
442 return this.HASH;
443 }
markchien74a4fa92019-09-09 20:50:49 +0800444 }
445
446 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
447 private final int mStartIndex;
448
449 private DhcpServerCallbacksImpl(int startIndex) {
450 mStartIndex = startIndex;
451 }
452
453 @Override
454 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
455 getHandler().post(() -> {
456 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
457 if (mStartIndex != mDhcpServerStartIndex) {
458 // This start request is obsolete. When the |server| binder token goes out of
459 // scope, the garbage collector will finalize it, which causes the network stack
460 // process garbage collector to collect the server itself.
461 return;
462 }
463
464 if (statusCode != STATUS_SUCCESS) {
465 mLog.e("Error obtaining DHCP server: " + statusCode);
466 handleError();
467 return;
468 }
469
470 mDhcpServer = server;
471 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900472 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800473 @Override
474 public void callback(int startStatusCode) {
475 if (startStatusCode != STATUS_SUCCESS) {
476 mLog.e("Error starting DHCP server: " + startStatusCode);
477 handleError();
478 }
479 }
Xiao Ma65401342020-05-14 06:52:59 +0000480 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800481 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800482 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800483 }
484 });
485 }
486
487 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800488 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800489 transitionTo(mInitialState);
490 }
491 }
492
Xiao Ma65401342020-05-14 06:52:59 +0000493 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900494 @Override
495 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
496 final ArrayList<TetheredClient> leases = new ArrayList<>();
497 for (DhcpLeaseParcelable lease : leaseParcelables) {
498 final LinkAddress address = new LinkAddress(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000499 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
500 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
501 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900502
503 final MacAddress macAddress;
504 try {
505 macAddress = MacAddress.fromBytes(lease.hwAddr);
506 } catch (IllegalArgumentException e) {
507 Log.wtf(TAG, "Invalid address received from DhcpServer: "
508 + Arrays.toString(lease.hwAddr));
509 return;
510 }
511
512 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000513 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900514 leases.add(new TetheredClient(
515 macAddress,
516 Collections.singletonList(addressInfo),
517 mInterfaceType));
518 }
519
520 getHandler().post(() -> {
521 mDhcpLeases = leases;
522 mCallback.dhcpLeasesChanged();
523 });
524 }
525
526 @Override
Xiao Ma65401342020-05-14 06:52:59 +0000527 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
528 Objects.requireNonNull(currentPrefix);
529 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma06c8ba02020-04-06 11:24:48 +0000530 }
531
532 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900533 public int getInterfaceVersion() {
534 return this.VERSION;
535 }
536
537 @Override
538 public String getInterfaceHash() throws RemoteException {
539 return this.HASH;
540 }
541 }
542
Xiao Ma65401342020-05-14 06:52:59 +0000543 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
544 Objects.requireNonNull(ipv4Address);
545 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
546 }
547
548 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
549 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
550 @Nullable Inet4Address clientAddr) {
551 final boolean changePrefixOnDecline =
552 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
553 return new DhcpServingParamsParcelExt()
554 .setDefaultRouters(defaultRouter)
555 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
556 .setDnsServers(dnsServer)
557 .setServerAddr(serverAddr)
558 .setMetered(true)
559 .setSingleClientAddr(clientAddr)
560 .setChangePrefixOnDecline(changePrefixOnDecline);
561 // TODO: also advertise link MTU
562 }
563
Treehugger Robot5da10702020-03-30 04:23:55 +0000564 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800565 if (mUsingLegacyDhcp) {
566 return true;
567 }
Treehugger Robot5da10702020-03-30 04:23:55 +0000568
569 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
Treehugger Robot5da10702020-03-30 04:23:55 +0000570 final Inet4Address clientAddr = clientLinkAddr == null ? null :
571 (Inet4Address) clientLinkAddr.getAddress();
572
Xiao Ma65401342020-05-14 06:52:59 +0000573 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
574 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800575 mDhcpServerStartIndex++;
576 mDeps.makeDhcpServer(
577 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
578 return true;
579 }
580
581 private void stopDhcp() {
582 // Make all previous start requests obsolete so servers are not started later
583 mDhcpServerStartIndex++;
584
585 if (mDhcpServer != null) {
586 try {
587 mDhcpServer.stop(new OnHandlerStatusCallback() {
588 @Override
589 public void callback(int statusCode) {
590 if (statusCode != STATUS_SUCCESS) {
591 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800592 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800593 // Not much more we can do here
594 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900595 mDhcpLeases.clear();
596 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800597 }
598 });
599 mDhcpServer = null;
600 } catch (RemoteException e) {
Xiao Ma65401342020-05-14 06:52:59 +0000601 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800602 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800603 }
604 }
605 }
606
Treehugger Robot5da10702020-03-30 04:23:55 +0000607 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
608 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800609 if (enable) {
Treehugger Robot5da10702020-03-30 04:23:55 +0000610 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800611 } else {
612 stopDhcp();
613 return true;
614 }
615 }
616
617 private void stopIPv4() {
618 configureIPv4(false);
619 // NOTE: All of configureIPv4() will be refactored out of existence
620 // into calls to InterfaceController, shared with startIPv4().
621 mInterfaceCtrl.clearIPv4Address();
Mark Chien2ecd3332020-05-29 22:07:37 +0000622 mPrivateAddressCoordinator.releaseDownstream(this);
markchien12c5bb82020-01-07 14:43:17 +0800623 mIpv4Address = null;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000624 mStaticIpv4ServerAddr = null;
625 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800626 }
627
markchien74a4fa92019-09-09 20:50:49 +0800628 private boolean configureIPv4(boolean enabled) {
629 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
630
Mark Chien2ecd3332020-05-29 22:07:37 +0000631 if (enabled) {
632 mIpv4Address = requestIpv4Address();
633 }
634
635 if (mIpv4Address == null) {
636 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800637 return false;
markchien74a4fa92019-09-09 20:50:49 +0800638 }
639
Mark Chien2ecd3332020-05-29 22:07:37 +0000640 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
641 // BT configures the interface elsewhere: only start DHCP.
642 // TODO: make all tethering types behave the same way, and delete the bluetooth
643 // code that calls into NetworkManagementService directly.
644 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
645 }
646
647 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
648
markchien12c5bb82020-01-07 14:43:17 +0800649 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800650 if (mInterfaceType == TetheringManager.TETHERING_WIFI
651 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800652 // The WiFi stack has ownership of the interface up/down state.
653 // It is unclear whether the Bluetooth or USB stacks will manage their own
654 // state.
655 setIfaceUp = null;
656 } else {
657 setIfaceUp = enabled;
658 }
659 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
660 mLog.e("Error configuring interface");
661 if (!enabled) stopDhcp();
662 return false;
663 }
markchien74a4fa92019-09-09 20:50:49 +0800664
markchien74a4fa92019-09-09 20:50:49 +0800665 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800666 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma65401342020-05-14 06:52:59 +0000667 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800668 } else {
markchien12c5bb82020-01-07 14:43:17 +0800669 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma65401342020-05-14 06:52:59 +0000670 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800671 }
Treehugger Robot5da10702020-03-30 04:23:55 +0000672 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800673 }
674
Mark Chien2ecd3332020-05-29 22:07:37 +0000675 private LinkAddress requestIpv4Address() {
676 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800677
Mark Chien2ecd3332020-05-29 22:07:37 +0000678 if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
679 return new LinkAddress(BLUETOOTH_IFACE_ADDR);
680 }
681
682 return mPrivateAddressCoordinator.requestDownstreamAddress(this);
Xiao Ma65401342020-05-14 06:52:59 +0000683 }
684
markchien74a4fa92019-09-09 20:50:49 +0800685 private boolean startIPv6() {
686 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
687 if (mInterfaceParams == null) {
688 mLog.e("Failed to find InterfaceParams");
689 stopIPv6();
690 return false;
691 }
692
693 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
694 if (!mRaDaemon.start()) {
695 stopIPv6();
696 return false;
697 }
698
699 return true;
700 }
701
702 private void stopIPv6() {
703 mInterfaceParams = null;
704 setRaParams(null);
705
706 if (mRaDaemon != null) {
707 mRaDaemon.stop();
708 mRaDaemon = null;
709 }
710 }
711
712 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
713 // LinkProperties. These have extraneous data filtered out and only the
714 // necessary prefixes included (per its prefix distribution policy).
715 //
716 // TODO: Evaluate using a data structure than is more directly suited to
717 // communicating only the relevant information.
Mark Chiencd309132020-05-25 02:04:59 +0000718 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800719 if (mRaDaemon == null) return;
720
721 // Avoid unnecessary work on spurious updates.
722 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
723 return;
724 }
725
726 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900727 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800728
729 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900730 final String upstreamIface = v6only.getInterfaceName();
731
markchien74a4fa92019-09-09 20:50:49 +0800732 params = new RaParams();
Nucca Chen0bbfe122020-05-12 11:34:28 +0000733 // When BPF offload is enabled, we advertise an mtu lower by 16, which is the closest
734 // multiple of 8 >= 14, the ethernet header size. This makes kernel ebpf tethering
735 // offload happy. This hack should be reverted once we have the kernel fixed up.
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800736 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
737 // see RouterAdvertisementDaemon.java putMtu()
Nucca Chen0bbfe122020-05-12 11:34:28 +0000738 params.mtu = mUsingBpfOffload ? v6only.getMtu() - 16 : v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800739 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
740
Mark Chiencd309132020-05-25 02:04:59 +0000741 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800742
743 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
744 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
745
746 final IpPrefix prefix = new IpPrefix(
747 linkAddr.getAddress(), linkAddr.getPrefixLength());
748 params.prefixes.add(prefix);
749
750 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
751 if (dnsServer != null) {
752 params.dnses.add(dnsServer);
753 }
754 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900755
756 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800757 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900758
markchien74a4fa92019-09-09 20:50:49 +0800759 // If v6only is null, we pass in null to setRaParams(), which handles
760 // deprecation of any existing RA data.
761
762 setRaParams(params);
763 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900764
765 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
766 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800767 }
768
Xiao Ma65401342020-05-14 06:52:59 +0000769 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
770 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
771 mNetd, toBeRemoved);
772 if (removalFailures > 0) {
773 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
774 removalFailures));
775 }
776
777 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
778 }
779
780 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
781 try {
782 // 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 IPv4/v6 routes to local table: " + e);
791 return;
792 }
793 } catch (ServiceSpecificException | RemoteException e) {
794 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
795 return;
796 }
797
798 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
799 }
800
markchien74a4fa92019-09-09 20:50:49 +0800801 private void configureLocalIPv6Routes(
802 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
803 // [1] Remove the routes that are deprecated.
804 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma65401342020-05-14 06:52:59 +0000805 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800806 }
807
808 // [2] Add only the routes that have not previously been added.
809 if (newPrefixes != null && !newPrefixes.isEmpty()) {
810 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
811 if (mLastRaParams != null) {
812 addedPrefixes.removeAll(mLastRaParams.prefixes);
813 }
814
815 if (!addedPrefixes.isEmpty()) {
Xiao Ma65401342020-05-14 06:52:59 +0000816 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800817 }
818 }
819 }
820
821 private void configureLocalIPv6Dns(
822 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
823 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
824 if (mNetd == null) {
825 if (newDnses != null) newDnses.clear();
826 mLog.e("No netd service instance available; not setting local IPv6 addresses");
827 return;
828 }
829
830 // [1] Remove deprecated local DNS IP addresses.
831 if (!deprecatedDnses.isEmpty()) {
832 for (Inet6Address dns : deprecatedDnses) {
833 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
834 mLog.e("Failed to remove local dns IP " + dns);
835 }
836
837 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
838 }
839 }
840
841 // [2] Add only the local DNS IP addresses that have not previously been added.
842 if (newDnses != null && !newDnses.isEmpty()) {
843 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
844 if (mLastRaParams != null) {
845 addedDnses.removeAll(mLastRaParams.dnses);
846 }
847
848 for (Inet6Address dns : addedDnses) {
849 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
850 mLog.e("Failed to add local dns IP " + dns);
851 newDnses.remove(dns);
852 }
853
854 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
855 }
856 }
857
858 try {
859 mNetd.tetherApplyDnsInterfaces();
860 } catch (ServiceSpecificException | RemoteException e) {
861 mLog.e("Failed to update local DNS caching server");
862 if (newDnses != null) newDnses.clear();
863 }
864 }
865
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900866 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Nucca Chen0bbfe122020-05-12 11:34:28 +0000867 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
868 // offload is disabled. Add this check just in case.
869 // TODO: Perhaps remove this protection check.
870 if (!mUsingBpfOffload) return;
871
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900872 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000873 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900874 mIpv6ForwardingRules.put(rule.address, rule);
875 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000876 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900877 }
878 }
879
880 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
Nucca Chen0bbfe122020-05-12 11:34:28 +0000881 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
882 // offload is disabled. Add this check just in case.
883 // TODO: Perhaps remove this protection check.
884 if (!mUsingBpfOffload) return;
885
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900886 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000887 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900888 if (removeFromMap) {
889 mIpv6ForwardingRules.remove(rule.address);
890 }
891 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000892 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900893 }
894 }
895
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000896 private void clearIpv6ForwardingRules() {
897 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
898 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
899 }
900 mIpv6ForwardingRules.clear();
901 }
902
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900903 // Convenience method to replace a rule with the same rule on a new upstream interface.
904 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
905 // Relies on the fact that rules are in a map indexed by IP address.
906 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
907 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
908 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
909 }
910
911 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
912 // changes or if a neighbor event is received.
913 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
914 NeighborEvent e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000915 // If we no longer have an upstream, clear forwarding rules and do nothing else.
916 if (upstreamIfindex == 0) {
917 clearIpv6ForwardingRules();
918 return;
919 }
920
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900921 // If the upstream interface has changed, remove all rules and re-add them with the new
922 // upstream interface.
923 if (prevUpstreamIfindex != upstreamIfindex) {
924 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
925 updateIpv6ForwardingRule(rule, upstreamIfindex);
926 }
927 }
928
929 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000930 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900931 if (e == null) return;
932 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
933 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
934 return;
935 }
936
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000937 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
938 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
939 // add rules with a null MAC, only delete them.
940 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000941 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti6f532ba2020-04-14 09:21:19 +0000942 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900943 if (e.isValid()) {
944 addIpv6ForwardingRule(rule);
945 } else {
946 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
947 }
948 }
949
950 private void handleNeighborEvent(NeighborEvent e) {
951 if (mInterfaceParams != null
952 && mInterfaceParams.index == e.ifindex
953 && mInterfaceParams.hasMacAddress) {
954 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
955 }
956 }
957
Xiao Ma65401342020-05-14 06:52:59 +0000958 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
959 if (!currentPrefix.contains(mIpv4Address.getAddress())
960 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
961 Log.e(TAG, "Invalid prefix: " + currentPrefix);
962 return;
963 }
964
965 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark Chien2ecd3332020-05-29 22:07:37 +0000966 mIpv4Address = requestIpv4Address();
967 if (mIpv4Address == null) {
Xiao Ma65401342020-05-14 06:52:59 +0000968 mLog.e("Fail to request a new downstream prefix");
969 return;
970 }
Mark Chien2ecd3332020-05-29 22:07:37 +0000971 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma65401342020-05-14 06:52:59 +0000972
973 // Add new IPv4 address on the interface.
974 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
975 mLog.e("Failed to add new IP " + srvAddr);
976 return;
977 }
978
979 // Remove deprecated routes from local network.
980 removeRoutesFromLocalNetwork(
981 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
982 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
983
984 // Add new routes to local network.
985 addRoutesToLocalNetwork(
986 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
987 mLinkProperties.addLinkAddress(mIpv4Address);
988
989 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
990 // listen on the interface configured with new IPv4 address, that results DNS validation
991 // failure of downstream client even if appropriate routes have been configured.
992 try {
993 mNetd.tetherApplyDnsInterfaces();
994 } catch (ServiceSpecificException | RemoteException e) {
995 mLog.e("Failed to update local DNS caching server");
996 return;
997 }
998 sendLinkProperties();
999
1000 // Notify DHCP server that new prefix/route has been applied on IpServer.
1001 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1002 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1003 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1004 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1005 try {
1006 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1007 @Override
1008 public void callback(int statusCode) {
1009 if (statusCode != STATUS_SUCCESS) {
1010 mLog.e("Error updating DHCP serving params: " + statusCode);
1011 }
1012 }
1013 });
1014 } catch (RemoteException e) {
1015 mLog.e("Error updating DHCP serving params", e);
1016 }
1017 }
1018
Mark Chiencd309132020-05-25 02:04:59 +00001019 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001020 try {
1021 int upstreamHopLimit = Integer.parseUnsignedInt(
1022 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
Mark Chiencd309132020-05-25 02:04:59 +00001023 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001024 // Cap the hop limit to 255.
1025 return (byte) Integer.min(upstreamHopLimit, 255);
1026 } catch (Exception e) {
1027 mLog.e("Failed to find upstream interface hop limit", e);
1028 }
1029 return RaParams.DEFAULT_HOPLIMIT;
1030 }
1031
1032 private void setRaParams(RaParams newParams) {
1033 if (mRaDaemon != null) {
1034 final RaParams deprecatedParams =
1035 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1036
1037 configureLocalIPv6Routes(deprecatedParams.prefixes,
1038 (newParams != null) ? newParams.prefixes : null);
1039
1040 configureLocalIPv6Dns(deprecatedParams.dnses,
1041 (newParams != null) ? newParams.dnses : null);
1042
1043 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1044 }
1045
1046 mLastRaParams = newParams;
1047 }
1048
1049 private void logMessage(State state, int what) {
1050 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
1051 }
1052
1053 private void sendInterfaceState(int newInterfaceState) {
1054 mServingMode = newInterfaceState;
1055 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1056 sendLinkProperties();
1057 }
1058
1059 private void sendLinkProperties() {
1060 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1061 }
1062
1063 private void resetLinkProperties() {
1064 mLinkProperties.clear();
1065 mLinkProperties.setInterfaceName(mIfaceName);
1066 }
1067
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001068 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
Treehugger Robot5da10702020-03-30 04:23:55 +00001069 // Ignore static address configuration if they are invalid or null. In theory, static
1070 // addresses should not be invalid here because TetheringManager do not allow caller to
1071 // specify invalid static address configuration.
1072 if (request == null || request.localIPv4Address == null
1073 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1074 request.localIPv4Address, request.staticClientAddress)) {
1075 return;
1076 }
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001077
1078 mStaticIpv4ServerAddr = request.localIPv4Address;
1079 mStaticIpv4ClientAddr = request.staticClientAddress;
1080 }
1081
markchien74a4fa92019-09-09 20:50:49 +08001082 class InitialState extends State {
1083 @Override
1084 public void enter() {
1085 sendInterfaceState(STATE_AVAILABLE);
1086 }
1087
1088 @Override
1089 public boolean processMessage(Message message) {
1090 logMessage(this, message.what);
1091 switch (message.what) {
1092 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001093 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001094 switch (message.arg1) {
1095 case STATE_LOCAL_ONLY:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001096 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001097 transitionTo(mLocalHotspotState);
1098 break;
1099 case STATE_TETHERED:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +00001100 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001101 transitionTo(mTetheredState);
1102 break;
1103 default:
1104 mLog.e("Invalid tethering interface serving state specified.");
1105 }
1106 break;
1107 case CMD_INTERFACE_DOWN:
1108 transitionTo(mUnavailableState);
1109 break;
1110 case CMD_IPV6_TETHER_UPDATE:
Mark Chiencd309132020-05-25 02:04:59 +00001111 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001112 break;
1113 default:
1114 return NOT_HANDLED;
1115 }
1116 return HANDLED;
1117 }
1118 }
1119
1120 class BaseServingState extends State {
1121 @Override
1122 public void enter() {
1123 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001124 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001125 return;
1126 }
1127
1128 try {
Mark Chien2ecd3332020-05-29 22:07:37 +00001129 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001130 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma65401342020-05-14 06:52:59 +00001131 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001132 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001133 return;
1134 }
1135
1136 if (!startIPv6()) {
1137 mLog.e("Failed to startIPv6");
1138 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1139 return;
1140 }
1141 }
1142
1143 @Override
1144 public void exit() {
1145 // Note that at this point, we're leaving the tethered state. We can fail any
1146 // of these operations, but it doesn't really change that we have to try them
1147 // all in sequence.
1148 stopIPv6();
1149
1150 try {
markchien12c5bb82020-01-07 14:43:17 +08001151 NetdUtils.untetherInterface(mNetd, mIfaceName);
1152 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001153 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001154 mLog.e("Failed to untether interface: " + e);
1155 }
1156
1157 stopIPv4();
1158
1159 resetLinkProperties();
1160 }
1161
1162 @Override
1163 public boolean processMessage(Message message) {
1164 logMessage(this, message.what);
1165 switch (message.what) {
1166 case CMD_TETHER_UNREQUESTED:
1167 transitionTo(mInitialState);
1168 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1169 break;
1170 case CMD_INTERFACE_DOWN:
1171 transitionTo(mUnavailableState);
1172 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1173 break;
1174 case CMD_IPV6_TETHER_UPDATE:
Mark Chiencd309132020-05-25 02:04:59 +00001175 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001176 sendLinkProperties();
1177 break;
1178 case CMD_IP_FORWARDING_ENABLE_ERROR:
1179 case CMD_IP_FORWARDING_DISABLE_ERROR:
1180 case CMD_START_TETHERING_ERROR:
1181 case CMD_STOP_TETHERING_ERROR:
1182 case CMD_SET_DNS_FORWARDERS_ERROR:
markchienf1332572020-03-19 13:37:43 +08001183 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001184 transitionTo(mInitialState);
1185 break;
Xiao Ma65401342020-05-14 06:52:59 +00001186 case CMD_NEW_PREFIX_REQUEST:
1187 handleNewPrefixRequest((IpPrefix) message.obj);
1188 break;
Mark Chien2ecd3332020-05-29 22:07:37 +00001189 case CMD_NOTIFY_PREFIX_CONFLICT:
1190 mLog.i("restart tethering: " + mInterfaceType);
1191 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1192 transitionTo(mWaitingForRestartState);
1193 break;
markchien74a4fa92019-09-09 20:50:49 +08001194 default:
1195 return false;
1196 }
1197 return true;
1198 }
1199 }
1200
1201 // Handling errors in BaseServingState.enter() by transitioning is
1202 // problematic because transitioning during a multi-state jump yields
1203 // a Log.wtf(). Ultimately, there should be only one ServingState,
1204 // and forwarding and NAT rules should be handled by a coordinating
1205 // functional element outside of IpServer.
1206 class LocalHotspotState extends BaseServingState {
1207 @Override
1208 public void enter() {
1209 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001210 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001211 transitionTo(mInitialState);
1212 }
1213
1214 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1215 sendInterfaceState(STATE_LOCAL_ONLY);
1216 }
1217
1218 @Override
1219 public boolean processMessage(Message message) {
1220 if (super.processMessage(message)) return true;
1221
1222 logMessage(this, message.what);
1223 switch (message.what) {
1224 case CMD_TETHER_REQUESTED:
1225 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1226 break;
1227 case CMD_TETHER_CONNECTION_CHANGED:
1228 // Ignored in local hotspot state.
1229 break;
1230 default:
1231 return false;
1232 }
1233 return true;
1234 }
1235 }
1236
1237 // Handling errors in BaseServingState.enter() by transitioning is
1238 // problematic because transitioning during a multi-state jump yields
1239 // a Log.wtf(). Ultimately, there should be only one ServingState,
1240 // and forwarding and NAT rules should be handled by a coordinating
1241 // functional element outside of IpServer.
1242 class TetheredState extends BaseServingState {
1243 @Override
1244 public void enter() {
1245 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001246 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001247 transitionTo(mInitialState);
1248 }
1249
1250 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1251 sendInterfaceState(STATE_TETHERED);
1252 }
1253
1254 @Override
1255 public void exit() {
1256 cleanupUpstream();
1257 super.exit();
1258 }
1259
1260 private void cleanupUpstream() {
1261 if (mUpstreamIfaceSet == null) return;
1262
1263 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1264 mUpstreamIfaceSet = null;
Automerger Merge Workerf1194882020-02-25 04:04:44 +00001265 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001266 }
1267
1268 private void cleanupUpstreamInterface(String upstreamIface) {
1269 // Note that we don't care about errors here.
1270 // Sometimes interfaces are gone before we get
1271 // to remove their rules, which generates errors.
1272 // Just do the best we can.
1273 try {
markchien12c5bb82020-01-07 14:43:17 +08001274 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1275 } catch (RemoteException | ServiceSpecificException e) {
1276 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001277 }
1278 try {
markchien12c5bb82020-01-07 14:43:17 +08001279 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1280 } catch (RemoteException | ServiceSpecificException e) {
1281 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001282 }
1283 }
1284
1285 @Override
1286 public boolean processMessage(Message message) {
1287 if (super.processMessage(message)) return true;
1288
1289 logMessage(this, message.what);
1290 switch (message.what) {
1291 case CMD_TETHER_REQUESTED:
1292 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1293 break;
1294 case CMD_TETHER_CONNECTION_CHANGED:
1295 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1296 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1297 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1298 break;
1299 }
1300
1301 if (newUpstreamIfaceSet == null) {
1302 cleanupUpstream();
1303 break;
1304 }
1305
1306 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1307 cleanupUpstreamInterface(removed);
1308 }
1309
1310 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1311 // This makes the call to cleanupUpstream() in the error
1312 // path for any interface neatly cleanup all the interfaces.
1313 mUpstreamIfaceSet = newUpstreamIfaceSet;
1314
1315 for (String ifname : added) {
1316 try {
markchien12c5bb82020-01-07 14:43:17 +08001317 mNetd.tetherAddForward(mIfaceName, ifname);
1318 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1319 } catch (RemoteException | ServiceSpecificException e) {
1320 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001321 cleanupUpstream();
markchienf1332572020-03-19 13:37:43 +08001322 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001323 transitionTo(mInitialState);
1324 return true;
1325 }
1326 }
1327 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001328 case CMD_NEIGHBOR_EVENT:
1329 handleNeighborEvent((NeighborEvent) message.obj);
1330 break;
markchien74a4fa92019-09-09 20:50:49 +08001331 default:
1332 return false;
1333 }
1334 return true;
1335 }
1336
1337 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1338 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1339 if (mUpstreamIfaceSet != null && newIfaces != null) {
1340 return mUpstreamIfaceSet.equals(newIfaces);
1341 }
1342 return false;
1343 }
1344
1345 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1346 if (mUpstreamIfaceSet == null) return new HashSet<>();
1347
1348 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1349 removed.removeAll(newIfaces.ifnames);
1350 return removed;
1351 }
1352
1353 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1354 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1355 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1356 return added;
1357 }
1358 }
1359
1360 /**
1361 * This state is terminal for the per interface state machine. At this
1362 * point, the master state machine should have removed this interface
1363 * specific state machine from its list of possible recipients of
1364 * tethering requests. The state machine itself will hang around until
1365 * the garbage collector finds it.
1366 */
1367 class UnavailableState extends State {
1368 @Override
1369 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001370 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001371 sendInterfaceState(STATE_UNAVAILABLE);
1372 }
1373 }
1374
Mark Chien2ecd3332020-05-29 22:07:37 +00001375 class WaitingForRestartState extends State {
1376 @Override
1377 public boolean processMessage(Message message) {
1378 logMessage(this, message.what);
1379 switch (message.what) {
1380 case CMD_TETHER_UNREQUESTED:
1381 transitionTo(mInitialState);
1382 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1383 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1384 break;
1385 case CMD_INTERFACE_DOWN:
1386 transitionTo(mUnavailableState);
1387 mLog.i("Untethered (interface down) and restarting" + mIfaceName);
1388 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1389 break;
1390 default:
1391 return false;
1392 }
1393 return true;
1394 }
1395 }
1396
markchien74a4fa92019-09-09 20:50:49 +08001397 // Accumulate routes representing "prefixes to be assigned to the local
1398 // interface", for subsequent modification of local_network routing.
1399 private static ArrayList<RouteInfo> getLocalRoutesFor(
1400 String ifname, HashSet<IpPrefix> prefixes) {
1401 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1402 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001403 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001404 }
1405 return localRoutes;
1406 }
1407
1408 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1409 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1410 final byte[] dnsBytes = localPrefix.getRawAddress();
1411 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1412 try {
1413 return Inet6Address.getByAddress(null, dnsBytes, 0);
1414 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001415 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001416 return null;
1417 }
1418 }
1419
1420 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1421 final byte random = (byte) (new Random()).nextInt();
1422 for (int value : excluded) {
1423 if (random == value) return dflt;
1424 }
1425 return random;
1426 }
1427}