1 // SPDX-License-Identifier: GPL-2.0-only
2 #define _GNU_SOURCE
3
4 #include <errno.h>
5 #include <stdbool.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <sched.h>
10
11 #include <arpa/inet.h>
12 #include <sys/mount.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <sys/un.h>
16 #include <sys/eventfd.h>
17
18 #include <linux/err.h>
19 #include <linux/in.h>
20 #include <linux/in6.h>
21 #include <linux/limits.h>
22
23 #include <linux/ip.h>
24 #include <netinet/udp.h>
25 #include <netinet/tcp.h>
26 #include <net/if.h>
27
28 #include "bpf_util.h"
29 #include "network_helpers.h"
30 #include "test_progs.h"
31
32 #ifdef TRAFFIC_MONITOR
33 /* Prevent pcap.h from including pcap/bpf.h and causing conflicts */
34 #define PCAP_DONT_INCLUDE_PCAP_BPF_H 1
35 #include <pcap/pcap.h>
36 #include <pcap/dlt.h>
37 #endif
38
39 #ifndef IPPROTO_MPTCP
40 #define IPPROTO_MPTCP 262
41 #endif
42
43 #define clean_errno() (errno == 0 ? "None" : strerror(errno))
44 #define log_err(MSG, ...) ({ \
45 int __save = errno; \
46 fprintf(stderr, "(%s:%d: errno: %s) " MSG "\n", \
47 __FILE__, __LINE__, clean_errno(), \
48 ##__VA_ARGS__); \
49 errno = __save; \
50 })
51
52 struct ipv4_packet pkt_v4 = {
53 .eth.h_proto = __bpf_constant_htons(ETH_P_IP),
54 .iph.ihl = 5,
55 .iph.protocol = IPPROTO_TCP,
56 .iph.tot_len = __bpf_constant_htons(MAGIC_BYTES),
57 .tcp.urg_ptr = 123,
58 .tcp.doff = 5,
59 };
60
61 struct ipv6_packet pkt_v6 = {
62 .eth.h_proto = __bpf_constant_htons(ETH_P_IPV6),
63 .iph.nexthdr = IPPROTO_TCP,
64 .iph.payload_len = __bpf_constant_htons(MAGIC_BYTES),
65 .tcp.urg_ptr = 123,
66 .tcp.doff = 5,
67 };
68
69 static const struct network_helper_opts default_opts;
70
settimeo(int fd,int timeout_ms)71 int settimeo(int fd, int timeout_ms)
72 {
73 struct timeval timeout = { .tv_sec = 3 };
74
75 if (timeout_ms > 0) {
76 timeout.tv_sec = timeout_ms / 1000;
77 timeout.tv_usec = (timeout_ms % 1000) * 1000;
78 }
79
80 if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout,
81 sizeof(timeout))) {
82 log_err("Failed to set SO_RCVTIMEO");
83 return -1;
84 }
85
86 if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout,
87 sizeof(timeout))) {
88 log_err("Failed to set SO_SNDTIMEO");
89 return -1;
90 }
91
92 return 0;
93 }
94
95 #define save_errno_close(fd) ({ int __save = errno; close(fd); errno = __save; })
96
start_server_addr(int type,const struct sockaddr_storage * addr,socklen_t addrlen,const struct network_helper_opts * opts)97 int start_server_addr(int type, const struct sockaddr_storage *addr, socklen_t addrlen,
98 const struct network_helper_opts *opts)
99 {
100 int on = 1, fd;
101
102 if (!opts)
103 opts = &default_opts;
104
105 fd = socket(addr->ss_family, type, opts->proto);
106 if (fd < 0) {
107 log_err("Failed to create server socket");
108 return -1;
109 }
110
111 if (settimeo(fd, opts->timeout_ms))
112 goto error_close;
113
114 if ((type & SOCK_TYPE_MASK) == SOCK_STREAM &&
115 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) {
116 log_err("Failed to enable SO_REUSEADDR");
117 goto error_close;
118 }
119
120 if (opts->post_socket_cb &&
121 opts->post_socket_cb(fd, opts->cb_opts)) {
122 log_err("Failed to call post_socket_cb");
123 goto error_close;
124 }
125
126 if (bind(fd, (struct sockaddr *)addr, addrlen) < 0) {
127 log_err("Failed to bind socket");
128 goto error_close;
129 }
130
131 if ((type & SOCK_TYPE_MASK) == SOCK_STREAM) {
132 if (listen(fd, opts->backlog ? MAX(opts->backlog, 0) : 1) < 0) {
133 log_err("Failed to listed on socket");
134 goto error_close;
135 }
136 }
137
138 return fd;
139
140 error_close:
141 save_errno_close(fd);
142 return -1;
143 }
144
start_server_str(int family,int type,const char * addr_str,__u16 port,const struct network_helper_opts * opts)145 int start_server_str(int family, int type, const char *addr_str, __u16 port,
146 const struct network_helper_opts *opts)
147 {
148 struct sockaddr_storage addr;
149 socklen_t addrlen;
150
151 if (!opts)
152 opts = &default_opts;
153
154 if (make_sockaddr(family, addr_str, port, &addr, &addrlen))
155 return -1;
156
157 return start_server_addr(type, &addr, addrlen, opts);
158 }
159
start_server(int family,int type,const char * addr_str,__u16 port,int timeout_ms)160 int start_server(int family, int type, const char *addr_str, __u16 port,
161 int timeout_ms)
162 {
163 struct network_helper_opts opts = {
164 .timeout_ms = timeout_ms,
165 };
166
167 return start_server_str(family, type, addr_str, port, &opts);
168 }
169
reuseport_cb(int fd,void * opts)170 static int reuseport_cb(int fd, void *opts)
171 {
172 int on = 1;
173
174 return setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
175 }
176
start_reuseport_server(int family,int type,const char * addr_str,__u16 port,int timeout_ms,unsigned int nr_listens)177 int *start_reuseport_server(int family, int type, const char *addr_str,
178 __u16 port, int timeout_ms, unsigned int nr_listens)
179 {
180 struct network_helper_opts opts = {
181 .timeout_ms = timeout_ms,
182 .post_socket_cb = reuseport_cb,
183 };
184 struct sockaddr_storage addr;
185 unsigned int nr_fds = 0;
186 socklen_t addrlen;
187 int *fds;
188
189 if (!nr_listens)
190 return NULL;
191
192 if (make_sockaddr(family, addr_str, port, &addr, &addrlen))
193 return NULL;
194
195 fds = malloc(sizeof(*fds) * nr_listens);
196 if (!fds)
197 return NULL;
198
199 fds[0] = start_server_addr(type, &addr, addrlen, &opts);
200 if (fds[0] == -1)
201 goto close_fds;
202 nr_fds = 1;
203
204 if (getsockname(fds[0], (struct sockaddr *)&addr, &addrlen))
205 goto close_fds;
206
207 for (; nr_fds < nr_listens; nr_fds++) {
208 fds[nr_fds] = start_server_addr(type, &addr, addrlen, &opts);
209 if (fds[nr_fds] == -1)
210 goto close_fds;
211 }
212
213 return fds;
214
215 close_fds:
216 free_fds(fds, nr_fds);
217 return NULL;
218 }
219
free_fds(int * fds,unsigned int nr_close_fds)220 void free_fds(int *fds, unsigned int nr_close_fds)
221 {
222 if (fds) {
223 while (nr_close_fds)
224 close(fds[--nr_close_fds]);
225 free(fds);
226 }
227 }
228
fastopen_connect(int server_fd,const char * data,unsigned int data_len,int timeout_ms)229 int fastopen_connect(int server_fd, const char *data, unsigned int data_len,
230 int timeout_ms)
231 {
232 struct sockaddr_storage addr;
233 socklen_t addrlen = sizeof(addr);
234 struct sockaddr_in *addr_in;
235 int fd, ret;
236
237 if (getsockname(server_fd, (struct sockaddr *)&addr, &addrlen)) {
238 log_err("Failed to get server addr");
239 return -1;
240 }
241
242 addr_in = (struct sockaddr_in *)&addr;
243 fd = socket(addr_in->sin_family, SOCK_STREAM, 0);
244 if (fd < 0) {
245 log_err("Failed to create client socket");
246 return -1;
247 }
248
249 if (settimeo(fd, timeout_ms))
250 goto error_close;
251
252 ret = sendto(fd, data, data_len, MSG_FASTOPEN, (struct sockaddr *)&addr,
253 addrlen);
254 if (ret != data_len) {
255 log_err("sendto(data, %u) != %d\n", data_len, ret);
256 goto error_close;
257 }
258
259 return fd;
260
261 error_close:
262 save_errno_close(fd);
263 return -1;
264 }
265
client_socket(int family,int type,const struct network_helper_opts * opts)266 int client_socket(int family, int type,
267 const struct network_helper_opts *opts)
268 {
269 int fd;
270
271 if (!opts)
272 opts = &default_opts;
273
274 fd = socket(family, type, opts->proto);
275 if (fd < 0) {
276 log_err("Failed to create client socket");
277 return -1;
278 }
279
280 if (settimeo(fd, opts->timeout_ms))
281 goto error_close;
282
283 if (opts->post_socket_cb &&
284 opts->post_socket_cb(fd, opts->cb_opts))
285 goto error_close;
286
287 return fd;
288
289 error_close:
290 save_errno_close(fd);
291 return -1;
292 }
293
connect_to_addr(int type,const struct sockaddr_storage * addr,socklen_t addrlen,const struct network_helper_opts * opts)294 int connect_to_addr(int type, const struct sockaddr_storage *addr, socklen_t addrlen,
295 const struct network_helper_opts *opts)
296 {
297 int fd;
298
299 if (!opts)
300 opts = &default_opts;
301
302 fd = client_socket(addr->ss_family, type, opts);
303 if (fd < 0) {
304 log_err("Failed to create client socket");
305 return -1;
306 }
307
308 if (connect(fd, (const struct sockaddr *)addr, addrlen)) {
309 log_err("Failed to connect to server");
310 save_errno_close(fd);
311 return -1;
312 }
313
314 return fd;
315 }
316
connect_to_addr_str(int family,int type,const char * addr_str,__u16 port,const struct network_helper_opts * opts)317 int connect_to_addr_str(int family, int type, const char *addr_str, __u16 port,
318 const struct network_helper_opts *opts)
319 {
320 struct sockaddr_storage addr;
321 socklen_t addrlen;
322
323 if (!opts)
324 opts = &default_opts;
325
326 if (make_sockaddr(family, addr_str, port, &addr, &addrlen))
327 return -1;
328
329 return connect_to_addr(type, &addr, addrlen, opts);
330 }
331
connect_to_fd_opts(int server_fd,const struct network_helper_opts * opts)332 int connect_to_fd_opts(int server_fd, const struct network_helper_opts *opts)
333 {
334 struct sockaddr_storage addr;
335 socklen_t addrlen, optlen;
336 int type;
337
338 if (!opts)
339 opts = &default_opts;
340
341 optlen = sizeof(type);
342 if (getsockopt(server_fd, SOL_SOCKET, SO_TYPE, &type, &optlen)) {
343 log_err("getsockopt(SOL_TYPE)");
344 return -1;
345 }
346
347 addrlen = sizeof(addr);
348 if (getsockname(server_fd, (struct sockaddr *)&addr, &addrlen)) {
349 log_err("Failed to get server addr");
350 return -1;
351 }
352
353 return connect_to_addr(type, &addr, addrlen, opts);
354 }
355
connect_to_fd(int server_fd,int timeout_ms)356 int connect_to_fd(int server_fd, int timeout_ms)
357 {
358 struct network_helper_opts opts = {
359 .timeout_ms = timeout_ms,
360 };
361 socklen_t optlen;
362 int protocol;
363
364 optlen = sizeof(protocol);
365 if (getsockopt(server_fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &optlen)) {
366 log_err("getsockopt(SOL_PROTOCOL)");
367 return -1;
368 }
369 opts.proto = protocol;
370
371 return connect_to_fd_opts(server_fd, &opts);
372 }
373
connect_fd_to_fd(int client_fd,int server_fd,int timeout_ms)374 int connect_fd_to_fd(int client_fd, int server_fd, int timeout_ms)
375 {
376 struct sockaddr_storage addr;
377 socklen_t len = sizeof(addr);
378
379 if (settimeo(client_fd, timeout_ms))
380 return -1;
381
382 if (getsockname(server_fd, (struct sockaddr *)&addr, &len)) {
383 log_err("Failed to get server addr");
384 return -1;
385 }
386
387 if (connect(client_fd, (const struct sockaddr *)&addr, len)) {
388 log_err("Failed to connect to server");
389 return -1;
390 }
391
392 return 0;
393 }
394
make_sockaddr(int family,const char * addr_str,__u16 port,struct sockaddr_storage * addr,socklen_t * len)395 int make_sockaddr(int family, const char *addr_str, __u16 port,
396 struct sockaddr_storage *addr, socklen_t *len)
397 {
398 if (family == AF_INET) {
399 struct sockaddr_in *sin = (void *)addr;
400
401 memset(addr, 0, sizeof(*sin));
402 sin->sin_family = AF_INET;
403 sin->sin_port = htons(port);
404 if (addr_str &&
405 inet_pton(AF_INET, addr_str, &sin->sin_addr) != 1) {
406 log_err("inet_pton(AF_INET, %s)", addr_str);
407 return -1;
408 }
409 if (len)
410 *len = sizeof(*sin);
411 return 0;
412 } else if (family == AF_INET6) {
413 struct sockaddr_in6 *sin6 = (void *)addr;
414
415 memset(addr, 0, sizeof(*sin6));
416 sin6->sin6_family = AF_INET6;
417 sin6->sin6_port = htons(port);
418 if (addr_str &&
419 inet_pton(AF_INET6, addr_str, &sin6->sin6_addr) != 1) {
420 log_err("inet_pton(AF_INET6, %s)", addr_str);
421 return -1;
422 }
423 if (len)
424 *len = sizeof(*sin6);
425 return 0;
426 } else if (family == AF_UNIX) {
427 /*
428 * Note that we always use abstract unix sockets to avoid having
429 * to clean up leftover files.
430 */
431 struct sockaddr_un *sun = (void *)addr;
432
433 memset(addr, 0, sizeof(*sun));
434 sun->sun_family = family;
435 sun->sun_path[0] = 0;
436 strscpy(sun->sun_path + 1, addr_str, sizeof(sun->sun_path) - 1);
437 if (len)
438 *len = offsetof(struct sockaddr_un, sun_path) + 1 + strlen(addr_str);
439 return 0;
440 }
441 return -1;
442 }
443
ping_command(int family)444 char *ping_command(int family)
445 {
446 if (family == AF_INET6) {
447 /* On some systems 'ping' doesn't support IPv6, so use ping6 if it is present. */
448 if (!system("which ping6 >/dev/null 2>&1"))
449 return "ping6";
450 else
451 return "ping -6";
452 }
453 return "ping";
454 }
455
append_tid(char * str,size_t sz)456 int append_tid(char *str, size_t sz)
457 {
458 size_t end;
459
460 if (!str)
461 return -1;
462
463 end = strlen(str);
464 if (end + 8 > sz)
465 return -1;
466
467 sprintf(&str[end], "%07ld", sys_gettid());
468 str[end + 7] = '\0';
469
470 return 0;
471 }
472
remove_netns(const char * name)473 int remove_netns(const char *name)
474 {
475 char *cmd;
476 int r;
477
478 r = asprintf(&cmd, "ip netns del %s >/dev/null 2>&1", name);
479 if (r < 0) {
480 log_err("Failed to malloc cmd");
481 return -1;
482 }
483
484 r = system(cmd);
485 free(cmd);
486 return r;
487 }
488
make_netns(const char * name)489 int make_netns(const char *name)
490 {
491 char *cmd;
492 int r;
493
494 r = asprintf(&cmd, "ip netns add %s", name);
495 if (r < 0) {
496 log_err("Failed to malloc cmd");
497 return -1;
498 }
499
500 r = system(cmd);
501 free(cmd);
502
503 if (r)
504 return r;
505
506 r = asprintf(&cmd, "ip -n %s link set lo up", name);
507 if (r < 0) {
508 log_err("Failed to malloc cmd for setting up lo");
509 remove_netns(name);
510 return -1;
511 }
512
513 r = system(cmd);
514 free(cmd);
515
516 return r;
517 }
518
519 struct nstoken {
520 int orig_netns_fd;
521 };
522
open_netns(const char * name)523 struct nstoken *open_netns(const char *name)
524 {
525 int nsfd;
526 char nspath[PATH_MAX];
527 int err;
528 struct nstoken *token;
529
530 token = calloc(1, sizeof(struct nstoken));
531 if (!token) {
532 log_err("Failed to malloc token");
533 return NULL;
534 }
535
536 token->orig_netns_fd = open("/proc/self/ns/net", O_RDONLY);
537 if (token->orig_netns_fd == -1) {
538 log_err("Failed to open(/proc/self/ns/net)");
539 goto fail;
540 }
541
542 snprintf(nspath, sizeof(nspath), "%s/%s", "/var/run/netns", name);
543 nsfd = open(nspath, O_RDONLY | O_CLOEXEC);
544 if (nsfd == -1) {
545 log_err("Failed to open(%s)", nspath);
546 goto fail;
547 }
548
549 err = setns(nsfd, CLONE_NEWNET);
550 close(nsfd);
551 if (err) {
552 log_err("Failed to setns(nsfd)");
553 goto fail;
554 }
555
556 return token;
557 fail:
558 if (token->orig_netns_fd != -1)
559 close(token->orig_netns_fd);
560 free(token);
561 return NULL;
562 }
563
close_netns(struct nstoken * token)564 void close_netns(struct nstoken *token)
565 {
566 if (!token)
567 return;
568
569 if (setns(token->orig_netns_fd, CLONE_NEWNET))
570 log_err("Failed to setns(orig_netns_fd)");
571 close(token->orig_netns_fd);
572 free(token);
573 }
574
open_tuntap(const char * dev_name,bool need_mac)575 int open_tuntap(const char *dev_name, bool need_mac)
576 {
577 int err = 0;
578 struct ifreq ifr;
579 int fd = open("/dev/net/tun", O_RDWR);
580
581 if (!ASSERT_GE(fd, 0, "open(/dev/net/tun)"))
582 return -1;
583
584 ifr.ifr_flags = IFF_NO_PI | (need_mac ? IFF_TAP : IFF_TUN);
585 strscpy(ifr.ifr_name, dev_name);
586
587 err = ioctl(fd, TUNSETIFF, &ifr);
588 if (!ASSERT_OK(err, "ioctl(TUNSETIFF)")) {
589 close(fd);
590 return -1;
591 }
592
593 err = fcntl(fd, F_SETFL, O_NONBLOCK);
594 if (!ASSERT_OK(err, "fcntl(O_NONBLOCK)")) {
595 close(fd);
596 return -1;
597 }
598
599 return fd;
600 }
601
get_socket_local_port(int sock_fd)602 int get_socket_local_port(int sock_fd)
603 {
604 struct sockaddr_storage addr;
605 socklen_t addrlen = sizeof(addr);
606 int err;
607
608 err = getsockname(sock_fd, (struct sockaddr *)&addr, &addrlen);
609 if (err < 0)
610 return err;
611
612 if (addr.ss_family == AF_INET) {
613 struct sockaddr_in *sin = (struct sockaddr_in *)&addr;
614
615 return sin->sin_port;
616 } else if (addr.ss_family == AF_INET6) {
617 struct sockaddr_in6 *sin = (struct sockaddr_in6 *)&addr;
618
619 return sin->sin6_port;
620 }
621
622 return -1;
623 }
624
get_hw_ring_size(char * ifname,struct ethtool_ringparam * ring_param)625 int get_hw_ring_size(char *ifname, struct ethtool_ringparam *ring_param)
626 {
627 struct ifreq ifr = {0};
628 int sockfd, err;
629
630 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
631 if (sockfd < 0)
632 return -errno;
633
634 memcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
635
636 ring_param->cmd = ETHTOOL_GRINGPARAM;
637 ifr.ifr_data = (char *)ring_param;
638
639 if (ioctl(sockfd, SIOCETHTOOL, &ifr) < 0) {
640 err = errno;
641 close(sockfd);
642 return -err;
643 }
644
645 close(sockfd);
646 return 0;
647 }
648
set_hw_ring_size(char * ifname,struct ethtool_ringparam * ring_param)649 int set_hw_ring_size(char *ifname, struct ethtool_ringparam *ring_param)
650 {
651 struct ifreq ifr = {0};
652 int sockfd, err;
653
654 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
655 if (sockfd < 0)
656 return -errno;
657
658 memcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
659
660 ring_param->cmd = ETHTOOL_SRINGPARAM;
661 ifr.ifr_data = (char *)ring_param;
662
663 if (ioctl(sockfd, SIOCETHTOOL, &ifr) < 0) {
664 err = errno;
665 close(sockfd);
666 return -err;
667 }
668
669 close(sockfd);
670 return 0;
671 }
672
673 struct send_recv_arg {
674 int fd;
675 uint32_t bytes;
676 int stop;
677 };
678
send_recv_server(void * arg)679 static void *send_recv_server(void *arg)
680 {
681 struct send_recv_arg *a = (struct send_recv_arg *)arg;
682 ssize_t nr_sent = 0, bytes = 0;
683 char batch[1500];
684 int err = 0, fd;
685
686 fd = accept(a->fd, NULL, NULL);
687 while (fd == -1) {
688 if (errno == EINTR)
689 continue;
690 err = -errno;
691 goto done;
692 }
693
694 if (settimeo(fd, 0)) {
695 err = -errno;
696 goto done;
697 }
698
699 while (bytes < a->bytes && !READ_ONCE(a->stop)) {
700 nr_sent = send(fd, &batch,
701 MIN(a->bytes - bytes, sizeof(batch)), 0);
702 if (nr_sent == -1 && errno == EINTR)
703 continue;
704 if (nr_sent == -1) {
705 err = -errno;
706 break;
707 }
708 bytes += nr_sent;
709 }
710
711 if (bytes != a->bytes) {
712 log_err("send %zd expected %u", bytes, a->bytes);
713 if (!err)
714 err = bytes > a->bytes ? -E2BIG : -EINTR;
715 }
716
717 done:
718 if (fd >= 0)
719 close(fd);
720 if (err) {
721 WRITE_ONCE(a->stop, 1);
722 return ERR_PTR(err);
723 }
724 return NULL;
725 }
726
send_recv_data(int lfd,int fd,uint32_t total_bytes)727 int send_recv_data(int lfd, int fd, uint32_t total_bytes)
728 {
729 ssize_t nr_recv = 0, bytes = 0;
730 struct send_recv_arg arg = {
731 .fd = lfd,
732 .bytes = total_bytes,
733 .stop = 0,
734 };
735 pthread_t srv_thread;
736 void *thread_ret;
737 char batch[1500];
738 int err = 0;
739
740 err = pthread_create(&srv_thread, NULL, send_recv_server, (void *)&arg);
741 if (err) {
742 log_err("Failed to pthread_create");
743 return err;
744 }
745
746 /* recv total_bytes */
747 while (bytes < total_bytes && !READ_ONCE(arg.stop)) {
748 nr_recv = recv(fd, &batch,
749 MIN(total_bytes - bytes, sizeof(batch)), 0);
750 if (nr_recv == -1 && errno == EINTR)
751 continue;
752 if (nr_recv == -1) {
753 err = -errno;
754 break;
755 }
756 bytes += nr_recv;
757 }
758
759 if (bytes != total_bytes) {
760 log_err("recv %zd expected %u", bytes, total_bytes);
761 if (!err)
762 err = bytes > total_bytes ? -E2BIG : -EINTR;
763 }
764
765 WRITE_ONCE(arg.stop, 1);
766 pthread_join(srv_thread, &thread_ret);
767 if (IS_ERR(thread_ret)) {
768 log_err("Failed in thread_ret %ld", PTR_ERR(thread_ret));
769 err = err ? : PTR_ERR(thread_ret);
770 }
771
772 return err;
773 }
774
tc_prog_attach(const char * dev,int ingress_fd,int egress_fd)775 int tc_prog_attach(const char *dev, int ingress_fd, int egress_fd)
776 {
777 int ifindex, ret;
778
779 if (!ASSERT_TRUE(ingress_fd >= 0 || egress_fd >= 0,
780 "at least one program fd is valid"))
781 return -1;
782
783 ifindex = if_nametoindex(dev);
784 if (!ASSERT_NEQ(ifindex, 0, "get ifindex"))
785 return -1;
786
787 DECLARE_LIBBPF_OPTS(bpf_tc_hook, hook, .ifindex = ifindex,
788 .attach_point = BPF_TC_INGRESS | BPF_TC_EGRESS);
789 DECLARE_LIBBPF_OPTS(bpf_tc_opts, opts1, .handle = 1,
790 .priority = 1, .prog_fd = ingress_fd);
791 DECLARE_LIBBPF_OPTS(bpf_tc_opts, opts2, .handle = 1,
792 .priority = 1, .prog_fd = egress_fd);
793
794 ret = bpf_tc_hook_create(&hook);
795 if (!ASSERT_OK(ret, "create tc hook"))
796 return ret;
797
798 if (ingress_fd >= 0) {
799 hook.attach_point = BPF_TC_INGRESS;
800 ret = bpf_tc_attach(&hook, &opts1);
801 if (!ASSERT_OK(ret, "bpf_tc_attach")) {
802 bpf_tc_hook_destroy(&hook);
803 return ret;
804 }
805 }
806
807 if (egress_fd >= 0) {
808 hook.attach_point = BPF_TC_EGRESS;
809 ret = bpf_tc_attach(&hook, &opts2);
810 if (!ASSERT_OK(ret, "bpf_tc_attach")) {
811 bpf_tc_hook_destroy(&hook);
812 return ret;
813 }
814 }
815
816 return 0;
817 }
818
819 #ifdef TRAFFIC_MONITOR
820 struct tmonitor_ctx {
821 pcap_t *pcap;
822 pcap_dumper_t *dumper;
823 pthread_t thread;
824 int wake_fd;
825
826 volatile bool done;
827 char pkt_fname[PATH_MAX];
828 int pcap_fd;
829 };
830
__base_pr(const char * format,va_list args)831 static int __base_pr(const char *format, va_list args)
832 {
833 return vfprintf(stdout, format, args);
834 }
835
836 static tm_print_fn_t __tm_pr = __base_pr;
837
traffic_monitor_set_print(tm_print_fn_t fn)838 tm_print_fn_t traffic_monitor_set_print(tm_print_fn_t fn)
839 {
840 tm_print_fn_t old_print_fn;
841
842 old_print_fn = __atomic_exchange_n(&__tm_pr, fn, __ATOMIC_RELAXED);
843
844 return old_print_fn;
845 }
846
tm_print(const char * format,...)847 void tm_print(const char *format, ...)
848 {
849 tm_print_fn_t print_fn;
850 va_list args;
851
852 print_fn = __atomic_load_n(&__tm_pr, __ATOMIC_RELAXED);
853 if (!print_fn)
854 return;
855
856 va_start(args, format);
857 print_fn(format, args);
858 va_end(args);
859 }
860
861 /* Is this packet captured with a Ethernet protocol type? */
is_ethernet(const u_char * packet)862 static bool is_ethernet(const u_char *packet)
863 {
864 u16 arphdr_type;
865
866 memcpy(&arphdr_type, packet + 8, 2);
867 arphdr_type = ntohs(arphdr_type);
868
869 /*
870 * Except the following cases, the protocol type contains the
871 * Ethernet protocol type for the packet.
872 *
873 * https://www.tcpdump.org/linktypes/LINKTYPE_LINUX_SLL2.html
874 */
875 switch (arphdr_type) {
876 case 770: /* ARPHRD_FRAD */
877 case 778: /* ARPHDR_IPGRE */
878 case 803: /* ARPHRD_IEEE80211_RADIOTAP */
879 tm_print("Packet captured: arphdr_type=%d\n", arphdr_type);
880 return false;
881 }
882 return true;
883 }
884
885 static const char * const pkt_types[] = {
886 "In",
887 "B", /* Broadcast */
888 "M", /* Multicast */
889 "C", /* Captured with the promiscuous mode */
890 "Out",
891 };
892
pkt_type_str(u16 pkt_type)893 static const char *pkt_type_str(u16 pkt_type)
894 {
895 if (pkt_type < ARRAY_SIZE(pkt_types))
896 return pkt_types[pkt_type];
897 return "Unknown";
898 }
899
900 #define MAX_FLAGS_STRLEN 21
901 /* Show the information of the transport layer in the packet */
show_transport(const u_char * packet,u16 len,u32 ifindex,const char * src_addr,const char * dst_addr,u16 proto,bool ipv6,u8 pkt_type)902 static void show_transport(const u_char *packet, u16 len, u32 ifindex,
903 const char *src_addr, const char *dst_addr,
904 u16 proto, bool ipv6, u8 pkt_type)
905 {
906 char *ifname, _ifname[IF_NAMESIZE], flags[MAX_FLAGS_STRLEN] = "";
907 const char *transport_str;
908 u16 src_port, dst_port;
909 struct udphdr *udp;
910 struct tcphdr *tcp;
911
912 ifname = if_indextoname(ifindex, _ifname);
913 if (!ifname) {
914 snprintf(_ifname, sizeof(_ifname), "unknown(%d)", ifindex);
915 ifname = _ifname;
916 }
917
918 if (proto == IPPROTO_UDP) {
919 udp = (struct udphdr *)packet;
920 src_port = ntohs(udp->source);
921 dst_port = ntohs(udp->dest);
922 transport_str = "UDP";
923 } else if (proto == IPPROTO_TCP) {
924 tcp = (struct tcphdr *)packet;
925 src_port = ntohs(tcp->source);
926 dst_port = ntohs(tcp->dest);
927 transport_str = "TCP";
928 } else if (proto == IPPROTO_ICMP) {
929 tm_print("%-7s %-3s IPv4 %s > %s: ICMP, length %d, type %d, code %d\n",
930 ifname, pkt_type_str(pkt_type), src_addr, dst_addr, len,
931 packet[0], packet[1]);
932 return;
933 } else if (proto == IPPROTO_ICMPV6) {
934 tm_print("%-7s %-3s IPv6 %s > %s: ICMPv6, length %d, type %d, code %d\n",
935 ifname, pkt_type_str(pkt_type), src_addr, dst_addr, len,
936 packet[0], packet[1]);
937 return;
938 } else {
939 tm_print("%-7s %-3s %s %s > %s: protocol %d\n",
940 ifname, pkt_type_str(pkt_type), ipv6 ? "IPv6" : "IPv4",
941 src_addr, dst_addr, proto);
942 return;
943 }
944
945 /* TCP or UDP*/
946
947 if (proto == IPPROTO_TCP)
948 snprintf(flags, MAX_FLAGS_STRLEN, "%s%s%s%s",
949 tcp->fin ? ", FIN" : "",
950 tcp->syn ? ", SYN" : "",
951 tcp->rst ? ", RST" : "",
952 tcp->ack ? ", ACK" : "");
953
954 if (ipv6)
955 tm_print("%-7s %-3s IPv6 %s.%d > %s.%d: %s, length %d%s\n",
956 ifname, pkt_type_str(pkt_type), src_addr, src_port,
957 dst_addr, dst_port, transport_str, len, flags);
958 else
959 tm_print("%-7s %-3s IPv4 %s:%d > %s:%d: %s, length %d%s\n",
960 ifname, pkt_type_str(pkt_type), src_addr, src_port,
961 dst_addr, dst_port, transport_str, len, flags);
962 }
963
show_ipv6_packet(const u_char * packet,u32 ifindex,u8 pkt_type)964 static void show_ipv6_packet(const u_char *packet, u32 ifindex, u8 pkt_type)
965 {
966 char src_buf[INET6_ADDRSTRLEN], dst_buf[INET6_ADDRSTRLEN];
967 struct ipv6hdr *pkt = (struct ipv6hdr *)packet;
968 const char *src, *dst;
969 u_char proto;
970
971 src = inet_ntop(AF_INET6, &pkt->saddr, src_buf, sizeof(src_buf));
972 if (!src)
973 src = "<invalid>";
974 dst = inet_ntop(AF_INET6, &pkt->daddr, dst_buf, sizeof(dst_buf));
975 if (!dst)
976 dst = "<invalid>";
977 proto = pkt->nexthdr;
978 show_transport(packet + sizeof(struct ipv6hdr),
979 ntohs(pkt->payload_len),
980 ifindex, src, dst, proto, true, pkt_type);
981 }
982
show_ipv4_packet(const u_char * packet,u32 ifindex,u8 pkt_type)983 static void show_ipv4_packet(const u_char *packet, u32 ifindex, u8 pkt_type)
984 {
985 char src_buf[INET_ADDRSTRLEN], dst_buf[INET_ADDRSTRLEN];
986 struct iphdr *pkt = (struct iphdr *)packet;
987 const char *src, *dst;
988 u_char proto;
989
990 src = inet_ntop(AF_INET, &pkt->saddr, src_buf, sizeof(src_buf));
991 if (!src)
992 src = "<invalid>";
993 dst = inet_ntop(AF_INET, &pkt->daddr, dst_buf, sizeof(dst_buf));
994 if (!dst)
995 dst = "<invalid>";
996 proto = pkt->protocol;
997 show_transport(packet + sizeof(struct iphdr),
998 ntohs(pkt->tot_len),
999 ifindex, src, dst, proto, false, pkt_type);
1000 }
1001
traffic_monitor_thread(void * arg)1002 static void *traffic_monitor_thread(void *arg)
1003 {
1004 char *ifname, _ifname[IF_NAMESIZE];
1005 const u_char *packet, *payload;
1006 struct tmonitor_ctx *ctx = arg;
1007 pcap_dumper_t *dumper = ctx->dumper;
1008 int fd = ctx->pcap_fd, nfds, r;
1009 int wake_fd = ctx->wake_fd;
1010 struct pcap_pkthdr header;
1011 pcap_t *pcap = ctx->pcap;
1012 u32 ifindex;
1013 fd_set fds;
1014 u16 proto;
1015 u8 ptype;
1016
1017 nfds = (fd > wake_fd ? fd : wake_fd) + 1;
1018 FD_ZERO(&fds);
1019
1020 while (!ctx->done) {
1021 FD_SET(fd, &fds);
1022 FD_SET(wake_fd, &fds);
1023 r = select(nfds, &fds, NULL, NULL, NULL);
1024 if (!r)
1025 continue;
1026 if (r < 0) {
1027 if (errno == EINTR)
1028 continue;
1029 log_err("Fail to select on pcap fd and wake fd");
1030 break;
1031 }
1032
1033 /* This instance of pcap is non-blocking */
1034 packet = pcap_next(pcap, &header);
1035 if (!packet)
1036 continue;
1037
1038 /*
1039 * According to the man page of pcap_dump(), first argument
1040 * is the pcap_dumper_t pointer even it's argument type is
1041 * u_char *.
1042 */
1043 pcap_dump((u_char *)dumper, &header, packet);
1044
1045 /*
1046 * Not sure what other types of packets look like. Here, we
1047 * parse only Ethernet and compatible packets.
1048 */
1049 if (!is_ethernet(packet))
1050 continue;
1051
1052 /*
1053 * Skip SLL2 header
1054 * https://www.tcpdump.org/linktypes/LINKTYPE_LINUX_SLL2.html
1055 *
1056 * Although the document doesn't mention that, the payload
1057 * doesn't include the Ethernet header. The payload starts
1058 * from the first byte of the network layer header.
1059 */
1060 payload = packet + 20;
1061
1062 memcpy(&proto, packet, 2);
1063 proto = ntohs(proto);
1064 memcpy(&ifindex, packet + 4, 4);
1065 ifindex = ntohl(ifindex);
1066 ptype = packet[10];
1067
1068 if (proto == ETH_P_IPV6) {
1069 show_ipv6_packet(payload, ifindex, ptype);
1070 } else if (proto == ETH_P_IP) {
1071 show_ipv4_packet(payload, ifindex, ptype);
1072 } else {
1073 ifname = if_indextoname(ifindex, _ifname);
1074 if (!ifname) {
1075 snprintf(_ifname, sizeof(_ifname), "unknown(%d)", ifindex);
1076 ifname = _ifname;
1077 }
1078
1079 tm_print("%-7s %-3s Unknown network protocol type 0x%x\n",
1080 ifname, pkt_type_str(ptype), proto);
1081 }
1082 }
1083
1084 return NULL;
1085 }
1086
1087 /*
1088 * Prepare the pcap handle to capture packets.
1089 *
1090 * This pcap is non-blocking and immediate mode is enabled to receive
1091 * captured packets as soon as possible. The snaplen is set to 1024 bytes
1092 * to limit the size of captured content. The format of the link-layer
1093 * header is set to DLT_LINUX_SLL2 to enable handling various link-layer
1094 * technologies.
1095 */
traffic_monitor_prepare_pcap(void)1096 static pcap_t *traffic_monitor_prepare_pcap(void)
1097 {
1098 char errbuf[PCAP_ERRBUF_SIZE];
1099 pcap_t *pcap;
1100 int r;
1101
1102 /* Listen on all NICs in the namespace */
1103 pcap = pcap_create("any", errbuf);
1104 if (!pcap) {
1105 log_err("Failed to open pcap: %s", errbuf);
1106 return NULL;
1107 }
1108 /* Limit the size of the packet (first N bytes) */
1109 r = pcap_set_snaplen(pcap, 1024);
1110 if (r) {
1111 log_err("Failed to set snaplen: %s", pcap_geterr(pcap));
1112 goto error;
1113 }
1114 /* To receive packets as fast as possible */
1115 r = pcap_set_immediate_mode(pcap, 1);
1116 if (r) {
1117 log_err("Failed to set immediate mode: %s", pcap_geterr(pcap));
1118 goto error;
1119 }
1120 r = pcap_setnonblock(pcap, 1, errbuf);
1121 if (r) {
1122 log_err("Failed to set nonblock: %s", errbuf);
1123 goto error;
1124 }
1125 r = pcap_activate(pcap);
1126 if (r) {
1127 log_err("Failed to activate pcap: %s", pcap_geterr(pcap));
1128 goto error;
1129 }
1130 /* Determine the format of the link-layer header */
1131 r = pcap_set_datalink(pcap, DLT_LINUX_SLL2);
1132 if (r) {
1133 log_err("Failed to set datalink: %s", pcap_geterr(pcap));
1134 goto error;
1135 }
1136
1137 return pcap;
1138 error:
1139 pcap_close(pcap);
1140 return NULL;
1141 }
1142
encode_test_name(char * buf,size_t len,const char * test_name,const char * subtest_name)1143 static void encode_test_name(char *buf, size_t len, const char *test_name, const char *subtest_name)
1144 {
1145 char *p;
1146
1147 if (subtest_name)
1148 snprintf(buf, len, "%s__%s", test_name, subtest_name);
1149 else
1150 snprintf(buf, len, "%s", test_name);
1151 while ((p = strchr(buf, '/')))
1152 *p = '_';
1153 while ((p = strchr(buf, ' ')))
1154 *p = '_';
1155 }
1156
1157 #define PCAP_DIR "/tmp/tmon_pcap"
1158
1159 /*
1160 * Start to monitor the network traffic in the given network namespace.
1161 *
1162 * netns: the name of the network namespace to monitor. If NULL, the
1163 * current network namespace is monitored.
1164 * test_name: the name of the running test.
1165 * subtest_name: the name of the running subtest if there is. It should be
1166 * NULL if it is not a subtest.
1167 *
1168 * This function will start a thread to capture packets going through NICs
1169 * in the give network namespace.
1170 */
traffic_monitor_start(const char * netns,const char * test_name,const char * subtest_name)1171 struct tmonitor_ctx *traffic_monitor_start(const char *netns, const char *test_name,
1172 const char *subtest_name)
1173 {
1174 struct nstoken *nstoken = NULL;
1175 struct tmonitor_ctx *ctx;
1176 char test_name_buf[64];
1177 static int tmon_seq;
1178 int r;
1179
1180 if (netns) {
1181 nstoken = open_netns(netns);
1182 if (!nstoken)
1183 return NULL;
1184 }
1185 ctx = malloc(sizeof(*ctx));
1186 if (!ctx) {
1187 log_err("Failed to malloc ctx");
1188 goto fail_ctx;
1189 }
1190 memset(ctx, 0, sizeof(*ctx));
1191
1192 encode_test_name(test_name_buf, sizeof(test_name_buf), test_name, subtest_name);
1193 snprintf(ctx->pkt_fname, sizeof(ctx->pkt_fname),
1194 PCAP_DIR "/packets-%d-%d-%s-%s.log", getpid(), tmon_seq++,
1195 test_name_buf, netns ? netns : "unknown");
1196
1197 r = mkdir(PCAP_DIR, 0755);
1198 if (r && errno != EEXIST) {
1199 log_err("Failed to create " PCAP_DIR);
1200 goto fail_pcap;
1201 }
1202
1203 ctx->pcap = traffic_monitor_prepare_pcap();
1204 if (!ctx->pcap)
1205 goto fail_pcap;
1206 ctx->pcap_fd = pcap_get_selectable_fd(ctx->pcap);
1207 if (ctx->pcap_fd < 0) {
1208 log_err("Failed to get pcap fd");
1209 goto fail_dumper;
1210 }
1211
1212 /* Create a packet file */
1213 ctx->dumper = pcap_dump_open(ctx->pcap, ctx->pkt_fname);
1214 if (!ctx->dumper) {
1215 log_err("Failed to open pcap dump: %s", ctx->pkt_fname);
1216 goto fail_dumper;
1217 }
1218
1219 /* Create an eventfd to wake up the monitor thread */
1220 ctx->wake_fd = eventfd(0, 0);
1221 if (ctx->wake_fd < 0) {
1222 log_err("Failed to create eventfd");
1223 goto fail_eventfd;
1224 }
1225
1226 r = pthread_create(&ctx->thread, NULL, traffic_monitor_thread, ctx);
1227 if (r) {
1228 log_err("Failed to create thread");
1229 goto fail;
1230 }
1231
1232 close_netns(nstoken);
1233
1234 return ctx;
1235
1236 fail:
1237 close(ctx->wake_fd);
1238
1239 fail_eventfd:
1240 pcap_dump_close(ctx->dumper);
1241 unlink(ctx->pkt_fname);
1242
1243 fail_dumper:
1244 pcap_close(ctx->pcap);
1245
1246 fail_pcap:
1247 free(ctx);
1248
1249 fail_ctx:
1250 close_netns(nstoken);
1251
1252 return NULL;
1253 }
1254
traffic_monitor_release(struct tmonitor_ctx * ctx)1255 static void traffic_monitor_release(struct tmonitor_ctx *ctx)
1256 {
1257 pcap_close(ctx->pcap);
1258 pcap_dump_close(ctx->dumper);
1259
1260 close(ctx->wake_fd);
1261
1262 free(ctx);
1263 }
1264
1265 /*
1266 * Stop the network traffic monitor.
1267 *
1268 * ctx: the context returned by traffic_monitor_start()
1269 */
traffic_monitor_stop(struct tmonitor_ctx * ctx)1270 void traffic_monitor_stop(struct tmonitor_ctx *ctx)
1271 {
1272 __u64 w = 1;
1273
1274 if (!ctx)
1275 return;
1276
1277 /* Stop the monitor thread */
1278 ctx->done = true;
1279 /* Wake up the background thread. */
1280 write(ctx->wake_fd, &w, sizeof(w));
1281 pthread_join(ctx->thread, NULL);
1282
1283 tm_print("Packet file: %s\n", strrchr(ctx->pkt_fname, '/') + 1);
1284
1285 traffic_monitor_release(ctx);
1286 }
1287
1288 #endif /* TRAFFIC_MONITOR */
1289