arm: All M profile cores are PMSA
[qemu/ar7.git] / util / qemu-sockets.c
blobb39ae74fe059593d3824478f916d15dc61ae5465
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/clone-visitor.h"
30 #include "qapi/qobject-input-visitor.h"
31 #include "qapi/qobject-output-visitor.h"
32 #include "qapi-visit.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;
96 * Matrix we're trying to apply
98 * ipv4 ipv6 family
99 * - - PF_UNSPEC
100 * - f PF_INET
101 * - t PF_INET6
102 * f - PF_INET6
103 * f f <error>
104 * f t PF_INET6
105 * t - PF_INET
106 * t f PF_INET
107 * t t PF_INET6
109 * NB, this matrix is only about getting the necessary results
110 * from getaddrinfo(). Some of the cases require further work
111 * after reading results from getaddrinfo in order to fully
112 * apply the logic the end user wants. eg with the last case
113 * ipv4=t + ipv6=t + PF_INET6, getaddrinfo alone can only
114 * guarantee the ipv6=t part of the request - we need more
115 * checks to provide ipv4=t part of the guarantee. This is
116 * outside scope of this method and not currently handled by
117 * callers at all.
119 int inet_ai_family_from_address(InetSocketAddress *addr,
120 Error **errp)
122 if (addr->has_ipv6 && addr->has_ipv4 &&
123 !addr->ipv6 && !addr->ipv4) {
124 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
125 return PF_UNSPEC;
127 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
128 return PF_INET6;
130 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
131 return PF_INET;
133 return PF_UNSPEC;
136 static int inet_listen_saddr(InetSocketAddress *saddr,
137 int port_offset,
138 bool update_addr,
139 Error **errp)
141 struct addrinfo ai,*res,*e;
142 char port[33];
143 char uaddr[INET6_ADDRSTRLEN+1];
144 char uport[33];
145 int slisten, rc, port_min, port_max, p;
146 Error *err = NULL;
148 memset(&ai,0, sizeof(ai));
149 ai.ai_flags = AI_PASSIVE;
150 if (saddr->has_numeric && saddr->numeric) {
151 ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
153 ai.ai_family = inet_ai_family_from_address(saddr, &err);
154 ai.ai_socktype = SOCK_STREAM;
156 if (err) {
157 error_propagate(errp, err);
158 return -1;
161 if (saddr->host == NULL) {
162 error_setg(errp, "host not specified");
163 return -1;
165 if (saddr->port != NULL) {
166 pstrcpy(port, sizeof(port), saddr->port);
167 } else {
168 port[0] = '\0';
171 /* lookup */
172 if (port_offset) {
173 unsigned long long baseport;
174 if (strlen(port) == 0) {
175 error_setg(errp, "port not specified");
176 return -1;
178 if (parse_uint_full(port, &baseport, 10) < 0) {
179 error_setg(errp, "can't convert to a number: %s", port);
180 return -1;
182 if (baseport > 65535 ||
183 baseport + port_offset > 65535) {
184 error_setg(errp, "port %s out of range", port);
185 return -1;
187 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
189 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
190 strlen(port) ? port : NULL, &ai, &res);
191 if (rc != 0) {
192 error_setg(errp, "address resolution failed for %s:%s: %s",
193 saddr->host, port, gai_strerror(rc));
194 return -1;
197 /* create socket + bind */
198 for (e = res; e != NULL; e = e->ai_next) {
199 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
200 uaddr,INET6_ADDRSTRLEN,uport,32,
201 NI_NUMERICHOST | NI_NUMERICSERV);
202 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
203 if (slisten < 0) {
204 if (!e->ai_next) {
205 error_setg_errno(errp, errno, "Failed to create socket");
207 continue;
210 socket_set_fast_reuse(slisten);
211 #ifdef IPV6_V6ONLY
212 if (e->ai_family == PF_INET6) {
213 /* listen on both ipv4 and ipv6 */
214 const int off = 0;
215 qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,
216 sizeof(off));
218 #endif
220 port_min = inet_getport(e);
221 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
222 for (p = port_min; p <= port_max; p++) {
223 inet_setport(e, p);
224 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
225 goto listen;
227 if (p == port_max) {
228 if (!e->ai_next) {
229 error_setg_errno(errp, errno, "Failed to bind socket");
233 closesocket(slisten);
235 freeaddrinfo(res);
236 return -1;
238 listen:
239 if (listen(slisten,1) != 0) {
240 error_setg_errno(errp, errno, "Failed to listen on socket");
241 closesocket(slisten);
242 freeaddrinfo(res);
243 return -1;
245 if (update_addr) {
246 g_free(saddr->host);
247 saddr->host = g_strdup(uaddr);
248 g_free(saddr->port);
249 saddr->port = g_strdup_printf("%d",
250 inet_getport(e) - port_offset);
251 saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
252 saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
254 freeaddrinfo(res);
255 return slisten;
258 #ifdef _WIN32
259 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
260 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
261 #else
262 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
263 ((rc) == -EINPROGRESS)
264 #endif
266 /* Struct to store connect state for non blocking connect */
267 typedef struct ConnectState {
268 int fd;
269 struct addrinfo *addr_list;
270 struct addrinfo *current_addr;
271 NonBlockingConnectHandler *callback;
272 void *opaque;
273 } ConnectState;
275 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
276 ConnectState *connect_state, Error **errp);
278 static void wait_for_connect(void *opaque)
280 ConnectState *s = opaque;
281 int val = 0, rc = 0;
282 socklen_t valsize = sizeof(val);
283 bool in_progress;
284 Error *err = NULL;
286 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
288 do {
289 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
290 } while (rc == -1 && errno == EINTR);
292 /* update rc to contain error */
293 if (!rc && val) {
294 rc = -1;
295 errno = val;
298 /* connect error */
299 if (rc < 0) {
300 error_setg_errno(&err, errno, "Error connecting to socket");
301 closesocket(s->fd);
302 s->fd = rc;
305 /* try to connect to the next address on the list */
306 if (s->current_addr) {
307 while (s->current_addr->ai_next != NULL && s->fd < 0) {
308 s->current_addr = s->current_addr->ai_next;
309 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
310 if (s->fd < 0) {
311 error_free(err);
312 err = NULL;
313 error_setg_errno(&err, errno, "Unable to start socket connect");
315 /* connect in progress */
316 if (in_progress) {
317 goto out;
321 freeaddrinfo(s->addr_list);
324 if (s->callback) {
325 s->callback(s->fd, err, s->opaque);
327 g_free(s);
328 out:
329 error_free(err);
332 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
333 ConnectState *connect_state, Error **errp)
335 int sock, rc;
337 *in_progress = false;
339 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
340 if (sock < 0) {
341 error_setg_errno(errp, errno, "Failed to create socket");
342 return -1;
344 socket_set_fast_reuse(sock);
345 if (connect_state != NULL) {
346 qemu_set_nonblock(sock);
348 /* connect to peer */
349 do {
350 rc = 0;
351 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
352 rc = -errno;
354 } while (rc == -EINTR);
356 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
357 connect_state->fd = sock;
358 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
359 *in_progress = true;
360 } else if (rc < 0) {
361 error_setg_errno(errp, errno, "Failed to connect socket");
362 closesocket(sock);
363 return -1;
365 return sock;
368 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
369 Error **errp)
371 struct addrinfo ai, *res;
372 int rc;
373 Error *err = NULL;
374 static int useV4Mapped = 1;
376 memset(&ai, 0, sizeof(ai));
378 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
379 if (atomic_read(&useV4Mapped)) {
380 ai.ai_flags |= AI_V4MAPPED;
382 ai.ai_family = inet_ai_family_from_address(saddr, &err);
383 ai.ai_socktype = SOCK_STREAM;
385 if (err) {
386 error_propagate(errp, err);
387 return NULL;
390 if (saddr->host == NULL || saddr->port == NULL) {
391 error_setg(errp, "host and/or port not specified");
392 return NULL;
395 /* lookup */
396 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
398 /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
399 * then don't implement it in their getaddrinfo(). Detect
400 * this and retry without the flag since that's preferrable
401 * to a fatal error
403 if (rc == EAI_BADFLAGS &&
404 (ai.ai_flags & AI_V4MAPPED)) {
405 atomic_set(&useV4Mapped, 0);
406 ai.ai_flags &= ~AI_V4MAPPED;
407 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
409 if (rc != 0) {
410 error_setg(errp, "address resolution failed for %s:%s: %s",
411 saddr->host, saddr->port, gai_strerror(rc));
412 return NULL;
414 return res;
418 * Create a socket and connect it to an address.
420 * @saddr: Inet socket address specification
421 * @errp: set on error
422 * @callback: callback function for non-blocking connect
423 * @opaque: opaque for callback function
425 * Returns: -1 on error, file descriptor on success.
427 * If @callback is non-null, the connect is non-blocking. If this
428 * function succeeds, callback will be called when the connection
429 * completes, with the file descriptor on success, or -1 on error.
431 int inet_connect_saddr(InetSocketAddress *saddr,
432 NonBlockingConnectHandler *callback, void *opaque,
433 Error **errp)
435 Error *local_err = NULL;
436 struct addrinfo *res, *e;
437 int sock = -1;
438 bool in_progress;
439 ConnectState *connect_state = NULL;
441 res = inet_parse_connect_saddr(saddr, errp);
442 if (!res) {
443 return -1;
446 if (callback != NULL) {
447 connect_state = g_malloc0(sizeof(*connect_state));
448 connect_state->addr_list = res;
449 connect_state->callback = callback;
450 connect_state->opaque = opaque;
453 for (e = res; e != NULL; e = e->ai_next) {
454 error_free(local_err);
455 local_err = NULL;
456 if (connect_state != NULL) {
457 connect_state->current_addr = e;
459 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
460 if (sock >= 0) {
461 break;
465 if (sock < 0) {
466 error_propagate(errp, local_err);
467 } else if (in_progress) {
468 /* wait_for_connect() will do the rest */
469 return sock;
470 } else {
471 if (callback) {
472 callback(sock, NULL, opaque);
475 g_free(connect_state);
476 freeaddrinfo(res);
477 return sock;
480 static int inet_dgram_saddr(InetSocketAddress *sraddr,
481 InetSocketAddress *sladdr,
482 Error **errp)
484 struct addrinfo ai, *peer = NULL, *local = NULL;
485 const char *addr;
486 const char *port;
487 int sock = -1, rc;
488 Error *err = NULL;
490 /* lookup peer addr */
491 memset(&ai,0, sizeof(ai));
492 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
493 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
494 ai.ai_socktype = SOCK_DGRAM;
496 if (err) {
497 error_propagate(errp, err);
498 goto err;
501 addr = sraddr->host;
502 port = sraddr->port;
503 if (addr == NULL || strlen(addr) == 0) {
504 addr = "localhost";
506 if (port == NULL || strlen(port) == 0) {
507 error_setg(errp, "remote port not specified");
508 goto err;
511 if ((rc = getaddrinfo(addr, port, &ai, &peer)) != 0) {
512 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
513 gai_strerror(rc));
514 goto err;
517 /* lookup local addr */
518 memset(&ai,0, sizeof(ai));
519 ai.ai_flags = AI_PASSIVE;
520 ai.ai_family = peer->ai_family;
521 ai.ai_socktype = SOCK_DGRAM;
523 if (sladdr) {
524 addr = sladdr->host;
525 port = sladdr->port;
526 if (addr == NULL || strlen(addr) == 0) {
527 addr = NULL;
529 if (!port || strlen(port) == 0) {
530 port = "0";
532 } else {
533 addr = NULL;
534 port = "0";
537 if ((rc = getaddrinfo(addr, port, &ai, &local)) != 0) {
538 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
539 gai_strerror(rc));
540 goto err;
543 /* create socket */
544 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
545 if (sock < 0) {
546 error_setg_errno(errp, errno, "Failed to create socket");
547 goto err;
549 socket_set_fast_reuse(sock);
551 /* bind socket */
552 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
553 error_setg_errno(errp, errno, "Failed to bind socket");
554 goto err;
557 /* connect to peer */
558 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
559 error_setg_errno(errp, errno, "Failed to connect socket");
560 goto err;
563 freeaddrinfo(local);
564 freeaddrinfo(peer);
565 return sock;
567 err:
568 if (sock != -1) {
569 closesocket(sock);
571 if (local) {
572 freeaddrinfo(local);
574 if (peer) {
575 freeaddrinfo(peer);
578 return -1;
581 /* compatibility wrapper */
582 int inet_parse(InetSocketAddress *addr, const char *str, Error **errp)
584 const char *optstr, *h;
585 char host[65];
586 char port[33];
587 int to;
588 int pos;
590 memset(addr, 0, sizeof(*addr));
592 /* parse address */
593 if (str[0] == ':') {
594 /* no host given */
595 host[0] = '\0';
596 if (sscanf(str, ":%32[^,]%n", port, &pos) != 1) {
597 error_setg(errp, "error parsing port in address '%s'", str);
598 return -1;
600 } else if (str[0] == '[') {
601 /* IPv6 addr */
602 if (sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos) != 2) {
603 error_setg(errp, "error parsing IPv6 address '%s'", str);
604 return -1;
606 addr->ipv6 = addr->has_ipv6 = true;
607 } else {
608 /* hostname or IPv4 addr */
609 if (sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos) != 2) {
610 error_setg(errp, "error parsing address '%s'", str);
611 return -1;
613 if (host[strspn(host, "0123456789.")] == '\0') {
614 addr->ipv4 = addr->has_ipv4 = true;
618 addr->host = g_strdup(host);
619 addr->port = g_strdup(port);
621 /* parse options */
622 optstr = str + pos;
623 h = strstr(optstr, ",to=");
624 if (h) {
625 h += 4;
626 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
627 (h[pos] != '\0' && h[pos] != ',')) {
628 error_setg(errp, "error parsing to= argument");
629 return -1;
631 addr->has_to = true;
632 addr->to = to;
634 if (strstr(optstr, ",ipv4")) {
635 addr->ipv4 = addr->has_ipv4 = true;
637 if (strstr(optstr, ",ipv6")) {
638 addr->ipv6 = addr->has_ipv6 = true;
640 return 0;
645 * Create a blocking socket and connect it to an address.
647 * @str: address string
648 * @errp: set in case of an error
650 * Returns -1 in case of error, file descriptor on success
652 int inet_connect(const char *str, Error **errp)
654 int sock = -1;
655 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
657 if (!inet_parse(addr, str, errp)) {
658 sock = inet_connect_saddr(addr, NULL, NULL, errp);
660 qapi_free_InetSocketAddress(addr);
661 return sock;
664 #ifdef CONFIG_AF_VSOCK
665 static bool vsock_parse_vaddr_to_sockaddr(const VsockSocketAddress *vaddr,
666 struct sockaddr_vm *svm,
667 Error **errp)
669 unsigned long long val;
671 memset(svm, 0, sizeof(*svm));
672 svm->svm_family = AF_VSOCK;
674 if (parse_uint_full(vaddr->cid, &val, 10) < 0 ||
675 val > UINT32_MAX) {
676 error_setg(errp, "Failed to parse cid '%s'", vaddr->cid);
677 return false;
679 svm->svm_cid = val;
681 if (parse_uint_full(vaddr->port, &val, 10) < 0 ||
682 val > UINT32_MAX) {
683 error_setg(errp, "Failed to parse port '%s'", vaddr->port);
684 return false;
686 svm->svm_port = val;
688 return true;
691 static int vsock_connect_addr(const struct sockaddr_vm *svm, bool *in_progress,
692 ConnectState *connect_state, Error **errp)
694 int sock, rc;
696 *in_progress = false;
698 sock = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
699 if (sock < 0) {
700 error_setg_errno(errp, errno, "Failed to create socket");
701 return -1;
703 if (connect_state != NULL) {
704 qemu_set_nonblock(sock);
706 /* connect to peer */
707 do {
708 rc = 0;
709 if (connect(sock, (const struct sockaddr *)svm, sizeof(*svm)) < 0) {
710 rc = -errno;
712 } while (rc == -EINTR);
714 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
715 connect_state->fd = sock;
716 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
717 *in_progress = true;
718 } else if (rc < 0) {
719 error_setg_errno(errp, errno, "Failed to connect socket");
720 closesocket(sock);
721 return -1;
723 return sock;
726 static int vsock_connect_saddr(VsockSocketAddress *vaddr,
727 NonBlockingConnectHandler *callback,
728 void *opaque,
729 Error **errp)
731 struct sockaddr_vm svm;
732 int sock = -1;
733 bool in_progress;
734 ConnectState *connect_state = NULL;
736 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
737 return -1;
740 if (callback != NULL) {
741 connect_state = g_malloc0(sizeof(*connect_state));
742 connect_state->callback = callback;
743 connect_state->opaque = opaque;
746 sock = vsock_connect_addr(&svm, &in_progress, connect_state, errp);
747 if (sock < 0) {
748 /* do nothing */
749 } else if (in_progress) {
750 /* wait_for_connect() will do the rest */
751 return sock;
752 } else {
753 if (callback) {
754 callback(sock, NULL, opaque);
757 g_free(connect_state);
758 return sock;
761 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
762 Error **errp)
764 struct sockaddr_vm svm;
765 int slisten;
767 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
768 return -1;
771 slisten = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
772 if (slisten < 0) {
773 error_setg_errno(errp, errno, "Failed to create socket");
774 return -1;
777 if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
778 error_setg_errno(errp, errno, "Failed to bind socket");
779 closesocket(slisten);
780 return -1;
783 if (listen(slisten, 1) != 0) {
784 error_setg_errno(errp, errno, "Failed to listen on socket");
785 closesocket(slisten);
786 return -1;
788 return slisten;
791 static int vsock_parse(VsockSocketAddress *addr, const char *str,
792 Error **errp)
794 char cid[33];
795 char port[33];
796 int n;
798 if (sscanf(str, "%32[^:]:%32[^,]%n", cid, port, &n) != 2) {
799 error_setg(errp, "error parsing address '%s'", str);
800 return -1;
802 if (str[n] != '\0') {
803 error_setg(errp, "trailing characters in address '%s'", str);
804 return -1;
807 addr->cid = g_strdup(cid);
808 addr->port = g_strdup(port);
809 return 0;
811 #else
812 static void vsock_unsupported(Error **errp)
814 error_setg(errp, "socket family AF_VSOCK unsupported");
817 static int vsock_connect_saddr(VsockSocketAddress *vaddr,
818 NonBlockingConnectHandler *callback,
819 void *opaque, Error **errp)
821 vsock_unsupported(errp);
822 return -1;
825 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
826 Error **errp)
828 vsock_unsupported(errp);
829 return -1;
832 static int vsock_parse(VsockSocketAddress *addr, const char *str,
833 Error **errp)
835 vsock_unsupported(errp);
836 return -1;
838 #endif /* CONFIG_AF_VSOCK */
840 #ifndef _WIN32
842 static int unix_listen_saddr(UnixSocketAddress *saddr,
843 bool update_addr,
844 Error **errp)
846 struct sockaddr_un un;
847 int sock, fd;
849 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
850 if (sock < 0) {
851 error_setg_errno(errp, errno, "Failed to create Unix socket");
852 return -1;
855 memset(&un, 0, sizeof(un));
856 un.sun_family = AF_UNIX;
857 if (saddr->path && strlen(saddr->path)) {
858 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
859 } else {
860 const char *tmpdir = getenv("TMPDIR");
861 tmpdir = tmpdir ? tmpdir : "/tmp";
862 if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
863 tmpdir) >= sizeof(un.sun_path)) {
864 error_setg_errno(errp, errno,
865 "TMPDIR environment variable (%s) too large", tmpdir);
866 goto err;
870 * This dummy fd usage silences the mktemp() unsecure warning.
871 * Using mkstemp() doesn't make things more secure here
872 * though. bind() complains about existing files, so we have
873 * to unlink first and thus re-open the race window. The
874 * worst case possible is bind() failing, i.e. a DoS attack.
876 fd = mkstemp(un.sun_path);
877 if (fd < 0) {
878 error_setg_errno(errp, errno,
879 "Failed to make a temporary socket name in %s", tmpdir);
880 goto err;
882 close(fd);
883 if (update_addr) {
884 g_free(saddr->path);
885 saddr->path = g_strdup(un.sun_path);
889 if (unlink(un.sun_path) < 0 && errno != ENOENT) {
890 error_setg_errno(errp, errno,
891 "Failed to unlink socket %s", un.sun_path);
892 goto err;
894 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
895 error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);
896 goto err;
898 if (listen(sock, 1) < 0) {
899 error_setg_errno(errp, errno, "Failed to listen on socket");
900 goto err;
903 return sock;
905 err:
906 closesocket(sock);
907 return -1;
910 static int unix_connect_saddr(UnixSocketAddress *saddr,
911 NonBlockingConnectHandler *callback, void *opaque,
912 Error **errp)
914 struct sockaddr_un un;
915 ConnectState *connect_state = NULL;
916 int sock, rc;
918 if (saddr->path == NULL) {
919 error_setg(errp, "unix connect: no path specified");
920 return -1;
923 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
924 if (sock < 0) {
925 error_setg_errno(errp, errno, "Failed to create socket");
926 return -1;
928 if (callback != NULL) {
929 connect_state = g_malloc0(sizeof(*connect_state));
930 connect_state->callback = callback;
931 connect_state->opaque = opaque;
932 qemu_set_nonblock(sock);
935 memset(&un, 0, sizeof(un));
936 un.sun_family = AF_UNIX;
937 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
939 /* connect to peer */
940 do {
941 rc = 0;
942 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
943 rc = -errno;
945 } while (rc == -EINTR);
947 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
948 connect_state->fd = sock;
949 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
950 return sock;
951 } else if (rc >= 0) {
952 /* non blocking socket immediate success, call callback */
953 if (callback != NULL) {
954 callback(sock, NULL, opaque);
958 if (rc < 0) {
959 error_setg_errno(errp, -rc, "Failed to connect socket");
960 close(sock);
961 sock = -1;
964 g_free(connect_state);
965 return sock;
968 #else
970 static int unix_listen_saddr(UnixSocketAddress *saddr,
971 bool update_addr,
972 Error **errp)
974 error_setg(errp, "unix sockets are not available on windows");
975 errno = ENOTSUP;
976 return -1;
979 static int unix_connect_saddr(UnixSocketAddress *saddr,
980 NonBlockingConnectHandler *callback, void *opaque,
981 Error **errp)
983 error_setg(errp, "unix sockets are not available on windows");
984 errno = ENOTSUP;
985 return -1;
987 #endif
989 /* compatibility wrapper */
990 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
992 char *path, *optstr;
993 int sock, len;
994 UnixSocketAddress *saddr;
996 saddr = g_new0(UnixSocketAddress, 1);
998 optstr = strchr(str, ',');
999 if (optstr) {
1000 len = optstr - str;
1001 if (len) {
1002 path = g_malloc(len+1);
1003 snprintf(path, len+1, "%.*s", len, str);
1004 saddr->path = path;
1006 } else {
1007 saddr->path = g_strdup(str);
1010 sock = unix_listen_saddr(saddr, true, errp);
1012 if (sock != -1 && ostr) {
1013 snprintf(ostr, olen, "%s%s", saddr->path, optstr ? optstr : "");
1016 qapi_free_UnixSocketAddress(saddr);
1017 return sock;
1020 int unix_connect(const char *path, Error **errp)
1022 UnixSocketAddress *saddr;
1023 int sock;
1025 saddr = g_new0(UnixSocketAddress, 1);
1026 saddr->path = g_strdup(path);
1027 sock = unix_connect_saddr(saddr, NULL, NULL, errp);
1028 qapi_free_UnixSocketAddress(saddr);
1029 return sock;
1033 SocketAddress *socket_parse(const char *str, Error **errp)
1035 SocketAddress *addr;
1037 addr = g_new0(SocketAddress, 1);
1038 if (strstart(str, "unix:", NULL)) {
1039 if (str[5] == '\0') {
1040 error_setg(errp, "invalid Unix socket address");
1041 goto fail;
1042 } else {
1043 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1044 addr->u.q_unix.path = g_strdup(str + 5);
1046 } else if (strstart(str, "fd:", NULL)) {
1047 if (str[3] == '\0') {
1048 error_setg(errp, "invalid file descriptor address");
1049 goto fail;
1050 } else {
1051 addr->type = SOCKET_ADDRESS_TYPE_FD;
1052 addr->u.fd.str = g_strdup(str + 3);
1054 } else if (strstart(str, "vsock:", NULL)) {
1055 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1056 if (vsock_parse(&addr->u.vsock, str + strlen("vsock:"), errp)) {
1057 goto fail;
1059 } else {
1060 addr->type = SOCKET_ADDRESS_TYPE_INET;
1061 if (inet_parse(&addr->u.inet, str, errp)) {
1062 goto fail;
1065 return addr;
1067 fail:
1068 qapi_free_SocketAddress(addr);
1069 return NULL;
1072 int socket_connect(SocketAddress *addr, NonBlockingConnectHandler *callback,
1073 void *opaque, Error **errp)
1075 int fd;
1077 switch (addr->type) {
1078 case SOCKET_ADDRESS_TYPE_INET:
1079 fd = inet_connect_saddr(&addr->u.inet, callback, opaque, errp);
1080 break;
1082 case SOCKET_ADDRESS_TYPE_UNIX:
1083 fd = unix_connect_saddr(&addr->u.q_unix, callback, opaque, errp);
1084 break;
1086 case SOCKET_ADDRESS_TYPE_FD:
1087 fd = monitor_get_fd(cur_mon, addr->u.fd.str, errp);
1088 if (fd >= 0 && callback) {
1089 qemu_set_nonblock(fd);
1090 callback(fd, NULL, opaque);
1092 break;
1094 case SOCKET_ADDRESS_TYPE_VSOCK:
1095 fd = vsock_connect_saddr(&addr->u.vsock, callback, opaque, errp);
1096 break;
1098 default:
1099 abort();
1101 return fd;
1104 int socket_listen(SocketAddress *addr, Error **errp)
1106 int fd;
1108 switch (addr->type) {
1109 case SOCKET_ADDRESS_TYPE_INET:
1110 fd = inet_listen_saddr(&addr->u.inet, 0, false, errp);
1111 break;
1113 case SOCKET_ADDRESS_TYPE_UNIX:
1114 fd = unix_listen_saddr(&addr->u.q_unix, false, errp);
1115 break;
1117 case SOCKET_ADDRESS_TYPE_FD:
1118 fd = monitor_get_fd(cur_mon, addr->u.fd.str, errp);
1119 break;
1121 case SOCKET_ADDRESS_TYPE_VSOCK:
1122 fd = vsock_listen_saddr(&addr->u.vsock, errp);
1123 break;
1125 default:
1126 abort();
1128 return fd;
1131 void socket_listen_cleanup(int fd, Error **errp)
1133 SocketAddress *addr;
1135 addr = socket_local_address(fd, errp);
1137 if (addr->type == SOCKET_ADDRESS_TYPE_UNIX
1138 && addr->u.q_unix.path) {
1139 if (unlink(addr->u.q_unix.path) < 0 && errno != ENOENT) {
1140 error_setg_errno(errp, errno,
1141 "Failed to unlink socket %s",
1142 addr->u.q_unix.path);
1146 qapi_free_SocketAddress(addr);
1149 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
1151 int fd;
1154 * TODO SOCKET_ADDRESS_TYPE_FD when fd is AF_INET or AF_INET6
1155 * (although other address families can do SOCK_DGRAM, too)
1157 switch (remote->type) {
1158 case SOCKET_ADDRESS_TYPE_INET:
1159 fd = inet_dgram_saddr(&remote->u.inet,
1160 local ? &local->u.inet : NULL, errp);
1161 break;
1163 default:
1164 error_setg(errp, "socket type unsupported for datagram");
1165 fd = -1;
1167 return fd;
1171 static SocketAddress *
1172 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1173 socklen_t salen,
1174 Error **errp)
1176 char host[NI_MAXHOST];
1177 char serv[NI_MAXSERV];
1178 SocketAddress *addr;
1179 InetSocketAddress *inet;
1180 int ret;
1182 ret = getnameinfo((struct sockaddr *)sa, salen,
1183 host, sizeof(host),
1184 serv, sizeof(serv),
1185 NI_NUMERICHOST | NI_NUMERICSERV);
1186 if (ret != 0) {
1187 error_setg(errp, "Cannot format numeric socket address: %s",
1188 gai_strerror(ret));
1189 return NULL;
1192 addr = g_new0(SocketAddress, 1);
1193 addr->type = SOCKET_ADDRESS_TYPE_INET;
1194 inet = &addr->u.inet;
1195 inet->host = g_strdup(host);
1196 inet->port = g_strdup(serv);
1197 if (sa->ss_family == AF_INET) {
1198 inet->has_ipv4 = inet->ipv4 = true;
1199 } else {
1200 inet->has_ipv6 = inet->ipv6 = true;
1203 return addr;
1207 #ifndef WIN32
1208 static SocketAddress *
1209 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1210 socklen_t salen,
1211 Error **errp)
1213 SocketAddress *addr;
1214 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1216 addr = g_new0(SocketAddress, 1);
1217 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1218 if (su->sun_path[0]) {
1219 addr->u.q_unix.path = g_strndup(su->sun_path, sizeof(su->sun_path));
1222 return addr;
1224 #endif /* WIN32 */
1226 #ifdef CONFIG_AF_VSOCK
1227 static SocketAddress *
1228 socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,
1229 socklen_t salen,
1230 Error **errp)
1232 SocketAddress *addr;
1233 VsockSocketAddress *vaddr;
1234 struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;
1236 addr = g_new0(SocketAddress, 1);
1237 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1238 vaddr = &addr->u.vsock;
1239 vaddr->cid = g_strdup_printf("%u", svm->svm_cid);
1240 vaddr->port = g_strdup_printf("%u", svm->svm_port);
1242 return addr;
1244 #endif /* CONFIG_AF_VSOCK */
1246 SocketAddress *
1247 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1248 socklen_t salen,
1249 Error **errp)
1251 switch (sa->ss_family) {
1252 case AF_INET:
1253 case AF_INET6:
1254 return socket_sockaddr_to_address_inet(sa, salen, errp);
1256 #ifndef WIN32
1257 case AF_UNIX:
1258 return socket_sockaddr_to_address_unix(sa, salen, errp);
1259 #endif /* WIN32 */
1261 #ifdef CONFIG_AF_VSOCK
1262 case AF_VSOCK:
1263 return socket_sockaddr_to_address_vsock(sa, salen, errp);
1264 #endif
1266 default:
1267 error_setg(errp, "socket family %d unsupported",
1268 sa->ss_family);
1269 return NULL;
1271 return 0;
1275 SocketAddress *socket_local_address(int fd, Error **errp)
1277 struct sockaddr_storage ss;
1278 socklen_t sslen = sizeof(ss);
1280 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1281 error_setg_errno(errp, errno, "%s",
1282 "Unable to query local socket address");
1283 return NULL;
1286 return socket_sockaddr_to_address(&ss, sslen, errp);
1290 SocketAddress *socket_remote_address(int fd, Error **errp)
1292 struct sockaddr_storage ss;
1293 socklen_t sslen = sizeof(ss);
1295 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1296 error_setg_errno(errp, errno, "%s",
1297 "Unable to query remote socket address");
1298 return NULL;
1301 return socket_sockaddr_to_address(&ss, sslen, errp);
1304 char *socket_address_to_string(struct SocketAddress *addr, Error **errp)
1306 char *buf;
1307 InetSocketAddress *inet;
1309 switch (addr->type) {
1310 case SOCKET_ADDRESS_TYPE_INET:
1311 inet = &addr->u.inet;
1312 if (strchr(inet->host, ':') == NULL) {
1313 buf = g_strdup_printf("%s:%s", inet->host, inet->port);
1314 } else {
1315 buf = g_strdup_printf("[%s]:%s", inet->host, inet->port);
1317 break;
1319 case SOCKET_ADDRESS_TYPE_UNIX:
1320 buf = g_strdup(addr->u.q_unix.path);
1321 break;
1323 case SOCKET_ADDRESS_TYPE_FD:
1324 buf = g_strdup(addr->u.fd.str);
1325 break;
1327 case SOCKET_ADDRESS_TYPE_VSOCK:
1328 buf = g_strdup_printf("%s:%s",
1329 addr->u.vsock.cid,
1330 addr->u.vsock.port);
1331 break;
1333 default:
1334 abort();
1336 return buf;
1339 SocketAddress *socket_address_flatten(SocketAddressLegacy *addr_legacy)
1341 SocketAddress *addr;
1343 if (!addr_legacy) {
1344 return NULL;
1347 addr = g_new(SocketAddress, 1);
1349 switch (addr_legacy->type) {
1350 case SOCKET_ADDRESS_LEGACY_KIND_INET:
1351 addr->type = SOCKET_ADDRESS_TYPE_INET;
1352 QAPI_CLONE_MEMBERS(InetSocketAddress, &addr->u.inet,
1353 addr_legacy->u.inet.data);
1354 break;
1355 case SOCKET_ADDRESS_LEGACY_KIND_UNIX:
1356 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1357 QAPI_CLONE_MEMBERS(UnixSocketAddress, &addr->u.q_unix,
1358 addr_legacy->u.q_unix.data);
1359 break;
1360 case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:
1361 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1362 QAPI_CLONE_MEMBERS(VsockSocketAddress, &addr->u.vsock,
1363 addr_legacy->u.vsock.data);
1364 break;
1365 case SOCKET_ADDRESS_LEGACY_KIND_FD:
1366 addr->type = SOCKET_ADDRESS_TYPE_FD;
1367 QAPI_CLONE_MEMBERS(String, &addr->u.fd, addr_legacy->u.fd.data);
1368 break;
1369 default:
1370 abort();
1373 return addr;