slirp: Rename "struct arphdr" to "struct slirp_arphdr"
[qemu/kevin.git] / util / qemu-sockets.c
blob2aed799e976179a4e3e2d0d38026bc0513083f33
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
33 #ifndef AI_V4MAPPED
34 # define AI_V4MAPPED 0
35 #endif
38 static int inet_getport(struct addrinfo *e)
40 struct sockaddr_in *i4;
41 struct sockaddr_in6 *i6;
43 switch (e->ai_family) {
44 case PF_INET6:
45 i6 = (void*)e->ai_addr;
46 return ntohs(i6->sin6_port);
47 case PF_INET:
48 i4 = (void*)e->ai_addr;
49 return ntohs(i4->sin_port);
50 default:
51 return 0;
55 static void inet_setport(struct addrinfo *e, int port)
57 struct sockaddr_in *i4;
58 struct sockaddr_in6 *i6;
60 switch (e->ai_family) {
61 case PF_INET6:
62 i6 = (void*)e->ai_addr;
63 i6->sin6_port = htons(port);
64 break;
65 case PF_INET:
66 i4 = (void*)e->ai_addr;
67 i4->sin_port = htons(port);
68 break;
72 NetworkAddressFamily inet_netfamily(int family)
74 switch (family) {
75 case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
76 case PF_INET: return NETWORK_ADDRESS_FAMILY_IPV4;
77 case PF_UNIX: return NETWORK_ADDRESS_FAMILY_UNIX;
79 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
83 * Matrix we're trying to apply
85 * ipv4 ipv6 family
86 * - - PF_UNSPEC
87 * - f PF_INET
88 * - t PF_INET6
89 * f - PF_INET6
90 * f f <error>
91 * f t PF_INET6
92 * t - PF_INET
93 * t f PF_INET
94 * t t PF_INET6
96 * NB, this matrix is only about getting the necessary results
97 * from getaddrinfo(). Some of the cases require further work
98 * after reading results from getaddrinfo in order to fully
99 * apply the logic the end user wants. eg with the last case
100 * ipv4=t + ipv6=t + PF_INET6, getaddrinfo alone can only
101 * guarantee the ipv6=t part of the request - we need more
102 * checks to provide ipv4=t part of the guarantee. This is
103 * outside scope of this method and not currently handled by
104 * callers at all.
106 static int inet_ai_family_from_address(InetSocketAddress *addr,
107 Error **errp)
109 if (addr->has_ipv6 && addr->has_ipv4 &&
110 !addr->ipv6 && !addr->ipv4) {
111 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
112 return PF_UNSPEC;
114 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
115 return PF_INET6;
117 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
118 return PF_INET;
120 return PF_UNSPEC;
123 static int inet_listen_saddr(InetSocketAddress *saddr,
124 int port_offset,
125 bool update_addr,
126 Error **errp)
128 struct addrinfo ai,*res,*e;
129 char port[33];
130 char uaddr[INET6_ADDRSTRLEN+1];
131 char uport[33];
132 int slisten, rc, port_min, port_max, p;
133 Error *err = NULL;
135 memset(&ai,0, sizeof(ai));
136 ai.ai_flags = AI_PASSIVE;
137 ai.ai_family = inet_ai_family_from_address(saddr, &err);
138 ai.ai_socktype = SOCK_STREAM;
140 if (err) {
141 error_propagate(errp, err);
142 return -1;
145 if (saddr->host == NULL) {
146 error_setg(errp, "host not specified");
147 return -1;
149 if (saddr->port != NULL) {
150 pstrcpy(port, sizeof(port), saddr->port);
151 } else {
152 port[0] = '\0';
155 /* lookup */
156 if (port_offset) {
157 unsigned long long baseport;
158 if (strlen(port) == 0) {
159 error_setg(errp, "port not specified");
160 return -1;
162 if (parse_uint_full(port, &baseport, 10) < 0) {
163 error_setg(errp, "can't convert to a number: %s", port);
164 return -1;
166 if (baseport > 65535 ||
167 baseport + port_offset > 65535) {
168 error_setg(errp, "port %s out of range", port);
169 return -1;
171 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
173 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
174 strlen(port) ? port : NULL, &ai, &res);
175 if (rc != 0) {
176 error_setg(errp, "address resolution failed for %s:%s: %s",
177 saddr->host, port, gai_strerror(rc));
178 return -1;
181 /* create socket + bind */
182 for (e = res; e != NULL; e = e->ai_next) {
183 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
184 uaddr,INET6_ADDRSTRLEN,uport,32,
185 NI_NUMERICHOST | NI_NUMERICSERV);
186 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
187 if (slisten < 0) {
188 if (!e->ai_next) {
189 error_setg_errno(errp, errno, "Failed to create socket");
191 continue;
194 socket_set_fast_reuse(slisten);
195 #ifdef IPV6_V6ONLY
196 if (e->ai_family == PF_INET6) {
197 /* listen on both ipv4 and ipv6 */
198 const int off = 0;
199 qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,
200 sizeof(off));
202 #endif
204 port_min = inet_getport(e);
205 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
206 for (p = port_min; p <= port_max; p++) {
207 inet_setport(e, p);
208 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
209 goto listen;
211 if (p == port_max) {
212 if (!e->ai_next) {
213 error_setg_errno(errp, errno, "Failed to bind socket");
217 closesocket(slisten);
219 freeaddrinfo(res);
220 return -1;
222 listen:
223 if (listen(slisten,1) != 0) {
224 error_setg_errno(errp, errno, "Failed to listen on socket");
225 closesocket(slisten);
226 freeaddrinfo(res);
227 return -1;
229 if (update_addr) {
230 g_free(saddr->host);
231 saddr->host = g_strdup(uaddr);
232 g_free(saddr->port);
233 saddr->port = g_strdup_printf("%d",
234 inet_getport(e) - port_offset);
235 saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
236 saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
238 freeaddrinfo(res);
239 return slisten;
242 #ifdef _WIN32
243 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
244 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
245 #else
246 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
247 ((rc) == -EINPROGRESS)
248 #endif
250 /* Struct to store connect state for non blocking connect */
251 typedef struct ConnectState {
252 int fd;
253 struct addrinfo *addr_list;
254 struct addrinfo *current_addr;
255 NonBlockingConnectHandler *callback;
256 void *opaque;
257 } ConnectState;
259 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
260 ConnectState *connect_state, Error **errp);
262 static void wait_for_connect(void *opaque)
264 ConnectState *s = opaque;
265 int val = 0, rc = 0;
266 socklen_t valsize = sizeof(val);
267 bool in_progress;
268 Error *err = NULL;
270 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
272 do {
273 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
274 } while (rc == -1 && errno == EINTR);
276 /* update rc to contain error */
277 if (!rc && val) {
278 rc = -1;
279 errno = val;
282 /* connect error */
283 if (rc < 0) {
284 error_setg_errno(&err, errno, "Error connecting to socket");
285 closesocket(s->fd);
286 s->fd = rc;
289 /* try to connect to the next address on the list */
290 if (s->current_addr) {
291 while (s->current_addr->ai_next != NULL && s->fd < 0) {
292 s->current_addr = s->current_addr->ai_next;
293 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
294 if (s->fd < 0) {
295 error_free(err);
296 err = NULL;
297 error_setg_errno(&err, errno, "Unable to start socket connect");
299 /* connect in progress */
300 if (in_progress) {
301 goto out;
305 freeaddrinfo(s->addr_list);
308 if (s->callback) {
309 s->callback(s->fd, err, s->opaque);
311 g_free(s);
312 out:
313 error_free(err);
316 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
317 ConnectState *connect_state, Error **errp)
319 int sock, rc;
321 *in_progress = false;
323 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
324 if (sock < 0) {
325 error_setg_errno(errp, errno, "Failed to create socket");
326 return -1;
328 socket_set_fast_reuse(sock);
329 if (connect_state != NULL) {
330 qemu_set_nonblock(sock);
332 /* connect to peer */
333 do {
334 rc = 0;
335 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
336 rc = -errno;
338 } while (rc == -EINTR);
340 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
341 connect_state->fd = sock;
342 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
343 *in_progress = true;
344 } else if (rc < 0) {
345 error_setg_errno(errp, errno, "Failed to connect socket");
346 closesocket(sock);
347 return -1;
349 return sock;
352 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
353 Error **errp)
355 struct addrinfo ai, *res;
356 int rc;
357 Error *err = NULL;
358 static int useV4Mapped = 1;
360 memset(&ai, 0, sizeof(ai));
362 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
363 if (atomic_read(&useV4Mapped)) {
364 ai.ai_flags |= AI_V4MAPPED;
366 ai.ai_family = inet_ai_family_from_address(saddr, &err);
367 ai.ai_socktype = SOCK_STREAM;
369 if (err) {
370 error_propagate(errp, err);
371 return NULL;
374 if (saddr->host == NULL || saddr->port == NULL) {
375 error_setg(errp, "host and/or port not specified");
376 return NULL;
379 /* lookup */
380 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
382 /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
383 * then don't implement it in their getaddrinfo(). Detect
384 * this and retry without the flag since that's preferrable
385 * to a fatal error
387 if (rc == EAI_BADFLAGS &&
388 (ai.ai_flags & AI_V4MAPPED)) {
389 atomic_set(&useV4Mapped, 0);
390 ai.ai_flags &= ~AI_V4MAPPED;
391 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
393 if (rc != 0) {
394 error_setg(errp, "address resolution failed for %s:%s: %s",
395 saddr->host, saddr->port, gai_strerror(rc));
396 return NULL;
398 return res;
402 * Create a socket and connect it to an address.
404 * @saddr: Inet socket address specification
405 * @errp: set on error
406 * @callback: callback function for non-blocking connect
407 * @opaque: opaque for callback function
409 * Returns: -1 on error, file descriptor on success.
411 * If @callback is non-null, the connect is non-blocking. If this
412 * function succeeds, callback will be called when the connection
413 * completes, with the file descriptor on success, or -1 on error.
415 static int inet_connect_saddr(InetSocketAddress *saddr, Error **errp,
416 NonBlockingConnectHandler *callback, void *opaque)
418 Error *local_err = NULL;
419 struct addrinfo *res, *e;
420 int sock = -1;
421 bool in_progress;
422 ConnectState *connect_state = NULL;
424 res = inet_parse_connect_saddr(saddr, errp);
425 if (!res) {
426 return -1;
429 if (callback != NULL) {
430 connect_state = g_malloc0(sizeof(*connect_state));
431 connect_state->addr_list = res;
432 connect_state->callback = callback;
433 connect_state->opaque = opaque;
436 for (e = res; e != NULL; e = e->ai_next) {
437 error_free(local_err);
438 local_err = NULL;
439 if (connect_state != NULL) {
440 connect_state->current_addr = e;
442 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
443 if (sock >= 0) {
444 break;
448 if (sock < 0) {
449 error_propagate(errp, local_err);
450 } else if (in_progress) {
451 /* wait_for_connect() will do the rest */
452 return sock;
453 } else {
454 if (callback) {
455 callback(sock, NULL, opaque);
458 g_free(connect_state);
459 freeaddrinfo(res);
460 return sock;
463 static int inet_dgram_saddr(InetSocketAddress *sraddr,
464 InetSocketAddress *sladdr,
465 Error **errp)
467 struct addrinfo ai, *peer = NULL, *local = NULL;
468 const char *addr;
469 const char *port;
470 int sock = -1, rc;
471 Error *err = NULL;
473 /* lookup peer addr */
474 memset(&ai,0, sizeof(ai));
475 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
476 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
477 ai.ai_socktype = SOCK_DGRAM;
479 if (err) {
480 error_propagate(errp, err);
481 goto err;
484 addr = sraddr->host;
485 port = sraddr->port;
486 if (addr == NULL || strlen(addr) == 0) {
487 addr = "localhost";
489 if (port == NULL || strlen(port) == 0) {
490 error_setg(errp, "remote port not specified");
491 goto err;
494 if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
495 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
496 gai_strerror(rc));
497 goto err;
500 /* lookup local addr */
501 memset(&ai,0, sizeof(ai));
502 ai.ai_flags = AI_PASSIVE;
503 ai.ai_family = peer->ai_family;
504 ai.ai_socktype = SOCK_DGRAM;
506 if (sladdr) {
507 addr = sladdr->host;
508 port = sladdr->port;
509 if (addr == NULL || strlen(addr) == 0) {
510 addr = NULL;
512 if (!port || strlen(port) == 0) {
513 port = "0";
515 } else {
516 addr = NULL;
517 port = "0";
520 if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
521 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
522 gai_strerror(rc));
523 goto err;
526 /* create socket */
527 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
528 if (sock < 0) {
529 error_setg_errno(errp, errno, "Failed to create socket");
530 goto err;
532 socket_set_fast_reuse(sock);
534 /* bind socket */
535 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
536 error_setg_errno(errp, errno, "Failed to bind socket");
537 goto err;
540 /* connect to peer */
541 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
542 error_setg_errno(errp, errno, "Failed to connect socket");
543 goto err;
546 freeaddrinfo(local);
547 freeaddrinfo(peer);
548 return sock;
550 err:
551 if (-1 != sock)
552 closesocket(sock);
553 if (local)
554 freeaddrinfo(local);
555 if (peer)
556 freeaddrinfo(peer);
557 return -1;
560 /* compatibility wrapper */
561 InetSocketAddress *inet_parse(const char *str, Error **errp)
563 InetSocketAddress *addr;
564 const char *optstr, *h;
565 char host[65];
566 char port[33];
567 int to;
568 int pos;
570 addr = g_new0(InetSocketAddress, 1);
572 /* parse address */
573 if (str[0] == ':') {
574 /* no host given */
575 host[0] = '\0';
576 if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
577 error_setg(errp, "error parsing port in address '%s'", str);
578 goto fail;
580 } else if (str[0] == '[') {
581 /* IPv6 addr */
582 if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
583 error_setg(errp, "error parsing IPv6 address '%s'", str);
584 goto fail;
586 addr->ipv6 = addr->has_ipv6 = true;
587 } else {
588 /* hostname or IPv4 addr */
589 if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
590 error_setg(errp, "error parsing address '%s'", str);
591 goto fail;
593 if (host[strspn(host, "0123456789.")] == '\0') {
594 addr->ipv4 = addr->has_ipv4 = true;
598 addr->host = g_strdup(host);
599 addr->port = g_strdup(port);
601 /* parse options */
602 optstr = str + pos;
603 h = strstr(optstr, ",to=");
604 if (h) {
605 h += 4;
606 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
607 (h[pos] != '\0' && h[pos] != ',')) {
608 error_setg(errp, "error parsing to= argument");
609 goto fail;
611 addr->has_to = true;
612 addr->to = to;
614 if (strstr(optstr, ",ipv4")) {
615 addr->ipv4 = addr->has_ipv4 = true;
617 if (strstr(optstr, ",ipv6")) {
618 addr->ipv6 = addr->has_ipv6 = true;
620 return addr;
622 fail:
623 qapi_free_InetSocketAddress(addr);
624 return NULL;
629 * Create a blocking socket and connect it to an address.
631 * @str: address string
632 * @errp: set in case of an error
634 * Returns -1 in case of error, file descriptor on success
636 int inet_connect(const char *str, Error **errp)
638 int sock = -1;
639 InetSocketAddress *addr;
641 addr = inet_parse(str, errp);
642 if (addr != NULL) {
643 sock = inet_connect_saddr(addr, errp, NULL, NULL);
644 qapi_free_InetSocketAddress(addr);
646 return sock;
649 #ifndef _WIN32
651 static int unix_listen_saddr(UnixSocketAddress *saddr,
652 bool update_addr,
653 Error **errp)
655 struct sockaddr_un un;
656 int sock, fd;
658 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
659 if (sock < 0) {
660 error_setg_errno(errp, errno, "Failed to create Unix socket");
661 return -1;
664 memset(&un, 0, sizeof(un));
665 un.sun_family = AF_UNIX;
666 if (saddr->path && strlen(saddr->path)) {
667 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
668 } else {
669 const char *tmpdir = getenv("TMPDIR");
670 tmpdir = tmpdir ? tmpdir : "/tmp";
671 if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
672 tmpdir) >= sizeof(un.sun_path)) {
673 error_setg_errno(errp, errno,
674 "TMPDIR environment variable (%s) too large", tmpdir);
675 goto err;
679 * This dummy fd usage silences the mktemp() unsecure warning.
680 * Using mkstemp() doesn't make things more secure here
681 * though. bind() complains about existing files, so we have
682 * to unlink first and thus re-open the race window. The
683 * worst case possible is bind() failing, i.e. a DoS attack.
685 fd = mkstemp(un.sun_path);
686 if (fd < 0) {
687 error_setg_errno(errp, errno,
688 "Failed to make a temporary socket name in %s", tmpdir);
689 goto err;
691 close(fd);
692 if (update_addr) {
693 g_free(saddr->path);
694 saddr->path = g_strdup(un.sun_path);
698 if (unlink(un.sun_path) < 0 && errno != ENOENT) {
699 error_setg_errno(errp, errno,
700 "Failed to unlink socket %s", un.sun_path);
701 goto err;
703 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
704 error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);
705 goto err;
707 if (listen(sock, 1) < 0) {
708 error_setg_errno(errp, errno, "Failed to listen on socket");
709 goto err;
712 return sock;
714 err:
715 closesocket(sock);
716 return -1;
719 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
720 NonBlockingConnectHandler *callback, void *opaque)
722 struct sockaddr_un un;
723 ConnectState *connect_state = NULL;
724 int sock, rc;
726 if (saddr->path == NULL) {
727 error_setg(errp, "unix connect: no path specified");
728 return -1;
731 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
732 if (sock < 0) {
733 error_setg_errno(errp, errno, "Failed to create socket");
734 return -1;
736 if (callback != NULL) {
737 connect_state = g_malloc0(sizeof(*connect_state));
738 connect_state->callback = callback;
739 connect_state->opaque = opaque;
740 qemu_set_nonblock(sock);
743 memset(&un, 0, sizeof(un));
744 un.sun_family = AF_UNIX;
745 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
747 /* connect to peer */
748 do {
749 rc = 0;
750 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
751 rc = -errno;
753 } while (rc == -EINTR);
755 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
756 connect_state->fd = sock;
757 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
758 return sock;
759 } else if (rc >= 0) {
760 /* non blocking socket immediate success, call callback */
761 if (callback != NULL) {
762 callback(sock, NULL, opaque);
766 if (rc < 0) {
767 error_setg_errno(errp, -rc, "Failed to connect socket");
768 close(sock);
769 sock = -1;
772 g_free(connect_state);
773 return sock;
776 #else
778 static int unix_listen_saddr(UnixSocketAddress *saddr,
779 bool update_addr,
780 Error **errp)
782 error_setg(errp, "unix sockets are not available on windows");
783 errno = ENOTSUP;
784 return -1;
787 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
788 NonBlockingConnectHandler *callback, void *opaque)
790 error_setg(errp, "unix sockets are not available on windows");
791 errno = ENOTSUP;
792 return -1;
794 #endif
796 /* compatibility wrapper */
797 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
799 char *path, *optstr;
800 int sock, len;
801 UnixSocketAddress *saddr;
803 saddr = g_new0(UnixSocketAddress, 1);
805 optstr = strchr(str, ',');
806 if (optstr) {
807 len = optstr - str;
808 if (len) {
809 path = g_malloc(len+1);
810 snprintf(path, len+1, "%.*s", len, str);
811 saddr->path = path;
813 } else {
814 saddr->path = g_strdup(str);
817 sock = unix_listen_saddr(saddr, true, errp);
819 if (sock != -1 && ostr)
820 snprintf(ostr, olen, "%s%s", saddr->path, optstr ? optstr : "");
821 qapi_free_UnixSocketAddress(saddr);
822 return sock;
825 int unix_connect(const char *path, Error **errp)
827 UnixSocketAddress *saddr;
828 int sock;
830 saddr = g_new0(UnixSocketAddress, 1);
831 saddr->path = g_strdup(path);
832 sock = unix_connect_saddr(saddr, errp, NULL, NULL);
833 qapi_free_UnixSocketAddress(saddr);
834 return sock;
838 SocketAddress *socket_parse(const char *str, Error **errp)
840 SocketAddress *addr;
842 addr = g_new0(SocketAddress, 1);
843 if (strstart(str, "unix:", NULL)) {
844 if (str[5] == '\0') {
845 error_setg(errp, "invalid Unix socket address");
846 goto fail;
847 } else {
848 addr->type = SOCKET_ADDRESS_KIND_UNIX;
849 addr->u.q_unix.data = g_new(UnixSocketAddress, 1);
850 addr->u.q_unix.data->path = g_strdup(str + 5);
852 } else if (strstart(str, "fd:", NULL)) {
853 if (str[3] == '\0') {
854 error_setg(errp, "invalid file descriptor address");
855 goto fail;
856 } else {
857 addr->type = SOCKET_ADDRESS_KIND_FD;
858 addr->u.fd.data = g_new(String, 1);
859 addr->u.fd.data->str = g_strdup(str + 3);
861 } else {
862 addr->type = SOCKET_ADDRESS_KIND_INET;
863 addr->u.inet.data = inet_parse(str, errp);
864 if (addr->u.inet.data == NULL) {
865 goto fail;
868 return addr;
870 fail:
871 qapi_free_SocketAddress(addr);
872 return NULL;
875 int socket_connect(SocketAddress *addr, Error **errp,
876 NonBlockingConnectHandler *callback, void *opaque)
878 int fd;
880 switch (addr->type) {
881 case SOCKET_ADDRESS_KIND_INET:
882 fd = inet_connect_saddr(addr->u.inet.data, errp, callback, opaque);
883 break;
885 case SOCKET_ADDRESS_KIND_UNIX:
886 fd = unix_connect_saddr(addr->u.q_unix.data, errp, callback, opaque);
887 break;
889 case SOCKET_ADDRESS_KIND_FD:
890 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
891 if (fd >= 0 && callback) {
892 qemu_set_nonblock(fd);
893 callback(fd, NULL, opaque);
895 break;
897 default:
898 abort();
900 return fd;
903 int socket_listen(SocketAddress *addr, Error **errp)
905 int fd;
907 switch (addr->type) {
908 case SOCKET_ADDRESS_KIND_INET:
909 fd = inet_listen_saddr(addr->u.inet.data, 0, false, errp);
910 break;
912 case SOCKET_ADDRESS_KIND_UNIX:
913 fd = unix_listen_saddr(addr->u.q_unix.data, false, errp);
914 break;
916 case SOCKET_ADDRESS_KIND_FD:
917 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
918 break;
920 default:
921 abort();
923 return fd;
926 void socket_listen_cleanup(int fd, Error **errp)
928 SocketAddress *addr;
930 addr = socket_local_address(fd, errp);
932 if (addr->type == SOCKET_ADDRESS_KIND_UNIX
933 && addr->u.q_unix.data->path) {
934 if (unlink(addr->u.q_unix.data->path) < 0 && errno != ENOENT) {
935 error_setg_errno(errp, errno,
936 "Failed to unlink socket %s",
937 addr->u.q_unix.data->path);
941 qapi_free_SocketAddress(addr);
944 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
946 int fd;
948 switch (remote->type) {
949 case SOCKET_ADDRESS_KIND_INET:
950 fd = inet_dgram_saddr(remote->u.inet.data,
951 local ? local->u.inet.data : NULL, errp);
952 break;
954 default:
955 error_setg(errp, "socket type unsupported for datagram");
956 fd = -1;
958 return fd;
962 static SocketAddress *
963 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
964 socklen_t salen,
965 Error **errp)
967 char host[NI_MAXHOST];
968 char serv[NI_MAXSERV];
969 SocketAddress *addr;
970 InetSocketAddress *inet;
971 int ret;
973 ret = getnameinfo((struct sockaddr *)sa, salen,
974 host, sizeof(host),
975 serv, sizeof(serv),
976 NI_NUMERICHOST | NI_NUMERICSERV);
977 if (ret != 0) {
978 error_setg(errp, "Cannot format numeric socket address: %s",
979 gai_strerror(ret));
980 return NULL;
983 addr = g_new0(SocketAddress, 1);
984 addr->type = SOCKET_ADDRESS_KIND_INET;
985 inet = addr->u.inet.data = g_new0(InetSocketAddress, 1);
986 inet->host = g_strdup(host);
987 inet->port = g_strdup(serv);
988 if (sa->ss_family == AF_INET) {
989 inet->has_ipv4 = inet->ipv4 = true;
990 } else {
991 inet->has_ipv6 = inet->ipv6 = true;
994 return addr;
998 #ifndef WIN32
999 static SocketAddress *
1000 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1001 socklen_t salen,
1002 Error **errp)
1004 SocketAddress *addr;
1005 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1007 addr = g_new0(SocketAddress, 1);
1008 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1009 addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
1010 if (su->sun_path[0]) {
1011 addr->u.q_unix.data->path = g_strndup(su->sun_path,
1012 sizeof(su->sun_path));
1015 return addr;
1017 #endif /* WIN32 */
1019 SocketAddress *
1020 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1021 socklen_t salen,
1022 Error **errp)
1024 switch (sa->ss_family) {
1025 case AF_INET:
1026 case AF_INET6:
1027 return socket_sockaddr_to_address_inet(sa, salen, errp);
1029 #ifndef WIN32
1030 case AF_UNIX:
1031 return socket_sockaddr_to_address_unix(sa, salen, errp);
1032 #endif /* WIN32 */
1034 default:
1035 error_setg(errp, "socket family %d unsupported",
1036 sa->ss_family);
1037 return NULL;
1039 return 0;
1043 SocketAddress *socket_local_address(int fd, Error **errp)
1045 struct sockaddr_storage ss;
1046 socklen_t sslen = sizeof(ss);
1048 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1049 error_setg_errno(errp, errno, "%s",
1050 "Unable to query local socket address");
1051 return NULL;
1054 return socket_sockaddr_to_address(&ss, sslen, errp);
1058 SocketAddress *socket_remote_address(int fd, Error **errp)
1060 struct sockaddr_storage ss;
1061 socklen_t sslen = sizeof(ss);
1063 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1064 error_setg_errno(errp, errno, "%s",
1065 "Unable to query remote socket address");
1066 return NULL;
1069 return socket_sockaddr_to_address(&ss, sslen, errp);
1072 char *socket_address_to_string(struct SocketAddress *addr, Error **errp)
1074 char *buf;
1075 InetSocketAddress *inet;
1076 char host_port[INET6_ADDRSTRLEN + 5 + 4];
1078 switch (addr->type) {
1079 case SOCKET_ADDRESS_KIND_INET:
1080 inet = addr->u.inet.data;
1081 if (strchr(inet->host, ':') == NULL) {
1082 snprintf(host_port, sizeof(host_port), "%s:%s", inet->host,
1083 inet->port);
1084 buf = g_strdup(host_port);
1085 } else {
1086 snprintf(host_port, sizeof(host_port), "[%s]:%s", inet->host,
1087 inet->port);
1088 buf = g_strdup(host_port);
1090 break;
1092 case SOCKET_ADDRESS_KIND_UNIX:
1093 buf = g_strdup(addr->u.q_unix.data->path);
1094 break;
1096 case SOCKET_ADDRESS_KIND_FD:
1097 buf = g_strdup(addr->u.fd.data->str);
1098 break;
1100 default:
1101 error_setg(errp, "socket family %d unsupported",
1102 addr->type);
1103 return NULL;
1105 return buf;