vring: remove
[qemu.git] / util / qemu-sockets.c
blob557da20bf2e3cf358e504fcb76c37cd4080a653b
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 #include "monitor/monitor.h"
21 #include "qemu/sockets.h"
22 #include "qemu/main-loop.h"
23 #include "qapi/qmp-input-visitor.h"
24 #include "qapi/qmp-output-visitor.h"
25 #include "qapi-visit.h"
27 #ifndef AI_ADDRCONFIG
28 # define AI_ADDRCONFIG 0
29 #endif
30 #ifndef AI_V4MAPPED
31 # define AI_V4MAPPED 0
32 #endif
35 static int inet_getport(struct addrinfo *e)
37 struct sockaddr_in *i4;
38 struct sockaddr_in6 *i6;
40 switch (e->ai_family) {
41 case PF_INET6:
42 i6 = (void*)e->ai_addr;
43 return ntohs(i6->sin6_port);
44 case PF_INET:
45 i4 = (void*)e->ai_addr;
46 return ntohs(i4->sin_port);
47 default:
48 return 0;
52 static void inet_setport(struct addrinfo *e, int port)
54 struct sockaddr_in *i4;
55 struct sockaddr_in6 *i6;
57 switch (e->ai_family) {
58 case PF_INET6:
59 i6 = (void*)e->ai_addr;
60 i6->sin6_port = htons(port);
61 break;
62 case PF_INET:
63 i4 = (void*)e->ai_addr;
64 i4->sin_port = htons(port);
65 break;
69 NetworkAddressFamily inet_netfamily(int family)
71 switch (family) {
72 case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
73 case PF_INET: return NETWORK_ADDRESS_FAMILY_IPV4;
74 case PF_UNIX: return NETWORK_ADDRESS_FAMILY_UNIX;
76 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
80 * Matrix we're trying to apply
82 * ipv4 ipv6 family
83 * - - PF_UNSPEC
84 * - f PF_INET
85 * - t PF_INET6
86 * f - PF_INET6
87 * f f <error>
88 * f t PF_INET6
89 * t - PF_INET
90 * t f PF_INET
91 * t t PF_INET6
93 * NB, this matrix is only about getting the neccessary results
94 * from getaddrinfo(). Some of the cases require further work
95 * after reading results from getaddrinfo in order to fully
96 * apply the logic the end user wants. eg with the last case
97 * ipv4=t + ipv6=t + PF_INET6, getaddrinfo alone can only
98 * guarantee the ipv6=t part of the request - we need more
99 * checks to provide ipv4=t part of the guarantee. This is
100 * outside scope of this method and not currently handled by
101 * callers at all.
103 static int inet_ai_family_from_address(InetSocketAddress *addr,
104 Error **errp)
106 if (addr->has_ipv6 && addr->has_ipv4 &&
107 !addr->ipv6 && !addr->ipv4) {
108 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
109 return PF_UNSPEC;
111 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
112 return PF_INET6;
114 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
115 return PF_INET;
117 return PF_UNSPEC;
120 static int inet_listen_saddr(InetSocketAddress *saddr,
121 int port_offset,
122 bool update_addr,
123 Error **errp)
125 struct addrinfo ai,*res,*e;
126 char port[33];
127 char uaddr[INET6_ADDRSTRLEN+1];
128 char uport[33];
129 int slisten, rc, port_min, port_max, p;
130 Error *err = NULL;
132 memset(&ai,0, sizeof(ai));
133 ai.ai_flags = AI_PASSIVE;
134 ai.ai_family = inet_ai_family_from_address(saddr, &err);
135 ai.ai_socktype = SOCK_STREAM;
137 if (err) {
138 error_propagate(errp, err);
139 return -1;
142 if (saddr->host == NULL) {
143 error_setg(errp, "host not specified");
144 return -1;
146 if (saddr->port != NULL) {
147 pstrcpy(port, sizeof(port), saddr->port);
148 } else {
149 port[0] = '\0';
152 /* lookup */
153 if (port_offset) {
154 unsigned long long baseport;
155 if (strlen(port) == 0) {
156 error_setg(errp, "port not specified");
157 return -1;
159 if (parse_uint_full(port, &baseport, 10) < 0) {
160 error_setg(errp, "can't convert to a number: %s", port);
161 return -1;
163 if (baseport > 65535 ||
164 baseport + port_offset > 65535) {
165 error_setg(errp, "port %s out of range", port);
166 return -1;
168 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
170 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
171 strlen(port) ? port : NULL, &ai, &res);
172 if (rc != 0) {
173 error_setg(errp, "address resolution failed for %s:%s: %s",
174 saddr->host, port, gai_strerror(rc));
175 return -1;
178 /* create socket + bind */
179 for (e = res; e != NULL; e = e->ai_next) {
180 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
181 uaddr,INET6_ADDRSTRLEN,uport,32,
182 NI_NUMERICHOST | NI_NUMERICSERV);
183 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
184 if (slisten < 0) {
185 if (!e->ai_next) {
186 error_setg_errno(errp, errno, "Failed to create socket");
188 continue;
191 socket_set_fast_reuse(slisten);
192 #ifdef IPV6_V6ONLY
193 if (e->ai_family == PF_INET6) {
194 /* listen on both ipv4 and ipv6 */
195 const int off = 0;
196 qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,
197 sizeof(off));
199 #endif
201 port_min = inet_getport(e);
202 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
203 for (p = port_min; p <= port_max; p++) {
204 inet_setport(e, p);
205 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
206 goto listen;
208 if (p == port_max) {
209 if (!e->ai_next) {
210 error_setg_errno(errp, errno, "Failed to bind socket");
214 closesocket(slisten);
216 freeaddrinfo(res);
217 return -1;
219 listen:
220 if (listen(slisten,1) != 0) {
221 error_setg_errno(errp, errno, "Failed to listen on socket");
222 closesocket(slisten);
223 freeaddrinfo(res);
224 return -1;
226 if (update_addr) {
227 g_free(saddr->host);
228 saddr->host = g_strdup(uaddr);
229 g_free(saddr->port);
230 saddr->port = g_strdup_printf("%d",
231 inet_getport(e) - port_offset);
232 saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
233 saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
235 freeaddrinfo(res);
236 return slisten;
239 #ifdef _WIN32
240 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
241 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
242 #else
243 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
244 ((rc) == -EINPROGRESS)
245 #endif
247 /* Struct to store connect state for non blocking connect */
248 typedef struct ConnectState {
249 int fd;
250 struct addrinfo *addr_list;
251 struct addrinfo *current_addr;
252 NonBlockingConnectHandler *callback;
253 void *opaque;
254 } ConnectState;
256 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
257 ConnectState *connect_state, Error **errp);
259 static void wait_for_connect(void *opaque)
261 ConnectState *s = opaque;
262 int val = 0, rc = 0;
263 socklen_t valsize = sizeof(val);
264 bool in_progress;
265 Error *err = NULL;
267 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
269 do {
270 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
271 } while (rc == -1 && socket_error() == EINTR);
273 /* update rc to contain error */
274 if (!rc && val) {
275 rc = -1;
276 errno = val;
279 /* connect error */
280 if (rc < 0) {
281 error_setg_errno(&err, errno, "Error connecting to socket");
282 closesocket(s->fd);
283 s->fd = rc;
286 /* try to connect to the next address on the list */
287 if (s->current_addr) {
288 while (s->current_addr->ai_next != NULL && s->fd < 0) {
289 s->current_addr = s->current_addr->ai_next;
290 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
291 if (s->fd < 0) {
292 error_free(err);
293 err = NULL;
294 error_setg_errno(&err, errno, "Unable to start socket connect");
296 /* connect in progress */
297 if (in_progress) {
298 goto out;
302 freeaddrinfo(s->addr_list);
305 if (s->callback) {
306 s->callback(s->fd, err, s->opaque);
308 g_free(s);
309 out:
310 error_free(err);
313 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
314 ConnectState *connect_state, Error **errp)
316 int sock, rc;
318 *in_progress = false;
320 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
321 if (sock < 0) {
322 error_setg_errno(errp, errno, "Failed to create socket");
323 return -1;
325 socket_set_fast_reuse(sock);
326 if (connect_state != NULL) {
327 qemu_set_nonblock(sock);
329 /* connect to peer */
330 do {
331 rc = 0;
332 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
333 rc = -socket_error();
335 } while (rc == -EINTR);
337 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
338 connect_state->fd = sock;
339 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
340 *in_progress = true;
341 } else if (rc < 0) {
342 error_setg_errno(errp, errno, "Failed to connect socket");
343 closesocket(sock);
344 return -1;
346 return sock;
349 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
350 Error **errp)
352 struct addrinfo ai, *res;
353 int rc;
354 Error *err = NULL;
356 memset(&ai, 0, sizeof(ai));
358 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
359 ai.ai_family = inet_ai_family_from_address(saddr, &err);
360 ai.ai_socktype = SOCK_STREAM;
362 if (err) {
363 error_propagate(errp, err);
364 return NULL;
367 if (saddr->host == NULL || saddr->port == NULL) {
368 error_setg(errp, "host and/or port not specified");
369 return NULL;
372 /* lookup */
373 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
374 if (rc != 0) {
375 error_setg(errp, "address resolution failed for %s:%s: %s",
376 saddr->host, saddr->port, gai_strerror(rc));
377 return NULL;
379 return res;
383 * Create a socket and connect it to an address.
385 * @saddr: Inet socket address specification
386 * @errp: set on error
387 * @callback: callback function for non-blocking connect
388 * @opaque: opaque for callback function
390 * Returns: -1 on error, file descriptor on success.
392 * If @callback is non-null, the connect is non-blocking. If this
393 * function succeeds, callback will be called when the connection
394 * completes, with the file descriptor on success, or -1 on error.
396 static int inet_connect_saddr(InetSocketAddress *saddr, Error **errp,
397 NonBlockingConnectHandler *callback, void *opaque)
399 Error *local_err = NULL;
400 struct addrinfo *res, *e;
401 int sock = -1;
402 bool in_progress;
403 ConnectState *connect_state = NULL;
405 res = inet_parse_connect_saddr(saddr, errp);
406 if (!res) {
407 return -1;
410 if (callback != NULL) {
411 connect_state = g_malloc0(sizeof(*connect_state));
412 connect_state->addr_list = res;
413 connect_state->callback = callback;
414 connect_state->opaque = opaque;
417 for (e = res; e != NULL; e = e->ai_next) {
418 error_free(local_err);
419 local_err = NULL;
420 if (connect_state != NULL) {
421 connect_state->current_addr = e;
423 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
424 if (sock >= 0) {
425 break;
429 if (sock < 0) {
430 error_propagate(errp, local_err);
431 } else if (in_progress) {
432 /* wait_for_connect() will do the rest */
433 return sock;
434 } else {
435 if (callback) {
436 callback(sock, NULL, opaque);
439 g_free(connect_state);
440 freeaddrinfo(res);
441 return sock;
444 static int inet_dgram_saddr(InetSocketAddress *sraddr,
445 InetSocketAddress *sladdr,
446 Error **errp)
448 struct addrinfo ai, *peer = NULL, *local = NULL;
449 const char *addr;
450 const char *port;
451 int sock = -1, rc;
452 Error *err = NULL;
454 /* lookup peer addr */
455 memset(&ai,0, sizeof(ai));
456 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
457 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
458 ai.ai_socktype = SOCK_DGRAM;
460 if (err) {
461 error_propagate(errp, err);
462 goto err;
465 addr = sraddr->host;
466 port = sraddr->port;
467 if (addr == NULL || strlen(addr) == 0) {
468 addr = "localhost";
470 if (port == NULL || strlen(port) == 0) {
471 error_setg(errp, "remote port not specified");
472 goto err;
475 if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
476 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
477 gai_strerror(rc));
478 goto err;
481 /* lookup local addr */
482 memset(&ai,0, sizeof(ai));
483 ai.ai_flags = AI_PASSIVE;
484 ai.ai_family = peer->ai_family;
485 ai.ai_socktype = SOCK_DGRAM;
487 if (sladdr) {
488 addr = sladdr->host;
489 port = sladdr->port;
490 if (addr == NULL || strlen(addr) == 0) {
491 addr = NULL;
493 if (!port || strlen(port) == 0) {
494 port = "0";
496 } else {
497 addr = NULL;
498 port = "0";
501 if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
502 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
503 gai_strerror(rc));
504 goto err;
507 /* create socket */
508 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
509 if (sock < 0) {
510 error_setg_errno(errp, errno, "Failed to create socket");
511 goto err;
513 socket_set_fast_reuse(sock);
515 /* bind socket */
516 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
517 error_setg_errno(errp, errno, "Failed to bind socket");
518 goto err;
521 /* connect to peer */
522 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
523 error_setg_errno(errp, errno, "Failed to connect socket");
524 goto err;
527 freeaddrinfo(local);
528 freeaddrinfo(peer);
529 return sock;
531 err:
532 if (-1 != sock)
533 closesocket(sock);
534 if (local)
535 freeaddrinfo(local);
536 if (peer)
537 freeaddrinfo(peer);
538 return -1;
541 /* compatibility wrapper */
542 InetSocketAddress *inet_parse(const char *str, Error **errp)
544 InetSocketAddress *addr;
545 const char *optstr, *h;
546 char host[65];
547 char port[33];
548 int to;
549 int pos;
551 addr = g_new0(InetSocketAddress, 1);
553 /* parse address */
554 if (str[0] == ':') {
555 /* no host given */
556 host[0] = '\0';
557 if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
558 error_setg(errp, "error parsing port in address '%s'", str);
559 goto fail;
561 } else if (str[0] == '[') {
562 /* IPv6 addr */
563 if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
564 error_setg(errp, "error parsing IPv6 address '%s'", str);
565 goto fail;
567 addr->ipv6 = addr->has_ipv6 = true;
568 } else {
569 /* hostname or IPv4 addr */
570 if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
571 error_setg(errp, "error parsing address '%s'", str);
572 goto fail;
574 if (host[strspn(host, "0123456789.")] == '\0') {
575 addr->ipv4 = addr->has_ipv4 = true;
579 addr->host = g_strdup(host);
580 addr->port = g_strdup(port);
582 /* parse options */
583 optstr = str + pos;
584 h = strstr(optstr, ",to=");
585 if (h) {
586 h += 4;
587 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
588 (h[pos] != '\0' && h[pos] != ',')) {
589 error_setg(errp, "error parsing to= argument");
590 goto fail;
592 addr->has_to = true;
593 addr->to = to;
595 if (strstr(optstr, ",ipv4")) {
596 addr->ipv4 = addr->has_ipv4 = true;
598 if (strstr(optstr, ",ipv6")) {
599 addr->ipv6 = addr->has_ipv6 = true;
601 return addr;
603 fail:
604 qapi_free_InetSocketAddress(addr);
605 return NULL;
608 int inet_listen(const char *str, char *ostr, int olen,
609 int socktype, int port_offset, Error **errp)
611 char *optstr;
612 int sock = -1;
613 InetSocketAddress *addr;
615 addr = inet_parse(str, errp);
616 if (addr != NULL) {
617 sock = inet_listen_saddr(addr, port_offset, true, errp);
618 if (sock != -1 && ostr) {
619 optstr = strchr(str, ',');
620 if (addr->ipv6) {
621 snprintf(ostr, olen, "[%s]:%s%s",
622 addr->host,
623 addr->port,
624 optstr ? optstr : "");
625 } else {
626 snprintf(ostr, olen, "%s:%s%s",
627 addr->host,
628 addr->port,
629 optstr ? optstr : "");
632 qapi_free_InetSocketAddress(addr);
634 return sock;
638 * Create a blocking socket and connect it to an address.
640 * @str: address string
641 * @errp: set in case of an error
643 * Returns -1 in case of error, file descriptor on success
645 int inet_connect(const char *str, Error **errp)
647 int sock = -1;
648 InetSocketAddress *addr;
650 addr = inet_parse(str, errp);
651 if (addr != NULL) {
652 sock = inet_connect_saddr(addr, errp, NULL, NULL);
653 qapi_free_InetSocketAddress(addr);
655 return sock;
659 * Create a non-blocking socket and connect it to an address.
660 * Calls the callback function with fd in case of success or -1 in case of
661 * error.
663 * @str: address string
664 * @callback: callback function that is called when connect completes,
665 * cannot be NULL.
666 * @opaque: opaque for callback function
667 * @errp: set in case of an error
669 * Returns: -1 on immediate error, file descriptor on success.
671 int inet_nonblocking_connect(const char *str,
672 NonBlockingConnectHandler *callback,
673 void *opaque, Error **errp)
675 int sock = -1;
676 InetSocketAddress *addr;
678 g_assert(callback != NULL);
680 addr = inet_parse(str, errp);
681 if (addr != NULL) {
682 sock = inet_connect_saddr(addr, errp, callback, opaque);
683 qapi_free_InetSocketAddress(addr);
685 return sock;
688 #ifndef _WIN32
690 static int unix_listen_saddr(UnixSocketAddress *saddr,
691 bool update_addr,
692 Error **errp)
694 struct sockaddr_un un;
695 int sock, fd;
697 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
698 if (sock < 0) {
699 error_setg_errno(errp, errno, "Failed to create Unix socket");
700 return -1;
703 memset(&un, 0, sizeof(un));
704 un.sun_family = AF_UNIX;
705 if (saddr->path && strlen(saddr->path)) {
706 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
707 } else {
708 const char *tmpdir = getenv("TMPDIR");
709 tmpdir = tmpdir ? tmpdir : "/tmp";
710 if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
711 tmpdir) >= sizeof(un.sun_path)) {
712 error_setg_errno(errp, errno,
713 "TMPDIR environment variable (%s) too large", tmpdir);
714 goto err;
718 * This dummy fd usage silences the mktemp() unsecure warning.
719 * Using mkstemp() doesn't make things more secure here
720 * though. bind() complains about existing files, so we have
721 * to unlink first and thus re-open the race window. The
722 * worst case possible is bind() failing, i.e. a DoS attack.
724 fd = mkstemp(un.sun_path);
725 if (fd < 0) {
726 error_setg_errno(errp, errno,
727 "Failed to make a temporary socket name in %s", tmpdir);
728 goto err;
730 close(fd);
731 if (update_addr) {
732 g_free(saddr->path);
733 saddr->path = g_strdup(un.sun_path);
737 if (unlink(un.sun_path) < 0 && errno != ENOENT) {
738 error_setg_errno(errp, errno,
739 "Failed to unlink socket %s", un.sun_path);
740 goto err;
742 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
743 error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);
744 goto err;
746 if (listen(sock, 1) < 0) {
747 error_setg_errno(errp, errno, "Failed to listen on socket");
748 goto err;
751 return sock;
753 err:
754 closesocket(sock);
755 return -1;
758 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
759 NonBlockingConnectHandler *callback, void *opaque)
761 struct sockaddr_un un;
762 ConnectState *connect_state = NULL;
763 int sock, rc;
765 if (saddr->path == NULL) {
766 error_setg(errp, "unix connect: no path specified");
767 return -1;
770 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
771 if (sock < 0) {
772 error_setg_errno(errp, errno, "Failed to create socket");
773 return -1;
775 if (callback != NULL) {
776 connect_state = g_malloc0(sizeof(*connect_state));
777 connect_state->callback = callback;
778 connect_state->opaque = opaque;
779 qemu_set_nonblock(sock);
782 memset(&un, 0, sizeof(un));
783 un.sun_family = AF_UNIX;
784 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
786 /* connect to peer */
787 do {
788 rc = 0;
789 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
790 rc = -socket_error();
792 } while (rc == -EINTR);
794 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
795 connect_state->fd = sock;
796 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
797 return sock;
798 } else if (rc >= 0) {
799 /* non blocking socket immediate success, call callback */
800 if (callback != NULL) {
801 callback(sock, NULL, opaque);
805 if (rc < 0) {
806 error_setg_errno(errp, -rc, "Failed to connect socket");
807 close(sock);
808 sock = -1;
811 g_free(connect_state);
812 return sock;
815 #else
817 static int unix_listen_saddr(UnixSocketAddress *saddr,
818 bool update_addr,
819 Error **errp)
821 error_setg(errp, "unix sockets are not available on windows");
822 errno = ENOTSUP;
823 return -1;
826 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
827 NonBlockingConnectHandler *callback, void *opaque)
829 error_setg(errp, "unix sockets are not available on windows");
830 errno = ENOTSUP;
831 return -1;
833 #endif
835 /* compatibility wrapper */
836 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
838 char *path, *optstr;
839 int sock, len;
840 UnixSocketAddress *saddr;
842 saddr = g_new0(UnixSocketAddress, 1);
844 optstr = strchr(str, ',');
845 if (optstr) {
846 len = optstr - str;
847 if (len) {
848 path = g_malloc(len+1);
849 snprintf(path, len+1, "%.*s", len, str);
850 saddr->path = path;
852 } else {
853 saddr->path = g_strdup(str);
856 sock = unix_listen_saddr(saddr, true, errp);
858 if (sock != -1 && ostr)
859 snprintf(ostr, olen, "%s%s", saddr->path, optstr ? optstr : "");
860 qapi_free_UnixSocketAddress(saddr);
861 return sock;
864 int unix_connect(const char *path, Error **errp)
866 UnixSocketAddress *saddr;
867 int sock;
869 saddr = g_new0(UnixSocketAddress, 1);
870 saddr->path = g_strdup(path);
871 sock = unix_connect_saddr(saddr, errp, NULL, NULL);
872 qapi_free_UnixSocketAddress(saddr);
873 return sock;
877 int unix_nonblocking_connect(const char *path,
878 NonBlockingConnectHandler *callback,
879 void *opaque, Error **errp)
881 UnixSocketAddress *saddr;
882 int sock = -1;
884 g_assert(callback != NULL);
886 saddr = g_new0(UnixSocketAddress, 1);
887 saddr->path = g_strdup(path);
888 sock = unix_connect_saddr(saddr, errp, callback, opaque);
889 qapi_free_UnixSocketAddress(saddr);
890 return sock;
893 SocketAddress *socket_parse(const char *str, Error **errp)
895 SocketAddress *addr;
897 addr = g_new0(SocketAddress, 1);
898 if (strstart(str, "unix:", NULL)) {
899 if (str[5] == '\0') {
900 error_setg(errp, "invalid Unix socket address");
901 goto fail;
902 } else {
903 addr->type = SOCKET_ADDRESS_KIND_UNIX;
904 addr->u.q_unix = g_new(UnixSocketAddress, 1);
905 addr->u.q_unix->path = g_strdup(str + 5);
907 } else if (strstart(str, "fd:", NULL)) {
908 if (str[3] == '\0') {
909 error_setg(errp, "invalid file descriptor address");
910 goto fail;
911 } else {
912 addr->type = SOCKET_ADDRESS_KIND_FD;
913 addr->u.fd = g_new(String, 1);
914 addr->u.fd->str = g_strdup(str + 3);
916 } else {
917 addr->type = SOCKET_ADDRESS_KIND_INET;
918 addr->u.inet = inet_parse(str, errp);
919 if (addr->u.inet == NULL) {
920 goto fail;
923 return addr;
925 fail:
926 qapi_free_SocketAddress(addr);
927 return NULL;
930 int socket_connect(SocketAddress *addr, Error **errp,
931 NonBlockingConnectHandler *callback, void *opaque)
933 int fd;
935 switch (addr->type) {
936 case SOCKET_ADDRESS_KIND_INET:
937 fd = inet_connect_saddr(addr->u.inet, errp, callback, opaque);
938 break;
940 case SOCKET_ADDRESS_KIND_UNIX:
941 fd = unix_connect_saddr(addr->u.q_unix, errp, callback, opaque);
942 break;
944 case SOCKET_ADDRESS_KIND_FD:
945 fd = monitor_get_fd(cur_mon, addr->u.fd->str, errp);
946 if (fd >= 0 && callback) {
947 qemu_set_nonblock(fd);
948 callback(fd, NULL, opaque);
950 break;
952 default:
953 abort();
955 return fd;
958 int socket_listen(SocketAddress *addr, Error **errp)
960 int fd;
962 switch (addr->type) {
963 case SOCKET_ADDRESS_KIND_INET:
964 fd = inet_listen_saddr(addr->u.inet, 0, false, errp);
965 break;
967 case SOCKET_ADDRESS_KIND_UNIX:
968 fd = unix_listen_saddr(addr->u.q_unix, false, errp);
969 break;
971 case SOCKET_ADDRESS_KIND_FD:
972 fd = monitor_get_fd(cur_mon, addr->u.fd->str, errp);
973 break;
975 default:
976 abort();
978 return fd;
981 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
983 int fd;
985 switch (remote->type) {
986 case SOCKET_ADDRESS_KIND_INET:
987 fd = inet_dgram_saddr(remote->u.inet, local ? local->u.inet : NULL, errp);
988 break;
990 default:
991 error_setg(errp, "socket type unsupported for datagram");
992 fd = -1;
994 return fd;
998 static SocketAddress *
999 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1000 socklen_t salen,
1001 Error **errp)
1003 char host[NI_MAXHOST];
1004 char serv[NI_MAXSERV];
1005 SocketAddress *addr;
1006 int ret;
1008 ret = getnameinfo((struct sockaddr *)sa, salen,
1009 host, sizeof(host),
1010 serv, sizeof(serv),
1011 NI_NUMERICHOST | NI_NUMERICSERV);
1012 if (ret != 0) {
1013 error_setg(errp, "Cannot format numeric socket address: %s",
1014 gai_strerror(ret));
1015 return NULL;
1018 addr = g_new0(SocketAddress, 1);
1019 addr->type = SOCKET_ADDRESS_KIND_INET;
1020 addr->u.inet = g_new0(InetSocketAddress, 1);
1021 addr->u.inet->host = g_strdup(host);
1022 addr->u.inet->port = g_strdup(serv);
1023 if (sa->ss_family == AF_INET) {
1024 addr->u.inet->has_ipv4 = addr->u.inet->ipv4 = true;
1025 } else {
1026 addr->u.inet->has_ipv6 = addr->u.inet->ipv6 = true;
1029 return addr;
1033 #ifndef WIN32
1034 static SocketAddress *
1035 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1036 socklen_t salen,
1037 Error **errp)
1039 SocketAddress *addr;
1040 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1042 addr = g_new0(SocketAddress, 1);
1043 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1044 addr->u.q_unix = g_new0(UnixSocketAddress, 1);
1045 if (su->sun_path[0]) {
1046 addr->u.q_unix->path = g_strndup(su->sun_path,
1047 sizeof(su->sun_path));
1050 return addr;
1052 #endif /* WIN32 */
1054 SocketAddress *
1055 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1056 socklen_t salen,
1057 Error **errp)
1059 switch (sa->ss_family) {
1060 case AF_INET:
1061 case AF_INET6:
1062 return socket_sockaddr_to_address_inet(sa, salen, errp);
1064 #ifndef WIN32
1065 case AF_UNIX:
1066 return socket_sockaddr_to_address_unix(sa, salen, errp);
1067 #endif /* WIN32 */
1069 default:
1070 error_setg(errp, "socket family %d unsupported",
1071 sa->ss_family);
1072 return NULL;
1074 return 0;
1078 SocketAddress *socket_local_address(int fd, Error **errp)
1080 struct sockaddr_storage ss;
1081 socklen_t sslen = sizeof(ss);
1083 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1084 error_setg_errno(errp, socket_error(), "%s",
1085 "Unable to query local socket address");
1086 return NULL;
1089 return socket_sockaddr_to_address(&ss, sslen, errp);
1093 SocketAddress *socket_remote_address(int fd, Error **errp)
1095 struct sockaddr_storage ss;
1096 socklen_t sslen = sizeof(ss);
1098 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1099 error_setg_errno(errp, socket_error(), "%s",
1100 "Unable to query remote socket address");
1101 return NULL;
1104 return socket_sockaddr_to_address(&ss, sslen, errp);
1108 void qapi_copy_SocketAddress(SocketAddress **p_dest,
1109 SocketAddress *src)
1111 QmpOutputVisitor *qov;
1112 QmpInputVisitor *qiv;
1113 Visitor *ov, *iv;
1114 QObject *obj;
1116 *p_dest = NULL;
1118 qov = qmp_output_visitor_new();
1119 ov = qmp_output_get_visitor(qov);
1120 visit_type_SocketAddress(ov, NULL, &src, &error_abort);
1121 obj = qmp_output_get_qobject(qov);
1122 qmp_output_visitor_cleanup(qov);
1123 if (!obj) {
1124 return;
1127 qiv = qmp_input_visitor_new(obj);
1128 iv = qmp_input_get_visitor(qiv);
1129 visit_type_SocketAddress(iv, NULL, p_dest, &error_abort);
1130 qmp_input_visitor_cleanup(qiv);
1131 qobject_decref(obj);