i386: hvf: fix licensing issues; isolate task handling code (GPL v2-only)
[qemu/ericb.git] / util / qemu-sockets.c
blobd6a1e1759e8a3b7e16c598a641ecb741d82892fc
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/clone-visitor.h"
26 #include "qapi/error.h"
27 #include "qemu/sockets.h"
28 #include "qemu/main-loop.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/PF_UNSPEC
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.
113 * In the first and last cases, we must set IPV6_V6ONLY=0
114 * when binding, to allow a single listener to potentially
115 * accept both IPv4+6 addresses.
117 int inet_ai_family_from_address(InetSocketAddress *addr,
118 Error **errp)
120 if (addr->has_ipv6 && addr->has_ipv4 &&
121 !addr->ipv6 && !addr->ipv4) {
122 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
123 return PF_UNSPEC;
125 if ((addr->has_ipv6 && addr->ipv6) && (addr->has_ipv4 && addr->ipv4)) {
127 * Some backends can only do a single listener. In that case
128 * we want empty hostname to resolve to "::" and then use the
129 * flag IPV6_V6ONLY==0 to get both protocols on 1 socket. This
130 * doesn't work for addresses other than "", so they're just
131 * inevitably broken until multiple listeners can be used,
132 * and thus we honour getaddrinfo automatic protocol detection
133 * Once all backends do multi-listener, remove the PF_INET6
134 * branch entirely.
136 if (!addr->host || g_str_equal(addr->host, "")) {
137 return PF_INET6;
138 } else {
139 return PF_UNSPEC;
142 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
143 return PF_INET6;
145 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
146 return PF_INET;
148 return PF_UNSPEC;
151 static int create_fast_reuse_socket(struct addrinfo *e)
153 int slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
154 if (slisten < 0) {
155 return -1;
157 socket_set_fast_reuse(slisten);
158 return slisten;
161 static int try_bind(int socket, InetSocketAddress *saddr, struct addrinfo *e)
163 #ifndef IPV6_V6ONLY
164 return bind(socket, e->ai_addr, e->ai_addrlen);
165 #else
167 * Deals with first & last cases in matrix in comment
168 * for inet_ai_family_from_address().
170 int v6only =
171 ((!saddr->has_ipv4 && !saddr->has_ipv6) ||
172 (saddr->has_ipv4 && saddr->ipv4 &&
173 saddr->has_ipv6 && saddr->ipv6)) ? 0 : 1;
174 int stat;
176 rebind:
177 if (e->ai_family == PF_INET6) {
178 qemu_setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, &v6only,
179 sizeof(v6only));
182 stat = bind(socket, e->ai_addr, e->ai_addrlen);
183 if (!stat) {
184 return 0;
187 /* If we got EADDRINUSE from an IPv6 bind & v6only is unset,
188 * it could be that the IPv4 port is already claimed, so retry
189 * with v6only set
191 if (e->ai_family == PF_INET6 && errno == EADDRINUSE && !v6only) {
192 v6only = 1;
193 goto rebind;
195 return stat;
196 #endif
199 static int inet_listen_saddr(InetSocketAddress *saddr,
200 int port_offset,
201 Error **errp)
203 struct addrinfo ai,*res,*e;
204 char port[33];
205 char uaddr[INET6_ADDRSTRLEN+1];
206 char uport[33];
207 int rc, port_min, port_max, p;
208 int slisten = -1;
209 int saved_errno = 0;
210 bool socket_created = false;
211 Error *err = NULL;
213 memset(&ai,0, sizeof(ai));
214 ai.ai_flags = AI_PASSIVE;
215 if (saddr->has_numeric && saddr->numeric) {
216 ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
218 ai.ai_family = inet_ai_family_from_address(saddr, &err);
219 ai.ai_socktype = SOCK_STREAM;
221 if (err) {
222 error_propagate(errp, err);
223 return -1;
226 if (saddr->host == NULL) {
227 error_setg(errp, "host not specified");
228 return -1;
230 if (saddr->port != NULL) {
231 pstrcpy(port, sizeof(port), saddr->port);
232 } else {
233 port[0] = '\0';
236 /* lookup */
237 if (port_offset) {
238 unsigned long long baseport;
239 if (strlen(port) == 0) {
240 error_setg(errp, "port not specified");
241 return -1;
243 if (parse_uint_full(port, &baseport, 10) < 0) {
244 error_setg(errp, "can't convert to a number: %s", port);
245 return -1;
247 if (baseport > 65535 ||
248 baseport + port_offset > 65535) {
249 error_setg(errp, "port %s out of range", port);
250 return -1;
252 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
254 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
255 strlen(port) ? port : NULL, &ai, &res);
256 if (rc != 0) {
257 error_setg(errp, "address resolution failed for %s:%s: %s",
258 saddr->host, port, gai_strerror(rc));
259 return -1;
262 /* create socket + bind/listen */
263 for (e = res; e != NULL; e = e->ai_next) {
264 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
265 uaddr,INET6_ADDRSTRLEN,uport,32,
266 NI_NUMERICHOST | NI_NUMERICSERV);
268 port_min = inet_getport(e);
269 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
270 for (p = port_min; p <= port_max; p++) {
271 inet_setport(e, p);
273 slisten = create_fast_reuse_socket(e);
274 if (slisten < 0) {
275 /* First time we expect we might fail to create the socket
276 * eg if 'e' has AF_INET6 but ipv6 kmod is not loaded.
277 * Later iterations should always succeed if first iteration
278 * worked though, so treat that as fatal.
280 if (p == port_min) {
281 continue;
282 } else {
283 error_setg_errno(errp, errno,
284 "Failed to recreate failed listening socket");
285 goto listen_failed;
288 socket_created = true;
290 rc = try_bind(slisten, saddr, e);
291 if (rc < 0) {
292 if (errno != EADDRINUSE) {
293 error_setg_errno(errp, errno, "Failed to bind socket");
294 goto listen_failed;
296 } else {
297 if (!listen(slisten, 1)) {
298 goto listen_ok;
300 if (errno != EADDRINUSE) {
301 error_setg_errno(errp, errno, "Failed to listen on socket");
302 goto listen_failed;
305 /* Someone else managed to bind to the same port and beat us
306 * to listen on it! Socket semantics does not allow us to
307 * recover from this situation, so we need to recreate the
308 * socket to allow bind attempts for subsequent ports:
310 closesocket(slisten);
311 slisten = -1;
314 error_setg_errno(errp, errno,
315 socket_created ?
316 "Failed to find an available port" :
317 "Failed to create a socket");
318 listen_failed:
319 saved_errno = errno;
320 if (slisten >= 0) {
321 closesocket(slisten);
323 freeaddrinfo(res);
324 errno = saved_errno;
325 return -1;
327 listen_ok:
328 freeaddrinfo(res);
329 return slisten;
332 #ifdef _WIN32
333 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
334 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
335 #else
336 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
337 ((rc) == -EINPROGRESS)
338 #endif
340 static int inet_connect_addr(struct addrinfo *addr, Error **errp);
342 static int inet_connect_addr(struct addrinfo *addr, Error **errp)
344 int sock, rc;
346 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
347 if (sock < 0) {
348 error_setg_errno(errp, errno, "Failed to create socket");
349 return -1;
351 socket_set_fast_reuse(sock);
353 /* connect to peer */
354 do {
355 rc = 0;
356 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
357 rc = -errno;
359 } while (rc == -EINTR);
361 if (rc < 0) {
362 error_setg_errno(errp, errno, "Failed to connect socket");
363 closesocket(sock);
364 return -1;
367 return sock;
370 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
371 Error **errp)
373 struct addrinfo ai, *res;
374 int rc;
375 Error *err = NULL;
376 static int useV4Mapped = 1;
378 memset(&ai, 0, sizeof(ai));
380 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
381 if (atomic_read(&useV4Mapped)) {
382 ai.ai_flags |= AI_V4MAPPED;
384 ai.ai_family = inet_ai_family_from_address(saddr, &err);
385 ai.ai_socktype = SOCK_STREAM;
387 if (err) {
388 error_propagate(errp, err);
389 return NULL;
392 if (saddr->host == NULL || saddr->port == NULL) {
393 error_setg(errp, "host and/or port not specified");
394 return NULL;
397 /* lookup */
398 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
400 /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
401 * then don't implement it in their getaddrinfo(). Detect
402 * this and retry without the flag since that's preferrable
403 * to a fatal error
405 if (rc == EAI_BADFLAGS &&
406 (ai.ai_flags & AI_V4MAPPED)) {
407 atomic_set(&useV4Mapped, 0);
408 ai.ai_flags &= ~AI_V4MAPPED;
409 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
411 if (rc != 0) {
412 error_setg(errp, "address resolution failed for %s:%s: %s",
413 saddr->host, saddr->port, gai_strerror(rc));
414 return NULL;
416 return res;
420 * Create a socket and connect it to an address.
422 * @saddr: Inet socket address specification
423 * @errp: set on error
425 * Returns: -1 on error, file descriptor on success.
427 int inet_connect_saddr(InetSocketAddress *saddr, Error **errp)
429 Error *local_err = NULL;
430 struct addrinfo *res, *e;
431 int sock = -1;
433 res = inet_parse_connect_saddr(saddr, errp);
434 if (!res) {
435 return -1;
438 for (e = res; e != NULL; e = e->ai_next) {
439 error_free(local_err);
440 local_err = NULL;
441 sock = inet_connect_addr(e, &local_err);
442 if (sock >= 0) {
443 break;
447 if (sock < 0) {
448 error_propagate(errp, local_err);
451 freeaddrinfo(res);
452 return sock;
455 static int inet_dgram_saddr(InetSocketAddress *sraddr,
456 InetSocketAddress *sladdr,
457 Error **errp)
459 struct addrinfo ai, *peer = NULL, *local = NULL;
460 const char *addr;
461 const char *port;
462 int sock = -1, rc;
463 Error *err = NULL;
465 /* lookup peer addr */
466 memset(&ai,0, sizeof(ai));
467 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
468 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
469 ai.ai_socktype = SOCK_DGRAM;
471 if (err) {
472 error_propagate(errp, err);
473 goto err;
476 addr = sraddr->host;
477 port = sraddr->port;
478 if (addr == NULL || strlen(addr) == 0) {
479 addr = "localhost";
481 if (port == NULL || strlen(port) == 0) {
482 error_setg(errp, "remote port not specified");
483 goto err;
486 if ((rc = getaddrinfo(addr, port, &ai, &peer)) != 0) {
487 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
488 gai_strerror(rc));
489 goto err;
492 /* lookup local addr */
493 memset(&ai,0, sizeof(ai));
494 ai.ai_flags = AI_PASSIVE;
495 ai.ai_family = peer->ai_family;
496 ai.ai_socktype = SOCK_DGRAM;
498 if (sladdr) {
499 addr = sladdr->host;
500 port = sladdr->port;
501 if (addr == NULL || strlen(addr) == 0) {
502 addr = NULL;
504 if (!port || strlen(port) == 0) {
505 port = "0";
507 } else {
508 addr = NULL;
509 port = "0";
512 if ((rc = getaddrinfo(addr, port, &ai, &local)) != 0) {
513 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
514 gai_strerror(rc));
515 goto err;
518 /* create socket */
519 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
520 if (sock < 0) {
521 error_setg_errno(errp, errno, "Failed to create socket");
522 goto err;
524 socket_set_fast_reuse(sock);
526 /* bind socket */
527 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
528 error_setg_errno(errp, errno, "Failed to bind socket");
529 goto err;
532 /* connect to peer */
533 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
534 error_setg_errno(errp, errno, "Failed to connect socket");
535 goto err;
538 freeaddrinfo(local);
539 freeaddrinfo(peer);
540 return sock;
542 err:
543 if (sock != -1) {
544 closesocket(sock);
546 if (local) {
547 freeaddrinfo(local);
549 if (peer) {
550 freeaddrinfo(peer);
553 return -1;
556 /* compatibility wrapper */
557 int inet_parse(InetSocketAddress *addr, const char *str, Error **errp)
559 const char *optstr, *h;
560 char host[65];
561 char port[33];
562 int to;
563 int pos;
565 memset(addr, 0, sizeof(*addr));
567 /* parse address */
568 if (str[0] == ':') {
569 /* no host given */
570 host[0] = '\0';
571 if (sscanf(str, ":%32[^,]%n", port, &pos) != 1) {
572 error_setg(errp, "error parsing port in address '%s'", str);
573 return -1;
575 } else if (str[0] == '[') {
576 /* IPv6 addr */
577 if (sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos) != 2) {
578 error_setg(errp, "error parsing IPv6 address '%s'", str);
579 return -1;
581 } else {
582 /* hostname or IPv4 addr */
583 if (sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos) != 2) {
584 error_setg(errp, "error parsing address '%s'", str);
585 return -1;
589 addr->host = g_strdup(host);
590 addr->port = g_strdup(port);
592 /* parse options */
593 optstr = str + pos;
594 h = strstr(optstr, ",to=");
595 if (h) {
596 h += 4;
597 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
598 (h[pos] != '\0' && h[pos] != ',')) {
599 error_setg(errp, "error parsing to= argument");
600 return -1;
602 addr->has_to = true;
603 addr->to = to;
605 if (strstr(optstr, ",ipv4")) {
606 addr->ipv4 = addr->has_ipv4 = true;
608 if (strstr(optstr, ",ipv6")) {
609 addr->ipv6 = addr->has_ipv6 = true;
611 return 0;
616 * Create a blocking socket and connect it to an address.
618 * @str: address string
619 * @errp: set in case of an error
621 * Returns -1 in case of error, file descriptor on success
623 int inet_connect(const char *str, Error **errp)
625 int sock = -1;
626 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
628 if (!inet_parse(addr, str, errp)) {
629 sock = inet_connect_saddr(addr, errp);
631 qapi_free_InetSocketAddress(addr);
632 return sock;
635 #ifdef CONFIG_AF_VSOCK
636 static bool vsock_parse_vaddr_to_sockaddr(const VsockSocketAddress *vaddr,
637 struct sockaddr_vm *svm,
638 Error **errp)
640 unsigned long long val;
642 memset(svm, 0, sizeof(*svm));
643 svm->svm_family = AF_VSOCK;
645 if (parse_uint_full(vaddr->cid, &val, 10) < 0 ||
646 val > UINT32_MAX) {
647 error_setg(errp, "Failed to parse cid '%s'", vaddr->cid);
648 return false;
650 svm->svm_cid = val;
652 if (parse_uint_full(vaddr->port, &val, 10) < 0 ||
653 val > UINT32_MAX) {
654 error_setg(errp, "Failed to parse port '%s'", vaddr->port);
655 return false;
657 svm->svm_port = val;
659 return true;
662 static int vsock_connect_addr(const struct sockaddr_vm *svm, Error **errp)
664 int sock, rc;
666 sock = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
667 if (sock < 0) {
668 error_setg_errno(errp, errno, "Failed to create socket");
669 return -1;
672 /* connect to peer */
673 do {
674 rc = 0;
675 if (connect(sock, (const struct sockaddr *)svm, sizeof(*svm)) < 0) {
676 rc = -errno;
678 } while (rc == -EINTR);
680 if (rc < 0) {
681 error_setg_errno(errp, errno, "Failed to connect socket");
682 closesocket(sock);
683 return -1;
686 return sock;
689 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
691 struct sockaddr_vm svm;
692 int sock = -1;
694 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
695 return -1;
698 sock = vsock_connect_addr(&svm, errp);
700 return sock;
703 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
704 Error **errp)
706 struct sockaddr_vm svm;
707 int slisten;
709 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
710 return -1;
713 slisten = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
714 if (slisten < 0) {
715 error_setg_errno(errp, errno, "Failed to create socket");
716 return -1;
719 if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
720 error_setg_errno(errp, errno, "Failed to bind socket");
721 closesocket(slisten);
722 return -1;
725 if (listen(slisten, 1) != 0) {
726 error_setg_errno(errp, errno, "Failed to listen on socket");
727 closesocket(slisten);
728 return -1;
730 return slisten;
733 static int vsock_parse(VsockSocketAddress *addr, const char *str,
734 Error **errp)
736 char cid[33];
737 char port[33];
738 int n;
740 if (sscanf(str, "%32[^:]:%32[^,]%n", cid, port, &n) != 2) {
741 error_setg(errp, "error parsing address '%s'", str);
742 return -1;
744 if (str[n] != '\0') {
745 error_setg(errp, "trailing characters in address '%s'", str);
746 return -1;
749 addr->cid = g_strdup(cid);
750 addr->port = g_strdup(port);
751 return 0;
753 #else
754 static void vsock_unsupported(Error **errp)
756 error_setg(errp, "socket family AF_VSOCK unsupported");
759 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
761 vsock_unsupported(errp);
762 return -1;
765 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
766 Error **errp)
768 vsock_unsupported(errp);
769 return -1;
772 static int vsock_parse(VsockSocketAddress *addr, const char *str,
773 Error **errp)
775 vsock_unsupported(errp);
776 return -1;
778 #endif /* CONFIG_AF_VSOCK */
780 #ifndef _WIN32
782 static int unix_listen_saddr(UnixSocketAddress *saddr,
783 Error **errp)
785 struct sockaddr_un un;
786 int sock, fd;
787 char *pathbuf = NULL;
788 const char *path;
790 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
791 if (sock < 0) {
792 error_setg_errno(errp, errno, "Failed to create Unix socket");
793 return -1;
796 if (saddr->path && saddr->path[0]) {
797 path = saddr->path;
798 } else {
799 const char *tmpdir = getenv("TMPDIR");
800 tmpdir = tmpdir ? tmpdir : "/tmp";
801 path = pathbuf = g_strdup_printf("%s/qemu-socket-XXXXXX", tmpdir);
804 if (strlen(path) > sizeof(un.sun_path)) {
805 error_setg(errp, "UNIX socket path '%s' is too long", path);
806 error_append_hint(errp, "Path must be less than %zu bytes\n",
807 sizeof(un.sun_path));
808 goto err;
811 if (pathbuf != NULL) {
813 * This dummy fd usage silences the mktemp() unsecure warning.
814 * Using mkstemp() doesn't make things more secure here
815 * though. bind() complains about existing files, so we have
816 * to unlink first and thus re-open the race window. The
817 * worst case possible is bind() failing, i.e. a DoS attack.
819 fd = mkstemp(pathbuf);
820 if (fd < 0) {
821 error_setg_errno(errp, errno,
822 "Failed to make a temporary socket %s", pathbuf);
823 goto err;
825 close(fd);
828 if (unlink(path) < 0 && errno != ENOENT) {
829 error_setg_errno(errp, errno,
830 "Failed to unlink socket %s", path);
831 goto err;
834 memset(&un, 0, sizeof(un));
835 un.sun_family = AF_UNIX;
836 strncpy(un.sun_path, path, sizeof(un.sun_path));
838 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
839 error_setg_errno(errp, errno, "Failed to bind socket to %s", path);
840 goto err;
842 if (listen(sock, 1) < 0) {
843 error_setg_errno(errp, errno, "Failed to listen on socket");
844 goto err;
847 g_free(pathbuf);
848 return sock;
850 err:
851 g_free(pathbuf);
852 closesocket(sock);
853 return -1;
856 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
858 struct sockaddr_un un;
859 int sock, rc;
861 if (saddr->path == NULL) {
862 error_setg(errp, "unix connect: no path specified");
863 return -1;
866 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
867 if (sock < 0) {
868 error_setg_errno(errp, errno, "Failed to create socket");
869 return -1;
872 if (strlen(saddr->path) > sizeof(un.sun_path)) {
873 error_setg(errp, "UNIX socket path '%s' is too long", saddr->path);
874 error_append_hint(errp, "Path must be less than %zu bytes\n",
875 sizeof(un.sun_path));
876 goto err;
879 memset(&un, 0, sizeof(un));
880 un.sun_family = AF_UNIX;
881 strncpy(un.sun_path, saddr->path, sizeof(un.sun_path));
883 /* connect to peer */
884 do {
885 rc = 0;
886 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
887 rc = -errno;
889 } while (rc == -EINTR);
891 if (rc < 0) {
892 error_setg_errno(errp, -rc, "Failed to connect socket %s",
893 saddr->path);
894 goto err;
897 return sock;
899 err:
900 close(sock);
901 return -1;
904 #else
906 static int unix_listen_saddr(UnixSocketAddress *saddr,
907 Error **errp)
909 error_setg(errp, "unix sockets are not available on windows");
910 errno = ENOTSUP;
911 return -1;
914 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
916 error_setg(errp, "unix sockets are not available on windows");
917 errno = ENOTSUP;
918 return -1;
920 #endif
922 /* compatibility wrapper */
923 int unix_listen(const char *str, Error **errp)
925 char *path, *optstr;
926 int sock, len;
927 UnixSocketAddress *saddr;
929 saddr = g_new0(UnixSocketAddress, 1);
931 optstr = strchr(str, ',');
932 if (optstr) {
933 len = optstr - str;
934 if (len) {
935 path = g_malloc(len+1);
936 snprintf(path, len+1, "%.*s", len, str);
937 saddr->path = path;
939 } else {
940 saddr->path = g_strdup(str);
943 sock = unix_listen_saddr(saddr, errp);
945 qapi_free_UnixSocketAddress(saddr);
946 return sock;
949 int unix_connect(const char *path, Error **errp)
951 UnixSocketAddress *saddr;
952 int sock;
954 saddr = g_new0(UnixSocketAddress, 1);
955 saddr->path = g_strdup(path);
956 sock = unix_connect_saddr(saddr, errp);
957 qapi_free_UnixSocketAddress(saddr);
958 return sock;
962 SocketAddress *socket_parse(const char *str, Error **errp)
964 SocketAddress *addr;
966 addr = g_new0(SocketAddress, 1);
967 if (strstart(str, "unix:", NULL)) {
968 if (str[5] == '\0') {
969 error_setg(errp, "invalid Unix socket address");
970 goto fail;
971 } else {
972 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
973 addr->u.q_unix.path = g_strdup(str + 5);
975 } else if (strstart(str, "fd:", NULL)) {
976 if (str[3] == '\0') {
977 error_setg(errp, "invalid file descriptor address");
978 goto fail;
979 } else {
980 addr->type = SOCKET_ADDRESS_TYPE_FD;
981 addr->u.fd.str = g_strdup(str + 3);
983 } else if (strstart(str, "vsock:", NULL)) {
984 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
985 if (vsock_parse(&addr->u.vsock, str + strlen("vsock:"), errp)) {
986 goto fail;
988 } else {
989 addr->type = SOCKET_ADDRESS_TYPE_INET;
990 if (inet_parse(&addr->u.inet, str, errp)) {
991 goto fail;
994 return addr;
996 fail:
997 qapi_free_SocketAddress(addr);
998 return NULL;
1001 int socket_connect(SocketAddress *addr, Error **errp)
1003 int fd;
1005 switch (addr->type) {
1006 case SOCKET_ADDRESS_TYPE_INET:
1007 fd = inet_connect_saddr(&addr->u.inet, errp);
1008 break;
1010 case SOCKET_ADDRESS_TYPE_UNIX:
1011 fd = unix_connect_saddr(&addr->u.q_unix, errp);
1012 break;
1014 case SOCKET_ADDRESS_TYPE_FD:
1015 fd = monitor_get_fd(cur_mon, addr->u.fd.str, errp);
1016 break;
1018 case SOCKET_ADDRESS_TYPE_VSOCK:
1019 fd = vsock_connect_saddr(&addr->u.vsock, errp);
1020 break;
1022 default:
1023 abort();
1025 return fd;
1028 int socket_listen(SocketAddress *addr, Error **errp)
1030 int fd;
1032 switch (addr->type) {
1033 case SOCKET_ADDRESS_TYPE_INET:
1034 fd = inet_listen_saddr(&addr->u.inet, 0, errp);
1035 break;
1037 case SOCKET_ADDRESS_TYPE_UNIX:
1038 fd = unix_listen_saddr(&addr->u.q_unix, errp);
1039 break;
1041 case SOCKET_ADDRESS_TYPE_FD:
1042 fd = monitor_get_fd(cur_mon, addr->u.fd.str, errp);
1043 break;
1045 case SOCKET_ADDRESS_TYPE_VSOCK:
1046 fd = vsock_listen_saddr(&addr->u.vsock, errp);
1047 break;
1049 default:
1050 abort();
1052 return fd;
1055 void socket_listen_cleanup(int fd, Error **errp)
1057 SocketAddress *addr;
1059 addr = socket_local_address(fd, errp);
1060 if (!addr) {
1061 return;
1064 if (addr->type == SOCKET_ADDRESS_TYPE_UNIX
1065 && addr->u.q_unix.path) {
1066 if (unlink(addr->u.q_unix.path) < 0 && errno != ENOENT) {
1067 error_setg_errno(errp, errno,
1068 "Failed to unlink socket %s",
1069 addr->u.q_unix.path);
1073 qapi_free_SocketAddress(addr);
1076 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
1078 int fd;
1081 * TODO SOCKET_ADDRESS_TYPE_FD when fd is AF_INET or AF_INET6
1082 * (although other address families can do SOCK_DGRAM, too)
1084 switch (remote->type) {
1085 case SOCKET_ADDRESS_TYPE_INET:
1086 fd = inet_dgram_saddr(&remote->u.inet,
1087 local ? &local->u.inet : NULL, errp);
1088 break;
1090 default:
1091 error_setg(errp, "socket type unsupported for datagram");
1092 fd = -1;
1094 return fd;
1098 static SocketAddress *
1099 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1100 socklen_t salen,
1101 Error **errp)
1103 char host[NI_MAXHOST];
1104 char serv[NI_MAXSERV];
1105 SocketAddress *addr;
1106 InetSocketAddress *inet;
1107 int ret;
1109 ret = getnameinfo((struct sockaddr *)sa, salen,
1110 host, sizeof(host),
1111 serv, sizeof(serv),
1112 NI_NUMERICHOST | NI_NUMERICSERV);
1113 if (ret != 0) {
1114 error_setg(errp, "Cannot format numeric socket address: %s",
1115 gai_strerror(ret));
1116 return NULL;
1119 addr = g_new0(SocketAddress, 1);
1120 addr->type = SOCKET_ADDRESS_TYPE_INET;
1121 inet = &addr->u.inet;
1122 inet->host = g_strdup(host);
1123 inet->port = g_strdup(serv);
1124 if (sa->ss_family == AF_INET) {
1125 inet->has_ipv4 = inet->ipv4 = true;
1126 } else {
1127 inet->has_ipv6 = inet->ipv6 = true;
1130 return addr;
1134 #ifndef WIN32
1135 static SocketAddress *
1136 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1137 socklen_t salen,
1138 Error **errp)
1140 SocketAddress *addr;
1141 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1143 addr = g_new0(SocketAddress, 1);
1144 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1145 if (su->sun_path[0]) {
1146 addr->u.q_unix.path = g_strndup(su->sun_path, sizeof(su->sun_path));
1149 return addr;
1151 #endif /* WIN32 */
1153 #ifdef CONFIG_AF_VSOCK
1154 static SocketAddress *
1155 socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,
1156 socklen_t salen,
1157 Error **errp)
1159 SocketAddress *addr;
1160 VsockSocketAddress *vaddr;
1161 struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;
1163 addr = g_new0(SocketAddress, 1);
1164 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1165 vaddr = &addr->u.vsock;
1166 vaddr->cid = g_strdup_printf("%u", svm->svm_cid);
1167 vaddr->port = g_strdup_printf("%u", svm->svm_port);
1169 return addr;
1171 #endif /* CONFIG_AF_VSOCK */
1173 SocketAddress *
1174 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1175 socklen_t salen,
1176 Error **errp)
1178 switch (sa->ss_family) {
1179 case AF_INET:
1180 case AF_INET6:
1181 return socket_sockaddr_to_address_inet(sa, salen, errp);
1183 #ifndef WIN32
1184 case AF_UNIX:
1185 return socket_sockaddr_to_address_unix(sa, salen, errp);
1186 #endif /* WIN32 */
1188 #ifdef CONFIG_AF_VSOCK
1189 case AF_VSOCK:
1190 return socket_sockaddr_to_address_vsock(sa, salen, errp);
1191 #endif
1193 default:
1194 error_setg(errp, "socket family %d unsupported",
1195 sa->ss_family);
1196 return NULL;
1198 return 0;
1202 SocketAddress *socket_local_address(int fd, Error **errp)
1204 struct sockaddr_storage ss;
1205 socklen_t sslen = sizeof(ss);
1207 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1208 error_setg_errno(errp, errno, "%s",
1209 "Unable to query local socket address");
1210 return NULL;
1213 return socket_sockaddr_to_address(&ss, sslen, errp);
1217 SocketAddress *socket_remote_address(int fd, Error **errp)
1219 struct sockaddr_storage ss;
1220 socklen_t sslen = sizeof(ss);
1222 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1223 error_setg_errno(errp, errno, "%s",
1224 "Unable to query remote socket address");
1225 return NULL;
1228 return socket_sockaddr_to_address(&ss, sslen, errp);
1232 SocketAddress *socket_address_flatten(SocketAddressLegacy *addr_legacy)
1234 SocketAddress *addr;
1236 if (!addr_legacy) {
1237 return NULL;
1240 addr = g_new(SocketAddress, 1);
1242 switch (addr_legacy->type) {
1243 case SOCKET_ADDRESS_LEGACY_KIND_INET:
1244 addr->type = SOCKET_ADDRESS_TYPE_INET;
1245 QAPI_CLONE_MEMBERS(InetSocketAddress, &addr->u.inet,
1246 addr_legacy->u.inet.data);
1247 break;
1248 case SOCKET_ADDRESS_LEGACY_KIND_UNIX:
1249 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1250 QAPI_CLONE_MEMBERS(UnixSocketAddress, &addr->u.q_unix,
1251 addr_legacy->u.q_unix.data);
1252 break;
1253 case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:
1254 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1255 QAPI_CLONE_MEMBERS(VsockSocketAddress, &addr->u.vsock,
1256 addr_legacy->u.vsock.data);
1257 break;
1258 case SOCKET_ADDRESS_LEGACY_KIND_FD:
1259 addr->type = SOCKET_ADDRESS_TYPE_FD;
1260 QAPI_CLONE_MEMBERS(String, &addr->u.fd, addr_legacy->u.fd.data);
1261 break;
1262 default:
1263 abort();
1266 return addr;