network_helpers.c 25 KB

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