xref: /linux/tools/testing/vsock/util.c (revision be239684b18e1cdcafcf8c7face4a2f562c745ad)
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 <errno.h>
11 #include <stdio.h>
12 #include <stdint.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <signal.h>
16 #include <unistd.h>
17 #include <assert.h>
18 #include <sys/epoll.h>
19 #include <sys/mman.h>
20 
21 #include "timeout.h"
22 #include "control.h"
23 #include "util.h"
24 
25 /* Install signal handlers */
26 void init_signals(void)
27 {
28 	struct sigaction act = {
29 		.sa_handler = sigalrm,
30 	};
31 
32 	sigaction(SIGALRM, &act, NULL);
33 	signal(SIGPIPE, SIG_IGN);
34 }
35 
36 /* Parse a CID in string representation */
37 unsigned int parse_cid(const char *str)
38 {
39 	char *endptr = NULL;
40 	unsigned long n;
41 
42 	errno = 0;
43 	n = strtoul(str, &endptr, 10);
44 	if (errno || *endptr != '\0') {
45 		fprintf(stderr, "malformed CID \"%s\"\n", str);
46 		exit(EXIT_FAILURE);
47 	}
48 	return n;
49 }
50 
51 /* Wait for the remote to close the connection */
52 void vsock_wait_remote_close(int fd)
53 {
54 	struct epoll_event ev;
55 	int epollfd, nfds;
56 
57 	epollfd = epoll_create1(0);
58 	if (epollfd == -1) {
59 		perror("epoll_create1");
60 		exit(EXIT_FAILURE);
61 	}
62 
63 	ev.events = EPOLLRDHUP | EPOLLHUP;
64 	ev.data.fd = fd;
65 	if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev) == -1) {
66 		perror("epoll_ctl");
67 		exit(EXIT_FAILURE);
68 	}
69 
70 	nfds = epoll_wait(epollfd, &ev, 1, TIMEOUT * 1000);
71 	if (nfds == -1) {
72 		perror("epoll_wait");
73 		exit(EXIT_FAILURE);
74 	}
75 
76 	if (nfds == 0) {
77 		fprintf(stderr, "epoll_wait timed out\n");
78 		exit(EXIT_FAILURE);
79 	}
80 
81 	assert(nfds == 1);
82 	assert(ev.events & (EPOLLRDHUP | EPOLLHUP));
83 	assert(ev.data.fd == fd);
84 
85 	close(epollfd);
86 }
87 
88 /* Bind to <bind_port>, connect to <cid, port> and return the file descriptor. */
89 int vsock_bind_connect(unsigned int cid, unsigned int port, unsigned int bind_port, int type)
90 {
91 	struct sockaddr_vm sa_client = {
92 		.svm_family = AF_VSOCK,
93 		.svm_cid = VMADDR_CID_ANY,
94 		.svm_port = bind_port,
95 	};
96 	struct sockaddr_vm sa_server = {
97 		.svm_family = AF_VSOCK,
98 		.svm_cid = cid,
99 		.svm_port = port,
100 	};
101 
102 	int client_fd, ret;
103 
104 	client_fd = socket(AF_VSOCK, type, 0);
105 	if (client_fd < 0) {
106 		perror("socket");
107 		exit(EXIT_FAILURE);
108 	}
109 
110 	if (bind(client_fd, (struct sockaddr *)&sa_client, sizeof(sa_client))) {
111 		perror("bind");
112 		exit(EXIT_FAILURE);
113 	}
114 
115 	timeout_begin(TIMEOUT);
116 	do {
117 		ret = connect(client_fd, (struct sockaddr *)&sa_server, sizeof(sa_server));
118 		timeout_check("connect");
119 	} while (ret < 0 && errno == EINTR);
120 	timeout_end();
121 
122 	if (ret < 0) {
123 		perror("connect");
124 		exit(EXIT_FAILURE);
125 	}
126 
127 	return client_fd;
128 }
129 
130 /* Connect to <cid, port> and return the file descriptor. */
131 static int vsock_connect(unsigned int cid, unsigned int port, int type)
132 {
133 	union {
134 		struct sockaddr sa;
135 		struct sockaddr_vm svm;
136 	} addr = {
137 		.svm = {
138 			.svm_family = AF_VSOCK,
139 			.svm_port = port,
140 			.svm_cid = cid,
141 		},
142 	};
143 	int ret;
144 	int fd;
145 
146 	control_expectln("LISTENING");
147 
148 	fd = socket(AF_VSOCK, type, 0);
149 	if (fd < 0) {
150 		perror("socket");
151 		exit(EXIT_FAILURE);
152 	}
153 
154 	timeout_begin(TIMEOUT);
155 	do {
156 		ret = connect(fd, &addr.sa, sizeof(addr.svm));
157 		timeout_check("connect");
158 	} while (ret < 0 && errno == EINTR);
159 	timeout_end();
160 
161 	if (ret < 0) {
162 		int old_errno = errno;
163 
164 		close(fd);
165 		fd = -1;
166 		errno = old_errno;
167 	}
168 	return fd;
169 }
170 
171 int vsock_stream_connect(unsigned int cid, unsigned int port)
172 {
173 	return vsock_connect(cid, port, SOCK_STREAM);
174 }
175 
176 int vsock_seqpacket_connect(unsigned int cid, unsigned int port)
177 {
178 	return vsock_connect(cid, port, SOCK_SEQPACKET);
179 }
180 
181 /* Listen on <cid, port> and return the file descriptor. */
182 static int vsock_listen(unsigned int cid, unsigned int port, int type)
183 {
184 	union {
185 		struct sockaddr sa;
186 		struct sockaddr_vm svm;
187 	} addr = {
188 		.svm = {
189 			.svm_family = AF_VSOCK,
190 			.svm_port = port,
191 			.svm_cid = cid,
192 		},
193 	};
194 	int fd;
195 
196 	fd = socket(AF_VSOCK, type, 0);
197 	if (fd < 0) {
198 		perror("socket");
199 		exit(EXIT_FAILURE);
200 	}
201 
202 	if (bind(fd, &addr.sa, sizeof(addr.svm)) < 0) {
203 		perror("bind");
204 		exit(EXIT_FAILURE);
205 	}
206 
207 	if (listen(fd, 1) < 0) {
208 		perror("listen");
209 		exit(EXIT_FAILURE);
210 	}
211 
212 	return fd;
213 }
214 
215 /* Listen on <cid, port> and return the first incoming connection.  The remote
216  * address is stored to clientaddrp.  clientaddrp may be NULL.
217  */
218 static int vsock_accept(unsigned int cid, unsigned int port,
219 			struct sockaddr_vm *clientaddrp, int type)
220 {
221 	union {
222 		struct sockaddr sa;
223 		struct sockaddr_vm svm;
224 	} clientaddr;
225 	socklen_t clientaddr_len = sizeof(clientaddr.svm);
226 	int fd, client_fd, old_errno;
227 
228 	fd = vsock_listen(cid, port, type);
229 
230 	control_writeln("LISTENING");
231 
232 	timeout_begin(TIMEOUT);
233 	do {
234 		client_fd = accept(fd, &clientaddr.sa, &clientaddr_len);
235 		timeout_check("accept");
236 	} while (client_fd < 0 && errno == EINTR);
237 	timeout_end();
238 
239 	old_errno = errno;
240 	close(fd);
241 	errno = old_errno;
242 
243 	if (client_fd < 0)
244 		return client_fd;
245 
246 	if (clientaddr_len != sizeof(clientaddr.svm)) {
247 		fprintf(stderr, "unexpected addrlen from accept(2), %zu\n",
248 			(size_t)clientaddr_len);
249 		exit(EXIT_FAILURE);
250 	}
251 	if (clientaddr.sa.sa_family != AF_VSOCK) {
252 		fprintf(stderr, "expected AF_VSOCK from accept(2), got %d\n",
253 			clientaddr.sa.sa_family);
254 		exit(EXIT_FAILURE);
255 	}
256 
257 	if (clientaddrp)
258 		*clientaddrp = clientaddr.svm;
259 	return client_fd;
260 }
261 
262 int vsock_stream_accept(unsigned int cid, unsigned int port,
263 			struct sockaddr_vm *clientaddrp)
264 {
265 	return vsock_accept(cid, port, clientaddrp, SOCK_STREAM);
266 }
267 
268 int vsock_stream_listen(unsigned int cid, unsigned int port)
269 {
270 	return vsock_listen(cid, port, SOCK_STREAM);
271 }
272 
273 int vsock_seqpacket_accept(unsigned int cid, unsigned int port,
274 			   struct sockaddr_vm *clientaddrp)
275 {
276 	return vsock_accept(cid, port, clientaddrp, SOCK_SEQPACKET);
277 }
278 
279 /* Transmit bytes from a buffer and check the return value.
280  *
281  * expected_ret:
282  *  <0 Negative errno (for testing errors)
283  *   0 End-of-file
284  *  >0 Success (bytes successfully written)
285  */
286 void send_buf(int fd, const void *buf, size_t len, int flags,
287 	      ssize_t expected_ret)
288 {
289 	ssize_t nwritten = 0;
290 	ssize_t ret;
291 
292 	timeout_begin(TIMEOUT);
293 	do {
294 		ret = send(fd, buf + nwritten, len - nwritten, flags);
295 		timeout_check("send");
296 
297 		if (ret == 0 || (ret < 0 && errno != EINTR))
298 			break;
299 
300 		nwritten += ret;
301 	} while (nwritten < len);
302 	timeout_end();
303 
304 	if (expected_ret < 0) {
305 		if (ret != -1) {
306 			fprintf(stderr, "bogus send(2) return value %zd (expected %zd)\n",
307 				ret, expected_ret);
308 			exit(EXIT_FAILURE);
309 		}
310 		if (errno != -expected_ret) {
311 			perror("send");
312 			exit(EXIT_FAILURE);
313 		}
314 		return;
315 	}
316 
317 	if (ret < 0) {
318 		perror("send");
319 		exit(EXIT_FAILURE);
320 	}
321 
322 	if (nwritten != expected_ret) {
323 		if (ret == 0)
324 			fprintf(stderr, "unexpected EOF while sending bytes\n");
325 
326 		fprintf(stderr, "bogus send(2) bytes written %zd (expected %zd)\n",
327 			nwritten, expected_ret);
328 		exit(EXIT_FAILURE);
329 	}
330 }
331 
332 /* Receive bytes in a buffer and check the return value.
333  *
334  * expected_ret:
335  *  <0 Negative errno (for testing errors)
336  *   0 End-of-file
337  *  >0 Success (bytes successfully read)
338  */
339 void recv_buf(int fd, void *buf, size_t len, int flags, ssize_t expected_ret)
340 {
341 	ssize_t nread = 0;
342 	ssize_t ret;
343 
344 	timeout_begin(TIMEOUT);
345 	do {
346 		ret = recv(fd, buf + nread, len - nread, flags);
347 		timeout_check("recv");
348 
349 		if (ret == 0 || (ret < 0 && errno != EINTR))
350 			break;
351 
352 		nread += ret;
353 	} while (nread < len);
354 	timeout_end();
355 
356 	if (expected_ret < 0) {
357 		if (ret != -1) {
358 			fprintf(stderr, "bogus recv(2) return value %zd (expected %zd)\n",
359 				ret, expected_ret);
360 			exit(EXIT_FAILURE);
361 		}
362 		if (errno != -expected_ret) {
363 			perror("recv");
364 			exit(EXIT_FAILURE);
365 		}
366 		return;
367 	}
368 
369 	if (ret < 0) {
370 		perror("recv");
371 		exit(EXIT_FAILURE);
372 	}
373 
374 	if (nread != expected_ret) {
375 		if (ret == 0)
376 			fprintf(stderr, "unexpected EOF while receiving bytes\n");
377 
378 		fprintf(stderr, "bogus recv(2) bytes read %zd (expected %zd)\n",
379 			nread, expected_ret);
380 		exit(EXIT_FAILURE);
381 	}
382 }
383 
384 /* Transmit one byte and check the return value.
385  *
386  * expected_ret:
387  *  <0 Negative errno (for testing errors)
388  *   0 End-of-file
389  *   1 Success
390  */
391 void send_byte(int fd, int expected_ret, int flags)
392 {
393 	const uint8_t byte = 'A';
394 
395 	send_buf(fd, &byte, sizeof(byte), flags, expected_ret);
396 }
397 
398 /* Receive one byte and check the return value.
399  *
400  * expected_ret:
401  *  <0 Negative errno (for testing errors)
402  *   0 End-of-file
403  *   1 Success
404  */
405 void recv_byte(int fd, int expected_ret, int flags)
406 {
407 	uint8_t byte;
408 
409 	recv_buf(fd, &byte, sizeof(byte), flags, expected_ret);
410 
411 	if (byte != 'A') {
412 		fprintf(stderr, "unexpected byte read %c\n", byte);
413 		exit(EXIT_FAILURE);
414 	}
415 }
416 
417 /* Run test cases.  The program terminates if a failure occurs. */
418 void run_tests(const struct test_case *test_cases,
419 	       const struct test_opts *opts)
420 {
421 	int i;
422 
423 	for (i = 0; test_cases[i].name; i++) {
424 		void (*run)(const struct test_opts *opts);
425 		char *line;
426 
427 		printf("%d - %s...", i, test_cases[i].name);
428 		fflush(stdout);
429 
430 		/* Full barrier before executing the next test.  This
431 		 * ensures that client and server are executing the
432 		 * same test case.  In particular, it means whoever is
433 		 * faster will not see the peer still executing the
434 		 * last test.  This is important because port numbers
435 		 * can be used by multiple test cases.
436 		 */
437 		if (test_cases[i].skip)
438 			control_writeln("SKIP");
439 		else
440 			control_writeln("NEXT");
441 
442 		line = control_readln();
443 		if (control_cmpln(line, "SKIP", false) || test_cases[i].skip) {
444 
445 			printf("skipped\n");
446 
447 			free(line);
448 			continue;
449 		}
450 
451 		control_cmpln(line, "NEXT", true);
452 		free(line);
453 
454 		if (opts->mode == TEST_MODE_CLIENT)
455 			run = test_cases[i].run_client;
456 		else
457 			run = test_cases[i].run_server;
458 
459 		if (run)
460 			run(opts);
461 
462 		printf("ok\n");
463 	}
464 }
465 
466 void list_tests(const struct test_case *test_cases)
467 {
468 	int i;
469 
470 	printf("ID\tTest name\n");
471 
472 	for (i = 0; test_cases[i].name; i++)
473 		printf("%d\t%s\n", i, test_cases[i].name);
474 
475 	exit(EXIT_FAILURE);
476 }
477 
478 void skip_test(struct test_case *test_cases, size_t test_cases_len,
479 	       const char *test_id_str)
480 {
481 	unsigned long test_id;
482 	char *endptr = NULL;
483 
484 	errno = 0;
485 	test_id = strtoul(test_id_str, &endptr, 10);
486 	if (errno || *endptr != '\0') {
487 		fprintf(stderr, "malformed test ID \"%s\"\n", test_id_str);
488 		exit(EXIT_FAILURE);
489 	}
490 
491 	if (test_id >= test_cases_len) {
492 		fprintf(stderr, "test ID (%lu) larger than the max allowed (%lu)\n",
493 			test_id, test_cases_len - 1);
494 		exit(EXIT_FAILURE);
495 	}
496 
497 	test_cases[test_id].skip = true;
498 }
499 
500 unsigned long hash_djb2(const void *data, size_t len)
501 {
502 	unsigned long hash = 5381;
503 	int i = 0;
504 
505 	while (i < len) {
506 		hash = ((hash << 5) + hash) + ((unsigned char *)data)[i];
507 		i++;
508 	}
509 
510 	return hash;
511 }
512 
513 size_t iovec_bytes(const struct iovec *iov, size_t iovnum)
514 {
515 	size_t bytes;
516 	int i;
517 
518 	for (bytes = 0, i = 0; i < iovnum; i++)
519 		bytes += iov[i].iov_len;
520 
521 	return bytes;
522 }
523 
524 unsigned long iovec_hash_djb2(const struct iovec *iov, size_t iovnum)
525 {
526 	unsigned long hash;
527 	size_t iov_bytes;
528 	size_t offs;
529 	void *tmp;
530 	int i;
531 
532 	iov_bytes = iovec_bytes(iov, iovnum);
533 
534 	tmp = malloc(iov_bytes);
535 	if (!tmp) {
536 		perror("malloc");
537 		exit(EXIT_FAILURE);
538 	}
539 
540 	for (offs = 0, i = 0; i < iovnum; i++) {
541 		memcpy(tmp + offs, iov[i].iov_base, iov[i].iov_len);
542 		offs += iov[i].iov_len;
543 	}
544 
545 	hash = hash_djb2(tmp, iov_bytes);
546 	free(tmp);
547 
548 	return hash;
549 }
550 
551 /* Allocates and returns new 'struct iovec *' according pattern
552  * in the 'test_iovec'. For each element in the 'test_iovec' it
553  * allocates new element in the resulting 'iovec'. 'iov_len'
554  * of the new element is copied from 'test_iovec'. 'iov_base' is
555  * allocated depending on the 'iov_base' of 'test_iovec':
556  *
557  * 'iov_base' == NULL -> valid buf: mmap('iov_len').
558  *
559  * 'iov_base' == MAP_FAILED -> invalid buf:
560  *               mmap('iov_len'), then munmap('iov_len').
561  *               'iov_base' still contains result of
562  *               mmap().
563  *
564  * 'iov_base' == number -> unaligned valid buf:
565  *               mmap('iov_len') + number.
566  *
567  * 'iovnum' is number of elements in 'test_iovec'.
568  *
569  * Returns new 'iovec' or calls 'exit()' on error.
570  */
571 struct iovec *alloc_test_iovec(const struct iovec *test_iovec, int iovnum)
572 {
573 	struct iovec *iovec;
574 	int i;
575 
576 	iovec = malloc(sizeof(*iovec) * iovnum);
577 	if (!iovec) {
578 		perror("malloc");
579 		exit(EXIT_FAILURE);
580 	}
581 
582 	for (i = 0; i < iovnum; i++) {
583 		iovec[i].iov_len = test_iovec[i].iov_len;
584 
585 		iovec[i].iov_base = mmap(NULL, iovec[i].iov_len,
586 					 PROT_READ | PROT_WRITE,
587 					 MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE,
588 					 -1, 0);
589 		if (iovec[i].iov_base == MAP_FAILED) {
590 			perror("mmap");
591 			exit(EXIT_FAILURE);
592 		}
593 
594 		if (test_iovec[i].iov_base != MAP_FAILED)
595 			iovec[i].iov_base += (uintptr_t)test_iovec[i].iov_base;
596 	}
597 
598 	/* Unmap "invalid" elements. */
599 	for (i = 0; i < iovnum; i++) {
600 		if (test_iovec[i].iov_base == MAP_FAILED) {
601 			if (munmap(iovec[i].iov_base, iovec[i].iov_len)) {
602 				perror("munmap");
603 				exit(EXIT_FAILURE);
604 			}
605 		}
606 	}
607 
608 	for (i = 0; i < iovnum; i++) {
609 		int j;
610 
611 		if (test_iovec[i].iov_base == MAP_FAILED)
612 			continue;
613 
614 		for (j = 0; j < iovec[i].iov_len; j++)
615 			((uint8_t *)iovec[i].iov_base)[j] = rand() & 0xff;
616 	}
617 
618 	return iovec;
619 }
620 
621 /* Frees 'iovec *', previously allocated by 'alloc_test_iovec()'.
622  * On error calls 'exit()'.
623  */
624 void free_test_iovec(const struct iovec *test_iovec,
625 		     struct iovec *iovec, int iovnum)
626 {
627 	int i;
628 
629 	for (i = 0; i < iovnum; i++) {
630 		if (test_iovec[i].iov_base != MAP_FAILED) {
631 			if (test_iovec[i].iov_base)
632 				iovec[i].iov_base -= (uintptr_t)test_iovec[i].iov_base;
633 
634 			if (munmap(iovec[i].iov_base, iovec[i].iov_len)) {
635 				perror("munmap");
636 				exit(EXIT_FAILURE);
637 			}
638 		}
639 	}
640 
641 	free(iovec);
642 }
643