1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 2017 Red Hat, Inc.
7 * Author: Stefan Hajnoczi <stefanha@redhat.com>
20 /* Install signal handlers */
21 void init_signals(void)
23 struct sigaction act = {
24 .sa_handler = sigalrm,
27 sigaction(SIGALRM, &act, NULL);
28 signal(SIGPIPE, SIG_IGN);
31 /* Parse a CID in string representation */
32 unsigned int parse_cid(const char *str)
38 n = strtoul(str, &endptr, 10);
39 if (errno || *endptr != '\0') {
40 fprintf(stderr, "malformed CID \"%s\"\n", str);
46 /* Connect to <cid, port> and return the file descriptor. */
47 int vsock_stream_connect(unsigned int cid, unsigned int port)
51 struct sockaddr_vm svm;
54 .svm_family = AF_VSOCK,
62 control_expectln("LISTENING");
64 fd = socket(AF_VSOCK, SOCK_STREAM, 0);
66 timeout_begin(TIMEOUT);
68 ret = connect(fd, &addr.sa, sizeof(addr.svm));
69 timeout_check("connect");
70 } while (ret < 0 && errno == EINTR);
74 int old_errno = errno;
83 /* Listen on <cid, port> and return the first incoming connection. The remote
84 * address is stored to clientaddrp. clientaddrp may be NULL.
86 int vsock_stream_accept(unsigned int cid, unsigned int port,
87 struct sockaddr_vm *clientaddrp)
91 struct sockaddr_vm svm;
94 .svm_family = AF_VSOCK,
101 struct sockaddr_vm svm;
103 socklen_t clientaddr_len = sizeof(clientaddr.svm);
108 fd = socket(AF_VSOCK, SOCK_STREAM, 0);
110 if (bind(fd, &addr.sa, sizeof(addr.svm)) < 0) {
115 if (listen(fd, 1) < 0) {
120 control_writeln("LISTENING");
122 timeout_begin(TIMEOUT);
124 client_fd = accept(fd, &clientaddr.sa, &clientaddr_len);
125 timeout_check("accept");
126 } while (client_fd < 0 && errno == EINTR);
136 if (clientaddr_len != sizeof(clientaddr.svm)) {
137 fprintf(stderr, "unexpected addrlen from accept(2), %zu\n",
138 (size_t)clientaddr_len);
141 if (clientaddr.sa.sa_family != AF_VSOCK) {
142 fprintf(stderr, "expected AF_VSOCK from accept(2), got %d\n",
143 clientaddr.sa.sa_family);
148 *clientaddrp = clientaddr.svm;
152 /* Run test cases. The program terminates if a failure occurs. */
153 void run_tests(const struct test_case *test_cases,
154 const struct test_opts *opts)
158 for (i = 0; test_cases[i].name; i++) {
159 void (*run)(const struct test_opts *opts);
161 printf("%s...", test_cases[i].name);
164 if (opts->mode == TEST_MODE_CLIENT) {
165 /* Full barrier before executing the next test. This
166 * ensures that client and server are executing the
167 * same test case. In particular, it means whoever is
168 * faster will not see the peer still executing the
169 * last test. This is important because port numbers
170 * can be used by multiple test cases.
172 control_expectln("NEXT");
173 control_writeln("NEXT");
175 run = test_cases[i].run_client;
177 control_writeln("NEXT");
178 control_expectln("NEXT");
180 run = test_cases[i].run_server;