Merge remote-tracking branch 'remotes/pmaydell/tags/pull-target-arm-20190613-1' into...
[qemu/ar7.git] / util / qemu-sockets.c
bloba5092dbd12e7747ae322488a0d9b6b69d9f7920d
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 "qemu-common.h"
25 #include "monitor/monitor.h"
26 #include "qapi/clone-visitor.h"
27 #include "qapi/error.h"
28 #include "qapi/qapi-visit-sockets.h"
29 #include "qemu/sockets.h"
30 #include "qemu/main-loop.h"
31 #include "qapi/qobject-input-visitor.h"
32 #include "qapi/qobject-output-visitor.h"
33 #include "qemu/cutils.h"
35 #ifndef AI_ADDRCONFIG
36 # define AI_ADDRCONFIG 0
37 #endif
39 #ifndef AI_V4MAPPED
40 # define AI_V4MAPPED 0
41 #endif
43 #ifndef AI_NUMERICSERV
44 # define AI_NUMERICSERV 0
45 #endif
48 static int inet_getport(struct addrinfo *e)
50 struct sockaddr_in *i4;
51 struct sockaddr_in6 *i6;
53 switch (e->ai_family) {
54 case PF_INET6:
55 i6 = (void*)e->ai_addr;
56 return ntohs(i6->sin6_port);
57 case PF_INET:
58 i4 = (void*)e->ai_addr;
59 return ntohs(i4->sin_port);
60 default:
61 return 0;
65 static void inet_setport(struct addrinfo *e, int port)
67 struct sockaddr_in *i4;
68 struct sockaddr_in6 *i6;
70 switch (e->ai_family) {
71 case PF_INET6:
72 i6 = (void*)e->ai_addr;
73 i6->sin6_port = htons(port);
74 break;
75 case PF_INET:
76 i4 = (void*)e->ai_addr;
77 i4->sin_port = htons(port);
78 break;
82 NetworkAddressFamily inet_netfamily(int family)
84 switch (family) {
85 case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
86 case PF_INET: return NETWORK_ADDRESS_FAMILY_IPV4;
87 case PF_UNIX: return NETWORK_ADDRESS_FAMILY_UNIX;
88 #ifdef CONFIG_AF_VSOCK
89 case PF_VSOCK: return NETWORK_ADDRESS_FAMILY_VSOCK;
90 #endif /* CONFIG_AF_VSOCK */
92 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
95 bool fd_is_socket(int fd)
97 int optval;
98 socklen_t optlen = sizeof(optval);
99 return !qemu_getsockopt(fd, SOL_SOCKET, SO_TYPE, &optval, &optlen);
104 * Matrix we're trying to apply
106 * ipv4 ipv6 family
107 * - - PF_UNSPEC
108 * - f PF_INET
109 * - t PF_INET6
110 * f - PF_INET6
111 * f f <error>
112 * f t PF_INET6
113 * t - PF_INET
114 * t f PF_INET
115 * t t PF_INET6/PF_UNSPEC
117 * NB, this matrix is only about getting the necessary results
118 * from getaddrinfo(). Some of the cases require further work
119 * after reading results from getaddrinfo in order to fully
120 * apply the logic the end user wants.
122 * In the first and last cases, we must set IPV6_V6ONLY=0
123 * when binding, to allow a single listener to potentially
124 * accept both IPv4+6 addresses.
126 int inet_ai_family_from_address(InetSocketAddress *addr,
127 Error **errp)
129 if (addr->has_ipv6 && addr->has_ipv4 &&
130 !addr->ipv6 && !addr->ipv4) {
131 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
132 return PF_UNSPEC;
134 if ((addr->has_ipv6 && addr->ipv6) && (addr->has_ipv4 && addr->ipv4)) {
136 * Some backends can only do a single listener. In that case
137 * we want empty hostname to resolve to "::" and then use the
138 * flag IPV6_V6ONLY==0 to get both protocols on 1 socket. This
139 * doesn't work for addresses other than "", so they're just
140 * inevitably broken until multiple listeners can be used,
141 * and thus we honour getaddrinfo automatic protocol detection
142 * Once all backends do multi-listener, remove the PF_INET6
143 * branch entirely.
145 if (!addr->host || g_str_equal(addr->host, "")) {
146 return PF_INET6;
147 } else {
148 return PF_UNSPEC;
151 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
152 return PF_INET6;
154 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
155 return PF_INET;
157 return PF_UNSPEC;
160 static int create_fast_reuse_socket(struct addrinfo *e)
162 int slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
163 if (slisten < 0) {
164 return -1;
166 socket_set_fast_reuse(slisten);
167 return slisten;
170 static int try_bind(int socket, InetSocketAddress *saddr, struct addrinfo *e)
172 #ifndef IPV6_V6ONLY
173 return bind(socket, e->ai_addr, e->ai_addrlen);
174 #else
176 * Deals with first & last cases in matrix in comment
177 * for inet_ai_family_from_address().
179 int v6only =
180 ((!saddr->has_ipv4 && !saddr->has_ipv6) ||
181 (saddr->has_ipv4 && saddr->ipv4 &&
182 saddr->has_ipv6 && saddr->ipv6)) ? 0 : 1;
183 int stat;
185 rebind:
186 if (e->ai_family == PF_INET6) {
187 qemu_setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, &v6only,
188 sizeof(v6only));
191 stat = bind(socket, e->ai_addr, e->ai_addrlen);
192 if (!stat) {
193 return 0;
196 /* If we got EADDRINUSE from an IPv6 bind & v6only is unset,
197 * it could be that the IPv4 port is already claimed, so retry
198 * with v6only set
200 if (e->ai_family == PF_INET6 && errno == EADDRINUSE && !v6only) {
201 v6only = 1;
202 goto rebind;
204 return stat;
205 #endif
208 static int inet_listen_saddr(InetSocketAddress *saddr,
209 int port_offset,
210 Error **errp)
212 struct addrinfo ai,*res,*e;
213 char port[33];
214 char uaddr[INET6_ADDRSTRLEN+1];
215 char uport[33];
216 int rc, port_min, port_max, p;
217 int slisten = -1;
218 int saved_errno = 0;
219 bool socket_created = false;
220 Error *err = NULL;
222 memset(&ai,0, sizeof(ai));
223 ai.ai_flags = AI_PASSIVE;
224 if (saddr->has_numeric && saddr->numeric) {
225 ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
227 ai.ai_family = inet_ai_family_from_address(saddr, &err);
228 ai.ai_socktype = SOCK_STREAM;
230 if (err) {
231 error_propagate(errp, err);
232 return -1;
235 if (saddr->host == NULL) {
236 error_setg(errp, "host not specified");
237 return -1;
239 if (saddr->port != NULL) {
240 pstrcpy(port, sizeof(port), saddr->port);
241 } else {
242 port[0] = '\0';
245 /* lookup */
246 if (port_offset) {
247 unsigned long long baseport;
248 if (strlen(port) == 0) {
249 error_setg(errp, "port not specified");
250 return -1;
252 if (parse_uint_full(port, &baseport, 10) < 0) {
253 error_setg(errp, "can't convert to a number: %s", port);
254 return -1;
256 if (baseport > 65535 ||
257 baseport + port_offset > 65535) {
258 error_setg(errp, "port %s out of range", port);
259 return -1;
261 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
263 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
264 strlen(port) ? port : NULL, &ai, &res);
265 if (rc != 0) {
266 error_setg(errp, "address resolution failed for %s:%s: %s",
267 saddr->host, port, gai_strerror(rc));
268 return -1;
271 /* create socket + bind/listen */
272 for (e = res; e != NULL; e = e->ai_next) {
273 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
274 uaddr,INET6_ADDRSTRLEN,uport,32,
275 NI_NUMERICHOST | NI_NUMERICSERV);
277 port_min = inet_getport(e);
278 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
279 for (p = port_min; p <= port_max; p++) {
280 inet_setport(e, p);
282 slisten = create_fast_reuse_socket(e);
283 if (slisten < 0) {
284 /* First time we expect we might fail to create the socket
285 * eg if 'e' has AF_INET6 but ipv6 kmod is not loaded.
286 * Later iterations should always succeed if first iteration
287 * worked though, so treat that as fatal.
289 if (p == port_min) {
290 continue;
291 } else {
292 error_setg_errno(errp, errno,
293 "Failed to recreate failed listening socket");
294 goto listen_failed;
297 socket_created = true;
299 rc = try_bind(slisten, saddr, e);
300 if (rc < 0) {
301 if (errno != EADDRINUSE) {
302 error_setg_errno(errp, errno, "Failed to bind socket");
303 goto listen_failed;
305 } else {
306 if (!listen(slisten, 1)) {
307 goto listen_ok;
309 if (errno != EADDRINUSE) {
310 error_setg_errno(errp, errno, "Failed to listen on socket");
311 goto listen_failed;
314 /* Someone else managed to bind to the same port and beat us
315 * to listen on it! Socket semantics does not allow us to
316 * recover from this situation, so we need to recreate the
317 * socket to allow bind attempts for subsequent ports:
319 closesocket(slisten);
320 slisten = -1;
323 error_setg_errno(errp, errno,
324 socket_created ?
325 "Failed to find an available port" :
326 "Failed to create a socket");
327 listen_failed:
328 saved_errno = errno;
329 if (slisten >= 0) {
330 closesocket(slisten);
332 freeaddrinfo(res);
333 errno = saved_errno;
334 return -1;
336 listen_ok:
337 freeaddrinfo(res);
338 return slisten;
341 #ifdef _WIN32
342 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
343 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
344 #else
345 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
346 ((rc) == -EINPROGRESS)
347 #endif
349 static int inet_connect_addr(struct addrinfo *addr, Error **errp);
351 static int inet_connect_addr(struct addrinfo *addr, Error **errp)
353 int sock, rc;
355 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
356 if (sock < 0) {
357 error_setg_errno(errp, errno, "Failed to create socket");
358 return -1;
360 socket_set_fast_reuse(sock);
362 /* connect to peer */
363 do {
364 rc = 0;
365 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
366 rc = -errno;
368 } while (rc == -EINTR);
370 if (rc < 0) {
371 error_setg_errno(errp, errno, "Failed to connect socket");
372 closesocket(sock);
373 return -1;
376 return sock;
379 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
380 Error **errp)
382 struct addrinfo ai, *res;
383 int rc;
384 Error *err = NULL;
385 static int useV4Mapped = 1;
387 memset(&ai, 0, sizeof(ai));
389 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
390 if (atomic_read(&useV4Mapped)) {
391 ai.ai_flags |= AI_V4MAPPED;
393 ai.ai_family = inet_ai_family_from_address(saddr, &err);
394 ai.ai_socktype = SOCK_STREAM;
396 if (err) {
397 error_propagate(errp, err);
398 return NULL;
401 if (saddr->host == NULL || saddr->port == NULL) {
402 error_setg(errp, "host and/or port not specified");
403 return NULL;
406 /* lookup */
407 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
409 /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
410 * then don't implement it in their getaddrinfo(). Detect
411 * this and retry without the flag since that's preferrable
412 * to a fatal error
414 if (rc == EAI_BADFLAGS &&
415 (ai.ai_flags & AI_V4MAPPED)) {
416 atomic_set(&useV4Mapped, 0);
417 ai.ai_flags &= ~AI_V4MAPPED;
418 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
420 if (rc != 0) {
421 error_setg(errp, "address resolution failed for %s:%s: %s",
422 saddr->host, saddr->port, gai_strerror(rc));
423 return NULL;
425 return res;
429 * Create a socket and connect it to an address.
431 * @saddr: Inet socket address specification
432 * @errp: set on error
434 * Returns: -1 on error, file descriptor on success.
436 int inet_connect_saddr(InetSocketAddress *saddr, Error **errp)
438 Error *local_err = NULL;
439 struct addrinfo *res, *e;
440 int sock = -1;
442 res = inet_parse_connect_saddr(saddr, errp);
443 if (!res) {
444 return -1;
447 for (e = res; e != NULL; e = e->ai_next) {
448 error_free(local_err);
449 local_err = NULL;
450 sock = inet_connect_addr(e, &local_err);
451 if (sock >= 0) {
452 break;
456 if (sock < 0) {
457 error_propagate(errp, local_err);
460 freeaddrinfo(res);
461 return sock;
464 static int inet_dgram_saddr(InetSocketAddress *sraddr,
465 InetSocketAddress *sladdr,
466 Error **errp)
468 struct addrinfo ai, *peer = NULL, *local = NULL;
469 const char *addr;
470 const char *port;
471 int sock = -1, rc;
472 Error *err = NULL;
474 /* lookup peer addr */
475 memset(&ai,0, sizeof(ai));
476 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
477 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
478 ai.ai_socktype = SOCK_DGRAM;
480 if (err) {
481 error_propagate(errp, err);
482 goto err;
485 addr = sraddr->host;
486 port = sraddr->port;
487 if (addr == NULL || strlen(addr) == 0) {
488 addr = "localhost";
490 if (port == NULL || strlen(port) == 0) {
491 error_setg(errp, "remote port not specified");
492 goto err;
495 if ((rc = getaddrinfo(addr, port, &ai, &peer)) != 0) {
496 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
497 gai_strerror(rc));
498 goto err;
501 /* lookup local addr */
502 memset(&ai,0, sizeof(ai));
503 ai.ai_flags = AI_PASSIVE;
504 ai.ai_family = peer->ai_family;
505 ai.ai_socktype = SOCK_DGRAM;
507 if (sladdr) {
508 addr = sladdr->host;
509 port = sladdr->port;
510 if (addr == NULL || strlen(addr) == 0) {
511 addr = NULL;
513 if (!port || strlen(port) == 0) {
514 port = "0";
516 } else {
517 addr = NULL;
518 port = "0";
521 if ((rc = getaddrinfo(addr, port, &ai, &local)) != 0) {
522 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
523 gai_strerror(rc));
524 goto err;
527 /* create socket */
528 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
529 if (sock < 0) {
530 error_setg_errno(errp, errno, "Failed to create socket");
531 goto err;
533 socket_set_fast_reuse(sock);
535 /* bind socket */
536 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
537 error_setg_errno(errp, errno, "Failed to bind socket");
538 goto err;
541 /* connect to peer */
542 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
543 error_setg_errno(errp, errno, "Failed to connect socket");
544 goto err;
547 freeaddrinfo(local);
548 freeaddrinfo(peer);
549 return sock;
551 err:
552 if (sock != -1) {
553 closesocket(sock);
555 if (local) {
556 freeaddrinfo(local);
558 if (peer) {
559 freeaddrinfo(peer);
562 return -1;
565 /* compatibility wrapper */
566 static int inet_parse_flag(const char *flagname, const char *optstr, bool *val,
567 Error **errp)
569 char *end;
570 size_t len;
572 end = strstr(optstr, ",");
573 if (end) {
574 if (end[1] == ',') { /* Reject 'ipv6=on,,foo' */
575 error_setg(errp, "error parsing '%s' flag '%s'", flagname, optstr);
576 return -1;
578 len = end - optstr;
579 } else {
580 len = strlen(optstr);
582 if (len == 0 || (len == 3 && strncmp(optstr, "=on", len) == 0)) {
583 *val = true;
584 } else if (len == 4 && strncmp(optstr, "=off", len) == 0) {
585 *val = false;
586 } else {
587 error_setg(errp, "error parsing '%s' flag '%s'", flagname, optstr);
588 return -1;
590 return 0;
593 int inet_parse(InetSocketAddress *addr, const char *str, Error **errp)
595 const char *optstr, *h;
596 char host[65];
597 char port[33];
598 int to;
599 int pos;
600 char *begin;
602 memset(addr, 0, sizeof(*addr));
604 /* parse address */
605 if (str[0] == ':') {
606 /* no host given */
607 host[0] = '\0';
608 if (sscanf(str, ":%32[^,]%n", port, &pos) != 1) {
609 error_setg(errp, "error parsing port in address '%s'", str);
610 return -1;
612 } else if (str[0] == '[') {
613 /* IPv6 addr */
614 if (sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos) != 2) {
615 error_setg(errp, "error parsing IPv6 address '%s'", str);
616 return -1;
618 } else {
619 /* hostname or IPv4 addr */
620 if (sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos) != 2) {
621 error_setg(errp, "error parsing address '%s'", str);
622 return -1;
626 addr->host = g_strdup(host);
627 addr->port = g_strdup(port);
629 /* parse options */
630 optstr = str + pos;
631 h = strstr(optstr, ",to=");
632 if (h) {
633 h += 4;
634 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
635 (h[pos] != '\0' && h[pos] != ',')) {
636 error_setg(errp, "error parsing to= argument");
637 return -1;
639 addr->has_to = true;
640 addr->to = to;
642 begin = strstr(optstr, ",ipv4");
643 if (begin) {
644 if (inet_parse_flag("ipv4", begin + 5, &addr->ipv4, errp) < 0) {
645 return -1;
647 addr->has_ipv4 = true;
649 begin = strstr(optstr, ",ipv6");
650 if (begin) {
651 if (inet_parse_flag("ipv6", begin + 5, &addr->ipv6, errp) < 0) {
652 return -1;
654 addr->has_ipv6 = true;
656 return 0;
661 * Create a blocking socket and connect it to an address.
663 * @str: address string
664 * @errp: set in case of an error
666 * Returns -1 in case of error, file descriptor on success
668 int inet_connect(const char *str, Error **errp)
670 int sock = -1;
671 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
673 if (!inet_parse(addr, str, errp)) {
674 sock = inet_connect_saddr(addr, errp);
676 qapi_free_InetSocketAddress(addr);
677 return sock;
680 #ifdef CONFIG_AF_VSOCK
681 static bool vsock_parse_vaddr_to_sockaddr(const VsockSocketAddress *vaddr,
682 struct sockaddr_vm *svm,
683 Error **errp)
685 unsigned long long val;
687 memset(svm, 0, sizeof(*svm));
688 svm->svm_family = AF_VSOCK;
690 if (parse_uint_full(vaddr->cid, &val, 10) < 0 ||
691 val > UINT32_MAX) {
692 error_setg(errp, "Failed to parse cid '%s'", vaddr->cid);
693 return false;
695 svm->svm_cid = val;
697 if (parse_uint_full(vaddr->port, &val, 10) < 0 ||
698 val > UINT32_MAX) {
699 error_setg(errp, "Failed to parse port '%s'", vaddr->port);
700 return false;
702 svm->svm_port = val;
704 return true;
707 static int vsock_connect_addr(const struct sockaddr_vm *svm, Error **errp)
709 int sock, rc;
711 sock = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
712 if (sock < 0) {
713 error_setg_errno(errp, errno, "Failed to create socket");
714 return -1;
717 /* connect to peer */
718 do {
719 rc = 0;
720 if (connect(sock, (const struct sockaddr *)svm, sizeof(*svm)) < 0) {
721 rc = -errno;
723 } while (rc == -EINTR);
725 if (rc < 0) {
726 error_setg_errno(errp, errno, "Failed to connect socket");
727 closesocket(sock);
728 return -1;
731 return sock;
734 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
736 struct sockaddr_vm svm;
737 int sock = -1;
739 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
740 return -1;
743 sock = vsock_connect_addr(&svm, errp);
745 return sock;
748 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
749 Error **errp)
751 struct sockaddr_vm svm;
752 int slisten;
754 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
755 return -1;
758 slisten = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
759 if (slisten < 0) {
760 error_setg_errno(errp, errno, "Failed to create socket");
761 return -1;
764 if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
765 error_setg_errno(errp, errno, "Failed to bind socket");
766 closesocket(slisten);
767 return -1;
770 if (listen(slisten, 1) != 0) {
771 error_setg_errno(errp, errno, "Failed to listen on socket");
772 closesocket(slisten);
773 return -1;
775 return slisten;
778 static int vsock_parse(VsockSocketAddress *addr, const char *str,
779 Error **errp)
781 char cid[33];
782 char port[33];
783 int n;
785 if (sscanf(str, "%32[^:]:%32[^,]%n", cid, port, &n) != 2) {
786 error_setg(errp, "error parsing address '%s'", str);
787 return -1;
789 if (str[n] != '\0') {
790 error_setg(errp, "trailing characters in address '%s'", str);
791 return -1;
794 addr->cid = g_strdup(cid);
795 addr->port = g_strdup(port);
796 return 0;
798 #else
799 static void vsock_unsupported(Error **errp)
801 error_setg(errp, "socket family AF_VSOCK unsupported");
804 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
806 vsock_unsupported(errp);
807 return -1;
810 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
811 Error **errp)
813 vsock_unsupported(errp);
814 return -1;
817 static int vsock_parse(VsockSocketAddress *addr, const char *str,
818 Error **errp)
820 vsock_unsupported(errp);
821 return -1;
823 #endif /* CONFIG_AF_VSOCK */
825 #ifndef _WIN32
827 static int unix_listen_saddr(UnixSocketAddress *saddr,
828 Error **errp)
830 struct sockaddr_un un;
831 int sock, fd;
832 char *pathbuf = NULL;
833 const char *path;
834 size_t pathlen;
836 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
837 if (sock < 0) {
838 error_setg_errno(errp, errno, "Failed to create Unix socket");
839 return -1;
842 if (saddr->path && saddr->path[0]) {
843 path = saddr->path;
844 } else {
845 const char *tmpdir = getenv("TMPDIR");
846 tmpdir = tmpdir ? tmpdir : "/tmp";
847 path = pathbuf = g_strdup_printf("%s/qemu-socket-XXXXXX", tmpdir);
850 pathlen = strlen(path);
851 if (pathlen > sizeof(un.sun_path)) {
852 error_setg(errp, "UNIX socket path '%s' is too long", path);
853 error_append_hint(errp, "Path must be less than %zu bytes\n",
854 sizeof(un.sun_path));
855 goto err;
858 if (pathbuf != NULL) {
860 * This dummy fd usage silences the mktemp() unsecure warning.
861 * Using mkstemp() doesn't make things more secure here
862 * though. bind() complains about existing files, so we have
863 * to unlink first and thus re-open the race window. The
864 * worst case possible is bind() failing, i.e. a DoS attack.
866 fd = mkstemp(pathbuf);
867 if (fd < 0) {
868 error_setg_errno(errp, errno,
869 "Failed to make a temporary socket %s", pathbuf);
870 goto err;
872 close(fd);
875 if (unlink(path) < 0 && errno != ENOENT) {
876 error_setg_errno(errp, errno,
877 "Failed to unlink socket %s", path);
878 goto err;
881 memset(&un, 0, sizeof(un));
882 un.sun_family = AF_UNIX;
883 memcpy(un.sun_path, path, pathlen);
885 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
886 error_setg_errno(errp, errno, "Failed to bind socket to %s", path);
887 goto err;
889 if (listen(sock, 1) < 0) {
890 error_setg_errno(errp, errno, "Failed to listen on socket");
891 goto err;
894 g_free(pathbuf);
895 return sock;
897 err:
898 g_free(pathbuf);
899 closesocket(sock);
900 return -1;
903 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
905 struct sockaddr_un un;
906 int sock, rc;
907 size_t pathlen;
909 if (saddr->path == NULL) {
910 error_setg(errp, "unix connect: no path specified");
911 return -1;
914 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
915 if (sock < 0) {
916 error_setg_errno(errp, errno, "Failed to create socket");
917 return -1;
920 pathlen = strlen(saddr->path);
921 if (pathlen > sizeof(un.sun_path)) {
922 error_setg(errp, "UNIX socket path '%s' is too long", saddr->path);
923 error_append_hint(errp, "Path must be less than %zu bytes\n",
924 sizeof(un.sun_path));
925 goto err;
928 memset(&un, 0, sizeof(un));
929 un.sun_family = AF_UNIX;
930 memcpy(un.sun_path, saddr->path, pathlen);
932 /* connect to peer */
933 do {
934 rc = 0;
935 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
936 rc = -errno;
938 } while (rc == -EINTR);
940 if (rc < 0) {
941 error_setg_errno(errp, -rc, "Failed to connect socket %s",
942 saddr->path);
943 goto err;
946 return sock;
948 err:
949 close(sock);
950 return -1;
953 #else
955 static int unix_listen_saddr(UnixSocketAddress *saddr,
956 Error **errp)
958 error_setg(errp, "unix sockets are not available on windows");
959 errno = ENOTSUP;
960 return -1;
963 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
965 error_setg(errp, "unix sockets are not available on windows");
966 errno = ENOTSUP;
967 return -1;
969 #endif
971 /* compatibility wrapper */
972 int unix_listen(const char *str, Error **errp)
974 UnixSocketAddress *saddr;
975 int sock;
977 saddr = g_new0(UnixSocketAddress, 1);
978 saddr->path = g_strdup(str);
979 sock = unix_listen_saddr(saddr, errp);
980 qapi_free_UnixSocketAddress(saddr);
981 return sock;
984 int unix_connect(const char *path, Error **errp)
986 UnixSocketAddress *saddr;
987 int sock;
989 saddr = g_new0(UnixSocketAddress, 1);
990 saddr->path = g_strdup(path);
991 sock = unix_connect_saddr(saddr, errp);
992 qapi_free_UnixSocketAddress(saddr);
993 return sock;
997 SocketAddress *socket_parse(const char *str, Error **errp)
999 SocketAddress *addr;
1001 addr = g_new0(SocketAddress, 1);
1002 if (strstart(str, "unix:", NULL)) {
1003 if (str[5] == '\0') {
1004 error_setg(errp, "invalid Unix socket address");
1005 goto fail;
1006 } else {
1007 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1008 addr->u.q_unix.path = g_strdup(str + 5);
1010 } else if (strstart(str, "fd:", NULL)) {
1011 if (str[3] == '\0') {
1012 error_setg(errp, "invalid file descriptor address");
1013 goto fail;
1014 } else {
1015 addr->type = SOCKET_ADDRESS_TYPE_FD;
1016 addr->u.fd.str = g_strdup(str + 3);
1018 } else if (strstart(str, "vsock:", NULL)) {
1019 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1020 if (vsock_parse(&addr->u.vsock, str + strlen("vsock:"), errp)) {
1021 goto fail;
1023 } else {
1024 addr->type = SOCKET_ADDRESS_TYPE_INET;
1025 if (inet_parse(&addr->u.inet, str, errp)) {
1026 goto fail;
1029 return addr;
1031 fail:
1032 qapi_free_SocketAddress(addr);
1033 return NULL;
1036 static int socket_get_fd(const char *fdstr, Error **errp)
1038 int fd;
1039 if (cur_mon) {
1040 fd = monitor_get_fd(cur_mon, fdstr, errp);
1041 if (fd < 0) {
1042 return -1;
1044 } else {
1045 if (qemu_strtoi(fdstr, NULL, 10, &fd) < 0) {
1046 error_setg_errno(errp, errno,
1047 "Unable to parse FD number %s",
1048 fdstr);
1049 return -1;
1052 if (!fd_is_socket(fd)) {
1053 error_setg(errp, "File descriptor '%s' is not a socket", fdstr);
1054 close(fd);
1055 return -1;
1057 return fd;
1060 int socket_connect(SocketAddress *addr, Error **errp)
1062 int fd;
1064 switch (addr->type) {
1065 case SOCKET_ADDRESS_TYPE_INET:
1066 fd = inet_connect_saddr(&addr->u.inet, errp);
1067 break;
1069 case SOCKET_ADDRESS_TYPE_UNIX:
1070 fd = unix_connect_saddr(&addr->u.q_unix, errp);
1071 break;
1073 case SOCKET_ADDRESS_TYPE_FD:
1074 fd = socket_get_fd(addr->u.fd.str, errp);
1075 break;
1077 case SOCKET_ADDRESS_TYPE_VSOCK:
1078 fd = vsock_connect_saddr(&addr->u.vsock, errp);
1079 break;
1081 default:
1082 abort();
1084 return fd;
1087 int socket_listen(SocketAddress *addr, Error **errp)
1089 int fd;
1091 switch (addr->type) {
1092 case SOCKET_ADDRESS_TYPE_INET:
1093 fd = inet_listen_saddr(&addr->u.inet, 0, errp);
1094 break;
1096 case SOCKET_ADDRESS_TYPE_UNIX:
1097 fd = unix_listen_saddr(&addr->u.q_unix, errp);
1098 break;
1100 case SOCKET_ADDRESS_TYPE_FD:
1101 fd = socket_get_fd(addr->u.fd.str, errp);
1102 break;
1104 case SOCKET_ADDRESS_TYPE_VSOCK:
1105 fd = vsock_listen_saddr(&addr->u.vsock, errp);
1106 break;
1108 default:
1109 abort();
1111 return fd;
1114 void socket_listen_cleanup(int fd, Error **errp)
1116 SocketAddress *addr;
1118 addr = socket_local_address(fd, errp);
1119 if (!addr) {
1120 return;
1123 if (addr->type == SOCKET_ADDRESS_TYPE_UNIX
1124 && addr->u.q_unix.path) {
1125 if (unlink(addr->u.q_unix.path) < 0 && errno != ENOENT) {
1126 error_setg_errno(errp, errno,
1127 "Failed to unlink socket %s",
1128 addr->u.q_unix.path);
1132 qapi_free_SocketAddress(addr);
1135 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
1137 int fd;
1140 * TODO SOCKET_ADDRESS_TYPE_FD when fd is AF_INET or AF_INET6
1141 * (although other address families can do SOCK_DGRAM, too)
1143 switch (remote->type) {
1144 case SOCKET_ADDRESS_TYPE_INET:
1145 fd = inet_dgram_saddr(&remote->u.inet,
1146 local ? &local->u.inet : NULL, errp);
1147 break;
1149 default:
1150 error_setg(errp, "socket type unsupported for datagram");
1151 fd = -1;
1153 return fd;
1157 static SocketAddress *
1158 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1159 socklen_t salen,
1160 Error **errp)
1162 char host[NI_MAXHOST];
1163 char serv[NI_MAXSERV];
1164 SocketAddress *addr;
1165 InetSocketAddress *inet;
1166 int ret;
1168 ret = getnameinfo((struct sockaddr *)sa, salen,
1169 host, sizeof(host),
1170 serv, sizeof(serv),
1171 NI_NUMERICHOST | NI_NUMERICSERV);
1172 if (ret != 0) {
1173 error_setg(errp, "Cannot format numeric socket address: %s",
1174 gai_strerror(ret));
1175 return NULL;
1178 addr = g_new0(SocketAddress, 1);
1179 addr->type = SOCKET_ADDRESS_TYPE_INET;
1180 inet = &addr->u.inet;
1181 inet->host = g_strdup(host);
1182 inet->port = g_strdup(serv);
1183 if (sa->ss_family == AF_INET) {
1184 inet->has_ipv4 = inet->ipv4 = true;
1185 } else {
1186 inet->has_ipv6 = inet->ipv6 = true;
1189 return addr;
1193 #ifndef WIN32
1194 static SocketAddress *
1195 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1196 socklen_t salen,
1197 Error **errp)
1199 SocketAddress *addr;
1200 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1202 addr = g_new0(SocketAddress, 1);
1203 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1204 if (su->sun_path[0]) {
1205 addr->u.q_unix.path = g_strndup(su->sun_path, sizeof(su->sun_path));
1208 return addr;
1210 #endif /* WIN32 */
1212 #ifdef CONFIG_AF_VSOCK
1213 static SocketAddress *
1214 socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,
1215 socklen_t salen,
1216 Error **errp)
1218 SocketAddress *addr;
1219 VsockSocketAddress *vaddr;
1220 struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;
1222 addr = g_new0(SocketAddress, 1);
1223 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1224 vaddr = &addr->u.vsock;
1225 vaddr->cid = g_strdup_printf("%u", svm->svm_cid);
1226 vaddr->port = g_strdup_printf("%u", svm->svm_port);
1228 return addr;
1230 #endif /* CONFIG_AF_VSOCK */
1232 SocketAddress *
1233 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1234 socklen_t salen,
1235 Error **errp)
1237 switch (sa->ss_family) {
1238 case AF_INET:
1239 case AF_INET6:
1240 return socket_sockaddr_to_address_inet(sa, salen, errp);
1242 #ifndef WIN32
1243 case AF_UNIX:
1244 return socket_sockaddr_to_address_unix(sa, salen, errp);
1245 #endif /* WIN32 */
1247 #ifdef CONFIG_AF_VSOCK
1248 case AF_VSOCK:
1249 return socket_sockaddr_to_address_vsock(sa, salen, errp);
1250 #endif
1252 default:
1253 error_setg(errp, "socket family %d unsupported",
1254 sa->ss_family);
1255 return NULL;
1257 return 0;
1261 SocketAddress *socket_local_address(int fd, Error **errp)
1263 struct sockaddr_storage ss;
1264 socklen_t sslen = sizeof(ss);
1266 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1267 error_setg_errno(errp, errno, "%s",
1268 "Unable to query local socket address");
1269 return NULL;
1272 return socket_sockaddr_to_address(&ss, sslen, errp);
1276 SocketAddress *socket_remote_address(int fd, Error **errp)
1278 struct sockaddr_storage ss;
1279 socklen_t sslen = sizeof(ss);
1281 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1282 error_setg_errno(errp, errno, "%s",
1283 "Unable to query remote socket address");
1284 return NULL;
1287 return socket_sockaddr_to_address(&ss, sslen, errp);
1291 SocketAddress *socket_address_flatten(SocketAddressLegacy *addr_legacy)
1293 SocketAddress *addr;
1295 if (!addr_legacy) {
1296 return NULL;
1299 addr = g_new(SocketAddress, 1);
1301 switch (addr_legacy->type) {
1302 case SOCKET_ADDRESS_LEGACY_KIND_INET:
1303 addr->type = SOCKET_ADDRESS_TYPE_INET;
1304 QAPI_CLONE_MEMBERS(InetSocketAddress, &addr->u.inet,
1305 addr_legacy->u.inet.data);
1306 break;
1307 case SOCKET_ADDRESS_LEGACY_KIND_UNIX:
1308 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1309 QAPI_CLONE_MEMBERS(UnixSocketAddress, &addr->u.q_unix,
1310 addr_legacy->u.q_unix.data);
1311 break;
1312 case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:
1313 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1314 QAPI_CLONE_MEMBERS(VsockSocketAddress, &addr->u.vsock,
1315 addr_legacy->u.vsock.data);
1316 break;
1317 case SOCKET_ADDRESS_LEGACY_KIND_FD:
1318 addr->type = SOCKET_ADDRESS_TYPE_FD;
1319 QAPI_CLONE_MEMBERS(String, &addr->u.fd, addr_legacy->u.fd.data);
1320 break;
1321 default:
1322 abort();
1325 return addr;