blob: 551b947c9cf1b08b72c0ad58011db4b53a13c764 [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"
36
37#include "android-base/properties.h"
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -070038#include "android-base/scopeguard.h"
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090039#include "android-base/unique_fd.h"
Maciej Żenczykowski55262712019-03-29 23:44:56 -070040#include "bpf/BpfMap.h"
41#include "netdbpf/bpf_shared.h"
42#include "netdutils/DumpWriter.h"
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090043
44extern "C" {
45#include "netutils/checksum.h"
46}
47
Maciej Żenczykowski55262712019-03-29 23:44:56 -070048#include "ClatUtils.h"
Lorenzo Colitti45d3dd02014-06-09 14:09:20 +090049#include "Fwmark.h"
Paul Jensen84c1d032014-05-30 13:29:41 -040050#include "NetdConstants.h"
51#include "NetworkController.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +090052#include "netid_client.h"
Daniel Drown0da73fc2012-06-20 16:51:39 -050053
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +090054static const char* kClatdPath = "/system/bin/clatd";
55
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090056// For historical reasons, start with 192.0.0.4, and after that, use all subsequent addresses in
57// 192.0.0.0/29 (RFC 7335).
58static const char* kV4AddrString = "192.0.0.4";
59static const in_addr kV4Addr = {inet_addr(kV4AddrString)};
60static const int kV4AddrLen = 29;
61
62using android::base::unique_fd;
Maciej Żenczykowski55262712019-03-29 23:44:56 -070063using android::bpf::BpfMap;
64using android::netdutils::DumpWriter;
65using android::netdutils::ScopedIndent;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090066
Lorenzo Colitti7035f222017-02-13 18:29:00 +090067namespace android {
68namespace net {
69
Maciej Żenczykowski56280272019-03-30 03:32:51 -070070void ClatdController::init(void) {
71 std::lock_guard guard(mutex);
72
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -070073 // TODO: should refactor into separate function for testability
74 if (bpf::getBpfSupportLevel() == bpf::BpfLevel::NONE) {
75 ALOGI("Pre-4.9 kernel or pre-P api shipping level - disabling clat ebpf.");
76 mClatEbpfMode = ClatEbpfDisabled;
77 return;
78 }
79
80 // We know the device initially shipped with at least P...,
81 // but did it ship with at least Q?
82
83 uint64_t api_level = base::GetUintProperty<uint64_t>("ro.product.first_api_level", 0);
84 if (api_level == 0) {
85 ALOGE("Cannot determine initial API level of the device.");
86 api_level = base::GetUintProperty<uint64_t>("ro.build.version.sdk", 0);
87 }
88
89 // Note: MINIMUM_API_REQUIRED is for eBPF as a whole and is thus P
90 if (api_level > bpf::MINIMUM_API_REQUIRED) {
91 ALOGI("4.9+ kernel and device shipped with Q+ - clat ebpf should work.");
92 mClatEbpfMode = ClatEbpfEnabled;
93 } else {
94 // We cannot guarantee that 4.9-P kernels will include NET_CLS_BPF support.
95 ALOGI("4.9+ kernel and device shipped with P - clat ebpf might work.");
96 mClatEbpfMode = ClatEbpfMaybe;
97 }
98
99 int rv = openNetlinkSocket();
100 if (rv < 0) {
101 ALOGE("openNetlinkSocket() failure: %s", strerror(-rv));
102 mClatEbpfMode = ClatEbpfDisabled;
103 return;
104 }
105 mNetlinkFd.reset(rv);
106
107 rv = getClatIngressMapFd();
108 if (rv < 0) {
109 ALOGE("getClatIngressMapFd() failure: %s", strerror(-rv));
110 mClatEbpfMode = ClatEbpfDisabled;
111 mNetlinkFd.reset(-1);
112 return;
113 }
114 mClatIngressMap.reset(rv);
115
116 int netlinkFd = mNetlinkFd.get();
117
118 // TODO: perhaps this initial cleanup should be in its own function?
119 const auto del = [&netlinkFd](const ClatIngressKey& key,
120 const BpfMap<ClatIngressKey, ClatIngressValue>&) {
121 ALOGW("Removing stale clat config on interface %d.", key.iif);
122 int rv = tcQdiscDelDevClsact(netlinkFd, key.iif);
123 if (rv < 0) ALOGE("tcQdiscDelDevClsact() failure: %s", strerror(-rv));
124 return netdutils::status::ok; // keep on going regardless
125 };
126 auto ret = mClatIngressMap.iterate(del);
127 if (!isOk(ret)) ALOGE("mClatIngressMap.iterate() failure: %s", strerror(ret.code()));
128 ret = mClatIngressMap.clear();
129 if (!isOk(ret)) ALOGE("mClatIngressMap.clear() failure: %s", strerror(ret.code()));
130}
131
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900132bool ClatdController::isIpv4AddressFree(in_addr_t addr) {
133 int s = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
134 if (s == -1) {
135 return 0;
136 }
137
138 // Attempt to connect to the address. If the connection succeeds and getsockname returns the
139 // same then the address is already assigned to the system and we can't use it.
140 struct sockaddr_in sin = {.sin_family = AF_INET, .sin_addr = {addr}, .sin_port = 53};
141 socklen_t len = sizeof(sin);
142 bool inuse = connect(s, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
143 getsockname(s, (struct sockaddr*)&sin, &len) == 0 && (size_t)len >= sizeof(sin) &&
144 sin.sin_addr.s_addr == addr;
145
146 close(s);
147 return !inuse;
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +0900148}
Daniel Drown0da73fc2012-06-20 16:51:39 -0500149
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900150// Picks a free IPv4 address, starting from ip and trying all addresses in the prefix in order.
151// ip - the IP address from the configuration file
152// prefixlen - the length of the prefix from which addresses may be selected.
153// returns: the IPv4 address, or INADDR_NONE if no addresses were available
154in_addr_t ClatdController::selectIpv4Address(const in_addr ip, int16_t prefixlen) {
155 // Don't accept prefixes that are too large because we scan addresses one by one.
156 if (prefixlen < 16 || prefixlen > 32) {
157 return INADDR_NONE;
158 }
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +0900159
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900160 // All these are in host byte order.
161 in_addr_t mask = 0xffffffff >> (32 - prefixlen) << (32 - prefixlen);
162 in_addr_t ipv4 = ntohl(ip.s_addr);
163 in_addr_t first_ipv4 = ipv4;
164 in_addr_t prefix = ipv4 & mask;
165
166 // Pick the first IPv4 address in the pool, wrapping around if necessary.
167 // So, for example, 192.0.0.4 -> 192.0.0.5 -> 192.0.0.6 -> 192.0.0.7 -> 192.0.0.0.
168 do {
169 if (isIpv4AddressFreeFunc(htonl(ipv4))) {
170 return htonl(ipv4);
171 }
172 ipv4 = prefix | ((ipv4 + 1) & ~mask);
173 } while (ipv4 != first_ipv4);
174
175 return INADDR_NONE;
176}
177
178// Alters the bits in the IPv6 address to make them checksum neutral with v4 and nat64Prefix.
179void ClatdController::makeChecksumNeutral(in6_addr* v6, const in_addr v4,
180 const in6_addr& nat64Prefix) {
181 // Fill last 8 bytes of IPv6 address with random bits.
182 arc4random_buf(&v6->s6_addr[8], 8);
183
184 // Make the IID checksum-neutral. That is, make it so that:
185 // checksum(Local IPv4 | Remote IPv4) = checksum(Local IPv6 | Remote IPv6)
186 // in other words (because remote IPv6 = NAT64 prefix | Remote IPv4):
187 // checksum(Local IPv4) = checksum(Local IPv6 | NAT64 prefix)
188 // Do this by adjusting the two bytes in the middle of the IID.
189
190 uint16_t middlebytes = (v6->s6_addr[11] << 8) + v6->s6_addr[12];
191
192 uint32_t c1 = ip_checksum_add(0, &v4, sizeof(v4));
193 uint32_t c2 = ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) +
194 ip_checksum_add(0, v6, sizeof(*v6));
195
196 uint16_t delta = ip_checksum_adjust(middlebytes, c1, c2);
197 v6->s6_addr[11] = delta >> 8;
198 v6->s6_addr[12] = delta & 0xff;
199}
200
201// Picks a random interface ID that is checksum neutral with the IPv4 address and the NAT64 prefix.
202int ClatdController::generateIpv6Address(const char* iface, const in_addr v4,
203 const in6_addr& nat64Prefix, in6_addr* v6) {
204 unique_fd s(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
205 if (s == -1) return -errno;
206
207 if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, iface, strlen(iface) + 1) == -1) {
Luke Huang6d301232018-08-01 14:05:18 +0800208 return -errno;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500209 }
210
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900211 sockaddr_in6 sin6 = {.sin6_family = AF_INET6, .sin6_addr = nat64Prefix};
212 if (connect(s, reinterpret_cast<struct sockaddr*>(&sin6), sizeof(sin6)) == -1) {
213 return -errno;
214 }
215
216 socklen_t len = sizeof(sin6);
217 if (getsockname(s, reinterpret_cast<struct sockaddr*>(&sin6), &len) == -1) {
218 return -errno;
219 }
220
221 *v6 = sin6.sin6_addr;
222
223 if (IN6_IS_ADDR_UNSPECIFIED(v6) || IN6_IS_ADDR_LOOPBACK(v6) || IN6_IS_ADDR_LINKLOCAL(v6) ||
224 IN6_IS_ADDR_SITELOCAL(v6) || IN6_IS_ADDR_ULA(v6)) {
225 return -ENETUNREACH;
226 }
227
228 makeChecksumNeutral(v6, v4, nat64Prefix);
229
230 return 0;
231}
232
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700233void ClatdController::maybeStartBpf(const ClatdTracker& tracker) {
234 if (mClatEbpfMode == ClatEbpfDisabled) return;
235
236 int rv = hardwareAddressType(tracker.iface);
237 if (rv < 0) {
238 ALOGE("hardwareAddressType(%s[%d]) failure: %s", tracker.iface, tracker.ifIndex,
239 strerror(-rv));
240 return;
241 }
242
243 bool isEthernet;
244 switch (rv) {
245 case ARPHRD_ETHER:
246 isEthernet = true;
247 break;
248 case ARPHRD_RAWIP: // in Linux 4.14+ rmnet support was upstreamed and this is 519
249 case 530: // this is ARPHRD_RAWIP on some Android 4.9 kernels with rmnet
250 isEthernet = false;
251 break;
252 default:
253 ALOGE("hardwareAddressType(%s[%d]) returned unknown type %d.", tracker.iface,
254 tracker.ifIndex, rv);
255 return;
256 }
257
258 rv = getClatIngressProgFd(isEthernet);
259 if (rv < 0) {
260 ALOGE("getClatIngressProgFd(%d) failure: %s", isEthernet, strerror(-rv));
261 return;
262 }
263 unique_fd progFd(rv);
264
265 ClatIngressKey key = {
266 .iif = tracker.ifIndex,
267 .pfx96 = tracker.pfx96,
268 .local6 = tracker.v6,
269 };
270 ClatIngressValue value = {
271 // Redirect the mangled packets to the same interface so we can see them in tcpdump.
272 // TODO: move the tun interface creation to netd, and use that ifindex instead.
273 // TODO: move all the clat code to eBPF and remove the tun interface entirely.
274 .oif = tracker.ifIndex,
275 .local4 = tracker.v4,
276 };
277
278 auto ret = mClatIngressMap.writeValue(key, value, BPF_ANY);
279 if (!isOk(ret)) {
280 ALOGE("mClatIngress.Map.writeValue failure: %s", strerror(ret.code()));
281 return;
282 }
283
284 // We do tc setup *after* populating map, so scanning through map
285 // can always be used to tell us what needs cleanup.
286
287 rv = tcQdiscAddDevClsact(mNetlinkFd, tracker.ifIndex);
288 if (rv) {
289 ALOGE("tcQdiscAddDevClsact(%d[%s]) failure: %s", tracker.ifIndex, tracker.iface,
290 strerror(-rv));
291 ret = mClatIngressMap.deleteValue(key);
292 if (!isOk(ret)) ALOGE("mClatIngressMap.deleteValue failure: %s", strerror(ret.code()));
293 return;
294 }
295
296 rv = tcFilterAddDevBpf(mNetlinkFd, tracker.ifIndex, progFd, isEthernet);
297 if (rv) {
298 if ((rv == -ENOENT) && (mClatEbpfMode == ClatEbpfMaybe)) {
299 ALOGI("tcFilterAddDevBpf(%d[%s], %d): %s", tracker.ifIndex, tracker.iface, isEthernet,
300 strerror(-rv));
301 } else {
302 ALOGE("tcFilterAddDevBpf(%d[%s], %d) failure: %s", tracker.ifIndex, tracker.iface,
303 isEthernet, strerror(-rv));
304 }
305 rv = tcQdiscDelDevClsact(mNetlinkFd, tracker.ifIndex);
306 if (rv)
307 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", tracker.ifIndex, tracker.iface,
308 strerror(-rv));
309 ret = mClatIngressMap.deleteValue(key);
310 if (!isOk(ret)) ALOGE("mClatIngressMap.deleteValue failure: %s", strerror(ret.code()));
311 return;
312 }
313
314 // success
315}
316
317void ClatdController::maybeStopBpf(const ClatdTracker& tracker) {
318 if (mClatEbpfMode == ClatEbpfDisabled) return;
319
320 // No need to remove filter, since we remove qdisc it is attached to,
321 // which automatically removes everything attached to the qdisc.
322 int rv = tcQdiscDelDevClsact(mNetlinkFd, tracker.ifIndex);
323 if (rv < 0)
324 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", tracker.ifIndex, tracker.iface,
325 strerror(-rv));
326
327 // We cleanup map last, so scanning through map can be used to
328 // determine what still needs cleanup.
329
330 ClatIngressKey key = {
331 .iif = tracker.ifIndex,
332 .pfx96 = tracker.pfx96,
333 .local6 = tracker.v6,
334 };
335
336 auto ret = mClatIngressMap.deleteValue(key);
337 if (!isOk(ret)) ALOGE("mClatIngressMap.deleteValue failure: %s", strerror(ret.code()));
338}
339
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900340// Finds the tracker of the clatd running on interface |interface|, or nullptr if clatd has not been
341// started on |interface|.
342ClatdController::ClatdTracker* ClatdController::getClatdTracker(const std::string& interface) {
343 auto it = mClatdTrackers.find(interface);
344 return (it == mClatdTrackers.end() ? nullptr : &it->second);
345}
346
347// Initializes a ClatdTracker for the specified interface.
Maciej Żenczykowskia56b2e62019-04-24 13:17:18 -0700348int ClatdController::ClatdTracker::init(unsigned networkId, const std::string& interface,
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900349 const std::string& nat64Prefix) {
Maciej Żenczykowskia56b2e62019-04-24 13:17:18 -0700350 netId = networkId;
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900351
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900352 fwmark.netId = netId;
353 fwmark.explicitlySelected = true;
354 fwmark.protectedFromVpn = true;
355 fwmark.permission = PERMISSION_SYSTEM;
356
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900357 snprintf(fwmarkString, sizeof(fwmarkString), "0x%x", fwmark.intValue);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900358 snprintf(netIdString, sizeof(netIdString), "%u", netId);
359 strlcpy(iface, interface.c_str(), sizeof(iface));
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700360 ifIndex = if_nametoindex(iface);
361 snprintf(v4iface, sizeof(v4iface), "v4-%s", iface);
362 v4ifIndex = if_nametoindex(v4iface);
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900363
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900364 // Pass in everything that clatd needs: interface, a netid to use for DNS lookups, a fwmark for
365 // outgoing packets, the NAT64 prefix, and the IPv4 and IPv6 addresses.
366 // Validate the prefix and strip off the prefix length.
367 uint8_t family;
368 uint8_t prefixLen;
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700369 int res = parsePrefix(nat64Prefix.c_str(), &family, &pfx96, sizeof(pfx96), &prefixLen);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900370 // clatd only supports /96 prefixes.
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700371 if (res != sizeof(pfx96)) return res;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900372 if (family != AF_INET6) return -EAFNOSUPPORT;
373 if (prefixLen != 96) return -EINVAL;
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700374 if (!inet_ntop(AF_INET6, &pfx96, pfx96String, sizeof(pfx96String))) return -errno;
Luke Huang6d301232018-08-01 14:05:18 +0800375
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900376 // Pick an IPv4 address.
377 // TODO: this picks the address based on other addresses that are assigned to interfaces, but
378 // the address is only actually assigned to an interface once clatd starts up. So we could end
379 // up with two clatd instances with the same IPv4 address.
380 // Stop doing this and instead pick a free one from the kV4Addr pool.
Maciej Żenczykowski55cacfb2019-03-30 02:01:35 -0700381 v4 = {selectIpv4Address(kV4Addr, kV4AddrLen)};
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900382 if (v4.s_addr == INADDR_NONE) {
383 ALOGE("No free IPv4 address in %s/%d", kV4AddrString, kV4AddrLen);
384 return -EADDRNOTAVAIL;
385 }
386 if (!inet_ntop(AF_INET, &v4, v4Str, sizeof(v4Str))) return -errno;
387
388 // Generate a checksum-neutral IID.
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700389 if (generateIpv6Address(iface, v4, pfx96, &v6)) {
390 ALOGE("Unable to find global source address on %s for %s", iface, pfx96String);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900391 return -EADDRNOTAVAIL;
392 }
393 if (!inet_ntop(AF_INET6, &v6, v6Str, sizeof(v6Str))) return -errno;
394
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700395 ALOGD("starting clatd on %s v4=%s v6=%s pfx96=%s", iface, v4Str, v6Str, pfx96String);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900396 return 0;
397}
398
399int ClatdController::startClatd(const std::string& interface, const std::string& nat64Prefix,
400 std::string* v6Str) {
Maciej Żenczykowski56280272019-03-30 03:32:51 -0700401 std::lock_guard guard(mutex);
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700402
403 // 1. fail if pre-existing tracker already exists
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900404 ClatdTracker* existing = getClatdTracker(interface);
405 if (existing != nullptr) {
406 ALOGE("clatd pid=%d already started on %s", existing->pid, interface.c_str());
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700407 return -EBUSY;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900408 }
409
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700410 // 2. get network id associated with this external interface
Maciej Żenczykowskia56b2e62019-04-24 13:17:18 -0700411 unsigned networkId = mNetCtrl->getNetworkForInterface(interface.c_str());
412 if (networkId == NETID_UNSET) {
413 ALOGE("Interface %s not assigned to any netId", interface.c_str());
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700414 return -ENODEV;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900415 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700416
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700417 // 3. open the tun device in non blocking mode as required by clatd
418 int res = open("/dev/tun", O_RDWR | O_NONBLOCK | O_CLOEXEC);
419 if (res == -1) {
420 res = errno;
421 ALOGE("open of tun device failed (%s)", strerror(res));
422 return -res;
423 }
424 unique_fd tmpTunFd(res);
425
426 // 4. create the v4-... tun interface
427 struct ifreq ifr = {
428 .ifr_flags = IFF_TUN,
429 };
430 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "v4-%s", interface.c_str());
431
432 res = ioctl(tmpTunFd, TUNSETIFF, &ifr, sizeof(ifr));
433 if (res == -1) {
434 res = errno;
435 ALOGE("ioctl(TUNSETIFF) failed (%s)", strerror(res));
436 return -res;
437 }
438
439 // 5. initialize tracker object
Maciej Żenczykowskia56b2e62019-04-24 13:17:18 -0700440 ClatdTracker tracker;
441 int ret = tracker.init(networkId, interface, nat64Prefix);
442 if (ret) return ret;
443
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700444 // 6. create a throwaway socket to reserve a file descriptor number
445 res = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
446 if (res == -1) {
447 res = errno;
448 ALOGE("socket(ipv6/udp) failed (%s)", strerror(res));
449 return -res;
450 }
451 unique_fd passedTunFd(res);
452
453 // 7. this is the FD we'll pass to clatd on the cli, so need it as a string
454 char passedTunFdStr[INT32_STRLEN];
455 snprintf(passedTunFdStr, sizeof(passedTunFdStr), "%d", passedTunFd.get());
456
457 // 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 +0900458 std::string progname("clatd-");
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900459 progname += tracker.iface;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500460
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900461 // clang-format off
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700462 const char* args[] = {progname.c_str(),
463 "-i", tracker.iface,
464 "-n", tracker.netIdString,
465 "-m", tracker.fwmarkString,
466 "-p", tracker.pfx96String,
467 "-4", tracker.v4Str,
468 "-6", tracker.v6Str,
469 "-t", passedTunFdStr,
470 nullptr};
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900471 // clang-format on
472
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700473 // 9. register vfork requirement
474 posix_spawnattr_t attr;
475 res = posix_spawnattr_init(&attr);
476 if (res) {
477 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
478 return -res;
479 }
480 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
481 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
482 if (res) {
483 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
484 return -res;
485 }
486
487 // 10. register dup2() action: this is what 'clears' the CLOEXEC flag
488 // on the tun fd that we want the child clatd process to inherit
489 // (this will happen after the vfork, and before the execve)
490 posix_spawn_file_actions_t fa;
491 res = posix_spawn_file_actions_init(&fa);
492 if (res) {
493 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
494 return -res;
495 }
496 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
497 res = posix_spawn_file_actions_adddup2(&fa, tmpTunFd, passedTunFd);
498 if (res) {
499 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
500 return -res;
501 }
502
503 // 11. actually perform vfork/dup2/execve
504 res = posix_spawn(&tracker.pid, kClatdPath, &fa, &attr, (char* const*)args, nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800505 if (res) {
506 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang6d301232018-08-01 14:05:18 +0800507 return -res;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500508 }
509
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700510 // 12. configure eBPF offload - if possible
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700511 maybeStartBpf(tracker);
512
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900513 mClatdTrackers[interface] = tracker;
514 ALOGD("clatd started on %s", interface.c_str());
Daniel Drown0da73fc2012-06-20 16:51:39 -0500515
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900516 *v6Str = tracker.v6Str;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500517 return 0;
518}
519
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900520int ClatdController::stopClatd(const std::string& interface) {
Maciej Żenczykowski56280272019-03-30 03:32:51 -0700521 std::lock_guard guard(mutex);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900522 ClatdTracker* tracker = getClatdTracker(interface);
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +0900523
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900524 if (tracker == nullptr) {
Daniel Drown0da73fc2012-06-20 16:51:39 -0500525 ALOGE("clatd already stopped");
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900526 return -ENODEV;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500527 }
528
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900529 ALOGD("Stopping clatd pid=%d on %s", tracker->pid, interface.c_str());
Daniel Drown0da73fc2012-06-20 16:51:39 -0500530
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700531 maybeStopBpf(*tracker);
532
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900533 kill(tracker->pid, SIGTERM);
534 waitpid(tracker->pid, nullptr, 0);
535 mClatdTrackers.erase(interface);
Daniel Drown0da73fc2012-06-20 16:51:39 -0500536
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900537 ALOGD("clatd on %s stopped", interface.c_str());
Daniel Drown0da73fc2012-06-20 16:51:39 -0500538
539 return 0;
540}
541
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700542void ClatdController::dump(DumpWriter& dw) {
543 std::lock_guard guard(mutex);
544
545 ScopedIndent clatdIndent(dw);
546 dw.println("ClatdController");
547
548 {
549 ScopedIndent trackerIndent(dw);
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700550 dw.println("Trackers: iif[iface] nat64Prefix v6Addr -> v4Addr v4iif[v4iface] [netId]");
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700551
552 ScopedIndent trackerDetailIndent(dw);
553 for (const auto& pair : mClatdTrackers) {
554 const ClatdTracker& tracker = pair.second;
Maciej Żenczykowskif4b44fe2019-04-08 16:18:50 -0700555 dw.println("%u[%s] %s/96 %s -> %s %u[%s] [%u]", tracker.ifIndex, tracker.iface,
556 tracker.pfx96String, tracker.v6Str, tracker.v4Str, tracker.v4ifIndex,
557 tracker.v4iface, tracker.netId);
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700558 }
559 }
560
Maciej Żenczykowskiabb2cbf2019-04-01 01:29:29 -0700561 int mapFd = getClatIngressMapFd();
562 if (mapFd < 0) return; // if unsupported just don't dump anything
563 BpfMap<ClatIngressKey, ClatIngressValue> configMap(mapFd);
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700564
565 ScopedIndent bpfIndent(dw);
566 dw.println("BPF ingress map: iif(iface) nat64Prefix v6Addr -> v4Addr oif(iface)");
567
568 ScopedIndent bpfDetailIndent(dw);
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700569 const auto printClatMap = [&dw](const ClatIngressKey& key, const ClatIngressValue& value,
570 const BpfMap<ClatIngressKey, ClatIngressValue>&) {
571 char iifStr[IFNAMSIZ] = "?";
572 char pfx96Str[INET6_ADDRSTRLEN] = "?";
573 char local6Str[INET6_ADDRSTRLEN] = "?";
574 char local4Str[INET_ADDRSTRLEN] = "?";
575 char oifStr[IFNAMSIZ] = "?";
576
577 if_indextoname(key.iif, iifStr);
578 inet_ntop(AF_INET6, &key.pfx96, pfx96Str, sizeof(pfx96Str));
579 inet_ntop(AF_INET6, &key.local6, local6Str, sizeof(local6Str));
580 inet_ntop(AF_INET, &value.local4, local4Str, sizeof(local4Str));
581 if_indextoname(value.oif, oifStr);
582
583 dw.println("%u(%s) %s/96 %s -> %s %u(%s)", key.iif, iifStr, pfx96Str, local6Str, local4Str,
584 value.oif, oifStr);
585 return netdutils::status::ok;
586 };
587 auto res = configMap.iterateWithValue(printClatMap);
588 if (!isOk(res)) {
589 dw.println("Error printing BPF map: %s", res.msg().c_str());
590 }
591}
592
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900593auto ClatdController::isIpv4AddressFreeFunc = isIpv4AddressFree;
594
Lorenzo Colitti7035f222017-02-13 18:29:00 +0900595} // namespace net
596} // namespace android