util: move declarations out of qemu-common.h
[qemu/ar7.git] / util / qemu-sockets.c
blobb87e17fa56e490bb7389c7272afe78d105a439dd
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 "qapi/error.h"
22 #include "qemu/sockets.h"
23 #include "qemu/main-loop.h"
24 #include "qapi/qmp-input-visitor.h"
25 #include "qapi/qmp-output-visitor.h"
26 #include "qapi-visit.h"
27 #include "qemu/cutils.h"
29 #ifndef AI_ADDRCONFIG
30 # define AI_ADDRCONFIG 0
31 #endif
32 #ifndef AI_V4MAPPED
33 # define AI_V4MAPPED 0
34 #endif
37 static int inet_getport(struct addrinfo *e)
39 struct sockaddr_in *i4;
40 struct sockaddr_in6 *i6;
42 switch (e->ai_family) {
43 case PF_INET6:
44 i6 = (void*)e->ai_addr;
45 return ntohs(i6->sin6_port);
46 case PF_INET:
47 i4 = (void*)e->ai_addr;
48 return ntohs(i4->sin_port);
49 default:
50 return 0;
54 static void inet_setport(struct addrinfo *e, int port)
56 struct sockaddr_in *i4;
57 struct sockaddr_in6 *i6;
59 switch (e->ai_family) {
60 case PF_INET6:
61 i6 = (void*)e->ai_addr;
62 i6->sin6_port = htons(port);
63 break;
64 case PF_INET:
65 i4 = (void*)e->ai_addr;
66 i4->sin_port = htons(port);
67 break;
71 NetworkAddressFamily inet_netfamily(int family)
73 switch (family) {
74 case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
75 case PF_INET: return NETWORK_ADDRESS_FAMILY_IPV4;
76 case PF_UNIX: return NETWORK_ADDRESS_FAMILY_UNIX;
78 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
82 * Matrix we're trying to apply
84 * ipv4 ipv6 family
85 * - - PF_UNSPEC
86 * - f PF_INET
87 * - t PF_INET6
88 * f - PF_INET6
89 * f f <error>
90 * f t PF_INET6
91 * t - PF_INET
92 * t f PF_INET
93 * t t PF_INET6
95 * NB, this matrix is only about getting the neccessary results
96 * from getaddrinfo(). Some of the cases require further work
97 * after reading results from getaddrinfo in order to fully
98 * apply the logic the end user wants. eg with the last case
99 * ipv4=t + ipv6=t + PF_INET6, getaddrinfo alone can only
100 * guarantee the ipv6=t part of the request - we need more
101 * checks to provide ipv4=t part of the guarantee. This is
102 * outside scope of this method and not currently handled by
103 * callers at all.
105 static int inet_ai_family_from_address(InetSocketAddress *addr,
106 Error **errp)
108 if (addr->has_ipv6 && addr->has_ipv4 &&
109 !addr->ipv6 && !addr->ipv4) {
110 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
111 return PF_UNSPEC;
113 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
114 return PF_INET6;
116 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
117 return PF_INET;
119 return PF_UNSPEC;
122 static int inet_listen_saddr(InetSocketAddress *saddr,
123 int port_offset,
124 bool update_addr,
125 Error **errp)
127 struct addrinfo ai,*res,*e;
128 char port[33];
129 char uaddr[INET6_ADDRSTRLEN+1];
130 char uport[33];
131 int slisten, rc, port_min, port_max, p;
132 Error *err = NULL;
134 memset(&ai,0, sizeof(ai));
135 ai.ai_flags = AI_PASSIVE;
136 ai.ai_family = inet_ai_family_from_address(saddr, &err);
137 ai.ai_socktype = SOCK_STREAM;
139 if (err) {
140 error_propagate(errp, err);
141 return -1;
144 if (saddr->host == NULL) {
145 error_setg(errp, "host not specified");
146 return -1;
148 if (saddr->port != NULL) {
149 pstrcpy(port, sizeof(port), saddr->port);
150 } else {
151 port[0] = '\0';
154 /* lookup */
155 if (port_offset) {
156 unsigned long long baseport;
157 if (strlen(port) == 0) {
158 error_setg(errp, "port not specified");
159 return -1;
161 if (parse_uint_full(port, &baseport, 10) < 0) {
162 error_setg(errp, "can't convert to a number: %s", port);
163 return -1;
165 if (baseport > 65535 ||
166 baseport + port_offset > 65535) {
167 error_setg(errp, "port %s out of range", port);
168 return -1;
170 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
172 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
173 strlen(port) ? port : NULL, &ai, &res);
174 if (rc != 0) {
175 error_setg(errp, "address resolution failed for %s:%s: %s",
176 saddr->host, port, gai_strerror(rc));
177 return -1;
180 /* create socket + bind */
181 for (e = res; e != NULL; e = e->ai_next) {
182 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
183 uaddr,INET6_ADDRSTRLEN,uport,32,
184 NI_NUMERICHOST | NI_NUMERICSERV);
185 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
186 if (slisten < 0) {
187 if (!e->ai_next) {
188 error_setg_errno(errp, errno, "Failed to create socket");
190 continue;
193 socket_set_fast_reuse(slisten);
194 #ifdef IPV6_V6ONLY
195 if (e->ai_family == PF_INET6) {
196 /* listen on both ipv4 and ipv6 */
197 const int off = 0;
198 qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,
199 sizeof(off));
201 #endif
203 port_min = inet_getport(e);
204 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
205 for (p = port_min; p <= port_max; p++) {
206 inet_setport(e, p);
207 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
208 goto listen;
210 if (p == port_max) {
211 if (!e->ai_next) {
212 error_setg_errno(errp, errno, "Failed to bind socket");
216 closesocket(slisten);
218 freeaddrinfo(res);
219 return -1;
221 listen:
222 if (listen(slisten,1) != 0) {
223 error_setg_errno(errp, errno, "Failed to listen on socket");
224 closesocket(slisten);
225 freeaddrinfo(res);
226 return -1;
228 if (update_addr) {
229 g_free(saddr->host);
230 saddr->host = g_strdup(uaddr);
231 g_free(saddr->port);
232 saddr->port = g_strdup_printf("%d",
233 inet_getport(e) - port_offset);
234 saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
235 saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
237 freeaddrinfo(res);
238 return slisten;
241 #ifdef _WIN32
242 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
243 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
244 #else
245 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
246 ((rc) == -EINPROGRESS)
247 #endif
249 /* Struct to store connect state for non blocking connect */
250 typedef struct ConnectState {
251 int fd;
252 struct addrinfo *addr_list;
253 struct addrinfo *current_addr;
254 NonBlockingConnectHandler *callback;
255 void *opaque;
256 } ConnectState;
258 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
259 ConnectState *connect_state, Error **errp);
261 static void wait_for_connect(void *opaque)
263 ConnectState *s = opaque;
264 int val = 0, rc = 0;
265 socklen_t valsize = sizeof(val);
266 bool in_progress;
267 Error *err = NULL;
269 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
271 do {
272 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
273 } while (rc == -1 && errno == EINTR);
275 /* update rc to contain error */
276 if (!rc && val) {
277 rc = -1;
278 errno = val;
281 /* connect error */
282 if (rc < 0) {
283 error_setg_errno(&err, errno, "Error connecting to socket");
284 closesocket(s->fd);
285 s->fd = rc;
288 /* try to connect to the next address on the list */
289 if (s->current_addr) {
290 while (s->current_addr->ai_next != NULL && s->fd < 0) {
291 s->current_addr = s->current_addr->ai_next;
292 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
293 if (s->fd < 0) {
294 error_free(err);
295 err = NULL;
296 error_setg_errno(&err, errno, "Unable to start socket connect");
298 /* connect in progress */
299 if (in_progress) {
300 goto out;
304 freeaddrinfo(s->addr_list);
307 if (s->callback) {
308 s->callback(s->fd, err, s->opaque);
310 g_free(s);
311 out:
312 error_free(err);
315 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
316 ConnectState *connect_state, Error **errp)
318 int sock, rc;
320 *in_progress = false;
322 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
323 if (sock < 0) {
324 error_setg_errno(errp, errno, "Failed to create socket");
325 return -1;
327 socket_set_fast_reuse(sock);
328 if (connect_state != NULL) {
329 qemu_set_nonblock(sock);
331 /* connect to peer */
332 do {
333 rc = 0;
334 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
335 rc = -errno;
337 } while (rc == -EINTR);
339 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
340 connect_state->fd = sock;
341 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
342 *in_progress = true;
343 } else if (rc < 0) {
344 error_setg_errno(errp, errno, "Failed to connect socket");
345 closesocket(sock);
346 return -1;
348 return sock;
351 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
352 Error **errp)
354 struct addrinfo ai, *res;
355 int rc;
356 Error *err = NULL;
358 memset(&ai, 0, sizeof(ai));
360 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
361 ai.ai_family = inet_ai_family_from_address(saddr, &err);
362 ai.ai_socktype = SOCK_STREAM;
364 if (err) {
365 error_propagate(errp, err);
366 return NULL;
369 if (saddr->host == NULL || saddr->port == NULL) {
370 error_setg(errp, "host and/or port not specified");
371 return NULL;
374 /* lookup */
375 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
376 if (rc != 0) {
377 error_setg(errp, "address resolution failed for %s:%s: %s",
378 saddr->host, saddr->port, gai_strerror(rc));
379 return NULL;
381 return res;
385 * Create a socket and connect it to an address.
387 * @saddr: Inet socket address specification
388 * @errp: set on error
389 * @callback: callback function for non-blocking connect
390 * @opaque: opaque for callback function
392 * Returns: -1 on error, file descriptor on success.
394 * If @callback is non-null, the connect is non-blocking. If this
395 * function succeeds, callback will be called when the connection
396 * completes, with the file descriptor on success, or -1 on error.
398 static int inet_connect_saddr(InetSocketAddress *saddr, Error **errp,
399 NonBlockingConnectHandler *callback, void *opaque)
401 Error *local_err = NULL;
402 struct addrinfo *res, *e;
403 int sock = -1;
404 bool in_progress;
405 ConnectState *connect_state = NULL;
407 res = inet_parse_connect_saddr(saddr, errp);
408 if (!res) {
409 return -1;
412 if (callback != NULL) {
413 connect_state = g_malloc0(sizeof(*connect_state));
414 connect_state->addr_list = res;
415 connect_state->callback = callback;
416 connect_state->opaque = opaque;
419 for (e = res; e != NULL; e = e->ai_next) {
420 error_free(local_err);
421 local_err = NULL;
422 if (connect_state != NULL) {
423 connect_state->current_addr = e;
425 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
426 if (sock >= 0) {
427 break;
431 if (sock < 0) {
432 error_propagate(errp, local_err);
433 } else if (in_progress) {
434 /* wait_for_connect() will do the rest */
435 return sock;
436 } else {
437 if (callback) {
438 callback(sock, NULL, opaque);
441 g_free(connect_state);
442 freeaddrinfo(res);
443 return sock;
446 static int inet_dgram_saddr(InetSocketAddress *sraddr,
447 InetSocketAddress *sladdr,
448 Error **errp)
450 struct addrinfo ai, *peer = NULL, *local = NULL;
451 const char *addr;
452 const char *port;
453 int sock = -1, rc;
454 Error *err = NULL;
456 /* lookup peer addr */
457 memset(&ai,0, sizeof(ai));
458 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
459 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
460 ai.ai_socktype = SOCK_DGRAM;
462 if (err) {
463 error_propagate(errp, err);
464 goto err;
467 addr = sraddr->host;
468 port = sraddr->port;
469 if (addr == NULL || strlen(addr) == 0) {
470 addr = "localhost";
472 if (port == NULL || strlen(port) == 0) {
473 error_setg(errp, "remote port not specified");
474 goto err;
477 if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
478 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
479 gai_strerror(rc));
480 goto err;
483 /* lookup local addr */
484 memset(&ai,0, sizeof(ai));
485 ai.ai_flags = AI_PASSIVE;
486 ai.ai_family = peer->ai_family;
487 ai.ai_socktype = SOCK_DGRAM;
489 if (sladdr) {
490 addr = sladdr->host;
491 port = sladdr->port;
492 if (addr == NULL || strlen(addr) == 0) {
493 addr = NULL;
495 if (!port || strlen(port) == 0) {
496 port = "0";
498 } else {
499 addr = NULL;
500 port = "0";
503 if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
504 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
505 gai_strerror(rc));
506 goto err;
509 /* create socket */
510 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
511 if (sock < 0) {
512 error_setg_errno(errp, errno, "Failed to create socket");
513 goto err;
515 socket_set_fast_reuse(sock);
517 /* bind socket */
518 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
519 error_setg_errno(errp, errno, "Failed to bind socket");
520 goto err;
523 /* connect to peer */
524 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
525 error_setg_errno(errp, errno, "Failed to connect socket");
526 goto err;
529 freeaddrinfo(local);
530 freeaddrinfo(peer);
531 return sock;
533 err:
534 if (-1 != sock)
535 closesocket(sock);
536 if (local)
537 freeaddrinfo(local);
538 if (peer)
539 freeaddrinfo(peer);
540 return -1;
543 /* compatibility wrapper */
544 InetSocketAddress *inet_parse(const char *str, Error **errp)
546 InetSocketAddress *addr;
547 const char *optstr, *h;
548 char host[65];
549 char port[33];
550 int to;
551 int pos;
553 addr = g_new0(InetSocketAddress, 1);
555 /* parse address */
556 if (str[0] == ':') {
557 /* no host given */
558 host[0] = '\0';
559 if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
560 error_setg(errp, "error parsing port in address '%s'", str);
561 goto fail;
563 } else if (str[0] == '[') {
564 /* IPv6 addr */
565 if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
566 error_setg(errp, "error parsing IPv6 address '%s'", str);
567 goto fail;
569 addr->ipv6 = addr->has_ipv6 = true;
570 } else {
571 /* hostname or IPv4 addr */
572 if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
573 error_setg(errp, "error parsing address '%s'", str);
574 goto fail;
576 if (host[strspn(host, "0123456789.")] == '\0') {
577 addr->ipv4 = addr->has_ipv4 = true;
581 addr->host = g_strdup(host);
582 addr->port = g_strdup(port);
584 /* parse options */
585 optstr = str + pos;
586 h = strstr(optstr, ",to=");
587 if (h) {
588 h += 4;
589 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
590 (h[pos] != '\0' && h[pos] != ',')) {
591 error_setg(errp, "error parsing to= argument");
592 goto fail;
594 addr->has_to = true;
595 addr->to = to;
597 if (strstr(optstr, ",ipv4")) {
598 addr->ipv4 = addr->has_ipv4 = true;
600 if (strstr(optstr, ",ipv6")) {
601 addr->ipv6 = addr->has_ipv6 = true;
603 return addr;
605 fail:
606 qapi_free_InetSocketAddress(addr);
607 return NULL;
610 int inet_listen(const char *str, char *ostr, int olen,
611 int socktype, int port_offset, Error **errp)
613 char *optstr;
614 int sock = -1;
615 InetSocketAddress *addr;
617 addr = inet_parse(str, errp);
618 if (addr != NULL) {
619 sock = inet_listen_saddr(addr, port_offset, true, errp);
620 if (sock != -1 && ostr) {
621 optstr = strchr(str, ',');
622 if (addr->ipv6) {
623 snprintf(ostr, olen, "[%s]:%s%s",
624 addr->host,
625 addr->port,
626 optstr ? optstr : "");
627 } else {
628 snprintf(ostr, olen, "%s:%s%s",
629 addr->host,
630 addr->port,
631 optstr ? optstr : "");
634 qapi_free_InetSocketAddress(addr);
636 return sock;
640 * Create a blocking socket and connect it to an address.
642 * @str: address string
643 * @errp: set in case of an error
645 * Returns -1 in case of error, file descriptor on success
647 int inet_connect(const char *str, Error **errp)
649 int sock = -1;
650 InetSocketAddress *addr;
652 addr = inet_parse(str, errp);
653 if (addr != NULL) {
654 sock = inet_connect_saddr(addr, errp, NULL, NULL);
655 qapi_free_InetSocketAddress(addr);
657 return sock;
661 * Create a non-blocking socket and connect it to an address.
662 * Calls the callback function with fd in case of success or -1 in case of
663 * error.
665 * @str: address string
666 * @callback: callback function that is called when connect completes,
667 * cannot be NULL.
668 * @opaque: opaque for callback function
669 * @errp: set in case of an error
671 * Returns: -1 on immediate error, file descriptor on success.
673 int inet_nonblocking_connect(const char *str,
674 NonBlockingConnectHandler *callback,
675 void *opaque, Error **errp)
677 int sock = -1;
678 InetSocketAddress *addr;
680 g_assert(callback != NULL);
682 addr = inet_parse(str, errp);
683 if (addr != NULL) {
684 sock = inet_connect_saddr(addr, errp, callback, opaque);
685 qapi_free_InetSocketAddress(addr);
687 return sock;
690 #ifndef _WIN32
692 static int unix_listen_saddr(UnixSocketAddress *saddr,
693 bool update_addr,
694 Error **errp)
696 struct sockaddr_un un;
697 int sock, fd;
699 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
700 if (sock < 0) {
701 error_setg_errno(errp, errno, "Failed to create Unix socket");
702 return -1;
705 memset(&un, 0, sizeof(un));
706 un.sun_family = AF_UNIX;
707 if (saddr->path && strlen(saddr->path)) {
708 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
709 } else {
710 const char *tmpdir = getenv("TMPDIR");
711 tmpdir = tmpdir ? tmpdir : "/tmp";
712 if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
713 tmpdir) >= sizeof(un.sun_path)) {
714 error_setg_errno(errp, errno,
715 "TMPDIR environment variable (%s) too large", tmpdir);
716 goto err;
720 * This dummy fd usage silences the mktemp() unsecure warning.
721 * Using mkstemp() doesn't make things more secure here
722 * though. bind() complains about existing files, so we have
723 * to unlink first and thus re-open the race window. The
724 * worst case possible is bind() failing, i.e. a DoS attack.
726 fd = mkstemp(un.sun_path);
727 if (fd < 0) {
728 error_setg_errno(errp, errno,
729 "Failed to make a temporary socket name in %s", tmpdir);
730 goto err;
732 close(fd);
733 if (update_addr) {
734 g_free(saddr->path);
735 saddr->path = g_strdup(un.sun_path);
739 if (unlink(un.sun_path) < 0 && errno != ENOENT) {
740 error_setg_errno(errp, errno,
741 "Failed to unlink socket %s", un.sun_path);
742 goto err;
744 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
745 error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);
746 goto err;
748 if (listen(sock, 1) < 0) {
749 error_setg_errno(errp, errno, "Failed to listen on socket");
750 goto err;
753 return sock;
755 err:
756 closesocket(sock);
757 return -1;
760 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
761 NonBlockingConnectHandler *callback, void *opaque)
763 struct sockaddr_un un;
764 ConnectState *connect_state = NULL;
765 int sock, rc;
767 if (saddr->path == NULL) {
768 error_setg(errp, "unix connect: no path specified");
769 return -1;
772 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
773 if (sock < 0) {
774 error_setg_errno(errp, errno, "Failed to create socket");
775 return -1;
777 if (callback != NULL) {
778 connect_state = g_malloc0(sizeof(*connect_state));
779 connect_state->callback = callback;
780 connect_state->opaque = opaque;
781 qemu_set_nonblock(sock);
784 memset(&un, 0, sizeof(un));
785 un.sun_family = AF_UNIX;
786 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
788 /* connect to peer */
789 do {
790 rc = 0;
791 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
792 rc = -errno;
794 } while (rc == -EINTR);
796 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
797 connect_state->fd = sock;
798 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
799 return sock;
800 } else if (rc >= 0) {
801 /* non blocking socket immediate success, call callback */
802 if (callback != NULL) {
803 callback(sock, NULL, opaque);
807 if (rc < 0) {
808 error_setg_errno(errp, -rc, "Failed to connect socket");
809 close(sock);
810 sock = -1;
813 g_free(connect_state);
814 return sock;
817 #else
819 static int unix_listen_saddr(UnixSocketAddress *saddr,
820 bool update_addr,
821 Error **errp)
823 error_setg(errp, "unix sockets are not available on windows");
824 errno = ENOTSUP;
825 return -1;
828 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
829 NonBlockingConnectHandler *callback, void *opaque)
831 error_setg(errp, "unix sockets are not available on windows");
832 errno = ENOTSUP;
833 return -1;
835 #endif
837 /* compatibility wrapper */
838 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
840 char *path, *optstr;
841 int sock, len;
842 UnixSocketAddress *saddr;
844 saddr = g_new0(UnixSocketAddress, 1);
846 optstr = strchr(str, ',');
847 if (optstr) {
848 len = optstr - str;
849 if (len) {
850 path = g_malloc(len+1);
851 snprintf(path, len+1, "%.*s", len, str);
852 saddr->path = path;
854 } else {
855 saddr->path = g_strdup(str);
858 sock = unix_listen_saddr(saddr, true, errp);
860 if (sock != -1 && ostr)
861 snprintf(ostr, olen, "%s%s", saddr->path, optstr ? optstr : "");
862 qapi_free_UnixSocketAddress(saddr);
863 return sock;
866 int unix_connect(const char *path, Error **errp)
868 UnixSocketAddress *saddr;
869 int sock;
871 saddr = g_new0(UnixSocketAddress, 1);
872 saddr->path = g_strdup(path);
873 sock = unix_connect_saddr(saddr, errp, NULL, NULL);
874 qapi_free_UnixSocketAddress(saddr);
875 return sock;
879 int unix_nonblocking_connect(const char *path,
880 NonBlockingConnectHandler *callback,
881 void *opaque, Error **errp)
883 UnixSocketAddress *saddr;
884 int sock = -1;
886 g_assert(callback != NULL);
888 saddr = g_new0(UnixSocketAddress, 1);
889 saddr->path = g_strdup(path);
890 sock = unix_connect_saddr(saddr, errp, callback, opaque);
891 qapi_free_UnixSocketAddress(saddr);
892 return sock;
895 SocketAddress *socket_parse(const char *str, Error **errp)
897 SocketAddress *addr;
899 addr = g_new0(SocketAddress, 1);
900 if (strstart(str, "unix:", NULL)) {
901 if (str[5] == '\0') {
902 error_setg(errp, "invalid Unix socket address");
903 goto fail;
904 } else {
905 addr->type = SOCKET_ADDRESS_KIND_UNIX;
906 addr->u.q_unix.data = g_new(UnixSocketAddress, 1);
907 addr->u.q_unix.data->path = g_strdup(str + 5);
909 } else if (strstart(str, "fd:", NULL)) {
910 if (str[3] == '\0') {
911 error_setg(errp, "invalid file descriptor address");
912 goto fail;
913 } else {
914 addr->type = SOCKET_ADDRESS_KIND_FD;
915 addr->u.fd.data = g_new(String, 1);
916 addr->u.fd.data->str = g_strdup(str + 3);
918 } else {
919 addr->type = SOCKET_ADDRESS_KIND_INET;
920 addr->u.inet.data = inet_parse(str, errp);
921 if (addr->u.inet.data == NULL) {
922 goto fail;
925 return addr;
927 fail:
928 qapi_free_SocketAddress(addr);
929 return NULL;
932 int socket_connect(SocketAddress *addr, Error **errp,
933 NonBlockingConnectHandler *callback, void *opaque)
935 int fd;
937 switch (addr->type) {
938 case SOCKET_ADDRESS_KIND_INET:
939 fd = inet_connect_saddr(addr->u.inet.data, errp, callback, opaque);
940 break;
942 case SOCKET_ADDRESS_KIND_UNIX:
943 fd = unix_connect_saddr(addr->u.q_unix.data, errp, callback, opaque);
944 break;
946 case SOCKET_ADDRESS_KIND_FD:
947 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
948 if (fd >= 0 && callback) {
949 qemu_set_nonblock(fd);
950 callback(fd, NULL, opaque);
952 break;
954 default:
955 abort();
957 return fd;
960 int socket_listen(SocketAddress *addr, Error **errp)
962 int fd;
964 switch (addr->type) {
965 case SOCKET_ADDRESS_KIND_INET:
966 fd = inet_listen_saddr(addr->u.inet.data, 0, false, errp);
967 break;
969 case SOCKET_ADDRESS_KIND_UNIX:
970 fd = unix_listen_saddr(addr->u.q_unix.data, false, errp);
971 break;
973 case SOCKET_ADDRESS_KIND_FD:
974 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
975 break;
977 default:
978 abort();
980 return fd;
983 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
985 int fd;
987 switch (remote->type) {
988 case SOCKET_ADDRESS_KIND_INET:
989 fd = inet_dgram_saddr(remote->u.inet.data,
990 local ? local->u.inet.data : NULL, errp);
991 break;
993 default:
994 error_setg(errp, "socket type unsupported for datagram");
995 fd = -1;
997 return fd;
1001 static SocketAddress *
1002 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1003 socklen_t salen,
1004 Error **errp)
1006 char host[NI_MAXHOST];
1007 char serv[NI_MAXSERV];
1008 SocketAddress *addr;
1009 InetSocketAddress *inet;
1010 int ret;
1012 ret = getnameinfo((struct sockaddr *)sa, salen,
1013 host, sizeof(host),
1014 serv, sizeof(serv),
1015 NI_NUMERICHOST | NI_NUMERICSERV);
1016 if (ret != 0) {
1017 error_setg(errp, "Cannot format numeric socket address: %s",
1018 gai_strerror(ret));
1019 return NULL;
1022 addr = g_new0(SocketAddress, 1);
1023 addr->type = SOCKET_ADDRESS_KIND_INET;
1024 inet = addr->u.inet.data = g_new0(InetSocketAddress, 1);
1025 inet->host = g_strdup(host);
1026 inet->port = g_strdup(serv);
1027 if (sa->ss_family == AF_INET) {
1028 inet->has_ipv4 = inet->ipv4 = true;
1029 } else {
1030 inet->has_ipv6 = inet->ipv6 = true;
1033 return addr;
1037 #ifndef WIN32
1038 static SocketAddress *
1039 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1040 socklen_t salen,
1041 Error **errp)
1043 SocketAddress *addr;
1044 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1046 addr = g_new0(SocketAddress, 1);
1047 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1048 addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
1049 if (su->sun_path[0]) {
1050 addr->u.q_unix.data->path = g_strndup(su->sun_path,
1051 sizeof(su->sun_path));
1054 return addr;
1056 #endif /* WIN32 */
1058 SocketAddress *
1059 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1060 socklen_t salen,
1061 Error **errp)
1063 switch (sa->ss_family) {
1064 case AF_INET:
1065 case AF_INET6:
1066 return socket_sockaddr_to_address_inet(sa, salen, errp);
1068 #ifndef WIN32
1069 case AF_UNIX:
1070 return socket_sockaddr_to_address_unix(sa, salen, errp);
1071 #endif /* WIN32 */
1073 default:
1074 error_setg(errp, "socket family %d unsupported",
1075 sa->ss_family);
1076 return NULL;
1078 return 0;
1082 SocketAddress *socket_local_address(int fd, Error **errp)
1084 struct sockaddr_storage ss;
1085 socklen_t sslen = sizeof(ss);
1087 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1088 error_setg_errno(errp, errno, "%s",
1089 "Unable to query local socket address");
1090 return NULL;
1093 return socket_sockaddr_to_address(&ss, sslen, errp);
1097 SocketAddress *socket_remote_address(int fd, Error **errp)
1099 struct sockaddr_storage ss;
1100 socklen_t sslen = sizeof(ss);
1102 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1103 error_setg_errno(errp, errno, "%s",
1104 "Unable to query remote socket address");
1105 return NULL;
1108 return socket_sockaddr_to_address(&ss, sslen, errp);
1112 void qapi_copy_SocketAddress(SocketAddress **p_dest,
1113 SocketAddress *src)
1115 QmpOutputVisitor *qov;
1116 QmpInputVisitor *qiv;
1117 Visitor *ov, *iv;
1118 QObject *obj;
1120 *p_dest = NULL;
1122 qov = qmp_output_visitor_new();
1123 ov = qmp_output_get_visitor(qov);
1124 visit_type_SocketAddress(ov, NULL, &src, &error_abort);
1125 obj = qmp_output_get_qobject(qov);
1126 qmp_output_visitor_cleanup(qov);
1127 if (!obj) {
1128 return;
1131 qiv = qmp_input_visitor_new(obj);
1132 iv = qmp_input_get_visitor(qiv);
1133 visit_type_SocketAddress(iv, NULL, p_dest, &error_abort);
1134 qmp_input_visitor_cleanup(qiv);
1135 qobject_decref(obj);