network_helpers.c 10.0 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2 3
#define _GNU_SOURCE

4 5 6 7 8
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
9
#include <sched.h>
10

11
#include <arpa/inet.h>
12 13
#include <sys/mount.h>
#include <sys/stat.h>
14

15 16 17
#include <linux/err.h>
#include <linux/in.h>
#include <linux/in6.h>
18
#include <linux/limits.h>
19

20
#include "bpf_util.h"
21
#include "network_helpers.h"
22
#include "test_progs.h"
23

24 25 26 27
#ifndef IPPROTO_MPTCP
#define IPPROTO_MPTCP 262
#endif

28
#define clean_errno() (errno == 0 ? "None" : strerror(errno))
29 30 31 32 33 34 35
#define log_err(MSG, ...) ({						\
			int __save = errno;				\
			fprintf(stderr, "(%s:%d: errno: %s) " MSG "\n", \
				__FILE__, __LINE__, clean_errno(),	\
				##__VA_ARGS__);				\
			errno = __save;					\
})
36

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
struct ipv4_packet pkt_v4 = {
	.eth.h_proto = __bpf_constant_htons(ETH_P_IP),
	.iph.ihl = 5,
	.iph.protocol = IPPROTO_TCP,
	.iph.tot_len = __bpf_constant_htons(MAGIC_BYTES),
	.tcp.urg_ptr = 123,
	.tcp.doff = 5,
};

struct ipv6_packet pkt_v6 = {
	.eth.h_proto = __bpf_constant_htons(ETH_P_IPV6),
	.iph.nexthdr = IPPROTO_TCP,
	.iph.payload_len = __bpf_constant_htons(MAGIC_BYTES),
	.tcp.urg_ptr = 123,
	.tcp.doff = 5,
};

54
int settimeo(int fd, int timeout_ms)
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
{
	struct timeval timeout = { .tv_sec = 3 };

	if (timeout_ms > 0) {
		timeout.tv_sec = timeout_ms / 1000;
		timeout.tv_usec = (timeout_ms % 1000) * 1000;
	}

	if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout,
		       sizeof(timeout))) {
		log_err("Failed to set SO_RCVTIMEO");
		return -1;
	}

	if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout,
		       sizeof(timeout))) {
		log_err("Failed to set SO_SNDTIMEO");
		return -1;
	}

	return 0;
}

#define save_errno_close(fd) ({ int __save = errno; close(fd); errno = __save; })

80
static int __start_server(int type, int protocol, const struct sockaddr *addr,
81
			  socklen_t addrlen, int timeout_ms, bool reuseport)
82
{
83
	int on = 1;
84 85
	int fd;

86
	fd = socket(addr->sa_family, type, protocol);
87 88 89 90 91
	if (fd < 0) {
		log_err("Failed to create server socket");
		return -1;
	}

92 93 94
	if (settimeo(fd, timeout_ms))
		goto error_close;

95 96 97 98 99 100 101
	if (reuseport &&
	    setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on))) {
		log_err("Failed to set SO_REUSEPORT");
		return -1;
	}

	if (bind(fd, addr, addrlen) < 0) {
102
		log_err("Failed to bind socket");
103
		goto error_close;
104 105 106 107 108
	}

	if (type == SOCK_STREAM) {
		if (listen(fd, 1) < 0) {
			log_err("Failed to listed on socket");
109
			goto error_close;
110 111 112 113 114
		}
	}

	return fd;

115 116 117
error_close:
	save_errno_close(fd);
	return -1;
118 119
}

120 121
static int start_server_proto(int family, int type, int protocol,
			      const char *addr_str, __u16 port, int timeout_ms)
122 123 124 125 126 127 128
{
	struct sockaddr_storage addr;
	socklen_t addrlen;

	if (make_sockaddr(family, addr_str, port, &addr, &addrlen))
		return -1;

129
	return __start_server(type, protocol, (struct sockaddr *)&addr,
130 131 132
			      addrlen, timeout_ms, false);
}

133 134 135 136 137 138 139 140 141 142 143 144 145
int start_server(int family, int type, const char *addr_str, __u16 port,
		 int timeout_ms)
{
	return start_server_proto(family, type, 0, addr_str, port, timeout_ms);
}

int start_mptcp_server(int family, const char *addr_str, __u16 port,
		       int timeout_ms)
{
	return start_server_proto(family, SOCK_STREAM, IPPROTO_MPTCP, addr_str,
				  port, timeout_ms);
}

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
int *start_reuseport_server(int family, int type, const char *addr_str,
			    __u16 port, int timeout_ms, unsigned int nr_listens)
{
	struct sockaddr_storage addr;
	unsigned int nr_fds = 0;
	socklen_t addrlen;
	int *fds;

	if (!nr_listens)
		return NULL;

	if (make_sockaddr(family, addr_str, port, &addr, &addrlen))
		return NULL;

	fds = malloc(sizeof(*fds) * nr_listens);
	if (!fds)
		return NULL;

164
	fds[0] = __start_server(type, 0, (struct sockaddr *)&addr, addrlen,
165 166 167 168 169 170 171 172 173
				timeout_ms, true);
	if (fds[0] == -1)
		goto close_fds;
	nr_fds = 1;

	if (getsockname(fds[0], (struct sockaddr *)&addr, &addrlen))
		goto close_fds;

	for (; nr_fds < nr_listens; nr_fds++) {
174
		fds[nr_fds] = __start_server(type, 0, (struct sockaddr *)&addr,
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
					     addrlen, timeout_ms, true);
		if (fds[nr_fds] == -1)
			goto close_fds;
	}

	return fds;

close_fds:
	free_fds(fds, nr_fds);
	return NULL;
}

void free_fds(int *fds, unsigned int nr_close_fds)
{
	if (fds) {
		while (nr_close_fds)
			close(fds[--nr_close_fds]);
		free(fds);
	}
}

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
int fastopen_connect(int server_fd, const char *data, unsigned int data_len,
		     int timeout_ms)
{
	struct sockaddr_storage addr;
	socklen_t addrlen = sizeof(addr);
	struct sockaddr_in *addr_in;
	int fd, ret;

	if (getsockname(server_fd, (struct sockaddr *)&addr, &addrlen)) {
		log_err("Failed to get server addr");
		return -1;
	}

	addr_in = (struct sockaddr_in *)&addr;
	fd = socket(addr_in->sin_family, SOCK_STREAM, 0);
	if (fd < 0) {
		log_err("Failed to create client socket");
		return -1;
	}

	if (settimeo(fd, timeout_ms))
		goto error_close;

	ret = sendto(fd, data, data_len, MSG_FASTOPEN, (struct sockaddr *)&addr,
		     addrlen);
	if (ret != data_len) {
		log_err("sendto(data, %u) != %d\n", data_len, ret);
		goto error_close;
	}

	return fd;

error_close:
	save_errno_close(fd);
	return -1;
}

233 234
static int connect_fd_to_addr(int fd,
			      const struct sockaddr_storage *addr,
235
			      socklen_t addrlen, const bool must_fail)
236
{
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
	int ret;

	errno = 0;
	ret = connect(fd, (const struct sockaddr *)addr, addrlen);
	if (must_fail) {
		if (!ret) {
			log_err("Unexpected success to connect to server");
			return -1;
		}
		if (errno != EPERM) {
			log_err("Unexpected error from connect to server");
			return -1;
		}
	} else {
		if (ret) {
			log_err("Failed to connect to server");
			return -1;
		}
255 256
	}

257
	return 0;
258 259
}

260 261 262
static const struct network_helper_opts default_opts;

int connect_to_fd_opts(int server_fd, const struct network_helper_opts *opts)
263 264
{
	struct sockaddr_storage addr;
265 266
	struct sockaddr_in *addr_in;
	socklen_t addrlen, optlen;
267
	int fd, type, protocol;
268

269 270 271
	if (!opts)
		opts = &default_opts;

272 273 274
	optlen = sizeof(type);
	if (getsockopt(server_fd, SOL_SOCKET, SO_TYPE, &type, &optlen)) {
		log_err("getsockopt(SOL_TYPE)");
275
		return -1;
276 277
	}

278 279 280 281 282
	if (getsockopt(server_fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &optlen)) {
		log_err("getsockopt(SOL_PROTOCOL)");
		return -1;
	}

283 284
	addrlen = sizeof(addr);
	if (getsockname(server_fd, (struct sockaddr *)&addr, &addrlen)) {
285
		log_err("Failed to get server addr");
286
		return -1;
287 288
	}

289
	addr_in = (struct sockaddr_in *)&addr;
290
	fd = socket(addr_in->sin_family, type, protocol);
291 292
	if (fd < 0) {
		log_err("Failed to create client socket");
293
		return -1;
294 295
	}

296 297 298 299 300 301
	if (settimeo(fd, opts->timeout_ms))
		goto error_close;

	if (opts->cc && opts->cc[0] &&
	    setsockopt(fd, SOL_TCP, TCP_CONGESTION, opts->cc,
		       strlen(opts->cc) + 1))
302 303
		goto error_close;

304
	if (connect_fd_to_addr(fd, &addr, addrlen, opts->must_fail))
305 306 307 308 309 310 311
		goto error_close;

	return fd;

error_close:
	save_errno_close(fd);
	return -1;
312 313
}

314 315 316 317 318 319 320 321 322
int connect_to_fd(int server_fd, int timeout_ms)
{
	struct network_helper_opts opts = {
		.timeout_ms = timeout_ms,
	};

	return connect_to_fd_opts(server_fd, &opts);
}

323
int connect_fd_to_fd(int client_fd, int server_fd, int timeout_ms)
324
{
325 326
	struct sockaddr_storage addr;
	socklen_t len = sizeof(addr);
327

328
	if (settimeo(client_fd, timeout_ms))
329 330
		return -1;

331 332
	if (getsockname(server_fd, (struct sockaddr *)&addr, &len)) {
		log_err("Failed to get server addr");
333 334 335
		return -1;
	}

336
	if (connect_fd_to_addr(client_fd, &addr, len, false))
337
		return -1;
338

339
	return 0;
340
}
341 342 343 344 345 346 347

int make_sockaddr(int family, const char *addr_str, __u16 port,
		  struct sockaddr_storage *addr, socklen_t *len)
{
	if (family == AF_INET) {
		struct sockaddr_in *sin = (void *)addr;

348
		memset(addr, 0, sizeof(*sin));
349 350 351 352 353 354 355 356 357 358 359 360 361
		sin->sin_family = AF_INET;
		sin->sin_port = htons(port);
		if (addr_str &&
		    inet_pton(AF_INET, addr_str, &sin->sin_addr) != 1) {
			log_err("inet_pton(AF_INET, %s)", addr_str);
			return -1;
		}
		if (len)
			*len = sizeof(*sin);
		return 0;
	} else if (family == AF_INET6) {
		struct sockaddr_in6 *sin6 = (void *)addr;

362
		memset(addr, 0, sizeof(*sin6));
363 364 365 366 367 368 369 370 371 372 373 374 375
		sin6->sin6_family = AF_INET6;
		sin6->sin6_port = htons(port);
		if (addr_str &&
		    inet_pton(AF_INET6, addr_str, &sin6->sin6_addr) != 1) {
			log_err("inet_pton(AF_INET6, %s)", addr_str);
			return -1;
		}
		if (len)
			*len = sizeof(*sin6);
		return 0;
	}
	return -1;
}
376 377 378 379 380 381 382 383 384 385 386 387

char *ping_command(int family)
{
	if (family == AF_INET6) {
		/* On some systems 'ping' doesn't support IPv6, so use ping6 if it is present. */
		if (!system("which ping6 >/dev/null 2>&1"))
			return "ping6";
		else
			return "ping -6";
	}
	return "ping";
}
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

struct nstoken {
	int orig_netns_fd;
};

static int setns_by_fd(int nsfd)
{
	int err;

	err = setns(nsfd, CLONE_NEWNET);
	close(nsfd);

	if (!ASSERT_OK(err, "setns"))
		return err;

	/* Switch /sys to the new namespace so that e.g. /sys/class/net
	 * reflects the devices in the new namespace.
	 */
	err = unshare(CLONE_NEWNS);
	if (!ASSERT_OK(err, "unshare"))
		return err;

	/* Make our /sys mount private, so the following umount won't
	 * trigger the global umount in case it's shared.
	 */
	err = mount("none", "/sys", NULL, MS_PRIVATE, NULL);
	if (!ASSERT_OK(err, "remount private /sys"))
		return err;

	err = umount2("/sys", MNT_DETACH);
	if (!ASSERT_OK(err, "umount2 /sys"))
		return err;

	err = mount("sysfs", "/sys", "sysfs", 0, NULL);
	if (!ASSERT_OK(err, "mount /sys"))
		return err;

	err = mount("bpffs", "/sys/fs/bpf", "bpf", 0, NULL);
	if (!ASSERT_OK(err, "mount /sys/fs/bpf"))
		return err;

	return 0;
}

struct nstoken *open_netns(const char *name)
{
	int nsfd;
	char nspath[PATH_MAX];
	int err;
	struct nstoken *token;

	token = malloc(sizeof(struct nstoken));
	if (!ASSERT_OK_PTR(token, "malloc token"))
		return NULL;

	token->orig_netns_fd = open("/proc/self/ns/net", O_RDONLY);
	if (!ASSERT_GE(token->orig_netns_fd, 0, "open /proc/self/ns/net"))
		goto fail;

	snprintf(nspath, sizeof(nspath), "%s/%s", "/var/run/netns", name);
	nsfd = open(nspath, O_RDONLY | O_CLOEXEC);
	if (!ASSERT_GE(nsfd, 0, "open netns fd"))
		goto fail;

	err = setns_by_fd(nsfd);
	if (!ASSERT_OK(err, "setns_by_fd"))
		goto fail;

	return token;
fail:
	free(token);
	return NULL;
}

void close_netns(struct nstoken *token)
{
	ASSERT_OK(setns_by_fd(token->orig_netns_fd), "setns_by_fd");
	free(token);
}