socket: Make errp the last parameter of vsock_connect_saddr
[qemu/ar7.git] / util / qemu-sockets.c
blob8188d9a8d720e537c1ef6b91ced20d7245e75f15
1 /*
2 * inet and unix socket functions for qemu
4 * (c) 2008 Gerd Hoffmann <kraxel@redhat.com>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; under version 2 of the License.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * Contributions after 2012-01-13 are licensed under the terms of the
16 * GNU GPL, version 2 or (at your option) any later version.
18 #include "qemu/osdep.h"
20 #ifdef CONFIG_AF_VSOCK
21 #include <linux/vm_sockets.h>
22 #endif /* CONFIG_AF_VSOCK */
24 #include "monitor/monitor.h"
25 #include "qapi/error.h"
26 #include "qemu/sockets.h"
27 #include "qemu/main-loop.h"
28 #include "qapi/clone-visitor.h"
29 #include "qapi/qobject-input-visitor.h"
30 #include "qapi/qobject-output-visitor.h"
31 #include "qapi-visit.h"
32 #include "qemu/cutils.h"
34 #ifndef AI_ADDRCONFIG
35 # define AI_ADDRCONFIG 0
36 #endif
38 #ifndef AI_V4MAPPED
39 # define AI_V4MAPPED 0
40 #endif
42 #ifndef AI_NUMERICSERV
43 # define AI_NUMERICSERV 0
44 #endif
47 static int inet_getport(struct addrinfo *e)
49 struct sockaddr_in *i4;
50 struct sockaddr_in6 *i6;
52 switch (e->ai_family) {
53 case PF_INET6:
54 i6 = (void*)e->ai_addr;
55 return ntohs(i6->sin6_port);
56 case PF_INET:
57 i4 = (void*)e->ai_addr;
58 return ntohs(i4->sin_port);
59 default:
60 return 0;
64 static void inet_setport(struct addrinfo *e, int port)
66 struct sockaddr_in *i4;
67 struct sockaddr_in6 *i6;
69 switch (e->ai_family) {
70 case PF_INET6:
71 i6 = (void*)e->ai_addr;
72 i6->sin6_port = htons(port);
73 break;
74 case PF_INET:
75 i4 = (void*)e->ai_addr;
76 i4->sin_port = htons(port);
77 break;
81 NetworkAddressFamily inet_netfamily(int family)
83 switch (family) {
84 case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
85 case PF_INET: return NETWORK_ADDRESS_FAMILY_IPV4;
86 case PF_UNIX: return NETWORK_ADDRESS_FAMILY_UNIX;
87 #ifdef CONFIG_AF_VSOCK
88 case PF_VSOCK: return NETWORK_ADDRESS_FAMILY_VSOCK;
89 #endif /* CONFIG_AF_VSOCK */
91 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
95 * Matrix we're trying to apply
97 * ipv4 ipv6 family
98 * - - PF_UNSPEC
99 * - f PF_INET
100 * - t PF_INET6
101 * f - PF_INET6
102 * f f <error>
103 * f t PF_INET6
104 * t - PF_INET
105 * t f PF_INET
106 * t t PF_INET6
108 * NB, this matrix is only about getting the necessary results
109 * from getaddrinfo(). Some of the cases require further work
110 * after reading results from getaddrinfo in order to fully
111 * apply the logic the end user wants. eg with the last case
112 * ipv4=t + ipv6=t + PF_INET6, getaddrinfo alone can only
113 * guarantee the ipv6=t part of the request - we need more
114 * checks to provide ipv4=t part of the guarantee. This is
115 * outside scope of this method and not currently handled by
116 * callers at all.
118 int inet_ai_family_from_address(InetSocketAddress *addr,
119 Error **errp)
121 if (addr->has_ipv6 && addr->has_ipv4 &&
122 !addr->ipv6 && !addr->ipv4) {
123 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
124 return PF_UNSPEC;
126 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
127 return PF_INET6;
129 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
130 return PF_INET;
132 return PF_UNSPEC;
135 static int inet_listen_saddr(InetSocketAddress *saddr,
136 int port_offset,
137 bool update_addr,
138 Error **errp)
140 struct addrinfo ai,*res,*e;
141 char port[33];
142 char uaddr[INET6_ADDRSTRLEN+1];
143 char uport[33];
144 int slisten, rc, port_min, port_max, p;
145 Error *err = NULL;
147 memset(&ai,0, sizeof(ai));
148 ai.ai_flags = AI_PASSIVE;
149 if (saddr->has_numeric && saddr->numeric) {
150 ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
152 ai.ai_family = inet_ai_family_from_address(saddr, &err);
153 ai.ai_socktype = SOCK_STREAM;
155 if (err) {
156 error_propagate(errp, err);
157 return -1;
160 if (saddr->host == NULL) {
161 error_setg(errp, "host not specified");
162 return -1;
164 if (saddr->port != NULL) {
165 pstrcpy(port, sizeof(port), saddr->port);
166 } else {
167 port[0] = '\0';
170 /* lookup */
171 if (port_offset) {
172 unsigned long long baseport;
173 if (strlen(port) == 0) {
174 error_setg(errp, "port not specified");
175 return -1;
177 if (parse_uint_full(port, &baseport, 10) < 0) {
178 error_setg(errp, "can't convert to a number: %s", port);
179 return -1;
181 if (baseport > 65535 ||
182 baseport + port_offset > 65535) {
183 error_setg(errp, "port %s out of range", port);
184 return -1;
186 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
188 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
189 strlen(port) ? port : NULL, &ai, &res);
190 if (rc != 0) {
191 error_setg(errp, "address resolution failed for %s:%s: %s",
192 saddr->host, port, gai_strerror(rc));
193 return -1;
196 /* create socket + bind */
197 for (e = res; e != NULL; e = e->ai_next) {
198 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
199 uaddr,INET6_ADDRSTRLEN,uport,32,
200 NI_NUMERICHOST | NI_NUMERICSERV);
201 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
202 if (slisten < 0) {
203 if (!e->ai_next) {
204 error_setg_errno(errp, errno, "Failed to create socket");
206 continue;
209 socket_set_fast_reuse(slisten);
210 #ifdef IPV6_V6ONLY
211 if (e->ai_family == PF_INET6) {
212 /* listen on both ipv4 and ipv6 */
213 const int off = 0;
214 qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,
215 sizeof(off));
217 #endif
219 port_min = inet_getport(e);
220 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
221 for (p = port_min; p <= port_max; p++) {
222 inet_setport(e, p);
223 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
224 goto listen;
226 if (p == port_max) {
227 if (!e->ai_next) {
228 error_setg_errno(errp, errno, "Failed to bind socket");
232 closesocket(slisten);
234 freeaddrinfo(res);
235 return -1;
237 listen:
238 if (listen(slisten,1) != 0) {
239 error_setg_errno(errp, errno, "Failed to listen on socket");
240 closesocket(slisten);
241 freeaddrinfo(res);
242 return -1;
244 if (update_addr) {
245 g_free(saddr->host);
246 saddr->host = g_strdup(uaddr);
247 g_free(saddr->port);
248 saddr->port = g_strdup_printf("%d",
249 inet_getport(e) - port_offset);
250 saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
251 saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
253 freeaddrinfo(res);
254 return slisten;
257 #ifdef _WIN32
258 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
259 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
260 #else
261 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
262 ((rc) == -EINPROGRESS)
263 #endif
265 /* Struct to store connect state for non blocking connect */
266 typedef struct ConnectState {
267 int fd;
268 struct addrinfo *addr_list;
269 struct addrinfo *current_addr;
270 NonBlockingConnectHandler *callback;
271 void *opaque;
272 } ConnectState;
274 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
275 ConnectState *connect_state, Error **errp);
277 static void wait_for_connect(void *opaque)
279 ConnectState *s = opaque;
280 int val = 0, rc = 0;
281 socklen_t valsize = sizeof(val);
282 bool in_progress;
283 Error *err = NULL;
285 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
287 do {
288 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
289 } while (rc == -1 && errno == EINTR);
291 /* update rc to contain error */
292 if (!rc && val) {
293 rc = -1;
294 errno = val;
297 /* connect error */
298 if (rc < 0) {
299 error_setg_errno(&err, errno, "Error connecting to socket");
300 closesocket(s->fd);
301 s->fd = rc;
304 /* try to connect to the next address on the list */
305 if (s->current_addr) {
306 while (s->current_addr->ai_next != NULL && s->fd < 0) {
307 s->current_addr = s->current_addr->ai_next;
308 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
309 if (s->fd < 0) {
310 error_free(err);
311 err = NULL;
312 error_setg_errno(&err, errno, "Unable to start socket connect");
314 /* connect in progress */
315 if (in_progress) {
316 goto out;
320 freeaddrinfo(s->addr_list);
323 if (s->callback) {
324 s->callback(s->fd, err, s->opaque);
326 g_free(s);
327 out:
328 error_free(err);
331 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
332 ConnectState *connect_state, Error **errp)
334 int sock, rc;
336 *in_progress = false;
338 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
339 if (sock < 0) {
340 error_setg_errno(errp, errno, "Failed to create socket");
341 return -1;
343 socket_set_fast_reuse(sock);
344 if (connect_state != NULL) {
345 qemu_set_nonblock(sock);
347 /* connect to peer */
348 do {
349 rc = 0;
350 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
351 rc = -errno;
353 } while (rc == -EINTR);
355 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
356 connect_state->fd = sock;
357 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
358 *in_progress = true;
359 } else if (rc < 0) {
360 error_setg_errno(errp, errno, "Failed to connect socket");
361 closesocket(sock);
362 return -1;
364 return sock;
367 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
368 Error **errp)
370 struct addrinfo ai, *res;
371 int rc;
372 Error *err = NULL;
373 static int useV4Mapped = 1;
375 memset(&ai, 0, sizeof(ai));
377 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
378 if (atomic_read(&useV4Mapped)) {
379 ai.ai_flags |= AI_V4MAPPED;
381 ai.ai_family = inet_ai_family_from_address(saddr, &err);
382 ai.ai_socktype = SOCK_STREAM;
384 if (err) {
385 error_propagate(errp, err);
386 return NULL;
389 if (saddr->host == NULL || saddr->port == NULL) {
390 error_setg(errp, "host and/or port not specified");
391 return NULL;
394 /* lookup */
395 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
397 /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
398 * then don't implement it in their getaddrinfo(). Detect
399 * this and retry without the flag since that's preferrable
400 * to a fatal error
402 if (rc == EAI_BADFLAGS &&
403 (ai.ai_flags & AI_V4MAPPED)) {
404 atomic_set(&useV4Mapped, 0);
405 ai.ai_flags &= ~AI_V4MAPPED;
406 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
408 if (rc != 0) {
409 error_setg(errp, "address resolution failed for %s:%s: %s",
410 saddr->host, saddr->port, gai_strerror(rc));
411 return NULL;
413 return res;
417 * Create a socket and connect it to an address.
419 * @saddr: Inet socket address specification
420 * @errp: set on error
421 * @callback: callback function for non-blocking connect
422 * @opaque: opaque for callback function
424 * Returns: -1 on error, file descriptor on success.
426 * If @callback is non-null, the connect is non-blocking. If this
427 * function succeeds, callback will be called when the connection
428 * completes, with the file descriptor on success, or -1 on error.
430 int inet_connect_saddr(InetSocketAddress *saddr,
431 NonBlockingConnectHandler *callback, void *opaque,
432 Error **errp)
434 Error *local_err = NULL;
435 struct addrinfo *res, *e;
436 int sock = -1;
437 bool in_progress;
438 ConnectState *connect_state = NULL;
440 res = inet_parse_connect_saddr(saddr, errp);
441 if (!res) {
442 return -1;
445 if (callback != NULL) {
446 connect_state = g_malloc0(sizeof(*connect_state));
447 connect_state->addr_list = res;
448 connect_state->callback = callback;
449 connect_state->opaque = opaque;
452 for (e = res; e != NULL; e = e->ai_next) {
453 error_free(local_err);
454 local_err = NULL;
455 if (connect_state != NULL) {
456 connect_state->current_addr = e;
458 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
459 if (sock >= 0) {
460 break;
464 if (sock < 0) {
465 error_propagate(errp, local_err);
466 } else if (in_progress) {
467 /* wait_for_connect() will do the rest */
468 return sock;
469 } else {
470 if (callback) {
471 callback(sock, NULL, opaque);
474 g_free(connect_state);
475 freeaddrinfo(res);
476 return sock;
479 static int inet_dgram_saddr(InetSocketAddress *sraddr,
480 InetSocketAddress *sladdr,
481 Error **errp)
483 struct addrinfo ai, *peer = NULL, *local = NULL;
484 const char *addr;
485 const char *port;
486 int sock = -1, rc;
487 Error *err = NULL;
489 /* lookup peer addr */
490 memset(&ai,0, sizeof(ai));
491 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
492 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
493 ai.ai_socktype = SOCK_DGRAM;
495 if (err) {
496 error_propagate(errp, err);
497 goto err;
500 addr = sraddr->host;
501 port = sraddr->port;
502 if (addr == NULL || strlen(addr) == 0) {
503 addr = "localhost";
505 if (port == NULL || strlen(port) == 0) {
506 error_setg(errp, "remote port not specified");
507 goto err;
510 if ((rc = getaddrinfo(addr, port, &ai, &peer)) != 0) {
511 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
512 gai_strerror(rc));
513 goto err;
516 /* lookup local addr */
517 memset(&ai,0, sizeof(ai));
518 ai.ai_flags = AI_PASSIVE;
519 ai.ai_family = peer->ai_family;
520 ai.ai_socktype = SOCK_DGRAM;
522 if (sladdr) {
523 addr = sladdr->host;
524 port = sladdr->port;
525 if (addr == NULL || strlen(addr) == 0) {
526 addr = NULL;
528 if (!port || strlen(port) == 0) {
529 port = "0";
531 } else {
532 addr = NULL;
533 port = "0";
536 if ((rc = getaddrinfo(addr, port, &ai, &local)) != 0) {
537 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
538 gai_strerror(rc));
539 goto err;
542 /* create socket */
543 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
544 if (sock < 0) {
545 error_setg_errno(errp, errno, "Failed to create socket");
546 goto err;
548 socket_set_fast_reuse(sock);
550 /* bind socket */
551 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
552 error_setg_errno(errp, errno, "Failed to bind socket");
553 goto err;
556 /* connect to peer */
557 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
558 error_setg_errno(errp, errno, "Failed to connect socket");
559 goto err;
562 freeaddrinfo(local);
563 freeaddrinfo(peer);
564 return sock;
566 err:
567 if (sock != -1) {
568 closesocket(sock);
570 if (local) {
571 freeaddrinfo(local);
573 if (peer) {
574 freeaddrinfo(peer);
577 return -1;
580 /* compatibility wrapper */
581 InetSocketAddress *inet_parse(const char *str, Error **errp)
583 InetSocketAddress *addr;
584 const char *optstr, *h;
585 char host[65];
586 char port[33];
587 int to;
588 int pos;
590 addr = g_new0(InetSocketAddress, 1);
592 /* parse address */
593 if (str[0] == ':') {
594 /* no host given */
595 host[0] = '\0';
596 if (sscanf(str, ":%32[^,]%n", port, &pos) != 1) {
597 error_setg(errp, "error parsing port in address '%s'", str);
598 goto fail;
600 } else if (str[0] == '[') {
601 /* IPv6 addr */
602 if (sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos) != 2) {
603 error_setg(errp, "error parsing IPv6 address '%s'", str);
604 goto fail;
606 addr->ipv6 = addr->has_ipv6 = true;
607 } else {
608 /* hostname or IPv4 addr */
609 if (sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos) != 2) {
610 error_setg(errp, "error parsing address '%s'", str);
611 goto fail;
613 if (host[strspn(host, "0123456789.")] == '\0') {
614 addr->ipv4 = addr->has_ipv4 = true;
618 addr->host = g_strdup(host);
619 addr->port = g_strdup(port);
621 /* parse options */
622 optstr = str + pos;
623 h = strstr(optstr, ",to=");
624 if (h) {
625 h += 4;
626 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
627 (h[pos] != '\0' && h[pos] != ',')) {
628 error_setg(errp, "error parsing to= argument");
629 goto fail;
631 addr->has_to = true;
632 addr->to = to;
634 if (strstr(optstr, ",ipv4")) {
635 addr->ipv4 = addr->has_ipv4 = true;
637 if (strstr(optstr, ",ipv6")) {
638 addr->ipv6 = addr->has_ipv6 = true;
640 return addr;
642 fail:
643 qapi_free_InetSocketAddress(addr);
644 return NULL;
649 * Create a blocking socket and connect it to an address.
651 * @str: address string
652 * @errp: set in case of an error
654 * Returns -1 in case of error, file descriptor on success
656 int inet_connect(const char *str, Error **errp)
658 int sock = -1;
659 InetSocketAddress *addr;
661 addr = inet_parse(str, errp);
662 if (addr != NULL) {
663 sock = inet_connect_saddr(addr, NULL, NULL, errp);
664 qapi_free_InetSocketAddress(addr);
666 return sock;
669 #ifdef CONFIG_AF_VSOCK
670 static bool vsock_parse_vaddr_to_sockaddr(const VsockSocketAddress *vaddr,
671 struct sockaddr_vm *svm,
672 Error **errp)
674 unsigned long long val;
676 memset(svm, 0, sizeof(*svm));
677 svm->svm_family = AF_VSOCK;
679 if (parse_uint_full(vaddr->cid, &val, 10) < 0 ||
680 val > UINT32_MAX) {
681 error_setg(errp, "Failed to parse cid '%s'", vaddr->cid);
682 return false;
684 svm->svm_cid = val;
686 if (parse_uint_full(vaddr->port, &val, 10) < 0 ||
687 val > UINT32_MAX) {
688 error_setg(errp, "Failed to parse port '%s'", vaddr->port);
689 return false;
691 svm->svm_port = val;
693 return true;
696 static int vsock_connect_addr(const struct sockaddr_vm *svm, bool *in_progress,
697 ConnectState *connect_state, Error **errp)
699 int sock, rc;
701 *in_progress = false;
703 sock = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
704 if (sock < 0) {
705 error_setg_errno(errp, errno, "Failed to create socket");
706 return -1;
708 if (connect_state != NULL) {
709 qemu_set_nonblock(sock);
711 /* connect to peer */
712 do {
713 rc = 0;
714 if (connect(sock, (const struct sockaddr *)svm, sizeof(*svm)) < 0) {
715 rc = -errno;
717 } while (rc == -EINTR);
719 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
720 connect_state->fd = sock;
721 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
722 *in_progress = true;
723 } else if (rc < 0) {
724 error_setg_errno(errp, errno, "Failed to connect socket");
725 closesocket(sock);
726 return -1;
728 return sock;
731 static int vsock_connect_saddr(VsockSocketAddress *vaddr,
732 NonBlockingConnectHandler *callback,
733 void *opaque,
734 Error **errp)
736 struct sockaddr_vm svm;
737 int sock = -1;
738 bool in_progress;
739 ConnectState *connect_state = NULL;
741 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
742 return -1;
745 if (callback != NULL) {
746 connect_state = g_malloc0(sizeof(*connect_state));
747 connect_state->callback = callback;
748 connect_state->opaque = opaque;
751 sock = vsock_connect_addr(&svm, &in_progress, connect_state, errp);
752 if (sock < 0) {
753 /* do nothing */
754 } else if (in_progress) {
755 /* wait_for_connect() will do the rest */
756 return sock;
757 } else {
758 if (callback) {
759 callback(sock, NULL, opaque);
762 g_free(connect_state);
763 return sock;
766 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
767 Error **errp)
769 struct sockaddr_vm svm;
770 int slisten;
772 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
773 return -1;
776 slisten = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
777 if (slisten < 0) {
778 error_setg_errno(errp, errno, "Failed to create socket");
779 return -1;
782 if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
783 error_setg_errno(errp, errno, "Failed to bind socket");
784 closesocket(slisten);
785 return -1;
788 if (listen(slisten, 1) != 0) {
789 error_setg_errno(errp, errno, "Failed to listen on socket");
790 closesocket(slisten);
791 return -1;
793 return slisten;
796 static VsockSocketAddress *vsock_parse(const char *str, Error **errp)
798 VsockSocketAddress *addr = NULL;
799 char cid[33];
800 char port[33];
801 int n;
803 if (sscanf(str, "%32[^:]:%32[^,]%n", cid, port, &n) != 2) {
804 error_setg(errp, "error parsing address '%s'", str);
805 return NULL;
807 if (str[n] != '\0') {
808 error_setg(errp, "trailing characters in address '%s'", str);
809 return NULL;
812 addr = g_new0(VsockSocketAddress, 1);
813 addr->cid = g_strdup(cid);
814 addr->port = g_strdup(port);
815 return addr;
817 #else
818 static void vsock_unsupported(Error **errp)
820 error_setg(errp, "socket family AF_VSOCK unsupported");
823 static int vsock_connect_saddr(VsockSocketAddress *vaddr,
824 NonBlockingConnectHandler *callback,
825 void *opaque, Error **errp)
827 vsock_unsupported(errp);
828 return -1;
831 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
832 Error **errp)
834 vsock_unsupported(errp);
835 return -1;
838 static VsockSocketAddress *vsock_parse(const char *str, Error **errp)
840 vsock_unsupported(errp);
841 return NULL;
843 #endif /* CONFIG_AF_VSOCK */
845 #ifndef _WIN32
847 static int unix_listen_saddr(UnixSocketAddress *saddr,
848 bool update_addr,
849 Error **errp)
851 struct sockaddr_un un;
852 int sock, fd;
854 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
855 if (sock < 0) {
856 error_setg_errno(errp, errno, "Failed to create Unix socket");
857 return -1;
860 memset(&un, 0, sizeof(un));
861 un.sun_family = AF_UNIX;
862 if (saddr->path && strlen(saddr->path)) {
863 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
864 } else {
865 const char *tmpdir = getenv("TMPDIR");
866 tmpdir = tmpdir ? tmpdir : "/tmp";
867 if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
868 tmpdir) >= sizeof(un.sun_path)) {
869 error_setg_errno(errp, errno,
870 "TMPDIR environment variable (%s) too large", tmpdir);
871 goto err;
875 * This dummy fd usage silences the mktemp() unsecure warning.
876 * Using mkstemp() doesn't make things more secure here
877 * though. bind() complains about existing files, so we have
878 * to unlink first and thus re-open the race window. The
879 * worst case possible is bind() failing, i.e. a DoS attack.
881 fd = mkstemp(un.sun_path);
882 if (fd < 0) {
883 error_setg_errno(errp, errno,
884 "Failed to make a temporary socket name in %s", tmpdir);
885 goto err;
887 close(fd);
888 if (update_addr) {
889 g_free(saddr->path);
890 saddr->path = g_strdup(un.sun_path);
894 if (unlink(un.sun_path) < 0 && errno != ENOENT) {
895 error_setg_errno(errp, errno,
896 "Failed to unlink socket %s", un.sun_path);
897 goto err;
899 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
900 error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);
901 goto err;
903 if (listen(sock, 1) < 0) {
904 error_setg_errno(errp, errno, "Failed to listen on socket");
905 goto err;
908 return sock;
910 err:
911 closesocket(sock);
912 return -1;
915 static int unix_connect_saddr(UnixSocketAddress *saddr,
916 NonBlockingConnectHandler *callback, void *opaque,
917 Error **errp)
919 struct sockaddr_un un;
920 ConnectState *connect_state = NULL;
921 int sock, rc;
923 if (saddr->path == NULL) {
924 error_setg(errp, "unix connect: no path specified");
925 return -1;
928 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
929 if (sock < 0) {
930 error_setg_errno(errp, errno, "Failed to create socket");
931 return -1;
933 if (callback != NULL) {
934 connect_state = g_malloc0(sizeof(*connect_state));
935 connect_state->callback = callback;
936 connect_state->opaque = opaque;
937 qemu_set_nonblock(sock);
940 memset(&un, 0, sizeof(un));
941 un.sun_family = AF_UNIX;
942 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
944 /* connect to peer */
945 do {
946 rc = 0;
947 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
948 rc = -errno;
950 } while (rc == -EINTR);
952 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
953 connect_state->fd = sock;
954 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
955 return sock;
956 } else if (rc >= 0) {
957 /* non blocking socket immediate success, call callback */
958 if (callback != NULL) {
959 callback(sock, NULL, opaque);
963 if (rc < 0) {
964 error_setg_errno(errp, -rc, "Failed to connect socket");
965 close(sock);
966 sock = -1;
969 g_free(connect_state);
970 return sock;
973 #else
975 static int unix_listen_saddr(UnixSocketAddress *saddr,
976 bool update_addr,
977 Error **errp)
979 error_setg(errp, "unix sockets are not available on windows");
980 errno = ENOTSUP;
981 return -1;
984 static int unix_connect_saddr(UnixSocketAddress *saddr,
985 NonBlockingConnectHandler *callback, void *opaque,
986 Error **errp)
988 error_setg(errp, "unix sockets are not available on windows");
989 errno = ENOTSUP;
990 return -1;
992 #endif
994 /* compatibility wrapper */
995 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
997 char *path, *optstr;
998 int sock, len;
999 UnixSocketAddress *saddr;
1001 saddr = g_new0(UnixSocketAddress, 1);
1003 optstr = strchr(str, ',');
1004 if (optstr) {
1005 len = optstr - str;
1006 if (len) {
1007 path = g_malloc(len+1);
1008 snprintf(path, len+1, "%.*s", len, str);
1009 saddr->path = path;
1011 } else {
1012 saddr->path = g_strdup(str);
1015 sock = unix_listen_saddr(saddr, true, errp);
1017 if (sock != -1 && ostr) {
1018 snprintf(ostr, olen, "%s%s", saddr->path, optstr ? optstr : "");
1021 qapi_free_UnixSocketAddress(saddr);
1022 return sock;
1025 int unix_connect(const char *path, Error **errp)
1027 UnixSocketAddress *saddr;
1028 int sock;
1030 saddr = g_new0(UnixSocketAddress, 1);
1031 saddr->path = g_strdup(path);
1032 sock = unix_connect_saddr(saddr, NULL, NULL, errp);
1033 qapi_free_UnixSocketAddress(saddr);
1034 return sock;
1038 SocketAddress *socket_parse(const char *str, Error **errp)
1040 SocketAddress *addr;
1042 addr = g_new0(SocketAddress, 1);
1043 if (strstart(str, "unix:", NULL)) {
1044 if (str[5] == '\0') {
1045 error_setg(errp, "invalid Unix socket address");
1046 goto fail;
1047 } else {
1048 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1049 addr->u.q_unix.data = g_new(UnixSocketAddress, 1);
1050 addr->u.q_unix.data->path = g_strdup(str + 5);
1052 } else if (strstart(str, "fd:", NULL)) {
1053 if (str[3] == '\0') {
1054 error_setg(errp, "invalid file descriptor address");
1055 goto fail;
1056 } else {
1057 addr->type = SOCKET_ADDRESS_KIND_FD;
1058 addr->u.fd.data = g_new(String, 1);
1059 addr->u.fd.data->str = g_strdup(str + 3);
1061 } else if (strstart(str, "vsock:", NULL)) {
1062 addr->type = SOCKET_ADDRESS_KIND_VSOCK;
1063 addr->u.vsock.data = vsock_parse(str + strlen("vsock:"), errp);
1064 if (addr->u.vsock.data == NULL) {
1065 goto fail;
1067 } else {
1068 addr->type = SOCKET_ADDRESS_KIND_INET;
1069 addr->u.inet.data = inet_parse(str, errp);
1070 if (addr->u.inet.data == NULL) {
1071 goto fail;
1074 return addr;
1076 fail:
1077 qapi_free_SocketAddress(addr);
1078 return NULL;
1081 int socket_connect(SocketAddress *addr, NonBlockingConnectHandler *callback,
1082 void *opaque, Error **errp)
1084 int fd;
1086 switch (addr->type) {
1087 case SOCKET_ADDRESS_KIND_INET:
1088 fd = inet_connect_saddr(addr->u.inet.data, callback, opaque, errp);
1089 break;
1091 case SOCKET_ADDRESS_KIND_UNIX:
1092 fd = unix_connect_saddr(addr->u.q_unix.data, callback, opaque, errp);
1093 break;
1095 case SOCKET_ADDRESS_KIND_FD:
1096 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
1097 if (fd >= 0 && callback) {
1098 qemu_set_nonblock(fd);
1099 callback(fd, NULL, opaque);
1101 break;
1103 case SOCKET_ADDRESS_KIND_VSOCK:
1104 fd = vsock_connect_saddr(addr->u.vsock.data, callback, opaque, errp);
1105 break;
1107 default:
1108 abort();
1110 return fd;
1113 int socket_listen(SocketAddress *addr, Error **errp)
1115 int fd;
1117 switch (addr->type) {
1118 case SOCKET_ADDRESS_KIND_INET:
1119 fd = inet_listen_saddr(addr->u.inet.data, 0, false, errp);
1120 break;
1122 case SOCKET_ADDRESS_KIND_UNIX:
1123 fd = unix_listen_saddr(addr->u.q_unix.data, false, errp);
1124 break;
1126 case SOCKET_ADDRESS_KIND_FD:
1127 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
1128 break;
1130 case SOCKET_ADDRESS_KIND_VSOCK:
1131 fd = vsock_listen_saddr(addr->u.vsock.data, errp);
1132 break;
1134 default:
1135 abort();
1137 return fd;
1140 void socket_listen_cleanup(int fd, Error **errp)
1142 SocketAddress *addr;
1144 addr = socket_local_address(fd, errp);
1146 if (addr->type == SOCKET_ADDRESS_KIND_UNIX
1147 && addr->u.q_unix.data->path) {
1148 if (unlink(addr->u.q_unix.data->path) < 0 && errno != ENOENT) {
1149 error_setg_errno(errp, errno,
1150 "Failed to unlink socket %s",
1151 addr->u.q_unix.data->path);
1155 qapi_free_SocketAddress(addr);
1158 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
1160 int fd;
1163 * TODO SOCKET_ADDRESS_KIND_FD when fd is AF_INET or AF_INET6
1164 * (although other address families can do SOCK_DGRAM, too)
1166 switch (remote->type) {
1167 case SOCKET_ADDRESS_KIND_INET:
1168 fd = inet_dgram_saddr(remote->u.inet.data,
1169 local ? local->u.inet.data : NULL, errp);
1170 break;
1172 default:
1173 error_setg(errp, "socket type unsupported for datagram");
1174 fd = -1;
1176 return fd;
1180 static SocketAddress *
1181 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1182 socklen_t salen,
1183 Error **errp)
1185 char host[NI_MAXHOST];
1186 char serv[NI_MAXSERV];
1187 SocketAddress *addr;
1188 InetSocketAddress *inet;
1189 int ret;
1191 ret = getnameinfo((struct sockaddr *)sa, salen,
1192 host, sizeof(host),
1193 serv, sizeof(serv),
1194 NI_NUMERICHOST | NI_NUMERICSERV);
1195 if (ret != 0) {
1196 error_setg(errp, "Cannot format numeric socket address: %s",
1197 gai_strerror(ret));
1198 return NULL;
1201 addr = g_new0(SocketAddress, 1);
1202 addr->type = SOCKET_ADDRESS_KIND_INET;
1203 inet = addr->u.inet.data = g_new0(InetSocketAddress, 1);
1204 inet->host = g_strdup(host);
1205 inet->port = g_strdup(serv);
1206 if (sa->ss_family == AF_INET) {
1207 inet->has_ipv4 = inet->ipv4 = true;
1208 } else {
1209 inet->has_ipv6 = inet->ipv6 = true;
1212 return addr;
1216 #ifndef WIN32
1217 static SocketAddress *
1218 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1219 socklen_t salen,
1220 Error **errp)
1222 SocketAddress *addr;
1223 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1225 addr = g_new0(SocketAddress, 1);
1226 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1227 addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
1228 if (su->sun_path[0]) {
1229 addr->u.q_unix.data->path = g_strndup(su->sun_path,
1230 sizeof(su->sun_path));
1233 return addr;
1235 #endif /* WIN32 */
1237 #ifdef CONFIG_AF_VSOCK
1238 static SocketAddress *
1239 socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,
1240 socklen_t salen,
1241 Error **errp)
1243 SocketAddress *addr;
1244 VsockSocketAddress *vaddr;
1245 struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;
1247 addr = g_new0(SocketAddress, 1);
1248 addr->type = SOCKET_ADDRESS_KIND_VSOCK;
1249 addr->u.vsock.data = vaddr = g_new0(VsockSocketAddress, 1);
1250 vaddr->cid = g_strdup_printf("%u", svm->svm_cid);
1251 vaddr->port = g_strdup_printf("%u", svm->svm_port);
1253 return addr;
1255 #endif /* CONFIG_AF_VSOCK */
1257 SocketAddress *
1258 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1259 socklen_t salen,
1260 Error **errp)
1262 switch (sa->ss_family) {
1263 case AF_INET:
1264 case AF_INET6:
1265 return socket_sockaddr_to_address_inet(sa, salen, errp);
1267 #ifndef WIN32
1268 case AF_UNIX:
1269 return socket_sockaddr_to_address_unix(sa, salen, errp);
1270 #endif /* WIN32 */
1272 #ifdef CONFIG_AF_VSOCK
1273 case AF_VSOCK:
1274 return socket_sockaddr_to_address_vsock(sa, salen, errp);
1275 #endif
1277 default:
1278 error_setg(errp, "socket family %d unsupported",
1279 sa->ss_family);
1280 return NULL;
1282 return 0;
1286 SocketAddress *socket_local_address(int fd, Error **errp)
1288 struct sockaddr_storage ss;
1289 socklen_t sslen = sizeof(ss);
1291 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1292 error_setg_errno(errp, errno, "%s",
1293 "Unable to query local socket address");
1294 return NULL;
1297 return socket_sockaddr_to_address(&ss, sslen, errp);
1301 SocketAddress *socket_remote_address(int fd, Error **errp)
1303 struct sockaddr_storage ss;
1304 socklen_t sslen = sizeof(ss);
1306 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1307 error_setg_errno(errp, errno, "%s",
1308 "Unable to query remote socket address");
1309 return NULL;
1312 return socket_sockaddr_to_address(&ss, sslen, errp);
1315 char *socket_address_to_string(struct SocketAddress *addr, Error **errp)
1317 char *buf;
1318 InetSocketAddress *inet;
1320 switch (addr->type) {
1321 case SOCKET_ADDRESS_KIND_INET:
1322 inet = addr->u.inet.data;
1323 if (strchr(inet->host, ':') == NULL) {
1324 buf = g_strdup_printf("%s:%s", inet->host, inet->port);
1325 } else {
1326 buf = g_strdup_printf("[%s]:%s", inet->host, inet->port);
1328 break;
1330 case SOCKET_ADDRESS_KIND_UNIX:
1331 buf = g_strdup(addr->u.q_unix.data->path);
1332 break;
1334 case SOCKET_ADDRESS_KIND_FD:
1335 buf = g_strdup(addr->u.fd.data->str);
1336 break;
1338 case SOCKET_ADDRESS_KIND_VSOCK:
1339 buf = g_strdup_printf("%s:%s",
1340 addr->u.vsock.data->cid,
1341 addr->u.vsock.data->port);
1342 break;
1344 default:
1345 abort();
1347 return buf;
1350 SocketAddress *socket_address_crumple(SocketAddressFlat *addr_flat)
1352 SocketAddress *addr = g_new(SocketAddress, 1);
1354 switch (addr_flat->type) {
1355 case SOCKET_ADDRESS_FLAT_TYPE_INET:
1356 addr->type = SOCKET_ADDRESS_KIND_INET;
1357 addr->u.inet.data = QAPI_CLONE(InetSocketAddress,
1358 &addr_flat->u.inet);
1359 break;
1360 case SOCKET_ADDRESS_FLAT_TYPE_UNIX:
1361 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1362 addr->u.q_unix.data = QAPI_CLONE(UnixSocketAddress,
1363 &addr_flat->u.q_unix);
1364 break;
1365 case SOCKET_ADDRESS_FLAT_TYPE_VSOCK:
1366 addr->type = SOCKET_ADDRESS_KIND_VSOCK;
1367 addr->u.vsock.data = QAPI_CLONE(VsockSocketAddress,
1368 &addr_flat->u.vsock);
1369 break;
1370 case SOCKET_ADDRESS_FLAT_TYPE_FD:
1371 addr->type = SOCKET_ADDRESS_KIND_FD;
1372 addr->u.fd.data = QAPI_CLONE(String, &addr_flat->u.fd);
1373 break;
1374 default:
1375 abort();
1378 return addr;