ram: Use page number instead of an address for the bitmap operations
[qemu/ar7.git] / util / qemu-sockets.c
blob21442c30dcab3c2d084962537ed0a85454988a96
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/error.h"
26 #include "qemu/sockets.h"
27 #include "qemu/main-loop.h"
28 #include "qapi/clone-visitor.h"
29 #include "qapi/qobject-input-visitor.h"
30 #include "qapi/qobject-output-visitor.h"
31 #include "qapi-visit.h"
32 #include "qemu/cutils.h"
34 #ifndef AI_ADDRCONFIG
35 # define AI_ADDRCONFIG 0
36 #endif
38 #ifndef AI_V4MAPPED
39 # define AI_V4MAPPED 0
40 #endif
42 #ifndef AI_NUMERICSERV
43 # define AI_NUMERICSERV 0
44 #endif
47 static int inet_getport(struct addrinfo *e)
49 struct sockaddr_in *i4;
50 struct sockaddr_in6 *i6;
52 switch (e->ai_family) {
53 case PF_INET6:
54 i6 = (void*)e->ai_addr;
55 return ntohs(i6->sin6_port);
56 case PF_INET:
57 i4 = (void*)e->ai_addr;
58 return ntohs(i4->sin_port);
59 default:
60 return 0;
64 static void inet_setport(struct addrinfo *e, int port)
66 struct sockaddr_in *i4;
67 struct sockaddr_in6 *i6;
69 switch (e->ai_family) {
70 case PF_INET6:
71 i6 = (void*)e->ai_addr;
72 i6->sin6_port = htons(port);
73 break;
74 case PF_INET:
75 i4 = (void*)e->ai_addr;
76 i4->sin_port = htons(port);
77 break;
81 NetworkAddressFamily inet_netfamily(int family)
83 switch (family) {
84 case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
85 case PF_INET: return NETWORK_ADDRESS_FAMILY_IPV4;
86 case PF_UNIX: return NETWORK_ADDRESS_FAMILY_UNIX;
87 #ifdef CONFIG_AF_VSOCK
88 case PF_VSOCK: return NETWORK_ADDRESS_FAMILY_VSOCK;
89 #endif /* CONFIG_AF_VSOCK */
91 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
95 * Matrix we're trying to apply
97 * ipv4 ipv6 family
98 * - - PF_UNSPEC
99 * - f PF_INET
100 * - t PF_INET6
101 * f - PF_INET6
102 * f f <error>
103 * f t PF_INET6
104 * t - PF_INET
105 * t f PF_INET
106 * t t PF_INET6
108 * NB, this matrix is only about getting the necessary results
109 * from getaddrinfo(). Some of the cases require further work
110 * after reading results from getaddrinfo in order to fully
111 * apply the logic the end user wants. eg with the last case
112 * ipv4=t + ipv6=t + PF_INET6, getaddrinfo alone can only
113 * guarantee the ipv6=t part of the request - we need more
114 * checks to provide ipv4=t part of the guarantee. This is
115 * outside scope of this method and not currently handled by
116 * callers at all.
118 int inet_ai_family_from_address(InetSocketAddress *addr,
119 Error **errp)
121 if (addr->has_ipv6 && addr->has_ipv4 &&
122 !addr->ipv6 && !addr->ipv4) {
123 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
124 return PF_UNSPEC;
126 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
127 return PF_INET6;
129 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
130 return PF_INET;
132 return PF_UNSPEC;
135 static int inet_listen_saddr(InetSocketAddress *saddr,
136 int port_offset,
137 bool update_addr,
138 Error **errp)
140 struct addrinfo ai,*res,*e;
141 char port[33];
142 char uaddr[INET6_ADDRSTRLEN+1];
143 char uport[33];
144 int slisten, rc, port_min, port_max, p;
145 Error *err = NULL;
147 memset(&ai,0, sizeof(ai));
148 ai.ai_flags = AI_PASSIVE;
149 if (saddr->has_numeric && saddr->numeric) {
150 ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
152 ai.ai_family = inet_ai_family_from_address(saddr, &err);
153 ai.ai_socktype = SOCK_STREAM;
155 if (err) {
156 error_propagate(errp, err);
157 return -1;
160 if (saddr->host == NULL) {
161 error_setg(errp, "host not specified");
162 return -1;
164 if (saddr->port != NULL) {
165 pstrcpy(port, sizeof(port), saddr->port);
166 } else {
167 port[0] = '\0';
170 /* lookup */
171 if (port_offset) {
172 unsigned long long baseport;
173 if (strlen(port) == 0) {
174 error_setg(errp, "port not specified");
175 return -1;
177 if (parse_uint_full(port, &baseport, 10) < 0) {
178 error_setg(errp, "can't convert to a number: %s", port);
179 return -1;
181 if (baseport > 65535 ||
182 baseport + port_offset > 65535) {
183 error_setg(errp, "port %s out of range", port);
184 return -1;
186 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
188 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
189 strlen(port) ? port : NULL, &ai, &res);
190 if (rc != 0) {
191 error_setg(errp, "address resolution failed for %s:%s: %s",
192 saddr->host, port, gai_strerror(rc));
193 return -1;
196 /* create socket + bind */
197 for (e = res; e != NULL; e = e->ai_next) {
198 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
199 uaddr,INET6_ADDRSTRLEN,uport,32,
200 NI_NUMERICHOST | NI_NUMERICSERV);
201 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
202 if (slisten < 0) {
203 if (!e->ai_next) {
204 error_setg_errno(errp, errno, "Failed to create socket");
206 continue;
209 socket_set_fast_reuse(slisten);
210 #ifdef IPV6_V6ONLY
211 if (e->ai_family == PF_INET6) {
212 /* listen on both ipv4 and ipv6 */
213 const int off = 0;
214 qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,
215 sizeof(off));
217 #endif
219 port_min = inet_getport(e);
220 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
221 for (p = port_min; p <= port_max; p++) {
222 inet_setport(e, p);
223 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
224 goto listen;
226 if (p == port_max) {
227 if (!e->ai_next) {
228 error_setg_errno(errp, errno, "Failed to bind socket");
232 closesocket(slisten);
234 freeaddrinfo(res);
235 return -1;
237 listen:
238 if (listen(slisten,1) != 0) {
239 error_setg_errno(errp, errno, "Failed to listen on socket");
240 closesocket(slisten);
241 freeaddrinfo(res);
242 return -1;
244 if (update_addr) {
245 g_free(saddr->host);
246 saddr->host = g_strdup(uaddr);
247 g_free(saddr->port);
248 saddr->port = g_strdup_printf("%d",
249 inet_getport(e) - port_offset);
250 saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
251 saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
253 freeaddrinfo(res);
254 return slisten;
257 #ifdef _WIN32
258 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
259 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
260 #else
261 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
262 ((rc) == -EINPROGRESS)
263 #endif
265 /* Struct to store connect state for non blocking connect */
266 typedef struct ConnectState {
267 int fd;
268 struct addrinfo *addr_list;
269 struct addrinfo *current_addr;
270 NonBlockingConnectHandler *callback;
271 void *opaque;
272 } ConnectState;
274 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
275 ConnectState *connect_state, Error **errp);
277 static void wait_for_connect(void *opaque)
279 ConnectState *s = opaque;
280 int val = 0, rc = 0;
281 socklen_t valsize = sizeof(val);
282 bool in_progress;
283 Error *err = NULL;
285 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
287 do {
288 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
289 } while (rc == -1 && errno == EINTR);
291 /* update rc to contain error */
292 if (!rc && val) {
293 rc = -1;
294 errno = val;
297 /* connect error */
298 if (rc < 0) {
299 error_setg_errno(&err, errno, "Error connecting to socket");
300 closesocket(s->fd);
301 s->fd = rc;
304 /* try to connect to the next address on the list */
305 if (s->current_addr) {
306 while (s->current_addr->ai_next != NULL && s->fd < 0) {
307 s->current_addr = s->current_addr->ai_next;
308 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
309 if (s->fd < 0) {
310 error_free(err);
311 err = NULL;
312 error_setg_errno(&err, errno, "Unable to start socket connect");
314 /* connect in progress */
315 if (in_progress) {
316 goto out;
320 freeaddrinfo(s->addr_list);
323 if (s->callback) {
324 s->callback(s->fd, err, s->opaque);
326 g_free(s);
327 out:
328 error_free(err);
331 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
332 ConnectState *connect_state, Error **errp)
334 int sock, rc;
336 *in_progress = false;
338 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
339 if (sock < 0) {
340 error_setg_errno(errp, errno, "Failed to create socket");
341 return -1;
343 socket_set_fast_reuse(sock);
344 if (connect_state != NULL) {
345 qemu_set_nonblock(sock);
347 /* connect to peer */
348 do {
349 rc = 0;
350 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
351 rc = -errno;
353 } while (rc == -EINTR);
355 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
356 connect_state->fd = sock;
357 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
358 *in_progress = true;
359 } else if (rc < 0) {
360 error_setg_errno(errp, errno, "Failed to connect socket");
361 closesocket(sock);
362 return -1;
364 return sock;
367 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
368 Error **errp)
370 struct addrinfo ai, *res;
371 int rc;
372 Error *err = NULL;
373 static int useV4Mapped = 1;
375 memset(&ai, 0, sizeof(ai));
377 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
378 if (atomic_read(&useV4Mapped)) {
379 ai.ai_flags |= AI_V4MAPPED;
381 ai.ai_family = inet_ai_family_from_address(saddr, &err);
382 ai.ai_socktype = SOCK_STREAM;
384 if (err) {
385 error_propagate(errp, err);
386 return NULL;
389 if (saddr->host == NULL || saddr->port == NULL) {
390 error_setg(errp, "host and/or port not specified");
391 return NULL;
394 /* lookup */
395 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
397 /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
398 * then don't implement it in their getaddrinfo(). Detect
399 * this and retry without the flag since that's preferrable
400 * to a fatal error
402 if (rc == EAI_BADFLAGS &&
403 (ai.ai_flags & AI_V4MAPPED)) {
404 atomic_set(&useV4Mapped, 0);
405 ai.ai_flags &= ~AI_V4MAPPED;
406 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
408 if (rc != 0) {
409 error_setg(errp, "address resolution failed for %s:%s: %s",
410 saddr->host, saddr->port, gai_strerror(rc));
411 return NULL;
413 return res;
417 * Create a socket and connect it to an address.
419 * @saddr: Inet socket address specification
420 * @errp: set on error
421 * @callback: callback function for non-blocking connect
422 * @opaque: opaque for callback function
424 * Returns: -1 on error, file descriptor on success.
426 * If @callback is non-null, the connect is non-blocking. If this
427 * function succeeds, callback will be called when the connection
428 * completes, with the file descriptor on success, or -1 on error.
430 int inet_connect_saddr(InetSocketAddress *saddr, Error **errp,
431 NonBlockingConnectHandler *callback, void *opaque)
433 Error *local_err = NULL;
434 struct addrinfo *res, *e;
435 int sock = -1;
436 bool in_progress;
437 ConnectState *connect_state = NULL;
439 res = inet_parse_connect_saddr(saddr, errp);
440 if (!res) {
441 return -1;
444 if (callback != NULL) {
445 connect_state = g_malloc0(sizeof(*connect_state));
446 connect_state->addr_list = res;
447 connect_state->callback = callback;
448 connect_state->opaque = opaque;
451 for (e = res; e != NULL; e = e->ai_next) {
452 error_free(local_err);
453 local_err = NULL;
454 if (connect_state != NULL) {
455 connect_state->current_addr = e;
457 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
458 if (sock >= 0) {
459 break;
463 if (sock < 0) {
464 error_propagate(errp, local_err);
465 } else if (in_progress) {
466 /* wait_for_connect() will do the rest */
467 return sock;
468 } else {
469 if (callback) {
470 callback(sock, NULL, opaque);
473 g_free(connect_state);
474 freeaddrinfo(res);
475 return sock;
478 static int inet_dgram_saddr(InetSocketAddress *sraddr,
479 InetSocketAddress *sladdr,
480 Error **errp)
482 struct addrinfo ai, *peer = NULL, *local = NULL;
483 const char *addr;
484 const char *port;
485 int sock = -1, rc;
486 Error *err = NULL;
488 /* lookup peer addr */
489 memset(&ai,0, sizeof(ai));
490 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
491 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
492 ai.ai_socktype = SOCK_DGRAM;
494 if (err) {
495 error_propagate(errp, err);
496 goto err;
499 addr = sraddr->host;
500 port = sraddr->port;
501 if (addr == NULL || strlen(addr) == 0) {
502 addr = "localhost";
504 if (port == NULL || strlen(port) == 0) {
505 error_setg(errp, "remote port not specified");
506 goto err;
509 if ((rc = getaddrinfo(addr, port, &ai, &peer)) != 0) {
510 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
511 gai_strerror(rc));
512 goto err;
515 /* lookup local addr */
516 memset(&ai,0, sizeof(ai));
517 ai.ai_flags = AI_PASSIVE;
518 ai.ai_family = peer->ai_family;
519 ai.ai_socktype = SOCK_DGRAM;
521 if (sladdr) {
522 addr = sladdr->host;
523 port = sladdr->port;
524 if (addr == NULL || strlen(addr) == 0) {
525 addr = NULL;
527 if (!port || strlen(port) == 0) {
528 port = "0";
530 } else {
531 addr = NULL;
532 port = "0";
535 if ((rc = getaddrinfo(addr, port, &ai, &local)) != 0) {
536 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
537 gai_strerror(rc));
538 goto err;
541 /* create socket */
542 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
543 if (sock < 0) {
544 error_setg_errno(errp, errno, "Failed to create socket");
545 goto err;
547 socket_set_fast_reuse(sock);
549 /* bind socket */
550 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
551 error_setg_errno(errp, errno, "Failed to bind socket");
552 goto err;
555 /* connect to peer */
556 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
557 error_setg_errno(errp, errno, "Failed to connect socket");
558 goto err;
561 freeaddrinfo(local);
562 freeaddrinfo(peer);
563 return sock;
565 err:
566 if (sock != -1) {
567 closesocket(sock);
569 if (local) {
570 freeaddrinfo(local);
572 if (peer) {
573 freeaddrinfo(peer);
576 return -1;
579 /* compatibility wrapper */
580 InetSocketAddress *inet_parse(const char *str, Error **errp)
582 InetSocketAddress *addr;
583 const char *optstr, *h;
584 char host[65];
585 char port[33];
586 int to;
587 int pos;
589 addr = g_new0(InetSocketAddress, 1);
591 /* parse address */
592 if (str[0] == ':') {
593 /* no host given */
594 host[0] = '\0';
595 if (sscanf(str, ":%32[^,]%n", port, &pos) != 1) {
596 error_setg(errp, "error parsing port in address '%s'", str);
597 goto fail;
599 } else if (str[0] == '[') {
600 /* IPv6 addr */
601 if (sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos) != 2) {
602 error_setg(errp, "error parsing IPv6 address '%s'", str);
603 goto fail;
605 addr->ipv6 = addr->has_ipv6 = true;
606 } else {
607 /* hostname or IPv4 addr */
608 if (sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos) != 2) {
609 error_setg(errp, "error parsing address '%s'", str);
610 goto fail;
612 if (host[strspn(host, "0123456789.")] == '\0') {
613 addr->ipv4 = addr->has_ipv4 = true;
617 addr->host = g_strdup(host);
618 addr->port = g_strdup(port);
620 /* parse options */
621 optstr = str + pos;
622 h = strstr(optstr, ",to=");
623 if (h) {
624 h += 4;
625 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
626 (h[pos] != '\0' && h[pos] != ',')) {
627 error_setg(errp, "error parsing to= argument");
628 goto fail;
630 addr->has_to = true;
631 addr->to = to;
633 if (strstr(optstr, ",ipv4")) {
634 addr->ipv4 = addr->has_ipv4 = true;
636 if (strstr(optstr, ",ipv6")) {
637 addr->ipv6 = addr->has_ipv6 = true;
639 return addr;
641 fail:
642 qapi_free_InetSocketAddress(addr);
643 return NULL;
648 * Create a blocking socket and connect it to an address.
650 * @str: address string
651 * @errp: set in case of an error
653 * Returns -1 in case of error, file descriptor on success
655 int inet_connect(const char *str, Error **errp)
657 int sock = -1;
658 InetSocketAddress *addr;
660 addr = inet_parse(str, errp);
661 if (addr != NULL) {
662 sock = inet_connect_saddr(addr, errp, NULL, NULL);
663 qapi_free_InetSocketAddress(addr);
665 return sock;
668 #ifdef CONFIG_AF_VSOCK
669 static bool vsock_parse_vaddr_to_sockaddr(const VsockSocketAddress *vaddr,
670 struct sockaddr_vm *svm,
671 Error **errp)
673 unsigned long long val;
675 memset(svm, 0, sizeof(*svm));
676 svm->svm_family = AF_VSOCK;
678 if (parse_uint_full(vaddr->cid, &val, 10) < 0 ||
679 val > UINT32_MAX) {
680 error_setg(errp, "Failed to parse cid '%s'", vaddr->cid);
681 return false;
683 svm->svm_cid = val;
685 if (parse_uint_full(vaddr->port, &val, 10) < 0 ||
686 val > UINT32_MAX) {
687 error_setg(errp, "Failed to parse port '%s'", vaddr->port);
688 return false;
690 svm->svm_port = val;
692 return true;
695 static int vsock_connect_addr(const struct sockaddr_vm *svm, bool *in_progress,
696 ConnectState *connect_state, Error **errp)
698 int sock, rc;
700 *in_progress = false;
702 sock = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
703 if (sock < 0) {
704 error_setg_errno(errp, errno, "Failed to create socket");
705 return -1;
707 if (connect_state != NULL) {
708 qemu_set_nonblock(sock);
710 /* connect to peer */
711 do {
712 rc = 0;
713 if (connect(sock, (const struct sockaddr *)svm, sizeof(*svm)) < 0) {
714 rc = -errno;
716 } while (rc == -EINTR);
718 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
719 connect_state->fd = sock;
720 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
721 *in_progress = true;
722 } else if (rc < 0) {
723 error_setg_errno(errp, errno, "Failed to connect socket");
724 closesocket(sock);
725 return -1;
727 return sock;
730 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp,
731 NonBlockingConnectHandler *callback,
732 void *opaque)
734 struct sockaddr_vm svm;
735 int sock = -1;
736 bool in_progress;
737 ConnectState *connect_state = NULL;
739 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
740 return -1;
743 if (callback != NULL) {
744 connect_state = g_malloc0(sizeof(*connect_state));
745 connect_state->callback = callback;
746 connect_state->opaque = opaque;
749 sock = vsock_connect_addr(&svm, &in_progress, connect_state, errp);
750 if (sock < 0) {
751 /* do nothing */
752 } else if (in_progress) {
753 /* wait_for_connect() will do the rest */
754 return sock;
755 } else {
756 if (callback) {
757 callback(sock, NULL, opaque);
760 g_free(connect_state);
761 return sock;
764 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
765 Error **errp)
767 struct sockaddr_vm svm;
768 int slisten;
770 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
771 return -1;
774 slisten = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
775 if (slisten < 0) {
776 error_setg_errno(errp, errno, "Failed to create socket");
777 return -1;
780 if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
781 error_setg_errno(errp, errno, "Failed to bind socket");
782 closesocket(slisten);
783 return -1;
786 if (listen(slisten, 1) != 0) {
787 error_setg_errno(errp, errno, "Failed to listen on socket");
788 closesocket(slisten);
789 return -1;
791 return slisten;
794 static VsockSocketAddress *vsock_parse(const char *str, Error **errp)
796 VsockSocketAddress *addr = NULL;
797 char cid[33];
798 char port[33];
799 int n;
801 if (sscanf(str, "%32[^:]:%32[^,]%n", cid, port, &n) != 2) {
802 error_setg(errp, "error parsing address '%s'", str);
803 return NULL;
805 if (str[n] != '\0') {
806 error_setg(errp, "trailing characters in address '%s'", str);
807 return NULL;
810 addr = g_new0(VsockSocketAddress, 1);
811 addr->cid = g_strdup(cid);
812 addr->port = g_strdup(port);
813 return addr;
815 #else
816 static void vsock_unsupported(Error **errp)
818 error_setg(errp, "socket family AF_VSOCK unsupported");
821 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp,
822 NonBlockingConnectHandler *callback,
823 void *opaque)
825 vsock_unsupported(errp);
826 return -1;
829 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
830 Error **errp)
832 vsock_unsupported(errp);
833 return -1;
836 static VsockSocketAddress *vsock_parse(const char *str, Error **errp)
838 vsock_unsupported(errp);
839 return NULL;
841 #endif /* CONFIG_AF_VSOCK */
843 #ifndef _WIN32
845 static int unix_listen_saddr(UnixSocketAddress *saddr,
846 bool update_addr,
847 Error **errp)
849 struct sockaddr_un un;
850 int sock, fd;
852 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
853 if (sock < 0) {
854 error_setg_errno(errp, errno, "Failed to create Unix socket");
855 return -1;
858 memset(&un, 0, sizeof(un));
859 un.sun_family = AF_UNIX;
860 if (saddr->path && strlen(saddr->path)) {
861 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
862 } else {
863 const char *tmpdir = getenv("TMPDIR");
864 tmpdir = tmpdir ? tmpdir : "/tmp";
865 if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
866 tmpdir) >= sizeof(un.sun_path)) {
867 error_setg_errno(errp, errno,
868 "TMPDIR environment variable (%s) too large", tmpdir);
869 goto err;
873 * This dummy fd usage silences the mktemp() unsecure warning.
874 * Using mkstemp() doesn't make things more secure here
875 * though. bind() complains about existing files, so we have
876 * to unlink first and thus re-open the race window. The
877 * worst case possible is bind() failing, i.e. a DoS attack.
879 fd = mkstemp(un.sun_path);
880 if (fd < 0) {
881 error_setg_errno(errp, errno,
882 "Failed to make a temporary socket name in %s", tmpdir);
883 goto err;
885 close(fd);
886 if (update_addr) {
887 g_free(saddr->path);
888 saddr->path = g_strdup(un.sun_path);
892 if (unlink(un.sun_path) < 0 && errno != ENOENT) {
893 error_setg_errno(errp, errno,
894 "Failed to unlink socket %s", un.sun_path);
895 goto err;
897 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
898 error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);
899 goto err;
901 if (listen(sock, 1) < 0) {
902 error_setg_errno(errp, errno, "Failed to listen on socket");
903 goto err;
906 return sock;
908 err:
909 closesocket(sock);
910 return -1;
913 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
914 NonBlockingConnectHandler *callback, void *opaque)
916 struct sockaddr_un un;
917 ConnectState *connect_state = NULL;
918 int sock, rc;
920 if (saddr->path == NULL) {
921 error_setg(errp, "unix connect: no path specified");
922 return -1;
925 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
926 if (sock < 0) {
927 error_setg_errno(errp, errno, "Failed to create socket");
928 return -1;
930 if (callback != NULL) {
931 connect_state = g_malloc0(sizeof(*connect_state));
932 connect_state->callback = callback;
933 connect_state->opaque = opaque;
934 qemu_set_nonblock(sock);
937 memset(&un, 0, sizeof(un));
938 un.sun_family = AF_UNIX;
939 snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);
941 /* connect to peer */
942 do {
943 rc = 0;
944 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
945 rc = -errno;
947 } while (rc == -EINTR);
949 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
950 connect_state->fd = sock;
951 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
952 return sock;
953 } else if (rc >= 0) {
954 /* non blocking socket immediate success, call callback */
955 if (callback != NULL) {
956 callback(sock, NULL, opaque);
960 if (rc < 0) {
961 error_setg_errno(errp, -rc, "Failed to connect socket");
962 close(sock);
963 sock = -1;
966 g_free(connect_state);
967 return sock;
970 #else
972 static int unix_listen_saddr(UnixSocketAddress *saddr,
973 bool update_addr,
974 Error **errp)
976 error_setg(errp, "unix sockets are not available on windows");
977 errno = ENOTSUP;
978 return -1;
981 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp,
982 NonBlockingConnectHandler *callback, void *opaque)
984 error_setg(errp, "unix sockets are not available on windows");
985 errno = ENOTSUP;
986 return -1;
988 #endif
990 /* compatibility wrapper */
991 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
993 char *path, *optstr;
994 int sock, len;
995 UnixSocketAddress *saddr;
997 saddr = g_new0(UnixSocketAddress, 1);
999 optstr = strchr(str, ',');
1000 if (optstr) {
1001 len = optstr - str;
1002 if (len) {
1003 path = g_malloc(len+1);
1004 snprintf(path, len+1, "%.*s", len, str);
1005 saddr->path = path;
1007 } else {
1008 saddr->path = g_strdup(str);
1011 sock = unix_listen_saddr(saddr, true, errp);
1013 if (sock != -1 && ostr) {
1014 snprintf(ostr, olen, "%s%s", saddr->path, optstr ? optstr : "");
1017 qapi_free_UnixSocketAddress(saddr);
1018 return sock;
1021 int unix_connect(const char *path, Error **errp)
1023 UnixSocketAddress *saddr;
1024 int sock;
1026 saddr = g_new0(UnixSocketAddress, 1);
1027 saddr->path = g_strdup(path);
1028 sock = unix_connect_saddr(saddr, errp, NULL, NULL);
1029 qapi_free_UnixSocketAddress(saddr);
1030 return sock;
1034 SocketAddress *socket_parse(const char *str, Error **errp)
1036 SocketAddress *addr;
1038 addr = g_new0(SocketAddress, 1);
1039 if (strstart(str, "unix:", NULL)) {
1040 if (str[5] == '\0') {
1041 error_setg(errp, "invalid Unix socket address");
1042 goto fail;
1043 } else {
1044 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1045 addr->u.q_unix.data = g_new(UnixSocketAddress, 1);
1046 addr->u.q_unix.data->path = g_strdup(str + 5);
1048 } else if (strstart(str, "fd:", NULL)) {
1049 if (str[3] == '\0') {
1050 error_setg(errp, "invalid file descriptor address");
1051 goto fail;
1052 } else {
1053 addr->type = SOCKET_ADDRESS_KIND_FD;
1054 addr->u.fd.data = g_new(String, 1);
1055 addr->u.fd.data->str = g_strdup(str + 3);
1057 } else if (strstart(str, "vsock:", NULL)) {
1058 addr->type = SOCKET_ADDRESS_KIND_VSOCK;
1059 addr->u.vsock.data = vsock_parse(str + strlen("vsock:"), errp);
1060 if (addr->u.vsock.data == NULL) {
1061 goto fail;
1063 } else {
1064 addr->type = SOCKET_ADDRESS_KIND_INET;
1065 addr->u.inet.data = inet_parse(str, errp);
1066 if (addr->u.inet.data == NULL) {
1067 goto fail;
1070 return addr;
1072 fail:
1073 qapi_free_SocketAddress(addr);
1074 return NULL;
1077 int socket_connect(SocketAddress *addr, Error **errp,
1078 NonBlockingConnectHandler *callback, void *opaque)
1080 int fd;
1082 switch (addr->type) {
1083 case SOCKET_ADDRESS_KIND_INET:
1084 fd = inet_connect_saddr(addr->u.inet.data, errp, callback, opaque);
1085 break;
1087 case SOCKET_ADDRESS_KIND_UNIX:
1088 fd = unix_connect_saddr(addr->u.q_unix.data, errp, callback, opaque);
1089 break;
1091 case SOCKET_ADDRESS_KIND_FD:
1092 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
1093 if (fd >= 0 && callback) {
1094 qemu_set_nonblock(fd);
1095 callback(fd, NULL, opaque);
1097 break;
1099 case SOCKET_ADDRESS_KIND_VSOCK:
1100 fd = vsock_connect_saddr(addr->u.vsock.data, errp, callback, opaque);
1101 break;
1103 default:
1104 abort();
1106 return fd;
1109 int socket_listen(SocketAddress *addr, Error **errp)
1111 int fd;
1113 switch (addr->type) {
1114 case SOCKET_ADDRESS_KIND_INET:
1115 fd = inet_listen_saddr(addr->u.inet.data, 0, false, errp);
1116 break;
1118 case SOCKET_ADDRESS_KIND_UNIX:
1119 fd = unix_listen_saddr(addr->u.q_unix.data, false, errp);
1120 break;
1122 case SOCKET_ADDRESS_KIND_FD:
1123 fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);
1124 break;
1126 case SOCKET_ADDRESS_KIND_VSOCK:
1127 fd = vsock_listen_saddr(addr->u.vsock.data, errp);
1128 break;
1130 default:
1131 abort();
1133 return fd;
1136 void socket_listen_cleanup(int fd, Error **errp)
1138 SocketAddress *addr;
1140 addr = socket_local_address(fd, errp);
1142 if (addr->type == SOCKET_ADDRESS_KIND_UNIX
1143 && addr->u.q_unix.data->path) {
1144 if (unlink(addr->u.q_unix.data->path) < 0 && errno != ENOENT) {
1145 error_setg_errno(errp, errno,
1146 "Failed to unlink socket %s",
1147 addr->u.q_unix.data->path);
1151 qapi_free_SocketAddress(addr);
1154 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
1156 int fd;
1159 * TODO SOCKET_ADDRESS_KIND_FD when fd is AF_INET or AF_INET6
1160 * (although other address families can do SOCK_DGRAM, too)
1162 switch (remote->type) {
1163 case SOCKET_ADDRESS_KIND_INET:
1164 fd = inet_dgram_saddr(remote->u.inet.data,
1165 local ? local->u.inet.data : NULL, errp);
1166 break;
1168 default:
1169 error_setg(errp, "socket type unsupported for datagram");
1170 fd = -1;
1172 return fd;
1176 static SocketAddress *
1177 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1178 socklen_t salen,
1179 Error **errp)
1181 char host[NI_MAXHOST];
1182 char serv[NI_MAXSERV];
1183 SocketAddress *addr;
1184 InetSocketAddress *inet;
1185 int ret;
1187 ret = getnameinfo((struct sockaddr *)sa, salen,
1188 host, sizeof(host),
1189 serv, sizeof(serv),
1190 NI_NUMERICHOST | NI_NUMERICSERV);
1191 if (ret != 0) {
1192 error_setg(errp, "Cannot format numeric socket address: %s",
1193 gai_strerror(ret));
1194 return NULL;
1197 addr = g_new0(SocketAddress, 1);
1198 addr->type = SOCKET_ADDRESS_KIND_INET;
1199 inet = addr->u.inet.data = g_new0(InetSocketAddress, 1);
1200 inet->host = g_strdup(host);
1201 inet->port = g_strdup(serv);
1202 if (sa->ss_family == AF_INET) {
1203 inet->has_ipv4 = inet->ipv4 = true;
1204 } else {
1205 inet->has_ipv6 = inet->ipv6 = true;
1208 return addr;
1212 #ifndef WIN32
1213 static SocketAddress *
1214 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1215 socklen_t salen,
1216 Error **errp)
1218 SocketAddress *addr;
1219 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1221 addr = g_new0(SocketAddress, 1);
1222 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1223 addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
1224 if (su->sun_path[0]) {
1225 addr->u.q_unix.data->path = g_strndup(su->sun_path,
1226 sizeof(su->sun_path));
1229 return addr;
1231 #endif /* WIN32 */
1233 #ifdef CONFIG_AF_VSOCK
1234 static SocketAddress *
1235 socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,
1236 socklen_t salen,
1237 Error **errp)
1239 SocketAddress *addr;
1240 VsockSocketAddress *vaddr;
1241 struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;
1243 addr = g_new0(SocketAddress, 1);
1244 addr->type = SOCKET_ADDRESS_KIND_VSOCK;
1245 addr->u.vsock.data = vaddr = g_new0(VsockSocketAddress, 1);
1246 vaddr->cid = g_strdup_printf("%u", svm->svm_cid);
1247 vaddr->port = g_strdup_printf("%u", svm->svm_port);
1249 return addr;
1251 #endif /* CONFIG_AF_VSOCK */
1253 SocketAddress *
1254 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1255 socklen_t salen,
1256 Error **errp)
1258 switch (sa->ss_family) {
1259 case AF_INET:
1260 case AF_INET6:
1261 return socket_sockaddr_to_address_inet(sa, salen, errp);
1263 #ifndef WIN32
1264 case AF_UNIX:
1265 return socket_sockaddr_to_address_unix(sa, salen, errp);
1266 #endif /* WIN32 */
1268 #ifdef CONFIG_AF_VSOCK
1269 case AF_VSOCK:
1270 return socket_sockaddr_to_address_vsock(sa, salen, errp);
1271 #endif
1273 default:
1274 error_setg(errp, "socket family %d unsupported",
1275 sa->ss_family);
1276 return NULL;
1278 return 0;
1282 SocketAddress *socket_local_address(int fd, Error **errp)
1284 struct sockaddr_storage ss;
1285 socklen_t sslen = sizeof(ss);
1287 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1288 error_setg_errno(errp, errno, "%s",
1289 "Unable to query local socket address");
1290 return NULL;
1293 return socket_sockaddr_to_address(&ss, sslen, errp);
1297 SocketAddress *socket_remote_address(int fd, Error **errp)
1299 struct sockaddr_storage ss;
1300 socklen_t sslen = sizeof(ss);
1302 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1303 error_setg_errno(errp, errno, "%s",
1304 "Unable to query remote socket address");
1305 return NULL;
1308 return socket_sockaddr_to_address(&ss, sslen, errp);
1311 char *socket_address_to_string(struct SocketAddress *addr, Error **errp)
1313 char *buf;
1314 InetSocketAddress *inet;
1316 switch (addr->type) {
1317 case SOCKET_ADDRESS_KIND_INET:
1318 inet = addr->u.inet.data;
1319 if (strchr(inet->host, ':') == NULL) {
1320 buf = g_strdup_printf("%s:%s", inet->host, inet->port);
1321 } else {
1322 buf = g_strdup_printf("[%s]:%s", inet->host, inet->port);
1324 break;
1326 case SOCKET_ADDRESS_KIND_UNIX:
1327 buf = g_strdup(addr->u.q_unix.data->path);
1328 break;
1330 case SOCKET_ADDRESS_KIND_FD:
1331 buf = g_strdup(addr->u.fd.data->str);
1332 break;
1334 case SOCKET_ADDRESS_KIND_VSOCK:
1335 buf = g_strdup_printf("%s:%s",
1336 addr->u.vsock.data->cid,
1337 addr->u.vsock.data->port);
1338 break;
1340 default:
1341 abort();
1343 return buf;
1346 SocketAddress *socket_address_crumple(SocketAddressFlat *addr_flat)
1348 SocketAddress *addr = g_new(SocketAddress, 1);
1350 switch (addr_flat->type) {
1351 case SOCKET_ADDRESS_FLAT_TYPE_INET:
1352 addr->type = SOCKET_ADDRESS_KIND_INET;
1353 addr->u.inet.data = QAPI_CLONE(InetSocketAddress,
1354 &addr_flat->u.inet);
1355 break;
1356 case SOCKET_ADDRESS_FLAT_TYPE_UNIX:
1357 addr->type = SOCKET_ADDRESS_KIND_UNIX;
1358 addr->u.q_unix.data = QAPI_CLONE(UnixSocketAddress,
1359 &addr_flat->u.q_unix);
1360 break;
1361 case SOCKET_ADDRESS_FLAT_TYPE_VSOCK:
1362 addr->type = SOCKET_ADDRESS_KIND_VSOCK;
1363 addr->u.vsock.data = QAPI_CLONE(VsockSocketAddress,
1364 &addr_flat->u.vsock);
1365 break;
1366 case SOCKET_ADDRESS_FLAT_TYPE_FD:
1367 addr->type = SOCKET_ADDRESS_KIND_FD;
1368 addr->u.fd.data = QAPI_CLONE(String, &addr_flat->u.fd);
1369 break;
1370 default:
1371 abort();
1374 return addr;