blob: 1f687bc5798323acbfadb13420510c2042ac8620 [file] [log] [blame]
Daniel Drown0da73fc2012-06-20 16:51:39 -05001/*
2 * Copyright (C) 2008 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 */
Bernie Innocenti51a0e0f2018-10-05 20:24:06 +090016
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +090017#include <map>
18#include <string>
19
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090020#include <arpa/inet.h>
Daniel Drown0da73fc2012-06-20 16:51:39 -050021#include <errno.h>
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -070022#include <linux/if_arp.h>
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -070023#include <linux/if_tun.h>
24#include <linux/ioctl.h>
Maciej Żenczykowskic8c38aa2019-03-29 01:24:51 -070025#include <net/if.h>
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090026#include <netinet/in.h>
Luke Huang94c43a12019-02-14 19:51:38 +080027#include <spawn.h>
Daniel Drown0da73fc2012-06-20 16:51:39 -050028#include <sys/types.h>
29#include <sys/wait.h>
Luke Huang94c43a12019-02-14 19:51:38 +080030#include <unistd.h>
Daniel Drown0da73fc2012-06-20 16:51:39 -050031
32#define LOG_TAG "ClatdController"
Logan Chien3f461482018-04-23 14:31:32 +080033#include <log/log.h>
Daniel Drown0da73fc2012-06-20 16:51:39 -050034
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -070035#include "ClatdController.h"
Maciej Żenczykowskia1699952019-05-11 17:07:44 -070036#include "InterfaceController.h"
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -070037
38#include "android-base/properties.h"
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -070039#include "android-base/scopeguard.h"
Lorenzo Colitti91fd5802019-06-28 19:22:01 +090040#include "android-base/stringprintf.h"
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090041#include "android-base/unique_fd.h"
Maciej Żenczykowski55262712019-03-29 23:44:56 -070042#include "bpf/BpfMap.h"
43#include "netdbpf/bpf_shared.h"
44#include "netdutils/DumpWriter.h"
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090045
46extern "C" {
47#include "netutils/checksum.h"
48}
49
Maciej Żenczykowski55262712019-03-29 23:44:56 -070050#include "ClatUtils.h"
Lorenzo Colitti45d3dd02014-06-09 14:09:20 +090051#include "Fwmark.h"
Paul Jensen84c1d032014-05-30 13:29:41 -040052#include "NetdConstants.h"
53#include "NetworkController.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +090054#include "netid_client.h"
Daniel Drown0da73fc2012-06-20 16:51:39 -050055
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +090056static const char* kClatdPath = "/system/bin/clatd";
57
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090058// For historical reasons, start with 192.0.0.4, and after that, use all subsequent addresses in
59// 192.0.0.0/29 (RFC 7335).
60static const char* kV4AddrString = "192.0.0.4";
61static const in_addr kV4Addr = {inet_addr(kV4AddrString)};
62static const int kV4AddrLen = 29;
63
Lorenzo Colitti91fd5802019-06-28 19:22:01 +090064using android::base::StringPrintf;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090065using android::base::unique_fd;
Maciej Żenczykowski55262712019-03-29 23:44:56 -070066using android::bpf::BpfMap;
67using android::netdutils::DumpWriter;
68using android::netdutils::ScopedIndent;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090069
Lorenzo Colitti7035f222017-02-13 18:29:00 +090070namespace android {
71namespace net {
72
Maciej Żenczykowski56280272019-03-30 03:32:51 -070073void ClatdController::init(void) {
74 std::lock_guard guard(mutex);
75
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -070076 // TODO: should refactor into separate function for testability
77 if (bpf::getBpfSupportLevel() == bpf::BpfLevel::NONE) {
78 ALOGI("Pre-4.9 kernel or pre-P api shipping level - disabling clat ebpf.");
79 mClatEbpfMode = ClatEbpfDisabled;
80 return;
81 }
82
83 // We know the device initially shipped with at least P...,
84 // but did it ship with at least Q?
85
86 uint64_t api_level = base::GetUintProperty<uint64_t>("ro.product.first_api_level", 0);
87 if (api_level == 0) {
88 ALOGE("Cannot determine initial API level of the device.");
89 api_level = base::GetUintProperty<uint64_t>("ro.build.version.sdk", 0);
90 }
91
92 // Note: MINIMUM_API_REQUIRED is for eBPF as a whole and is thus P
93 if (api_level > bpf::MINIMUM_API_REQUIRED) {
94 ALOGI("4.9+ kernel and device shipped with Q+ - clat ebpf should work.");
95 mClatEbpfMode = ClatEbpfEnabled;
96 } else {
97 // We cannot guarantee that 4.9-P kernels will include NET_CLS_BPF support.
98 ALOGI("4.9+ kernel and device shipped with P - clat ebpf might work.");
99 mClatEbpfMode = ClatEbpfMaybe;
100 }
101
102 int rv = openNetlinkSocket();
103 if (rv < 0) {
104 ALOGE("openNetlinkSocket() failure: %s", strerror(-rv));
105 mClatEbpfMode = ClatEbpfDisabled;
106 return;
107 }
108 mNetlinkFd.reset(rv);
109
110 rv = getClatIngressMapFd();
111 if (rv < 0) {
112 ALOGE("getClatIngressMapFd() failure: %s", strerror(-rv));
113 mClatEbpfMode = ClatEbpfDisabled;
114 mNetlinkFd.reset(-1);
115 return;
116 }
117 mClatIngressMap.reset(rv);
118
119 int netlinkFd = mNetlinkFd.get();
120
121 // TODO: perhaps this initial cleanup should be in its own function?
122 const auto del = [&netlinkFd](const ClatIngressKey& key,
123 const BpfMap<ClatIngressKey, ClatIngressValue>&) {
124 ALOGW("Removing stale clat config on interface %d.", key.iif);
125 int rv = tcQdiscDelDevClsact(netlinkFd, key.iif);
126 if (rv < 0) ALOGE("tcQdiscDelDevClsact() failure: %s", strerror(-rv));
127 return netdutils::status::ok; // keep on going regardless
128 };
129 auto ret = mClatIngressMap.iterate(del);
130 if (!isOk(ret)) ALOGE("mClatIngressMap.iterate() failure: %s", strerror(ret.code()));
131 ret = mClatIngressMap.clear();
132 if (!isOk(ret)) ALOGE("mClatIngressMap.clear() failure: %s", strerror(ret.code()));
133}
134
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900135bool ClatdController::isIpv4AddressFree(in_addr_t addr) {
136 int s = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
137 if (s == -1) {
138 return 0;
139 }
140
141 // Attempt to connect to the address. If the connection succeeds and getsockname returns the
142 // same then the address is already assigned to the system and we can't use it.
Nick Desaulniers6b357502019-10-11 09:26:44 -0700143 struct sockaddr_in sin = {
144 .sin_family = AF_INET,
Maciej Żenczykowski268190e2019-10-31 23:47:53 -0700145 .sin_port = htons(53),
Nick Desaulniers6b357502019-10-11 09:26:44 -0700146 .sin_addr = {addr},
147 };
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900148 socklen_t len = sizeof(sin);
149 bool inuse = connect(s, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
150 getsockname(s, (struct sockaddr*)&sin, &len) == 0 && (size_t)len >= sizeof(sin) &&
151 sin.sin_addr.s_addr == addr;
152
153 close(s);
154 return !inuse;
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +0900155}
Daniel Drown0da73fc2012-06-20 16:51:39 -0500156
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900157// Picks a free IPv4 address, starting from ip and trying all addresses in the prefix in order.
158// ip - the IP address from the configuration file
159// prefixlen - the length of the prefix from which addresses may be selected.
160// returns: the IPv4 address, or INADDR_NONE if no addresses were available
161in_addr_t ClatdController::selectIpv4Address(const in_addr ip, int16_t prefixlen) {
162 // Don't accept prefixes that are too large because we scan addresses one by one.
163 if (prefixlen < 16 || prefixlen > 32) {
164 return INADDR_NONE;
165 }
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +0900166
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900167 // All these are in host byte order.
168 in_addr_t mask = 0xffffffff >> (32 - prefixlen) << (32 - prefixlen);
169 in_addr_t ipv4 = ntohl(ip.s_addr);
170 in_addr_t first_ipv4 = ipv4;
171 in_addr_t prefix = ipv4 & mask;
172
173 // Pick the first IPv4 address in the pool, wrapping around if necessary.
174 // So, for example, 192.0.0.4 -> 192.0.0.5 -> 192.0.0.6 -> 192.0.0.7 -> 192.0.0.0.
175 do {
176 if (isIpv4AddressFreeFunc(htonl(ipv4))) {
177 return htonl(ipv4);
178 }
179 ipv4 = prefix | ((ipv4 + 1) & ~mask);
180 } while (ipv4 != first_ipv4);
181
182 return INADDR_NONE;
183}
184
185// Alters the bits in the IPv6 address to make them checksum neutral with v4 and nat64Prefix.
186void ClatdController::makeChecksumNeutral(in6_addr* v6, const in_addr v4,
187 const in6_addr& nat64Prefix) {
188 // Fill last 8 bytes of IPv6 address with random bits.
189 arc4random_buf(&v6->s6_addr[8], 8);
190
191 // Make the IID checksum-neutral. That is, make it so that:
192 // checksum(Local IPv4 | Remote IPv4) = checksum(Local IPv6 | Remote IPv6)
193 // in other words (because remote IPv6 = NAT64 prefix | Remote IPv4):
194 // checksum(Local IPv4) = checksum(Local IPv6 | NAT64 prefix)
195 // Do this by adjusting the two bytes in the middle of the IID.
196
197 uint16_t middlebytes = (v6->s6_addr[11] << 8) + v6->s6_addr[12];
198
199 uint32_t c1 = ip_checksum_add(0, &v4, sizeof(v4));
200 uint32_t c2 = ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) +
201 ip_checksum_add(0, v6, sizeof(*v6));
202
203 uint16_t delta = ip_checksum_adjust(middlebytes, c1, c2);
204 v6->s6_addr[11] = delta >> 8;
205 v6->s6_addr[12] = delta & 0xff;
206}
207
208// Picks a random interface ID that is checksum neutral with the IPv4 address and the NAT64 prefix.
209int ClatdController::generateIpv6Address(const char* iface, const in_addr v4,
210 const in6_addr& nat64Prefix, in6_addr* v6) {
211 unique_fd s(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
212 if (s == -1) return -errno;
213
214 if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, iface, strlen(iface) + 1) == -1) {
Luke Huang6d301232018-08-01 14:05:18 +0800215 return -errno;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500216 }
217
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900218 sockaddr_in6 sin6 = {.sin6_family = AF_INET6, .sin6_addr = nat64Prefix};
219 if (connect(s, reinterpret_cast<struct sockaddr*>(&sin6), sizeof(sin6)) == -1) {
220 return -errno;
221 }
222
223 socklen_t len = sizeof(sin6);
224 if (getsockname(s, reinterpret_cast<struct sockaddr*>(&sin6), &len) == -1) {
225 return -errno;
226 }
227
228 *v6 = sin6.sin6_addr;
229
230 if (IN6_IS_ADDR_UNSPECIFIED(v6) || IN6_IS_ADDR_LOOPBACK(v6) || IN6_IS_ADDR_LINKLOCAL(v6) ||
231 IN6_IS_ADDR_SITELOCAL(v6) || IN6_IS_ADDR_ULA(v6)) {
232 return -ENETUNREACH;
233 }
234
235 makeChecksumNeutral(v6, v4, nat64Prefix);
236
237 return 0;
238}
239
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700240void ClatdController::maybeStartBpf(const ClatdTracker& tracker) {
241 if (mClatEbpfMode == ClatEbpfDisabled) return;
242
243 int rv = hardwareAddressType(tracker.iface);
244 if (rv < 0) {
245 ALOGE("hardwareAddressType(%s[%d]) failure: %s", tracker.iface, tracker.ifIndex,
246 strerror(-rv));
247 return;
248 }
249
250 bool isEthernet;
251 switch (rv) {
252 case ARPHRD_ETHER:
253 isEthernet = true;
254 break;
255 case ARPHRD_RAWIP: // in Linux 4.14+ rmnet support was upstreamed and this is 519
256 case 530: // this is ARPHRD_RAWIP on some Android 4.9 kernels with rmnet
257 isEthernet = false;
258 break;
259 default:
260 ALOGE("hardwareAddressType(%s[%d]) returned unknown type %d.", tracker.iface,
261 tracker.ifIndex, rv);
262 return;
263 }
264
265 rv = getClatIngressProgFd(isEthernet);
266 if (rv < 0) {
267 ALOGE("getClatIngressProgFd(%d) failure: %s", isEthernet, strerror(-rv));
268 return;
269 }
270 unique_fd progFd(rv);
271
272 ClatIngressKey key = {
273 .iif = tracker.ifIndex,
274 .pfx96 = tracker.pfx96,
275 .local6 = tracker.v6,
276 };
277 ClatIngressValue value = {
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700278 // TODO: move all the clat code to eBPF and remove the tun interface entirely.
Maciej Żenczykowski39b0b902019-05-08 00:36:30 -0700279 .oif = tracker.v4ifIndex,
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700280 .local4 = tracker.v4,
281 };
282
283 auto ret = mClatIngressMap.writeValue(key, value, BPF_ANY);
284 if (!isOk(ret)) {
285 ALOGE("mClatIngress.Map.writeValue failure: %s", strerror(ret.code()));
286 return;
287 }
288
289 // We do tc setup *after* populating map, so scanning through map
290 // can always be used to tell us what needs cleanup.
291
292 rv = tcQdiscAddDevClsact(mNetlinkFd, tracker.ifIndex);
293 if (rv) {
294 ALOGE("tcQdiscAddDevClsact(%d[%s]) failure: %s", tracker.ifIndex, tracker.iface,
295 strerror(-rv));
296 ret = mClatIngressMap.deleteValue(key);
297 if (!isOk(ret)) ALOGE("mClatIngressMap.deleteValue failure: %s", strerror(ret.code()));
298 return;
299 }
300
Maciej Żenczykowskib140a3a2019-12-15 11:53:46 -0800301 rv = tcFilterAddDevIngressBpf(mNetlinkFd, tracker.ifIndex, progFd, isEthernet);
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700302 if (rv) {
303 if ((rv == -ENOENT) && (mClatEbpfMode == ClatEbpfMaybe)) {
Maciej Żenczykowskib140a3a2019-12-15 11:53:46 -0800304 ALOGI("tcFilterAddDevIngressBpf(%d[%s], %d): %s", tracker.ifIndex, tracker.iface,
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700305 isEthernet, strerror(-rv));
Maciej Żenczykowskib140a3a2019-12-15 11:53:46 -0800306 } else {
307 ALOGE("tcFilterAddDevIngressBpf(%d[%s], %d) failure: %s", tracker.ifIndex,
308 tracker.iface, isEthernet, strerror(-rv));
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700309 }
310 rv = tcQdiscDelDevClsact(mNetlinkFd, tracker.ifIndex);
311 if (rv)
312 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", tracker.ifIndex, tracker.iface,
313 strerror(-rv));
314 ret = mClatIngressMap.deleteValue(key);
315 if (!isOk(ret)) ALOGE("mClatIngressMap.deleteValue failure: %s", strerror(ret.code()));
316 return;
317 }
318
319 // success
320}
321
Lorenzo Colitti91fd5802019-06-28 19:22:01 +0900322void ClatdController::maybeSetIptablesDropRule(bool add, const char* pfx96Str, const char* v6Str) {
323 if (mClatEbpfMode == ClatEbpfDisabled) return;
324
325 std::string cmd = StringPrintf(
326 "*raw\n"
327 "%s %s -s %s/96 -d %s -j DROP\n"
328 "COMMIT\n",
329 (add ? "-A" : "-D"), LOCAL_RAW_PREROUTING, pfx96Str, v6Str);
330
331 iptablesRestoreFunction(V6, cmd);
332}
333
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700334void ClatdController::maybeStopBpf(const ClatdTracker& tracker) {
335 if (mClatEbpfMode == ClatEbpfDisabled) return;
336
337 // No need to remove filter, since we remove qdisc it is attached to,
338 // which automatically removes everything attached to the qdisc.
339 int rv = tcQdiscDelDevClsact(mNetlinkFd, tracker.ifIndex);
340 if (rv < 0)
341 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", tracker.ifIndex, tracker.iface,
342 strerror(-rv));
343
344 // We cleanup map last, so scanning through map can be used to
345 // determine what still needs cleanup.
346
347 ClatIngressKey key = {
348 .iif = tracker.ifIndex,
349 .pfx96 = tracker.pfx96,
350 .local6 = tracker.v6,
351 };
352
353 auto ret = mClatIngressMap.deleteValue(key);
354 if (!isOk(ret)) ALOGE("mClatIngressMap.deleteValue failure: %s", strerror(ret.code()));
355}
356
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900357// Finds the tracker of the clatd running on interface |interface|, or nullptr if clatd has not been
358// started on |interface|.
359ClatdController::ClatdTracker* ClatdController::getClatdTracker(const std::string& interface) {
360 auto it = mClatdTrackers.find(interface);
361 return (it == mClatdTrackers.end() ? nullptr : &it->second);
362}
363
364// Initializes a ClatdTracker for the specified interface.
Maciej Żenczykowskia56b2e62019-04-24 13:17:18 -0700365int ClatdController::ClatdTracker::init(unsigned networkId, const std::string& interface,
Maciej Żenczykowski4657e512019-05-08 06:35:08 -0700366 const std::string& v4interface,
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900367 const std::string& nat64Prefix) {
Maciej Żenczykowskia56b2e62019-04-24 13:17:18 -0700368 netId = networkId;
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900369
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900370 fwmark.netId = netId;
371 fwmark.explicitlySelected = true;
372 fwmark.protectedFromVpn = true;
373 fwmark.permission = PERMISSION_SYSTEM;
374
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900375 snprintf(fwmarkString, sizeof(fwmarkString), "0x%x", fwmark.intValue);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900376 snprintf(netIdString, sizeof(netIdString), "%u", netId);
377 strlcpy(iface, interface.c_str(), sizeof(iface));
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700378 ifIndex = if_nametoindex(iface);
Maciej Żenczykowski4657e512019-05-08 06:35:08 -0700379 strlcpy(v4iface, v4interface.c_str(), sizeof(v4iface));
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700380 v4ifIndex = if_nametoindex(v4iface);
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900381
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900382 // Pass in everything that clatd needs: interface, a netid to use for DNS lookups, a fwmark for
383 // outgoing packets, the NAT64 prefix, and the IPv4 and IPv6 addresses.
384 // Validate the prefix and strip off the prefix length.
385 uint8_t family;
386 uint8_t prefixLen;
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700387 int res = parsePrefix(nat64Prefix.c_str(), &family, &pfx96, sizeof(pfx96), &prefixLen);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900388 // clatd only supports /96 prefixes.
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700389 if (res != sizeof(pfx96)) return res;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900390 if (family != AF_INET6) return -EAFNOSUPPORT;
391 if (prefixLen != 96) return -EINVAL;
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700392 if (!inet_ntop(AF_INET6, &pfx96, pfx96String, sizeof(pfx96String))) return -errno;
Luke Huang6d301232018-08-01 14:05:18 +0800393
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900394 // Pick an IPv4 address.
395 // TODO: this picks the address based on other addresses that are assigned to interfaces, but
396 // the address is only actually assigned to an interface once clatd starts up. So we could end
397 // up with two clatd instances with the same IPv4 address.
398 // Stop doing this and instead pick a free one from the kV4Addr pool.
Maciej Żenczykowski55cacfb2019-03-30 02:01:35 -0700399 v4 = {selectIpv4Address(kV4Addr, kV4AddrLen)};
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900400 if (v4.s_addr == INADDR_NONE) {
401 ALOGE("No free IPv4 address in %s/%d", kV4AddrString, kV4AddrLen);
402 return -EADDRNOTAVAIL;
403 }
404 if (!inet_ntop(AF_INET, &v4, v4Str, sizeof(v4Str))) return -errno;
405
406 // Generate a checksum-neutral IID.
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700407 if (generateIpv6Address(iface, v4, pfx96, &v6)) {
408 ALOGE("Unable to find global source address on %s for %s", iface, pfx96String);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900409 return -EADDRNOTAVAIL;
410 }
411 if (!inet_ntop(AF_INET6, &v6, v6Str, sizeof(v6Str))) return -errno;
412
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700413 ALOGD("starting clatd on %s v4=%s v6=%s pfx96=%s", iface, v4Str, v6Str, pfx96String);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900414 return 0;
415}
416
417int ClatdController::startClatd(const std::string& interface, const std::string& nat64Prefix,
418 std::string* v6Str) {
Maciej Żenczykowski56280272019-03-30 03:32:51 -0700419 std::lock_guard guard(mutex);
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700420
421 // 1. fail if pre-existing tracker already exists
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900422 ClatdTracker* existing = getClatdTracker(interface);
423 if (existing != nullptr) {
424 ALOGE("clatd pid=%d already started on %s", existing->pid, interface.c_str());
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700425 return -EBUSY;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900426 }
427
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700428 // 2. get network id associated with this external interface
Maciej Żenczykowskia56b2e62019-04-24 13:17:18 -0700429 unsigned networkId = mNetCtrl->getNetworkForInterface(interface.c_str());
430 if (networkId == NETID_UNSET) {
431 ALOGE("Interface %s not assigned to any netId", interface.c_str());
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700432 return -ENODEV;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900433 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700434
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700435 // 3. open the tun device in non blocking mode as required by clatd
436 int res = open("/dev/tun", O_RDWR | O_NONBLOCK | O_CLOEXEC);
437 if (res == -1) {
438 res = errno;
439 ALOGE("open of tun device failed (%s)", strerror(res));
440 return -res;
441 }
442 unique_fd tmpTunFd(res);
443
444 // 4. create the v4-... tun interface
Maciej Żenczykowski4657e512019-05-08 06:35:08 -0700445 std::string v4interface("v4-");
446 v4interface += interface;
447
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700448 struct ifreq ifr = {
449 .ifr_flags = IFF_TUN,
450 };
Maciej Żenczykowski4657e512019-05-08 06:35:08 -0700451 strlcpy(ifr.ifr_name, v4interface.c_str(), sizeof(ifr.ifr_name));
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700452
453 res = ioctl(tmpTunFd, TUNSETIFF, &ifr, sizeof(ifr));
454 if (res == -1) {
455 res = errno;
456 ALOGE("ioctl(TUNSETIFF) failed (%s)", strerror(res));
457 return -res;
458 }
459
Maciej Żenczykowskia1699952019-05-11 17:07:44 -0700460 // disable IPv6 on it - failing to do so is not a critical error
461 res = InterfaceController::setEnableIPv6(v4interface.c_str(), 0);
462 if (res) ALOGE("setEnableIPv6 %s failed (%s)", v4interface.c_str(), strerror(res));
463
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700464 // 5. initialize tracker object
Maciej Żenczykowskia56b2e62019-04-24 13:17:18 -0700465 ClatdTracker tracker;
Maciej Żenczykowski4657e512019-05-08 06:35:08 -0700466 int ret = tracker.init(networkId, interface, v4interface, nat64Prefix);
Maciej Żenczykowskia56b2e62019-04-24 13:17:18 -0700467 if (ret) return ret;
468
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700469 // 6. create a throwaway socket to reserve a file descriptor number
470 res = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
471 if (res == -1) {
472 res = errno;
473 ALOGE("socket(ipv6/udp) failed (%s)", strerror(res));
474 return -res;
475 }
476 unique_fd passedTunFd(res);
477
478 // 7. this is the FD we'll pass to clatd on the cli, so need it as a string
479 char passedTunFdStr[INT32_STRLEN];
480 snprintf(passedTunFdStr, sizeof(passedTunFdStr), "%d", passedTunFd.get());
481
482 // 8. we're going to use this as argv[0] to clatd to make ps output more useful
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +0900483 std::string progname("clatd-");
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900484 progname += tracker.iface;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500485
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900486 // clang-format off
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700487 const char* args[] = {progname.c_str(),
488 "-i", tracker.iface,
489 "-n", tracker.netIdString,
490 "-m", tracker.fwmarkString,
491 "-p", tracker.pfx96String,
492 "-4", tracker.v4Str,
493 "-6", tracker.v6Str,
494 "-t", passedTunFdStr,
495 nullptr};
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900496 // clang-format on
497
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700498 // 9. register vfork requirement
499 posix_spawnattr_t attr;
500 res = posix_spawnattr_init(&attr);
501 if (res) {
502 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
503 return -res;
504 }
505 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
506 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
507 if (res) {
508 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
509 return -res;
510 }
511
512 // 10. register dup2() action: this is what 'clears' the CLOEXEC flag
513 // on the tun fd that we want the child clatd process to inherit
514 // (this will happen after the vfork, and before the execve)
515 posix_spawn_file_actions_t fa;
516 res = posix_spawn_file_actions_init(&fa);
517 if (res) {
518 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
519 return -res;
520 }
521 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
522 res = posix_spawn_file_actions_adddup2(&fa, tmpTunFd, passedTunFd);
523 if (res) {
524 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
525 return -res;
526 }
527
Lorenzo Colitti91fd5802019-06-28 19:22:01 +0900528 // 11. If necessary, add the drop rule for iptables.
529 maybeSetIptablesDropRule(true, tracker.pfx96String, tracker.v6Str);
530
531 // 12. actually perform vfork/dup2/execve
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700532 res = posix_spawn(&tracker.pid, kClatdPath, &fa, &attr, (char* const*)args, nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800533 if (res) {
534 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang6d301232018-08-01 14:05:18 +0800535 return -res;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500536 }
537
Lorenzo Colitti91fd5802019-06-28 19:22:01 +0900538 // 13. configure eBPF offload - if possible
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700539 maybeStartBpf(tracker);
540
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900541 mClatdTrackers[interface] = tracker;
542 ALOGD("clatd started on %s", interface.c_str());
Daniel Drown0da73fc2012-06-20 16:51:39 -0500543
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900544 *v6Str = tracker.v6Str;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500545 return 0;
546}
547
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900548int ClatdController::stopClatd(const std::string& interface) {
Maciej Żenczykowski56280272019-03-30 03:32:51 -0700549 std::lock_guard guard(mutex);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900550 ClatdTracker* tracker = getClatdTracker(interface);
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +0900551
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900552 if (tracker == nullptr) {
Daniel Drown0da73fc2012-06-20 16:51:39 -0500553 ALOGE("clatd already stopped");
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900554 return -ENODEV;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500555 }
556
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900557 ALOGD("Stopping clatd pid=%d on %s", tracker->pid, interface.c_str());
Daniel Drown0da73fc2012-06-20 16:51:39 -0500558
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700559 maybeStopBpf(*tracker);
560
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900561 kill(tracker->pid, SIGTERM);
562 waitpid(tracker->pid, nullptr, 0);
Lorenzo Colitti91fd5802019-06-28 19:22:01 +0900563
564 maybeSetIptablesDropRule(false, tracker->pfx96String, tracker->v6Str);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900565 mClatdTrackers.erase(interface);
Daniel Drown0da73fc2012-06-20 16:51:39 -0500566
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900567 ALOGD("clatd on %s stopped", interface.c_str());
Daniel Drown0da73fc2012-06-20 16:51:39 -0500568
569 return 0;
570}
571
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700572void ClatdController::dump(DumpWriter& dw) {
573 std::lock_guard guard(mutex);
574
575 ScopedIndent clatdIndent(dw);
576 dw.println("ClatdController");
577
578 {
579 ScopedIndent trackerIndent(dw);
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700580 dw.println("Trackers: iif[iface] nat64Prefix v6Addr -> v4Addr v4iif[v4iface] [netId]");
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700581
582 ScopedIndent trackerDetailIndent(dw);
583 for (const auto& pair : mClatdTrackers) {
584 const ClatdTracker& tracker = pair.second;
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700585 dw.println("%u[%s] %s/96 %s -> %s %u[%s] [%u]", tracker.ifIndex, tracker.iface,
586 tracker.pfx96String, tracker.v6Str, tracker.v4Str, tracker.v4ifIndex,
587 tracker.v4iface, tracker.netId);
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700588 }
589 }
590
Maciej Żenczykowskiabb2cbf2019-04-01 01:29:29 -0700591 int mapFd = getClatIngressMapFd();
592 if (mapFd < 0) return; // if unsupported just don't dump anything
593 BpfMap<ClatIngressKey, ClatIngressValue> configMap(mapFd);
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700594
595 ScopedIndent bpfIndent(dw);
596 dw.println("BPF ingress map: iif(iface) nat64Prefix v6Addr -> v4Addr oif(iface)");
597
598 ScopedIndent bpfDetailIndent(dw);
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700599 const auto printClatMap = [&dw](const ClatIngressKey& key, const ClatIngressValue& value,
600 const BpfMap<ClatIngressKey, ClatIngressValue>&) {
601 char iifStr[IFNAMSIZ] = "?";
602 char pfx96Str[INET6_ADDRSTRLEN] = "?";
603 char local6Str[INET6_ADDRSTRLEN] = "?";
604 char local4Str[INET_ADDRSTRLEN] = "?";
605 char oifStr[IFNAMSIZ] = "?";
606
607 if_indextoname(key.iif, iifStr);
608 inet_ntop(AF_INET6, &key.pfx96, pfx96Str, sizeof(pfx96Str));
609 inet_ntop(AF_INET6, &key.local6, local6Str, sizeof(local6Str));
610 inet_ntop(AF_INET, &value.local4, local4Str, sizeof(local4Str));
611 if_indextoname(value.oif, oifStr);
612
613 dw.println("%u(%s) %s/96 %s -> %s %u(%s)", key.iif, iifStr, pfx96Str, local6Str, local4Str,
614 value.oif, oifStr);
615 return netdutils::status::ok;
616 };
617 auto res = configMap.iterateWithValue(printClatMap);
618 if (!isOk(res)) {
619 dw.println("Error printing BPF map: %s", res.msg().c_str());
620 }
621}
622
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900623auto ClatdController::isIpv4AddressFreeFunc = isIpv4AddressFree;
Lorenzo Colitti91fd5802019-06-28 19:22:01 +0900624auto ClatdController::iptablesRestoreFunction = execIptablesRestore;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900625
Lorenzo Colitti7035f222017-02-13 18:29:00 +0900626} // namespace net
627} // namespace android