network_helpers.c 28 KB

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