xref: /linux/tools/testing/vsock/util.c (revision a55f7f5f29b32c2c53cc291899cf9b0c25a07f7c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * vsock test utilities
4  *
5  * Copyright (C) 2017 Red Hat, Inc.
6  *
7  * Author: Stefan Hajnoczi <stefanha@redhat.com>
8  */
9 
10 #include <ctype.h>
11 #include <errno.h>
12 #include <stdio.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <signal.h>
17 #include <unistd.h>
18 #include <assert.h>
19 #include <sys/epoll.h>
20 #include <sys/ioctl.h>
21 #include <sys/mman.h>
22 #include <linux/sockios.h>
23 
24 #include "timeout.h"
25 #include "control.h"
26 #include "util.h"
27 
28 #define KALLSYMS_PATH		"/proc/kallsyms"
29 #define KALLSYMS_LINE_LEN	512
30 
31 /* Install signal handlers */
init_signals(void)32 void init_signals(void)
33 {
34 	struct sigaction act = {
35 		.sa_handler = sigalrm,
36 	};
37 
38 	sigaction(SIGALRM, &act, NULL);
39 	signal(SIGPIPE, SIG_IGN);
40 }
41 
parse_uint(const char * str,const char * err_str)42 static unsigned int parse_uint(const char *str, const char *err_str)
43 {
44 	char *endptr = NULL;
45 	unsigned long n;
46 
47 	errno = 0;
48 	n = strtoul(str, &endptr, 10);
49 	if (errno || *endptr != '\0') {
50 		fprintf(stderr, "malformed %s \"%s\"\n", err_str, str);
51 		exit(EXIT_FAILURE);
52 	}
53 	return n;
54 }
55 
56 /* Parse a CID in string representation */
parse_cid(const char * str)57 unsigned int parse_cid(const char *str)
58 {
59 	return parse_uint(str, "CID");
60 }
61 
62 /* Parse a port in string representation */
parse_port(const char * str)63 unsigned int parse_port(const char *str)
64 {
65 	return parse_uint(str, "port");
66 }
67 
68 /* Wait for the remote to close the connection */
vsock_wait_remote_close(int fd)69 void vsock_wait_remote_close(int fd)
70 {
71 	struct epoll_event ev;
72 	int epollfd, nfds;
73 
74 	epollfd = epoll_create1(0);
75 	if (epollfd == -1) {
76 		perror("epoll_create1");
77 		exit(EXIT_FAILURE);
78 	}
79 
80 	ev.events = EPOLLRDHUP | EPOLLHUP;
81 	ev.data.fd = fd;
82 	if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev) == -1) {
83 		perror("epoll_ctl");
84 		exit(EXIT_FAILURE);
85 	}
86 
87 	nfds = epoll_wait(epollfd, &ev, 1, TIMEOUT * 1000);
88 	if (nfds == -1) {
89 		perror("epoll_wait");
90 		exit(EXIT_FAILURE);
91 	}
92 
93 	if (nfds == 0) {
94 		fprintf(stderr, "epoll_wait timed out\n");
95 		exit(EXIT_FAILURE);
96 	}
97 
98 	assert(nfds == 1);
99 	assert(ev.events & (EPOLLRDHUP | EPOLLHUP));
100 	assert(ev.data.fd == fd);
101 
102 	close(epollfd);
103 }
104 
105 /* Wait until ioctl gives an expected int value.
106  * Return false if the op is not supported.
107  */
vsock_ioctl_int(int fd,unsigned long op,int expected)108 bool vsock_ioctl_int(int fd, unsigned long op, int expected)
109 {
110 	int actual, ret;
111 	char name[32];
112 
113 	snprintf(name, sizeof(name), "ioctl(%lu)", op);
114 
115 	timeout_begin(TIMEOUT);
116 	do {
117 		ret = ioctl(fd, op, &actual);
118 		if (ret < 0) {
119 			if (errno == EOPNOTSUPP || errno == ENOTTY)
120 				break;
121 
122 			perror(name);
123 			exit(EXIT_FAILURE);
124 		}
125 		timeout_check(name);
126 	} while (actual != expected);
127 	timeout_end();
128 
129 	return ret >= 0;
130 }
131 
132 /* Wait until transport reports no data left to be sent.
133  * Return false if transport does not implement the unsent_bytes() callback.
134  */
vsock_wait_sent(int fd)135 bool vsock_wait_sent(int fd)
136 {
137 	return vsock_ioctl_int(fd, SIOCOUTQ, 0);
138 }
139 
140 /* Create socket <type>, bind to <cid, port>.
141  * Return the file descriptor, or -1 on error.
142  */
vsock_bind_try(unsigned int cid,unsigned int port,int type)143 int vsock_bind_try(unsigned int cid, unsigned int port, int type)
144 {
145 	struct sockaddr_vm sa = {
146 		.svm_family = AF_VSOCK,
147 		.svm_cid = cid,
148 		.svm_port = port,
149 	};
150 	int fd, saved_errno;
151 
152 	fd = socket(AF_VSOCK, type, 0);
153 	if (fd < 0) {
154 		perror("socket");
155 		exit(EXIT_FAILURE);
156 	}
157 
158 	if (bind(fd, (struct sockaddr *)&sa, sizeof(sa))) {
159 		saved_errno = errno;
160 		close(fd);
161 		errno = saved_errno;
162 		fd = -1;
163 	}
164 
165 	return fd;
166 }
167 
168 /* Create socket <type>, bind to <cid, port> and return the file descriptor. */
vsock_bind(unsigned int cid,unsigned int port,int type)169 int vsock_bind(unsigned int cid, unsigned int port, int type)
170 {
171 	int fd;
172 
173 	fd = vsock_bind_try(cid, port, type);
174 	if (fd < 0) {
175 		perror("bind");
176 		exit(EXIT_FAILURE);
177 	}
178 
179 	return fd;
180 }
181 
vsock_connect_fd(int fd,unsigned int cid,unsigned int port)182 int vsock_connect_fd(int fd, unsigned int cid, unsigned int port)
183 {
184 	struct sockaddr_vm sa = {
185 		.svm_family = AF_VSOCK,
186 		.svm_cid = cid,
187 		.svm_port = port,
188 	};
189 	int ret;
190 
191 	timeout_begin(TIMEOUT);
192 	do {
193 		ret = connect(fd, (struct sockaddr *)&sa, sizeof(sa));
194 		timeout_check("connect");
195 	} while (ret < 0 && errno == EINTR);
196 	timeout_end();
197 
198 	return ret;
199 }
200 
201 /* Bind to <bind_port>, connect to <cid, port> and return the file descriptor. */
vsock_bind_connect(unsigned int cid,unsigned int port,unsigned int bind_port,int type)202 int vsock_bind_connect(unsigned int cid, unsigned int port, unsigned int bind_port, int type)
203 {
204 	int client_fd;
205 
206 	client_fd = vsock_bind(VMADDR_CID_ANY, bind_port, type);
207 
208 	if (vsock_connect_fd(client_fd, cid, port)) {
209 		perror("connect");
210 		exit(EXIT_FAILURE);
211 	}
212 
213 	return client_fd;
214 }
215 
216 /* Connect to <cid, port> and return the file descriptor. */
vsock_connect(unsigned int cid,unsigned int port,int type)217 int vsock_connect(unsigned int cid, unsigned int port, int type)
218 {
219 	int fd;
220 
221 	control_expectln("LISTENING");
222 
223 	fd = socket(AF_VSOCK, type, 0);
224 	if (fd < 0) {
225 		perror("socket");
226 		exit(EXIT_FAILURE);
227 	}
228 
229 	if (vsock_connect_fd(fd, cid, port)) {
230 		int old_errno = errno;
231 
232 		close(fd);
233 		fd = -1;
234 		errno = old_errno;
235 	}
236 
237 	return fd;
238 }
239 
vsock_stream_connect(unsigned int cid,unsigned int port)240 int vsock_stream_connect(unsigned int cid, unsigned int port)
241 {
242 	return vsock_connect(cid, port, SOCK_STREAM);
243 }
244 
vsock_seqpacket_connect(unsigned int cid,unsigned int port)245 int vsock_seqpacket_connect(unsigned int cid, unsigned int port)
246 {
247 	return vsock_connect(cid, port, SOCK_SEQPACKET);
248 }
249 
250 /* Listen on <cid, port> and return the file descriptor. */
vsock_listen(unsigned int cid,unsigned int port,int type)251 static int vsock_listen(unsigned int cid, unsigned int port, int type)
252 {
253 	int fd;
254 
255 	fd = vsock_bind(cid, port, type);
256 
257 	if (listen(fd, 1) < 0) {
258 		perror("listen");
259 		exit(EXIT_FAILURE);
260 	}
261 
262 	return fd;
263 }
264 
265 /* Listen on <cid, port> and return the first incoming connection.  The remote
266  * address is stored to clientaddrp.  clientaddrp may be NULL.
267  */
vsock_accept(unsigned int cid,unsigned int port,struct sockaddr_vm * clientaddrp,int type)268 int vsock_accept(unsigned int cid, unsigned int port,
269 		 struct sockaddr_vm *clientaddrp, int type)
270 {
271 	union {
272 		struct sockaddr sa;
273 		struct sockaddr_vm svm;
274 	} clientaddr;
275 	socklen_t clientaddr_len = sizeof(clientaddr.svm);
276 	int fd, client_fd, old_errno;
277 
278 	fd = vsock_listen(cid, port, type);
279 
280 	control_writeln("LISTENING");
281 
282 	timeout_begin(TIMEOUT);
283 	do {
284 		client_fd = accept(fd, &clientaddr.sa, &clientaddr_len);
285 		timeout_check("accept");
286 	} while (client_fd < 0 && errno == EINTR);
287 	timeout_end();
288 
289 	old_errno = errno;
290 	close(fd);
291 	errno = old_errno;
292 
293 	if (client_fd < 0)
294 		return client_fd;
295 
296 	if (clientaddr_len != sizeof(clientaddr.svm)) {
297 		fprintf(stderr, "unexpected addrlen from accept(2), %zu\n",
298 			(size_t)clientaddr_len);
299 		exit(EXIT_FAILURE);
300 	}
301 	if (clientaddr.sa.sa_family != AF_VSOCK) {
302 		fprintf(stderr, "expected AF_VSOCK from accept(2), got %d\n",
303 			clientaddr.sa.sa_family);
304 		exit(EXIT_FAILURE);
305 	}
306 
307 	if (clientaddrp)
308 		*clientaddrp = clientaddr.svm;
309 	return client_fd;
310 }
311 
vsock_stream_accept(unsigned int cid,unsigned int port,struct sockaddr_vm * clientaddrp)312 int vsock_stream_accept(unsigned int cid, unsigned int port,
313 			struct sockaddr_vm *clientaddrp)
314 {
315 	return vsock_accept(cid, port, clientaddrp, SOCK_STREAM);
316 }
317 
vsock_stream_listen(unsigned int cid,unsigned int port)318 int vsock_stream_listen(unsigned int cid, unsigned int port)
319 {
320 	return vsock_listen(cid, port, SOCK_STREAM);
321 }
322 
vsock_seqpacket_accept(unsigned int cid,unsigned int port,struct sockaddr_vm * clientaddrp)323 int vsock_seqpacket_accept(unsigned int cid, unsigned int port,
324 			   struct sockaddr_vm *clientaddrp)
325 {
326 	return vsock_accept(cid, port, clientaddrp, SOCK_SEQPACKET);
327 }
328 
329 /* Transmit bytes from a buffer and check the return value.
330  *
331  * expected_ret:
332  *  <0 Negative errno (for testing errors)
333  *   0 End-of-file
334  *  >0 Success (bytes successfully written)
335  */
send_buf(int fd,const void * buf,size_t len,int flags,ssize_t expected_ret)336 void send_buf(int fd, const void *buf, size_t len, int flags,
337 	      ssize_t expected_ret)
338 {
339 	ssize_t nwritten = 0;
340 	ssize_t ret;
341 
342 	timeout_begin(TIMEOUT);
343 	do {
344 		ret = send(fd, buf + nwritten, len - nwritten, flags);
345 		timeout_check("send");
346 
347 		if (ret < 0 && errno == EINTR)
348 			continue;
349 		if (ret <= 0)
350 			break;
351 
352 		nwritten += ret;
353 	} while (nwritten < len);
354 	timeout_end();
355 
356 	if (expected_ret < 0) {
357 		if (ret != -1) {
358 			fprintf(stderr, "bogus send(2) return value %zd (expected %zd)\n",
359 				ret, expected_ret);
360 			exit(EXIT_FAILURE);
361 		}
362 		if (errno != -expected_ret) {
363 			perror("send");
364 			exit(EXIT_FAILURE);
365 		}
366 		return;
367 	}
368 
369 	if (ret < 0) {
370 		perror("send");
371 		exit(EXIT_FAILURE);
372 	}
373 
374 	if (nwritten != expected_ret) {
375 		if (ret == 0)
376 			fprintf(stderr, "unexpected EOF while sending bytes\n");
377 
378 		fprintf(stderr, "bogus send(2) bytes written %zd (expected %zd)\n",
379 			nwritten, expected_ret);
380 		exit(EXIT_FAILURE);
381 	}
382 }
383 
384 /* Receive bytes in a buffer and check the return value.
385  *
386  * expected_ret:
387  *  <0 Negative errno (for testing errors)
388  *   0 End-of-file
389  *  >0 Success (bytes successfully read)
390  */
recv_buf(int fd,void * buf,size_t len,int flags,ssize_t expected_ret)391 void recv_buf(int fd, void *buf, size_t len, int flags, ssize_t expected_ret)
392 {
393 	ssize_t nread = 0;
394 	ssize_t ret;
395 
396 	timeout_begin(TIMEOUT);
397 	do {
398 		ret = recv(fd, buf + nread, len - nread, flags);
399 		timeout_check("recv");
400 
401 		if (ret < 0 && errno == EINTR)
402 			continue;
403 		if (ret <= 0)
404 			break;
405 
406 		nread += ret;
407 	} while (nread < len);
408 	timeout_end();
409 
410 	if (expected_ret < 0) {
411 		if (ret != -1) {
412 			fprintf(stderr, "bogus recv(2) return value %zd (expected %zd)\n",
413 				ret, expected_ret);
414 			exit(EXIT_FAILURE);
415 		}
416 		if (errno != -expected_ret) {
417 			perror("recv");
418 			exit(EXIT_FAILURE);
419 		}
420 		return;
421 	}
422 
423 	if (ret < 0) {
424 		perror("recv");
425 		exit(EXIT_FAILURE);
426 	}
427 
428 	if (nread != expected_ret) {
429 		if (ret == 0)
430 			fprintf(stderr, "unexpected EOF while receiving bytes\n");
431 
432 		fprintf(stderr, "bogus recv(2) bytes read %zd (expected %zd)\n",
433 			nread, expected_ret);
434 		exit(EXIT_FAILURE);
435 	}
436 }
437 
438 /* Transmit one byte and check the return value.
439  *
440  * expected_ret:
441  *  <0 Negative errno (for testing errors)
442  *   0 End-of-file
443  *   1 Success
444  */
send_byte(int fd,int expected_ret,int flags)445 void send_byte(int fd, int expected_ret, int flags)
446 {
447 	static const uint8_t byte = 'A';
448 
449 	send_buf(fd, &byte, sizeof(byte), flags, expected_ret);
450 }
451 
452 /* Receive one byte and check the return value.
453  *
454  * expected_ret:
455  *  <0 Negative errno (for testing errors)
456  *   0 End-of-file
457  *   1 Success
458  */
recv_byte(int fd,int expected_ret,int flags)459 void recv_byte(int fd, int expected_ret, int flags)
460 {
461 	uint8_t byte;
462 
463 	recv_buf(fd, &byte, sizeof(byte), flags, expected_ret);
464 
465 	if (byte != 'A') {
466 		fprintf(stderr, "unexpected byte read 0x%02x\n", byte);
467 		exit(EXIT_FAILURE);
468 	}
469 }
470 
471 /* Run test cases.  The program terminates if a failure occurs. */
run_tests(const struct test_case * test_cases,const struct test_opts * opts)472 void run_tests(const struct test_case *test_cases,
473 	       const struct test_opts *opts)
474 {
475 	int i;
476 
477 	for (i = 0; test_cases[i].name; i++) {
478 		void (*run)(const struct test_opts *opts);
479 		char *line;
480 
481 		printf("%d - %s...", i, test_cases[i].name);
482 		fflush(stdout);
483 
484 		/* Full barrier before executing the next test.  This
485 		 * ensures that client and server are executing the
486 		 * same test case.  In particular, it means whoever is
487 		 * faster will not see the peer still executing the
488 		 * last test.  This is important because port numbers
489 		 * can be used by multiple test cases.
490 		 */
491 		if (test_cases[i].skip)
492 			control_writeln("SKIP");
493 		else
494 			control_writeln("NEXT");
495 
496 		line = control_readln();
497 		if (control_cmpln(line, "SKIP", false) || test_cases[i].skip) {
498 
499 			printf("skipped\n");
500 
501 			free(line);
502 			continue;
503 		}
504 
505 		control_cmpln(line, "NEXT", true);
506 		free(line);
507 
508 		if (opts->mode == TEST_MODE_CLIENT)
509 			run = test_cases[i].run_client;
510 		else
511 			run = test_cases[i].run_server;
512 
513 		if (run)
514 			run(opts);
515 
516 		printf("ok\n");
517 	}
518 
519 	printf("All tests have been executed. Waiting other peer...");
520 	fflush(stdout);
521 
522 	/*
523 	 * Final full barrier, to ensure that all tests have been run and
524 	 * that even the last one has been successful on both sides.
525 	 */
526 	control_writeln("COMPLETED");
527 	control_expectln("COMPLETED");
528 
529 	printf("ok\n");
530 }
531 
list_tests(const struct test_case * test_cases)532 void list_tests(const struct test_case *test_cases)
533 {
534 	int i;
535 
536 	printf("ID\tTest name\n");
537 
538 	for (i = 0; test_cases[i].name; i++)
539 		printf("%d\t%s\n", i, test_cases[i].name);
540 
541 	exit(EXIT_FAILURE);
542 }
543 
parse_test_id(const char * test_id_str,size_t test_cases_len)544 static unsigned long parse_test_id(const char *test_id_str, size_t test_cases_len)
545 {
546 	unsigned long test_id;
547 	char *endptr = NULL;
548 
549 	errno = 0;
550 	test_id = strtoul(test_id_str, &endptr, 10);
551 	if (errno || *endptr != '\0') {
552 		fprintf(stderr, "malformed test ID \"%s\"\n", test_id_str);
553 		exit(EXIT_FAILURE);
554 	}
555 
556 	if (test_id >= test_cases_len) {
557 		fprintf(stderr, "test ID (%lu) larger than the max allowed (%lu)\n",
558 			test_id, test_cases_len - 1);
559 		exit(EXIT_FAILURE);
560 	}
561 
562 	return test_id;
563 }
564 
skip_test(struct test_case * test_cases,size_t test_cases_len,const char * test_id_str)565 void skip_test(struct test_case *test_cases, size_t test_cases_len,
566 	       const char *test_id_str)
567 {
568 	unsigned long test_id = parse_test_id(test_id_str, test_cases_len);
569 	test_cases[test_id].skip = true;
570 }
571 
pick_test(struct test_case * test_cases,size_t test_cases_len,const char * test_id_str)572 void pick_test(struct test_case *test_cases, size_t test_cases_len,
573 	       const char *test_id_str)
574 {
575 	static bool skip_all = true;
576 	unsigned long test_id;
577 
578 	if (skip_all) {
579 		unsigned long i;
580 
581 		for (i = 0; i < test_cases_len; ++i)
582 			test_cases[i].skip = true;
583 
584 		skip_all = false;
585 	}
586 
587 	test_id = parse_test_id(test_id_str, test_cases_len);
588 	test_cases[test_id].skip = false;
589 }
590 
hash_djb2(const void * data,size_t len)591 unsigned long hash_djb2(const void *data, size_t len)
592 {
593 	unsigned long hash = 5381;
594 	int i = 0;
595 
596 	while (i < len) {
597 		hash = ((hash << 5) + hash) + ((unsigned char *)data)[i];
598 		i++;
599 	}
600 
601 	return hash;
602 }
603 
iovec_bytes(const struct iovec * iov,size_t iovnum)604 size_t iovec_bytes(const struct iovec *iov, size_t iovnum)
605 {
606 	size_t bytes;
607 	int i;
608 
609 	for (bytes = 0, i = 0; i < iovnum; i++)
610 		bytes += iov[i].iov_len;
611 
612 	return bytes;
613 }
614 
iovec_hash_djb2(const struct iovec * iov,size_t iovnum)615 unsigned long iovec_hash_djb2(const struct iovec *iov, size_t iovnum)
616 {
617 	unsigned long hash;
618 	size_t iov_bytes;
619 	size_t offs;
620 	void *tmp;
621 	int i;
622 
623 	iov_bytes = iovec_bytes(iov, iovnum);
624 
625 	tmp = malloc(iov_bytes);
626 	if (!tmp) {
627 		perror("malloc");
628 		exit(EXIT_FAILURE);
629 	}
630 
631 	for (offs = 0, i = 0; i < iovnum; i++) {
632 		memcpy(tmp + offs, iov[i].iov_base, iov[i].iov_len);
633 		offs += iov[i].iov_len;
634 	}
635 
636 	hash = hash_djb2(tmp, iov_bytes);
637 	free(tmp);
638 
639 	return hash;
640 }
641 
642 /* Allocates and returns new 'struct iovec *' according pattern
643  * in the 'test_iovec'. For each element in the 'test_iovec' it
644  * allocates new element in the resulting 'iovec'. 'iov_len'
645  * of the new element is copied from 'test_iovec'. 'iov_base' is
646  * allocated depending on the 'iov_base' of 'test_iovec':
647  *
648  * 'iov_base' == NULL -> valid buf: mmap('iov_len').
649  *
650  * 'iov_base' == MAP_FAILED -> invalid buf:
651  *               mmap('iov_len'), then munmap('iov_len').
652  *               'iov_base' still contains result of
653  *               mmap().
654  *
655  * 'iov_base' == number -> unaligned valid buf:
656  *               mmap('iov_len') + number.
657  *
658  * 'iovnum' is number of elements in 'test_iovec'.
659  *
660  * Returns new 'iovec' or calls 'exit()' on error.
661  */
alloc_test_iovec(const struct iovec * test_iovec,int iovnum)662 struct iovec *alloc_test_iovec(const struct iovec *test_iovec, int iovnum)
663 {
664 	struct iovec *iovec;
665 	int i;
666 
667 	iovec = malloc(sizeof(*iovec) * iovnum);
668 	if (!iovec) {
669 		perror("malloc");
670 		exit(EXIT_FAILURE);
671 	}
672 
673 	for (i = 0; i < iovnum; i++) {
674 		iovec[i].iov_len = test_iovec[i].iov_len;
675 
676 		iovec[i].iov_base = mmap(NULL, iovec[i].iov_len,
677 					 PROT_READ | PROT_WRITE,
678 					 MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE,
679 					 -1, 0);
680 		if (iovec[i].iov_base == MAP_FAILED) {
681 			perror("mmap");
682 			exit(EXIT_FAILURE);
683 		}
684 
685 		if (test_iovec[i].iov_base != MAP_FAILED)
686 			iovec[i].iov_base += (uintptr_t)test_iovec[i].iov_base;
687 	}
688 
689 	/* Unmap "invalid" elements. */
690 	for (i = 0; i < iovnum; i++) {
691 		if (test_iovec[i].iov_base == MAP_FAILED) {
692 			if (munmap(iovec[i].iov_base, iovec[i].iov_len)) {
693 				perror("munmap");
694 				exit(EXIT_FAILURE);
695 			}
696 		}
697 	}
698 
699 	for (i = 0; i < iovnum; i++) {
700 		int j;
701 
702 		if (test_iovec[i].iov_base == MAP_FAILED)
703 			continue;
704 
705 		for (j = 0; j < iovec[i].iov_len; j++)
706 			((uint8_t *)iovec[i].iov_base)[j] = rand() & 0xff;
707 	}
708 
709 	return iovec;
710 }
711 
712 /* Frees 'iovec *', previously allocated by 'alloc_test_iovec()'.
713  * On error calls 'exit()'.
714  */
free_test_iovec(const struct iovec * test_iovec,struct iovec * iovec,int iovnum)715 void free_test_iovec(const struct iovec *test_iovec,
716 		     struct iovec *iovec, int iovnum)
717 {
718 	int i;
719 
720 	for (i = 0; i < iovnum; i++) {
721 		if (test_iovec[i].iov_base != MAP_FAILED) {
722 			if (test_iovec[i].iov_base)
723 				iovec[i].iov_base -= (uintptr_t)test_iovec[i].iov_base;
724 
725 			if (munmap(iovec[i].iov_base, iovec[i].iov_len)) {
726 				perror("munmap");
727 				exit(EXIT_FAILURE);
728 			}
729 		}
730 	}
731 
732 	free(iovec);
733 }
734 
735 /* Set "unsigned long long" socket option and check that it's indeed set */
setsockopt_ull_check(int fd,int level,int optname,unsigned long long val,char const * errmsg)736 void setsockopt_ull_check(int fd, int level, int optname,
737 			  unsigned long long val, char const *errmsg)
738 {
739 	unsigned long long chkval;
740 	socklen_t chklen;
741 	int err;
742 
743 	err = setsockopt(fd, level, optname, &val, sizeof(val));
744 	if (err) {
745 		fprintf(stderr, "setsockopt err: %s (%d)\n",
746 			strerror(errno), errno);
747 		goto fail;
748 	}
749 
750 	chkval = ~val; /* just make storage != val */
751 	chklen = sizeof(chkval);
752 
753 	err = getsockopt(fd, level, optname, &chkval, &chklen);
754 	if (err) {
755 		fprintf(stderr, "getsockopt err: %s (%d)\n",
756 			strerror(errno), errno);
757 		goto fail;
758 	}
759 
760 	if (chklen != sizeof(chkval)) {
761 		fprintf(stderr, "size mismatch: set %zu got %d\n", sizeof(val),
762 			chklen);
763 		goto fail;
764 	}
765 
766 	if (chkval != val) {
767 		fprintf(stderr, "value mismatch: set %llu got %llu\n", val,
768 			chkval);
769 		goto fail;
770 	}
771 	return;
772 fail:
773 	fprintf(stderr, "%s  val %llu\n", errmsg, val);
774 	exit(EXIT_FAILURE);
775 }
776 
777 /* Set "int" socket option and check that it's indeed set */
setsockopt_int_check(int fd,int level,int optname,int val,char const * errmsg)778 void setsockopt_int_check(int fd, int level, int optname, int val,
779 			  char const *errmsg)
780 {
781 	int chkval;
782 	socklen_t chklen;
783 	int err;
784 
785 	err = setsockopt(fd, level, optname, &val, sizeof(val));
786 	if (err) {
787 		fprintf(stderr, "setsockopt err: %s (%d)\n",
788 			strerror(errno), errno);
789 		goto fail;
790 	}
791 
792 	chkval = ~val; /* just make storage != val */
793 	chklen = sizeof(chkval);
794 
795 	err = getsockopt(fd, level, optname, &chkval, &chklen);
796 	if (err) {
797 		fprintf(stderr, "getsockopt err: %s (%d)\n",
798 			strerror(errno), errno);
799 		goto fail;
800 	}
801 
802 	if (chklen != sizeof(chkval)) {
803 		fprintf(stderr, "size mismatch: set %zu got %d\n", sizeof(val),
804 			chklen);
805 		goto fail;
806 	}
807 
808 	if (chkval != val) {
809 		fprintf(stderr, "value mismatch: set %d got %d\n", val, chkval);
810 		goto fail;
811 	}
812 	return;
813 fail:
814 	fprintf(stderr, "%s val %d\n", errmsg, val);
815 	exit(EXIT_FAILURE);
816 }
817 
mem_invert(unsigned char * mem,size_t size)818 static void mem_invert(unsigned char *mem, size_t size)
819 {
820 	size_t i;
821 
822 	for (i = 0; i < size; i++)
823 		mem[i] = ~mem[i];
824 }
825 
826 /* Set "timeval" socket option and check that it's indeed set */
setsockopt_timeval_check(int fd,int level,int optname,struct timeval val,char const * errmsg)827 void setsockopt_timeval_check(int fd, int level, int optname,
828 			      struct timeval val, char const *errmsg)
829 {
830 	struct timeval chkval;
831 	socklen_t chklen;
832 	int err;
833 
834 	err = setsockopt(fd, level, optname, &val, sizeof(val));
835 	if (err) {
836 		fprintf(stderr, "setsockopt err: %s (%d)\n",
837 			strerror(errno), errno);
838 		goto fail;
839 	}
840 
841 	 /* just make storage != val */
842 	chkval = val;
843 	mem_invert((unsigned char *)&chkval, sizeof(chkval));
844 	chklen = sizeof(chkval);
845 
846 	err = getsockopt(fd, level, optname, &chkval, &chklen);
847 	if (err) {
848 		fprintf(stderr, "getsockopt err: %s (%d)\n",
849 			strerror(errno), errno);
850 		goto fail;
851 	}
852 
853 	if (chklen != sizeof(chkval)) {
854 		fprintf(stderr, "size mismatch: set %zu got %d\n", sizeof(val),
855 			chklen);
856 		goto fail;
857 	}
858 
859 	if (memcmp(&chkval, &val, sizeof(val)) != 0) {
860 		fprintf(stderr, "value mismatch: set %ld:%ld got %ld:%ld\n",
861 			val.tv_sec, val.tv_usec, chkval.tv_sec, chkval.tv_usec);
862 		goto fail;
863 	}
864 	return;
865 fail:
866 	fprintf(stderr, "%s val %ld:%ld\n", errmsg, val.tv_sec, val.tv_usec);
867 	exit(EXIT_FAILURE);
868 }
869 
enable_so_zerocopy_check(int fd)870 void enable_so_zerocopy_check(int fd)
871 {
872 	setsockopt_int_check(fd, SOL_SOCKET, SO_ZEROCOPY, 1,
873 			     "setsockopt SO_ZEROCOPY");
874 }
875 
enable_so_linger(int fd,int timeout)876 void enable_so_linger(int fd, int timeout)
877 {
878 	struct linger optval = {
879 		.l_onoff = 1,
880 		.l_linger = timeout
881 	};
882 
883 	if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &optval, sizeof(optval))) {
884 		perror("setsockopt(SO_LINGER)");
885 		exit(EXIT_FAILURE);
886 	}
887 }
888 
__get_transports(void)889 static int __get_transports(void)
890 {
891 	char buf[KALLSYMS_LINE_LEN];
892 	const char *ksym;
893 	int ret = 0;
894 	FILE *f;
895 
896 	f = fopen(KALLSYMS_PATH, "r");
897 	if (!f) {
898 		perror("Can't open " KALLSYMS_PATH);
899 		exit(EXIT_FAILURE);
900 	}
901 
902 	while (fgets(buf, sizeof(buf), f)) {
903 		char *match;
904 		int i;
905 
906 		assert(buf[strlen(buf) - 1] == '\n');
907 
908 		for (i = 0; i < TRANSPORT_NUM; ++i) {
909 			if (ret & BIT(i))
910 				continue;
911 
912 			/* Match should be followed by '\t' or '\n'.
913 			 * See kallsyms.c:s_show().
914 			 */
915 			ksym = transport_ksyms[i];
916 			match = strstr(buf, ksym);
917 			if (match && isspace(match[strlen(ksym)])) {
918 				ret |= BIT(i);
919 				break;
920 			}
921 		}
922 	}
923 
924 	fclose(f);
925 	return ret;
926 }
927 
928 /* Return integer with TRANSPORT_* bit set for every (known) registered vsock
929  * transport.
930  */
get_transports(void)931 int get_transports(void)
932 {
933 	static int tr = -1;
934 
935 	if (tr == -1)
936 		tr = __get_transports();
937 
938 	return tr;
939 }
940