qapi/run-state.json: introduce memory failure event
[qemu.git] / util / qemu-sockets.c
blobde4bf7616e9e67dbb3b81e1559f7f8f41d69d0cc
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"
34 #include "trace.h"
36 #ifndef AI_ADDRCONFIG
37 # define AI_ADDRCONFIG 0
38 #endif
40 #ifndef AI_V4MAPPED
41 # define AI_V4MAPPED 0
42 #endif
44 #ifndef AI_NUMERICSERV
45 # define AI_NUMERICSERV 0
46 #endif
49 static int inet_getport(struct addrinfo *e)
51 struct sockaddr_in *i4;
52 struct sockaddr_in6 *i6;
54 switch (e->ai_family) {
55 case PF_INET6:
56 i6 = (void*)e->ai_addr;
57 return ntohs(i6->sin6_port);
58 case PF_INET:
59 i4 = (void*)e->ai_addr;
60 return ntohs(i4->sin_port);
61 default:
62 return 0;
66 static void inet_setport(struct addrinfo *e, int port)
68 struct sockaddr_in *i4;
69 struct sockaddr_in6 *i6;
71 switch (e->ai_family) {
72 case PF_INET6:
73 i6 = (void*)e->ai_addr;
74 i6->sin6_port = htons(port);
75 break;
76 case PF_INET:
77 i4 = (void*)e->ai_addr;
78 i4->sin_port = htons(port);
79 break;
83 NetworkAddressFamily inet_netfamily(int family)
85 switch (family) {
86 case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
87 case PF_INET: return NETWORK_ADDRESS_FAMILY_IPV4;
88 case PF_UNIX: return NETWORK_ADDRESS_FAMILY_UNIX;
89 #ifdef CONFIG_AF_VSOCK
90 case PF_VSOCK: return NETWORK_ADDRESS_FAMILY_VSOCK;
91 #endif /* CONFIG_AF_VSOCK */
93 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
96 bool fd_is_socket(int fd)
98 int optval;
99 socklen_t optlen = sizeof(optval);
100 return !qemu_getsockopt(fd, SOL_SOCKET, SO_TYPE, &optval, &optlen);
105 * Matrix we're trying to apply
107 * ipv4 ipv6 family
108 * - - PF_UNSPEC
109 * - f PF_INET
110 * - t PF_INET6
111 * f - PF_INET6
112 * f f <error>
113 * f t PF_INET6
114 * t - PF_INET
115 * t f PF_INET
116 * t t PF_INET6/PF_UNSPEC
118 * NB, this matrix is only about getting the necessary results
119 * from getaddrinfo(). Some of the cases require further work
120 * after reading results from getaddrinfo in order to fully
121 * apply the logic the end user wants.
123 * In the first and last cases, we must set IPV6_V6ONLY=0
124 * when binding, to allow a single listener to potentially
125 * accept both IPv4+6 addresses.
127 int inet_ai_family_from_address(InetSocketAddress *addr,
128 Error **errp)
130 if (addr->has_ipv6 && addr->has_ipv4 &&
131 !addr->ipv6 && !addr->ipv4) {
132 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
133 return PF_UNSPEC;
135 if ((addr->has_ipv6 && addr->ipv6) && (addr->has_ipv4 && addr->ipv4)) {
137 * Some backends can only do a single listener. In that case
138 * we want empty hostname to resolve to "::" and then use the
139 * flag IPV6_V6ONLY==0 to get both protocols on 1 socket. This
140 * doesn't work for addresses other than "", so they're just
141 * inevitably broken until multiple listeners can be used,
142 * and thus we honour getaddrinfo automatic protocol detection
143 * Once all backends do multi-listener, remove the PF_INET6
144 * branch entirely.
146 if (!addr->host || g_str_equal(addr->host, "")) {
147 return PF_INET6;
148 } else {
149 return PF_UNSPEC;
152 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
153 return PF_INET6;
155 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
156 return PF_INET;
158 return PF_UNSPEC;
161 static int create_fast_reuse_socket(struct addrinfo *e)
163 int slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
164 if (slisten < 0) {
165 return -1;
167 socket_set_fast_reuse(slisten);
168 return slisten;
171 static int try_bind(int socket, InetSocketAddress *saddr, struct addrinfo *e)
173 #ifndef IPV6_V6ONLY
174 return bind(socket, e->ai_addr, e->ai_addrlen);
175 #else
177 * Deals with first & last cases in matrix in comment
178 * for inet_ai_family_from_address().
180 int v6only =
181 ((!saddr->has_ipv4 && !saddr->has_ipv6) ||
182 (saddr->has_ipv4 && saddr->ipv4 &&
183 saddr->has_ipv6 && saddr->ipv6)) ? 0 : 1;
184 int stat;
186 rebind:
187 if (e->ai_family == PF_INET6) {
188 qemu_setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, &v6only,
189 sizeof(v6only));
192 stat = bind(socket, e->ai_addr, e->ai_addrlen);
193 if (!stat) {
194 return 0;
197 /* If we got EADDRINUSE from an IPv6 bind & v6only is unset,
198 * it could be that the IPv4 port is already claimed, so retry
199 * with v6only set
201 if (e->ai_family == PF_INET6 && errno == EADDRINUSE && !v6only) {
202 v6only = 1;
203 goto rebind;
205 return stat;
206 #endif
209 static int inet_listen_saddr(InetSocketAddress *saddr,
210 int port_offset,
211 int num,
212 Error **errp)
214 struct addrinfo ai,*res,*e;
215 char port[33];
216 char uaddr[INET6_ADDRSTRLEN+1];
217 char uport[33];
218 int rc, port_min, port_max, p;
219 int slisten = -1;
220 int saved_errno = 0;
221 bool socket_created = false;
222 Error *err = NULL;
224 if (saddr->keep_alive) {
225 error_setg(errp, "keep-alive option is not supported for passive "
226 "sockets");
227 return -1;
230 memset(&ai,0, sizeof(ai));
231 ai.ai_flags = AI_PASSIVE;
232 if (saddr->has_numeric && saddr->numeric) {
233 ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
235 ai.ai_family = inet_ai_family_from_address(saddr, &err);
236 ai.ai_socktype = SOCK_STREAM;
238 if (err) {
239 error_propagate(errp, err);
240 return -1;
243 if (saddr->host == NULL) {
244 error_setg(errp, "host not specified");
245 return -1;
247 if (saddr->port != NULL) {
248 pstrcpy(port, sizeof(port), saddr->port);
249 } else {
250 port[0] = '\0';
253 /* lookup */
254 if (port_offset) {
255 unsigned long long baseport;
256 if (strlen(port) == 0) {
257 error_setg(errp, "port not specified");
258 return -1;
260 if (parse_uint_full(port, &baseport, 10) < 0) {
261 error_setg(errp, "can't convert to a number: %s", port);
262 return -1;
264 if (baseport > 65535 ||
265 baseport + port_offset > 65535) {
266 error_setg(errp, "port %s out of range", port);
267 return -1;
269 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
271 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
272 strlen(port) ? port : NULL, &ai, &res);
273 if (rc != 0) {
274 error_setg(errp, "address resolution failed for %s:%s: %s",
275 saddr->host, port, gai_strerror(rc));
276 return -1;
279 /* create socket + bind/listen */
280 for (e = res; e != NULL; e = e->ai_next) {
281 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
282 uaddr,INET6_ADDRSTRLEN,uport,32,
283 NI_NUMERICHOST | NI_NUMERICSERV);
285 port_min = inet_getport(e);
286 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
287 for (p = port_min; p <= port_max; p++) {
288 inet_setport(e, p);
290 slisten = create_fast_reuse_socket(e);
291 if (slisten < 0) {
292 /* First time we expect we might fail to create the socket
293 * eg if 'e' has AF_INET6 but ipv6 kmod is not loaded.
294 * Later iterations should always succeed if first iteration
295 * worked though, so treat that as fatal.
297 if (p == port_min) {
298 continue;
299 } else {
300 error_setg_errno(errp, errno,
301 "Failed to recreate failed listening socket");
302 goto listen_failed;
305 socket_created = true;
307 rc = try_bind(slisten, saddr, e);
308 if (rc < 0) {
309 if (errno != EADDRINUSE) {
310 error_setg_errno(errp, errno, "Failed to bind socket");
311 goto listen_failed;
313 } else {
314 if (!listen(slisten, num)) {
315 goto listen_ok;
317 if (errno != EADDRINUSE) {
318 error_setg_errno(errp, errno, "Failed to listen on socket");
319 goto listen_failed;
322 /* Someone else managed to bind to the same port and beat us
323 * to listen on it! Socket semantics does not allow us to
324 * recover from this situation, so we need to recreate the
325 * socket to allow bind attempts for subsequent ports:
327 closesocket(slisten);
328 slisten = -1;
331 error_setg_errno(errp, errno,
332 socket_created ?
333 "Failed to find an available port" :
334 "Failed to create a socket");
335 listen_failed:
336 saved_errno = errno;
337 if (slisten >= 0) {
338 closesocket(slisten);
340 freeaddrinfo(res);
341 errno = saved_errno;
342 return -1;
344 listen_ok:
345 freeaddrinfo(res);
346 return slisten;
349 #ifdef _WIN32
350 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
351 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
352 #else
353 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
354 ((rc) == -EINPROGRESS)
355 #endif
357 static int inet_connect_addr(struct addrinfo *addr, Error **errp);
359 static int inet_connect_addr(struct addrinfo *addr, Error **errp)
361 int sock, rc;
363 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
364 if (sock < 0) {
365 error_setg_errno(errp, errno, "Failed to create socket");
366 return -1;
368 socket_set_fast_reuse(sock);
370 /* connect to peer */
371 do {
372 rc = 0;
373 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
374 rc = -errno;
376 } while (rc == -EINTR);
378 if (rc < 0) {
379 error_setg_errno(errp, errno, "Failed to connect socket");
380 closesocket(sock);
381 return -1;
384 return sock;
387 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
388 Error **errp)
390 struct addrinfo ai, *res;
391 int rc;
392 Error *err = NULL;
393 static int useV4Mapped = 1;
395 memset(&ai, 0, sizeof(ai));
397 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
398 if (qatomic_read(&useV4Mapped)) {
399 ai.ai_flags |= AI_V4MAPPED;
401 ai.ai_family = inet_ai_family_from_address(saddr, &err);
402 ai.ai_socktype = SOCK_STREAM;
404 if (err) {
405 error_propagate(errp, err);
406 return NULL;
409 if (saddr->host == NULL || saddr->port == NULL) {
410 error_setg(errp, "host and/or port not specified");
411 return NULL;
414 /* lookup */
415 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
417 /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
418 * then don't implement it in their getaddrinfo(). Detect
419 * this and retry without the flag since that's preferable
420 * to a fatal error
422 if (rc == EAI_BADFLAGS &&
423 (ai.ai_flags & AI_V4MAPPED)) {
424 qatomic_set(&useV4Mapped, 0);
425 ai.ai_flags &= ~AI_V4MAPPED;
426 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
428 if (rc != 0) {
429 error_setg(errp, "address resolution failed for %s:%s: %s",
430 saddr->host, saddr->port, gai_strerror(rc));
431 return NULL;
433 return res;
437 * Create a socket and connect it to an address.
439 * @saddr: Inet socket address specification
440 * @errp: set on error
442 * Returns: -1 on error, file descriptor on success.
444 int inet_connect_saddr(InetSocketAddress *saddr, Error **errp)
446 Error *local_err = NULL;
447 struct addrinfo *res, *e;
448 int sock = -1;
450 res = inet_parse_connect_saddr(saddr, errp);
451 if (!res) {
452 return -1;
455 for (e = res; e != NULL; e = e->ai_next) {
456 error_free(local_err);
457 local_err = NULL;
458 sock = inet_connect_addr(e, &local_err);
459 if (sock >= 0) {
460 break;
464 freeaddrinfo(res);
466 if (sock < 0) {
467 error_propagate(errp, local_err);
468 return sock;
471 if (saddr->keep_alive) {
472 int val = 1;
473 int ret = qemu_setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
474 &val, sizeof(val));
476 if (ret < 0) {
477 error_setg_errno(errp, errno, "Unable to set KEEPALIVE");
478 close(sock);
479 return -1;
483 return sock;
486 static int inet_dgram_saddr(InetSocketAddress *sraddr,
487 InetSocketAddress *sladdr,
488 Error **errp)
490 struct addrinfo ai, *peer = NULL, *local = NULL;
491 const char *addr;
492 const char *port;
493 int sock = -1, rc;
494 Error *err = NULL;
496 /* lookup peer addr */
497 memset(&ai,0, sizeof(ai));
498 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
499 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
500 ai.ai_socktype = SOCK_DGRAM;
502 if (err) {
503 error_propagate(errp, err);
504 goto err;
507 addr = sraddr->host;
508 port = sraddr->port;
509 if (addr == NULL || strlen(addr) == 0) {
510 addr = "localhost";
512 if (port == NULL || strlen(port) == 0) {
513 error_setg(errp, "remote port not specified");
514 goto err;
517 if ((rc = getaddrinfo(addr, port, &ai, &peer)) != 0) {
518 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
519 gai_strerror(rc));
520 goto err;
523 /* lookup local addr */
524 memset(&ai,0, sizeof(ai));
525 ai.ai_flags = AI_PASSIVE;
526 ai.ai_family = peer->ai_family;
527 ai.ai_socktype = SOCK_DGRAM;
529 if (sladdr) {
530 addr = sladdr->host;
531 port = sladdr->port;
532 if (addr == NULL || strlen(addr) == 0) {
533 addr = NULL;
535 if (!port || strlen(port) == 0) {
536 port = "0";
538 } else {
539 addr = NULL;
540 port = "0";
543 if ((rc = getaddrinfo(addr, port, &ai, &local)) != 0) {
544 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
545 gai_strerror(rc));
546 goto err;
549 /* create socket */
550 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
551 if (sock < 0) {
552 error_setg_errno(errp, errno, "Failed to create socket");
553 goto err;
555 socket_set_fast_reuse(sock);
557 /* bind socket */
558 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
559 error_setg_errno(errp, errno, "Failed to bind socket");
560 goto err;
563 /* connect to peer */
564 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
565 error_setg_errno(errp, errno, "Failed to connect socket");
566 goto err;
569 freeaddrinfo(local);
570 freeaddrinfo(peer);
571 return sock;
573 err:
574 if (sock != -1) {
575 closesocket(sock);
577 if (local) {
578 freeaddrinfo(local);
580 if (peer) {
581 freeaddrinfo(peer);
584 return -1;
587 /* compatibility wrapper */
588 static int inet_parse_flag(const char *flagname, const char *optstr, bool *val,
589 Error **errp)
591 char *end;
592 size_t len;
594 end = strstr(optstr, ",");
595 if (end) {
596 if (end[1] == ',') { /* Reject 'ipv6=on,,foo' */
597 error_setg(errp, "error parsing '%s' flag '%s'", flagname, optstr);
598 return -1;
600 len = end - optstr;
601 } else {
602 len = strlen(optstr);
604 if (len == 0 || (len == 3 && strncmp(optstr, "=on", len) == 0)) {
605 *val = true;
606 } else if (len == 4 && strncmp(optstr, "=off", len) == 0) {
607 *val = false;
608 } else {
609 error_setg(errp, "error parsing '%s' flag '%s'", flagname, optstr);
610 return -1;
612 return 0;
615 int inet_parse(InetSocketAddress *addr, const char *str, Error **errp)
617 const char *optstr, *h;
618 char host[65];
619 char port[33];
620 int to;
621 int pos;
622 char *begin;
624 memset(addr, 0, sizeof(*addr));
626 /* parse address */
627 if (str[0] == ':') {
628 /* no host given */
629 host[0] = '\0';
630 if (sscanf(str, ":%32[^,]%n", port, &pos) != 1) {
631 error_setg(errp, "error parsing port in address '%s'", str);
632 return -1;
634 } else if (str[0] == '[') {
635 /* IPv6 addr */
636 if (sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos) != 2) {
637 error_setg(errp, "error parsing IPv6 address '%s'", str);
638 return -1;
640 } else {
641 /* hostname or IPv4 addr */
642 if (sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos) != 2) {
643 error_setg(errp, "error parsing address '%s'", str);
644 return -1;
648 addr->host = g_strdup(host);
649 addr->port = g_strdup(port);
651 /* parse options */
652 optstr = str + pos;
653 h = strstr(optstr, ",to=");
654 if (h) {
655 h += 4;
656 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
657 (h[pos] != '\0' && h[pos] != ',')) {
658 error_setg(errp, "error parsing to= argument");
659 return -1;
661 addr->has_to = true;
662 addr->to = to;
664 begin = strstr(optstr, ",ipv4");
665 if (begin) {
666 if (inet_parse_flag("ipv4", begin + 5, &addr->ipv4, errp) < 0) {
667 return -1;
669 addr->has_ipv4 = true;
671 begin = strstr(optstr, ",ipv6");
672 if (begin) {
673 if (inet_parse_flag("ipv6", begin + 5, &addr->ipv6, errp) < 0) {
674 return -1;
676 addr->has_ipv6 = true;
678 begin = strstr(optstr, ",keep-alive");
679 if (begin) {
680 if (inet_parse_flag("keep-alive", begin + strlen(",keep-alive"),
681 &addr->keep_alive, errp) < 0)
683 return -1;
685 addr->has_keep_alive = true;
687 return 0;
692 * Create a blocking socket and connect it to an address.
694 * @str: address string
695 * @errp: set in case of an error
697 * Returns -1 in case of error, file descriptor on success
699 int inet_connect(const char *str, Error **errp)
701 int sock = -1;
702 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
704 if (!inet_parse(addr, str, errp)) {
705 sock = inet_connect_saddr(addr, errp);
707 qapi_free_InetSocketAddress(addr);
708 return sock;
711 #ifdef CONFIG_AF_VSOCK
712 static bool vsock_parse_vaddr_to_sockaddr(const VsockSocketAddress *vaddr,
713 struct sockaddr_vm *svm,
714 Error **errp)
716 unsigned long long val;
718 memset(svm, 0, sizeof(*svm));
719 svm->svm_family = AF_VSOCK;
721 if (parse_uint_full(vaddr->cid, &val, 10) < 0 ||
722 val > UINT32_MAX) {
723 error_setg(errp, "Failed to parse cid '%s'", vaddr->cid);
724 return false;
726 svm->svm_cid = val;
728 if (parse_uint_full(vaddr->port, &val, 10) < 0 ||
729 val > UINT32_MAX) {
730 error_setg(errp, "Failed to parse port '%s'", vaddr->port);
731 return false;
733 svm->svm_port = val;
735 return true;
738 static int vsock_connect_addr(const struct sockaddr_vm *svm, Error **errp)
740 int sock, rc;
742 sock = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
743 if (sock < 0) {
744 error_setg_errno(errp, errno, "Failed to create socket");
745 return -1;
748 /* connect to peer */
749 do {
750 rc = 0;
751 if (connect(sock, (const struct sockaddr *)svm, sizeof(*svm)) < 0) {
752 rc = -errno;
754 } while (rc == -EINTR);
756 if (rc < 0) {
757 error_setg_errno(errp, errno, "Failed to connect socket");
758 closesocket(sock);
759 return -1;
762 return sock;
765 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
767 struct sockaddr_vm svm;
769 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
770 return -1;
773 return vsock_connect_addr(&svm, errp);
776 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
777 int num,
778 Error **errp)
780 struct sockaddr_vm svm;
781 int slisten;
783 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
784 return -1;
787 slisten = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
788 if (slisten < 0) {
789 error_setg_errno(errp, errno, "Failed to create socket");
790 return -1;
793 if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
794 error_setg_errno(errp, errno, "Failed to bind socket");
795 closesocket(slisten);
796 return -1;
799 if (listen(slisten, num) != 0) {
800 error_setg_errno(errp, errno, "Failed to listen on socket");
801 closesocket(slisten);
802 return -1;
804 return slisten;
807 static int vsock_parse(VsockSocketAddress *addr, const char *str,
808 Error **errp)
810 char cid[33];
811 char port[33];
812 int n;
814 if (sscanf(str, "%32[^:]:%32[^,]%n", cid, port, &n) != 2) {
815 error_setg(errp, "error parsing address '%s'", str);
816 return -1;
818 if (str[n] != '\0') {
819 error_setg(errp, "trailing characters in address '%s'", str);
820 return -1;
823 addr->cid = g_strdup(cid);
824 addr->port = g_strdup(port);
825 return 0;
827 #else
828 static void vsock_unsupported(Error **errp)
830 error_setg(errp, "socket family AF_VSOCK unsupported");
833 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
835 vsock_unsupported(errp);
836 return -1;
839 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
840 int num,
841 Error **errp)
843 vsock_unsupported(errp);
844 return -1;
847 static int vsock_parse(VsockSocketAddress *addr, const char *str,
848 Error **errp)
850 vsock_unsupported(errp);
851 return -1;
853 #endif /* CONFIG_AF_VSOCK */
855 #ifndef _WIN32
857 static int unix_listen_saddr(UnixSocketAddress *saddr,
858 int num,
859 Error **errp)
861 struct sockaddr_un un;
862 int sock, fd;
863 char *pathbuf = NULL;
864 const char *path;
865 size_t pathlen;
866 size_t addrlen;
868 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
869 if (sock < 0) {
870 error_setg_errno(errp, errno, "Failed to create Unix socket");
871 return -1;
874 if (saddr->path && saddr->path[0]) {
875 path = saddr->path;
876 } else {
877 const char *tmpdir = getenv("TMPDIR");
878 tmpdir = tmpdir ? tmpdir : "/tmp";
879 path = pathbuf = g_strdup_printf("%s/qemu-socket-XXXXXX", tmpdir);
882 pathlen = strlen(path);
883 if (pathlen > sizeof(un.sun_path) ||
884 (saddr->abstract && pathlen > (sizeof(un.sun_path) - 1))) {
885 error_setg(errp, "UNIX socket path '%s' is too long", path);
886 error_append_hint(errp, "Path must be less than %zu bytes\n",
887 saddr->abstract ? sizeof(un.sun_path) - 1 :
888 sizeof(un.sun_path));
889 goto err;
892 if (pathbuf != NULL) {
894 * This dummy fd usage silences the mktemp() unsecure warning.
895 * Using mkstemp() doesn't make things more secure here
896 * though. bind() complains about existing files, so we have
897 * to unlink first and thus re-open the race window. The
898 * worst case possible is bind() failing, i.e. a DoS attack.
900 fd = mkstemp(pathbuf);
901 if (fd < 0) {
902 error_setg_errno(errp, errno,
903 "Failed to make a temporary socket %s", pathbuf);
904 goto err;
906 close(fd);
909 if (!saddr->abstract && unlink(path) < 0 && errno != ENOENT) {
910 error_setg_errno(errp, errno,
911 "Failed to unlink socket %s", path);
912 goto err;
915 memset(&un, 0, sizeof(un));
916 un.sun_family = AF_UNIX;
917 addrlen = sizeof(un);
919 if (saddr->abstract) {
920 un.sun_path[0] = '\0';
921 memcpy(&un.sun_path[1], path, pathlen);
922 if (saddr->tight) {
923 addrlen = offsetof(struct sockaddr_un, sun_path) + 1 + pathlen;
925 } else {
926 memcpy(un.sun_path, path, pathlen);
929 if (bind(sock, (struct sockaddr *) &un, addrlen) < 0) {
930 error_setg_errno(errp, errno, "Failed to bind socket to %s", path);
931 goto err;
933 if (listen(sock, num) < 0) {
934 error_setg_errno(errp, errno, "Failed to listen on socket");
935 goto err;
938 g_free(pathbuf);
939 return sock;
941 err:
942 g_free(pathbuf);
943 closesocket(sock);
944 return -1;
947 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
949 struct sockaddr_un un;
950 int sock, rc;
951 size_t pathlen;
952 size_t addrlen;
954 if (saddr->path == NULL) {
955 error_setg(errp, "unix connect: no path specified");
956 return -1;
959 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
960 if (sock < 0) {
961 error_setg_errno(errp, errno, "Failed to create socket");
962 return -1;
965 pathlen = strlen(saddr->path);
966 if (pathlen > sizeof(un.sun_path) ||
967 (saddr->abstract && pathlen > (sizeof(un.sun_path) - 1))) {
968 error_setg(errp, "UNIX socket path '%s' is too long", saddr->path);
969 error_append_hint(errp, "Path must be less than %zu bytes\n",
970 saddr->abstract ? sizeof(un.sun_path) - 1 :
971 sizeof(un.sun_path));
972 goto err;
975 memset(&un, 0, sizeof(un));
976 un.sun_family = AF_UNIX;
977 addrlen = sizeof(un);
979 if (saddr->abstract) {
980 un.sun_path[0] = '\0';
981 memcpy(&un.sun_path[1], saddr->path, pathlen);
982 if (saddr->tight) {
983 addrlen = offsetof(struct sockaddr_un, sun_path) + 1 + pathlen;
985 } else {
986 memcpy(un.sun_path, saddr->path, pathlen);
988 /* connect to peer */
989 do {
990 rc = 0;
991 if (connect(sock, (struct sockaddr *) &un, addrlen) < 0) {
992 rc = -errno;
994 } while (rc == -EINTR);
996 if (rc < 0) {
997 error_setg_errno(errp, -rc, "Failed to connect socket %s",
998 saddr->path);
999 goto err;
1002 return sock;
1004 err:
1005 close(sock);
1006 return -1;
1009 #else
1011 static int unix_listen_saddr(UnixSocketAddress *saddr,
1012 int num,
1013 Error **errp)
1015 error_setg(errp, "unix sockets are not available on windows");
1016 errno = ENOTSUP;
1017 return -1;
1020 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
1022 error_setg(errp, "unix sockets are not available on windows");
1023 errno = ENOTSUP;
1024 return -1;
1026 #endif
1028 /* compatibility wrapper */
1029 int unix_listen(const char *str, Error **errp)
1031 UnixSocketAddress *saddr;
1032 int sock;
1034 saddr = g_new0(UnixSocketAddress, 1);
1035 saddr->path = g_strdup(str);
1036 sock = unix_listen_saddr(saddr, 1, errp);
1037 qapi_free_UnixSocketAddress(saddr);
1038 return sock;
1041 int unix_connect(const char *path, Error **errp)
1043 UnixSocketAddress *saddr;
1044 int sock;
1046 saddr = g_new0(UnixSocketAddress, 1);
1047 saddr->path = g_strdup(path);
1048 sock = unix_connect_saddr(saddr, errp);
1049 qapi_free_UnixSocketAddress(saddr);
1050 return sock;
1054 SocketAddress *socket_parse(const char *str, Error **errp)
1056 SocketAddress *addr;
1058 addr = g_new0(SocketAddress, 1);
1059 if (strstart(str, "unix:", NULL)) {
1060 if (str[5] == '\0') {
1061 error_setg(errp, "invalid Unix socket address");
1062 goto fail;
1063 } else {
1064 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1065 addr->u.q_unix.path = g_strdup(str + 5);
1067 } else if (strstart(str, "fd:", NULL)) {
1068 if (str[3] == '\0') {
1069 error_setg(errp, "invalid file descriptor address");
1070 goto fail;
1071 } else {
1072 addr->type = SOCKET_ADDRESS_TYPE_FD;
1073 addr->u.fd.str = g_strdup(str + 3);
1075 } else if (strstart(str, "vsock:", NULL)) {
1076 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1077 if (vsock_parse(&addr->u.vsock, str + strlen("vsock:"), errp)) {
1078 goto fail;
1080 } else {
1081 addr->type = SOCKET_ADDRESS_TYPE_INET;
1082 if (inet_parse(&addr->u.inet, str, errp)) {
1083 goto fail;
1086 return addr;
1088 fail:
1089 qapi_free_SocketAddress(addr);
1090 return NULL;
1093 static int socket_get_fd(const char *fdstr, int num, Error **errp)
1095 int fd;
1096 if (num != 1) {
1097 error_setg_errno(errp, EINVAL, "socket_get_fd: too many connections");
1098 return -1;
1100 if (cur_mon) {
1101 fd = monitor_get_fd(cur_mon, fdstr, errp);
1102 if (fd < 0) {
1103 return -1;
1105 } else {
1106 if (qemu_strtoi(fdstr, NULL, 10, &fd) < 0) {
1107 error_setg_errno(errp, errno,
1108 "Unable to parse FD number %s",
1109 fdstr);
1110 return -1;
1113 if (!fd_is_socket(fd)) {
1114 error_setg(errp, "File descriptor '%s' is not a socket", fdstr);
1115 close(fd);
1116 return -1;
1118 return fd;
1121 int socket_connect(SocketAddress *addr, Error **errp)
1123 int fd;
1125 switch (addr->type) {
1126 case SOCKET_ADDRESS_TYPE_INET:
1127 fd = inet_connect_saddr(&addr->u.inet, errp);
1128 break;
1130 case SOCKET_ADDRESS_TYPE_UNIX:
1131 fd = unix_connect_saddr(&addr->u.q_unix, errp);
1132 break;
1134 case SOCKET_ADDRESS_TYPE_FD:
1135 fd = socket_get_fd(addr->u.fd.str, 1, errp);
1136 break;
1138 case SOCKET_ADDRESS_TYPE_VSOCK:
1139 fd = vsock_connect_saddr(&addr->u.vsock, errp);
1140 break;
1142 default:
1143 abort();
1145 return fd;
1148 int socket_listen(SocketAddress *addr, int num, Error **errp)
1150 int fd;
1152 trace_socket_listen(num);
1153 switch (addr->type) {
1154 case SOCKET_ADDRESS_TYPE_INET:
1155 fd = inet_listen_saddr(&addr->u.inet, 0, num, errp);
1156 break;
1158 case SOCKET_ADDRESS_TYPE_UNIX:
1159 fd = unix_listen_saddr(&addr->u.q_unix, num, errp);
1160 break;
1162 case SOCKET_ADDRESS_TYPE_FD:
1163 fd = socket_get_fd(addr->u.fd.str, num, errp);
1164 break;
1166 case SOCKET_ADDRESS_TYPE_VSOCK:
1167 fd = vsock_listen_saddr(&addr->u.vsock, num, errp);
1168 break;
1170 default:
1171 abort();
1173 return fd;
1176 void socket_listen_cleanup(int fd, Error **errp)
1178 SocketAddress *addr;
1180 addr = socket_local_address(fd, errp);
1181 if (!addr) {
1182 return;
1185 if (addr->type == SOCKET_ADDRESS_TYPE_UNIX
1186 && addr->u.q_unix.path) {
1187 if (unlink(addr->u.q_unix.path) < 0 && errno != ENOENT) {
1188 error_setg_errno(errp, errno,
1189 "Failed to unlink socket %s",
1190 addr->u.q_unix.path);
1194 qapi_free_SocketAddress(addr);
1197 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
1199 int fd;
1202 * TODO SOCKET_ADDRESS_TYPE_FD when fd is AF_INET or AF_INET6
1203 * (although other address families can do SOCK_DGRAM, too)
1205 switch (remote->type) {
1206 case SOCKET_ADDRESS_TYPE_INET:
1207 fd = inet_dgram_saddr(&remote->u.inet,
1208 local ? &local->u.inet : NULL, errp);
1209 break;
1211 default:
1212 error_setg(errp, "socket type unsupported for datagram");
1213 fd = -1;
1215 return fd;
1219 static SocketAddress *
1220 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1221 socklen_t salen,
1222 Error **errp)
1224 char host[NI_MAXHOST];
1225 char serv[NI_MAXSERV];
1226 SocketAddress *addr;
1227 InetSocketAddress *inet;
1228 int ret;
1230 ret = getnameinfo((struct sockaddr *)sa, salen,
1231 host, sizeof(host),
1232 serv, sizeof(serv),
1233 NI_NUMERICHOST | NI_NUMERICSERV);
1234 if (ret != 0) {
1235 error_setg(errp, "Cannot format numeric socket address: %s",
1236 gai_strerror(ret));
1237 return NULL;
1240 addr = g_new0(SocketAddress, 1);
1241 addr->type = SOCKET_ADDRESS_TYPE_INET;
1242 inet = &addr->u.inet;
1243 inet->host = g_strdup(host);
1244 inet->port = g_strdup(serv);
1245 if (sa->ss_family == AF_INET) {
1246 inet->has_ipv4 = inet->ipv4 = true;
1247 } else {
1248 inet->has_ipv6 = inet->ipv6 = true;
1251 return addr;
1255 #ifndef WIN32
1256 static SocketAddress *
1257 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1258 socklen_t salen,
1259 Error **errp)
1261 SocketAddress *addr;
1262 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1264 addr = g_new0(SocketAddress, 1);
1265 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1266 if (su->sun_path[0]) {
1267 addr->u.q_unix.path = g_strndup(su->sun_path, sizeof(su->sun_path));
1270 return addr;
1272 #endif /* WIN32 */
1274 #ifdef CONFIG_AF_VSOCK
1275 static SocketAddress *
1276 socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,
1277 socklen_t salen,
1278 Error **errp)
1280 SocketAddress *addr;
1281 VsockSocketAddress *vaddr;
1282 struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;
1284 addr = g_new0(SocketAddress, 1);
1285 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1286 vaddr = &addr->u.vsock;
1287 vaddr->cid = g_strdup_printf("%u", svm->svm_cid);
1288 vaddr->port = g_strdup_printf("%u", svm->svm_port);
1290 return addr;
1292 #endif /* CONFIG_AF_VSOCK */
1294 SocketAddress *
1295 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1296 socklen_t salen,
1297 Error **errp)
1299 switch (sa->ss_family) {
1300 case AF_INET:
1301 case AF_INET6:
1302 return socket_sockaddr_to_address_inet(sa, salen, errp);
1304 #ifndef WIN32
1305 case AF_UNIX:
1306 return socket_sockaddr_to_address_unix(sa, salen, errp);
1307 #endif /* WIN32 */
1309 #ifdef CONFIG_AF_VSOCK
1310 case AF_VSOCK:
1311 return socket_sockaddr_to_address_vsock(sa, salen, errp);
1312 #endif
1314 default:
1315 error_setg(errp, "socket family %d unsupported",
1316 sa->ss_family);
1317 return NULL;
1319 return 0;
1323 SocketAddress *socket_local_address(int fd, Error **errp)
1325 struct sockaddr_storage ss;
1326 socklen_t sslen = sizeof(ss);
1328 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1329 error_setg_errno(errp, errno, "%s",
1330 "Unable to query local socket address");
1331 return NULL;
1334 return socket_sockaddr_to_address(&ss, sslen, errp);
1338 SocketAddress *socket_remote_address(int fd, Error **errp)
1340 struct sockaddr_storage ss;
1341 socklen_t sslen = sizeof(ss);
1343 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1344 error_setg_errno(errp, errno, "%s",
1345 "Unable to query remote socket address");
1346 return NULL;
1349 return socket_sockaddr_to_address(&ss, sslen, errp);
1353 SocketAddress *socket_address_flatten(SocketAddressLegacy *addr_legacy)
1355 SocketAddress *addr;
1357 if (!addr_legacy) {
1358 return NULL;
1361 addr = g_new(SocketAddress, 1);
1363 switch (addr_legacy->type) {
1364 case SOCKET_ADDRESS_LEGACY_KIND_INET:
1365 addr->type = SOCKET_ADDRESS_TYPE_INET;
1366 QAPI_CLONE_MEMBERS(InetSocketAddress, &addr->u.inet,
1367 addr_legacy->u.inet.data);
1368 break;
1369 case SOCKET_ADDRESS_LEGACY_KIND_UNIX:
1370 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1371 QAPI_CLONE_MEMBERS(UnixSocketAddress, &addr->u.q_unix,
1372 addr_legacy->u.q_unix.data);
1373 break;
1374 case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:
1375 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1376 QAPI_CLONE_MEMBERS(VsockSocketAddress, &addr->u.vsock,
1377 addr_legacy->u.vsock.data);
1378 break;
1379 case SOCKET_ADDRESS_LEGACY_KIND_FD:
1380 addr->type = SOCKET_ADDRESS_TYPE_FD;
1381 QAPI_CLONE_MEMBERS(String, &addr->u.fd, addr_legacy->u.fd.data);
1382 break;
1383 default:
1384 abort();
1387 return addr;