iothread: add iothread_by_id() API
[qemu/ar7.git] / util / qemu-sockets.c
blobaf4f01211a3010997157cba8b4b7f3bb6e570603
1 /*
2 * inet and unix socket functions for qemu
4 * (c) 2008 Gerd Hoffmann <kraxel@redhat.com>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; under version 2 of the License.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * Contributions after 2012-01-13 are licensed under the terms of the
16 * GNU GPL, version 2 or (at your option) any later version.
18 #include "qemu/osdep.h"
20 #ifdef CONFIG_AF_VSOCK
21 #include <linux/vm_sockets.h>
22 #endif /* CONFIG_AF_VSOCK */
24 #include "monitor/monitor.h"
25 #include "qapi/clone-visitor.h"
26 #include "qapi/error.h"
27 #include "qemu/sockets.h"
28 #include "qemu/main-loop.h"
29 #include "qapi/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/PF_UNSPEC
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.
113 * In the first and last cases, we must set IPV6_V6ONLY=0
114 * when binding, to allow a single listener to potentially
115 * accept both IPv4+6 addresses.
117 int inet_ai_family_from_address(InetSocketAddress *addr,
118 Error **errp)
120 if (addr->has_ipv6 && addr->has_ipv4 &&
121 !addr->ipv6 && !addr->ipv4) {
122 error_setg(errp, "Cannot disable IPv4 and IPv6 at same time");
123 return PF_UNSPEC;
125 if ((addr->has_ipv6 && addr->ipv6) && (addr->has_ipv4 && addr->ipv4)) {
127 * Some backends can only do a single listener. In that case
128 * we want empty hostname to resolve to "::" and then use the
129 * flag IPV6_V6ONLY==0 to get both protocols on 1 socket. This
130 * doesn't work for addresses other than "", so they're just
131 * inevitably broken until multiple listeners can be used,
132 * and thus we honour getaddrinfo automatic protocol detection
133 * Once all backends do multi-listener, remove the PF_INET6
134 * branch entirely.
136 if (!addr->host || g_str_equal(addr->host, "")) {
137 return PF_INET6;
138 } else {
139 return PF_UNSPEC;
142 if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
143 return PF_INET6;
145 if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
146 return PF_INET;
148 return PF_UNSPEC;
151 static int create_fast_reuse_socket(struct addrinfo *e)
153 int slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
154 if (slisten < 0) {
155 return -1;
157 socket_set_fast_reuse(slisten);
158 return slisten;
161 static int try_bind(int socket, InetSocketAddress *saddr, struct addrinfo *e)
163 #ifndef IPV6_V6ONLY
164 return bind(socket, e->ai_addr, e->ai_addrlen);
165 #else
167 * Deals with first & last cases in matrix in comment
168 * for inet_ai_family_from_address().
170 int v6only =
171 ((!saddr->has_ipv4 && !saddr->has_ipv6) ||
172 (saddr->has_ipv4 && saddr->ipv4 &&
173 saddr->has_ipv6 && saddr->ipv6)) ? 0 : 1;
174 int stat;
176 rebind:
177 if (e->ai_family == PF_INET6) {
178 qemu_setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, &v6only,
179 sizeof(v6only));
182 stat = bind(socket, e->ai_addr, e->ai_addrlen);
183 if (!stat) {
184 return 0;
187 /* If we got EADDRINUSE from an IPv6 bind & v6only is unset,
188 * it could be that the IPv4 port is already claimed, so retry
189 * with v6only set
191 if (e->ai_family == PF_INET6 && errno == EADDRINUSE && !v6only) {
192 v6only = 1;
193 goto rebind;
195 return stat;
196 #endif
199 static int inet_listen_saddr(InetSocketAddress *saddr,
200 int port_offset,
201 bool update_addr,
202 Error **errp)
204 struct addrinfo ai,*res,*e;
205 char port[33];
206 char uaddr[INET6_ADDRSTRLEN+1];
207 char uport[33];
208 int rc, port_min, port_max, p;
209 int slisten = -1;
210 int saved_errno = 0;
211 bool socket_created = false;
212 Error *err = NULL;
214 memset(&ai,0, sizeof(ai));
215 ai.ai_flags = AI_PASSIVE;
216 if (saddr->has_numeric && saddr->numeric) {
217 ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
219 ai.ai_family = inet_ai_family_from_address(saddr, &err);
220 ai.ai_socktype = SOCK_STREAM;
222 if (err) {
223 error_propagate(errp, err);
224 return -1;
227 if (saddr->host == NULL) {
228 error_setg(errp, "host not specified");
229 return -1;
231 if (saddr->port != NULL) {
232 pstrcpy(port, sizeof(port), saddr->port);
233 } else {
234 port[0] = '\0';
237 /* lookup */
238 if (port_offset) {
239 unsigned long long baseport;
240 if (strlen(port) == 0) {
241 error_setg(errp, "port not specified");
242 return -1;
244 if (parse_uint_full(port, &baseport, 10) < 0) {
245 error_setg(errp, "can't convert to a number: %s", port);
246 return -1;
248 if (baseport > 65535 ||
249 baseport + port_offset > 65535) {
250 error_setg(errp, "port %s out of range", port);
251 return -1;
253 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
255 rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
256 strlen(port) ? port : NULL, &ai, &res);
257 if (rc != 0) {
258 error_setg(errp, "address resolution failed for %s:%s: %s",
259 saddr->host, port, gai_strerror(rc));
260 return -1;
263 /* create socket + bind/listen */
264 for (e = res; e != NULL; e = e->ai_next) {
265 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
266 uaddr,INET6_ADDRSTRLEN,uport,32,
267 NI_NUMERICHOST | NI_NUMERICSERV);
269 port_min = inet_getport(e);
270 port_max = saddr->has_to ? saddr->to + port_offset : port_min;
271 for (p = port_min; p <= port_max; p++) {
272 inet_setport(e, p);
274 slisten = create_fast_reuse_socket(e);
275 if (slisten < 0) {
276 /* First time we expect we might fail to create the socket
277 * eg if 'e' has AF_INET6 but ipv6 kmod is not loaded.
278 * Later iterations should always succeed if first iteration
279 * worked though, so treat that as fatal.
281 if (p == port_min) {
282 continue;
283 } else {
284 error_setg_errno(errp, errno,
285 "Failed to recreate failed listening socket");
286 goto listen_failed;
289 socket_created = true;
291 rc = try_bind(slisten, saddr, e);
292 if (rc < 0) {
293 if (errno != EADDRINUSE) {
294 error_setg_errno(errp, errno, "Failed to bind socket");
295 goto listen_failed;
297 } else {
298 if (!listen(slisten, 1)) {
299 goto listen_ok;
301 if (errno != EADDRINUSE) {
302 error_setg_errno(errp, errno, "Failed to listen on socket");
303 goto listen_failed;
306 /* Someone else managed to bind to the same port and beat us
307 * to listen on it! Socket semantics does not allow us to
308 * recover from this situation, so we need to recreate the
309 * socket to allow bind attempts for subsequent ports:
311 closesocket(slisten);
312 slisten = -1;
315 error_setg_errno(errp, errno,
316 socket_created ?
317 "Failed to find an available port" :
318 "Failed to create a socket");
319 listen_failed:
320 saved_errno = errno;
321 if (slisten >= 0) {
322 closesocket(slisten);
324 freeaddrinfo(res);
325 errno = saved_errno;
326 return -1;
328 listen_ok:
329 if (update_addr) {
330 g_free(saddr->host);
331 saddr->host = g_strdup(uaddr);
332 g_free(saddr->port);
333 saddr->port = g_strdup_printf("%d",
334 inet_getport(e) - port_offset);
335 saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
336 saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
338 freeaddrinfo(res);
339 return slisten;
342 #ifdef _WIN32
343 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
344 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
345 #else
346 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
347 ((rc) == -EINPROGRESS)
348 #endif
350 static int inet_connect_addr(struct addrinfo *addr, Error **errp);
352 static int inet_connect_addr(struct addrinfo *addr, Error **errp)
354 int sock, rc;
356 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
357 if (sock < 0) {
358 error_setg_errno(errp, errno, "Failed to create socket");
359 return -1;
361 socket_set_fast_reuse(sock);
363 /* connect to peer */
364 do {
365 rc = 0;
366 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
367 rc = -errno;
369 } while (rc == -EINTR);
371 if (rc < 0) {
372 error_setg_errno(errp, errno, "Failed to connect socket");
373 closesocket(sock);
374 return -1;
377 return sock;
380 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
381 Error **errp)
383 struct addrinfo ai, *res;
384 int rc;
385 Error *err = NULL;
386 static int useV4Mapped = 1;
388 memset(&ai, 0, sizeof(ai));
390 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
391 if (atomic_read(&useV4Mapped)) {
392 ai.ai_flags |= AI_V4MAPPED;
394 ai.ai_family = inet_ai_family_from_address(saddr, &err);
395 ai.ai_socktype = SOCK_STREAM;
397 if (err) {
398 error_propagate(errp, err);
399 return NULL;
402 if (saddr->host == NULL || saddr->port == NULL) {
403 error_setg(errp, "host and/or port not specified");
404 return NULL;
407 /* lookup */
408 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
410 /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
411 * then don't implement it in their getaddrinfo(). Detect
412 * this and retry without the flag since that's preferrable
413 * to a fatal error
415 if (rc == EAI_BADFLAGS &&
416 (ai.ai_flags & AI_V4MAPPED)) {
417 atomic_set(&useV4Mapped, 0);
418 ai.ai_flags &= ~AI_V4MAPPED;
419 rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
421 if (rc != 0) {
422 error_setg(errp, "address resolution failed for %s:%s: %s",
423 saddr->host, saddr->port, gai_strerror(rc));
424 return NULL;
426 return res;
430 * Create a socket and connect it to an address.
432 * @saddr: Inet socket address specification
433 * @errp: set on error
435 * Returns: -1 on error, file descriptor on success.
437 int inet_connect_saddr(InetSocketAddress *saddr, Error **errp)
439 Error *local_err = NULL;
440 struct addrinfo *res, *e;
441 int sock = -1;
443 res = inet_parse_connect_saddr(saddr, errp);
444 if (!res) {
445 return -1;
448 for (e = res; e != NULL; e = e->ai_next) {
449 error_free(local_err);
450 local_err = NULL;
451 sock = inet_connect_addr(e, &local_err);
452 if (sock >= 0) {
453 break;
457 if (sock < 0) {
458 error_propagate(errp, local_err);
461 freeaddrinfo(res);
462 return sock;
465 static int inet_dgram_saddr(InetSocketAddress *sraddr,
466 InetSocketAddress *sladdr,
467 Error **errp)
469 struct addrinfo ai, *peer = NULL, *local = NULL;
470 const char *addr;
471 const char *port;
472 int sock = -1, rc;
473 Error *err = NULL;
475 /* lookup peer addr */
476 memset(&ai,0, sizeof(ai));
477 ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
478 ai.ai_family = inet_ai_family_from_address(sraddr, &err);
479 ai.ai_socktype = SOCK_DGRAM;
481 if (err) {
482 error_propagate(errp, err);
483 goto err;
486 addr = sraddr->host;
487 port = sraddr->port;
488 if (addr == NULL || strlen(addr) == 0) {
489 addr = "localhost";
491 if (port == NULL || strlen(port) == 0) {
492 error_setg(errp, "remote port not specified");
493 goto err;
496 if ((rc = getaddrinfo(addr, port, &ai, &peer)) != 0) {
497 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
498 gai_strerror(rc));
499 goto err;
502 /* lookup local addr */
503 memset(&ai,0, sizeof(ai));
504 ai.ai_flags = AI_PASSIVE;
505 ai.ai_family = peer->ai_family;
506 ai.ai_socktype = SOCK_DGRAM;
508 if (sladdr) {
509 addr = sladdr->host;
510 port = sladdr->port;
511 if (addr == NULL || strlen(addr) == 0) {
512 addr = NULL;
514 if (!port || strlen(port) == 0) {
515 port = "0";
517 } else {
518 addr = NULL;
519 port = "0";
522 if ((rc = getaddrinfo(addr, port, &ai, &local)) != 0) {
523 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
524 gai_strerror(rc));
525 goto err;
528 /* create socket */
529 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
530 if (sock < 0) {
531 error_setg_errno(errp, errno, "Failed to create socket");
532 goto err;
534 socket_set_fast_reuse(sock);
536 /* bind socket */
537 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
538 error_setg_errno(errp, errno, "Failed to bind socket");
539 goto err;
542 /* connect to peer */
543 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
544 error_setg_errno(errp, errno, "Failed to connect socket");
545 goto err;
548 freeaddrinfo(local);
549 freeaddrinfo(peer);
550 return sock;
552 err:
553 if (sock != -1) {
554 closesocket(sock);
556 if (local) {
557 freeaddrinfo(local);
559 if (peer) {
560 freeaddrinfo(peer);
563 return -1;
566 /* compatibility wrapper */
567 int inet_parse(InetSocketAddress *addr, const char *str, Error **errp)
569 const char *optstr, *h;
570 char host[65];
571 char port[33];
572 int to;
573 int pos;
575 memset(addr, 0, sizeof(*addr));
577 /* parse address */
578 if (str[0] == ':') {
579 /* no host given */
580 host[0] = '\0';
581 if (sscanf(str, ":%32[^,]%n", port, &pos) != 1) {
582 error_setg(errp, "error parsing port in address '%s'", str);
583 return -1;
585 } else if (str[0] == '[') {
586 /* IPv6 addr */
587 if (sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos) != 2) {
588 error_setg(errp, "error parsing IPv6 address '%s'", str);
589 return -1;
591 } else {
592 /* hostname or IPv4 addr */
593 if (sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos) != 2) {
594 error_setg(errp, "error parsing address '%s'", str);
595 return -1;
599 addr->host = g_strdup(host);
600 addr->port = g_strdup(port);
602 /* parse options */
603 optstr = str + pos;
604 h = strstr(optstr, ",to=");
605 if (h) {
606 h += 4;
607 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
608 (h[pos] != '\0' && h[pos] != ',')) {
609 error_setg(errp, "error parsing to= argument");
610 return -1;
612 addr->has_to = true;
613 addr->to = to;
615 if (strstr(optstr, ",ipv4")) {
616 addr->ipv4 = addr->has_ipv4 = true;
618 if (strstr(optstr, ",ipv6")) {
619 addr->ipv6 = addr->has_ipv6 = true;
621 return 0;
626 * Create a blocking socket and connect it to an address.
628 * @str: address string
629 * @errp: set in case of an error
631 * Returns -1 in case of error, file descriptor on success
633 int inet_connect(const char *str, Error **errp)
635 int sock = -1;
636 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
638 if (!inet_parse(addr, str, errp)) {
639 sock = inet_connect_saddr(addr, errp);
641 qapi_free_InetSocketAddress(addr);
642 return sock;
645 #ifdef CONFIG_AF_VSOCK
646 static bool vsock_parse_vaddr_to_sockaddr(const VsockSocketAddress *vaddr,
647 struct sockaddr_vm *svm,
648 Error **errp)
650 unsigned long long val;
652 memset(svm, 0, sizeof(*svm));
653 svm->svm_family = AF_VSOCK;
655 if (parse_uint_full(vaddr->cid, &val, 10) < 0 ||
656 val > UINT32_MAX) {
657 error_setg(errp, "Failed to parse cid '%s'", vaddr->cid);
658 return false;
660 svm->svm_cid = val;
662 if (parse_uint_full(vaddr->port, &val, 10) < 0 ||
663 val > UINT32_MAX) {
664 error_setg(errp, "Failed to parse port '%s'", vaddr->port);
665 return false;
667 svm->svm_port = val;
669 return true;
672 static int vsock_connect_addr(const struct sockaddr_vm *svm, Error **errp)
674 int sock, rc;
676 sock = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
677 if (sock < 0) {
678 error_setg_errno(errp, errno, "Failed to create socket");
679 return -1;
682 /* connect to peer */
683 do {
684 rc = 0;
685 if (connect(sock, (const struct sockaddr *)svm, sizeof(*svm)) < 0) {
686 rc = -errno;
688 } while (rc == -EINTR);
690 if (rc < 0) {
691 error_setg_errno(errp, errno, "Failed to connect socket");
692 closesocket(sock);
693 return -1;
696 return sock;
699 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
701 struct sockaddr_vm svm;
702 int sock = -1;
704 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
705 return -1;
708 sock = vsock_connect_addr(&svm, errp);
710 return sock;
713 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
714 Error **errp)
716 struct sockaddr_vm svm;
717 int slisten;
719 if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
720 return -1;
723 slisten = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
724 if (slisten < 0) {
725 error_setg_errno(errp, errno, "Failed to create socket");
726 return -1;
729 if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
730 error_setg_errno(errp, errno, "Failed to bind socket");
731 closesocket(slisten);
732 return -1;
735 if (listen(slisten, 1) != 0) {
736 error_setg_errno(errp, errno, "Failed to listen on socket");
737 closesocket(slisten);
738 return -1;
740 return slisten;
743 static int vsock_parse(VsockSocketAddress *addr, const char *str,
744 Error **errp)
746 char cid[33];
747 char port[33];
748 int n;
750 if (sscanf(str, "%32[^:]:%32[^,]%n", cid, port, &n) != 2) {
751 error_setg(errp, "error parsing address '%s'", str);
752 return -1;
754 if (str[n] != '\0') {
755 error_setg(errp, "trailing characters in address '%s'", str);
756 return -1;
759 addr->cid = g_strdup(cid);
760 addr->port = g_strdup(port);
761 return 0;
763 #else
764 static void vsock_unsupported(Error **errp)
766 error_setg(errp, "socket family AF_VSOCK unsupported");
769 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
771 vsock_unsupported(errp);
772 return -1;
775 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
776 Error **errp)
778 vsock_unsupported(errp);
779 return -1;
782 static int vsock_parse(VsockSocketAddress *addr, const char *str,
783 Error **errp)
785 vsock_unsupported(errp);
786 return -1;
788 #endif /* CONFIG_AF_VSOCK */
790 #ifndef _WIN32
792 static int unix_listen_saddr(UnixSocketAddress *saddr,
793 bool update_addr,
794 Error **errp)
796 struct sockaddr_un un;
797 int sock, fd;
798 char *pathbuf = NULL;
799 const char *path;
801 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
802 if (sock < 0) {
803 error_setg_errno(errp, errno, "Failed to create Unix socket");
804 return -1;
807 if (saddr->path && saddr->path[0]) {
808 path = saddr->path;
809 } else {
810 const char *tmpdir = getenv("TMPDIR");
811 tmpdir = tmpdir ? tmpdir : "/tmp";
812 path = pathbuf = g_strdup_printf("%s/qemu-socket-XXXXXX", tmpdir);
815 if (strlen(path) > sizeof(un.sun_path)) {
816 error_setg(errp, "UNIX socket path '%s' is too long", path);
817 error_append_hint(errp, "Path must be less than %zu bytes\n",
818 sizeof(un.sun_path));
819 goto err;
822 if (pathbuf != NULL) {
824 * This dummy fd usage silences the mktemp() unsecure warning.
825 * Using mkstemp() doesn't make things more secure here
826 * though. bind() complains about existing files, so we have
827 * to unlink first and thus re-open the race window. The
828 * worst case possible is bind() failing, i.e. a DoS attack.
830 fd = mkstemp(pathbuf);
831 if (fd < 0) {
832 error_setg_errno(errp, errno,
833 "Failed to make a temporary socket %s", pathbuf);
834 goto err;
836 close(fd);
839 if (unlink(path) < 0 && errno != ENOENT) {
840 error_setg_errno(errp, errno,
841 "Failed to unlink socket %s", path);
842 goto err;
845 memset(&un, 0, sizeof(un));
846 un.sun_family = AF_UNIX;
847 strncpy(un.sun_path, path, sizeof(un.sun_path));
849 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
850 error_setg_errno(errp, errno, "Failed to bind socket to %s", path);
851 goto err;
853 if (listen(sock, 1) < 0) {
854 error_setg_errno(errp, errno, "Failed to listen on socket");
855 goto err;
858 if (update_addr && pathbuf) {
859 g_free(saddr->path);
860 saddr->path = pathbuf;
861 } else {
862 g_free(pathbuf);
864 return sock;
866 err:
867 g_free(pathbuf);
868 closesocket(sock);
869 return -1;
872 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
874 struct sockaddr_un un;
875 int sock, rc;
877 if (saddr->path == NULL) {
878 error_setg(errp, "unix connect: no path specified");
879 return -1;
882 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
883 if (sock < 0) {
884 error_setg_errno(errp, errno, "Failed to create socket");
885 return -1;
888 if (strlen(saddr->path) > sizeof(un.sun_path)) {
889 error_setg(errp, "UNIX socket path '%s' is too long", saddr->path);
890 error_append_hint(errp, "Path must be less than %zu bytes\n",
891 sizeof(un.sun_path));
892 goto err;
895 memset(&un, 0, sizeof(un));
896 un.sun_family = AF_UNIX;
897 strncpy(un.sun_path, saddr->path, sizeof(un.sun_path));
899 /* connect to peer */
900 do {
901 rc = 0;
902 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
903 rc = -errno;
905 } while (rc == -EINTR);
907 if (rc < 0) {
908 error_setg_errno(errp, -rc, "Failed to connect socket %s",
909 saddr->path);
910 goto err;
913 return sock;
915 err:
916 close(sock);
917 return -1;
920 #else
922 static int unix_listen_saddr(UnixSocketAddress *saddr,
923 bool update_addr,
924 Error **errp)
926 error_setg(errp, "unix sockets are not available on windows");
927 errno = ENOTSUP;
928 return -1;
931 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
933 error_setg(errp, "unix sockets are not available on windows");
934 errno = ENOTSUP;
935 return -1;
937 #endif
939 /* compatibility wrapper */
940 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
942 char *path, *optstr;
943 int sock, len;
944 UnixSocketAddress *saddr;
946 saddr = g_new0(UnixSocketAddress, 1);
948 optstr = strchr(str, ',');
949 if (optstr) {
950 len = optstr - str;
951 if (len) {
952 path = g_malloc(len+1);
953 snprintf(path, len+1, "%.*s", len, str);
954 saddr->path = path;
956 } else {
957 saddr->path = g_strdup(str);
960 sock = unix_listen_saddr(saddr, true, errp);
962 if (sock != -1 && ostr) {
963 snprintf(ostr, olen, "%s%s", saddr->path, optstr ? optstr : "");
966 qapi_free_UnixSocketAddress(saddr);
967 return sock;
970 int unix_connect(const char *path, Error **errp)
972 UnixSocketAddress *saddr;
973 int sock;
975 saddr = g_new0(UnixSocketAddress, 1);
976 saddr->path = g_strdup(path);
977 sock = unix_connect_saddr(saddr, errp);
978 qapi_free_UnixSocketAddress(saddr);
979 return sock;
983 SocketAddress *socket_parse(const char *str, Error **errp)
985 SocketAddress *addr;
987 addr = g_new0(SocketAddress, 1);
988 if (strstart(str, "unix:", NULL)) {
989 if (str[5] == '\0') {
990 error_setg(errp, "invalid Unix socket address");
991 goto fail;
992 } else {
993 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
994 addr->u.q_unix.path = g_strdup(str + 5);
996 } else if (strstart(str, "fd:", NULL)) {
997 if (str[3] == '\0') {
998 error_setg(errp, "invalid file descriptor address");
999 goto fail;
1000 } else {
1001 addr->type = SOCKET_ADDRESS_TYPE_FD;
1002 addr->u.fd.str = g_strdup(str + 3);
1004 } else if (strstart(str, "vsock:", NULL)) {
1005 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1006 if (vsock_parse(&addr->u.vsock, str + strlen("vsock:"), errp)) {
1007 goto fail;
1009 } else {
1010 addr->type = SOCKET_ADDRESS_TYPE_INET;
1011 if (inet_parse(&addr->u.inet, str, errp)) {
1012 goto fail;
1015 return addr;
1017 fail:
1018 qapi_free_SocketAddress(addr);
1019 return NULL;
1022 int socket_connect(SocketAddress *addr, Error **errp)
1024 int fd;
1026 switch (addr->type) {
1027 case SOCKET_ADDRESS_TYPE_INET:
1028 fd = inet_connect_saddr(&addr->u.inet, errp);
1029 break;
1031 case SOCKET_ADDRESS_TYPE_UNIX:
1032 fd = unix_connect_saddr(&addr->u.q_unix, errp);
1033 break;
1035 case SOCKET_ADDRESS_TYPE_FD:
1036 fd = monitor_get_fd(cur_mon, addr->u.fd.str, errp);
1037 break;
1039 case SOCKET_ADDRESS_TYPE_VSOCK:
1040 fd = vsock_connect_saddr(&addr->u.vsock, errp);
1041 break;
1043 default:
1044 abort();
1046 return fd;
1049 int socket_listen(SocketAddress *addr, Error **errp)
1051 int fd;
1053 switch (addr->type) {
1054 case SOCKET_ADDRESS_TYPE_INET:
1055 fd = inet_listen_saddr(&addr->u.inet, 0, false, errp);
1056 break;
1058 case SOCKET_ADDRESS_TYPE_UNIX:
1059 fd = unix_listen_saddr(&addr->u.q_unix, false, errp);
1060 break;
1062 case SOCKET_ADDRESS_TYPE_FD:
1063 fd = monitor_get_fd(cur_mon, addr->u.fd.str, errp);
1064 break;
1066 case SOCKET_ADDRESS_TYPE_VSOCK:
1067 fd = vsock_listen_saddr(&addr->u.vsock, errp);
1068 break;
1070 default:
1071 abort();
1073 return fd;
1076 void socket_listen_cleanup(int fd, Error **errp)
1078 SocketAddress *addr;
1080 addr = socket_local_address(fd, errp);
1081 if (!addr) {
1082 return;
1085 if (addr->type == SOCKET_ADDRESS_TYPE_UNIX
1086 && addr->u.q_unix.path) {
1087 if (unlink(addr->u.q_unix.path) < 0 && errno != ENOENT) {
1088 error_setg_errno(errp, errno,
1089 "Failed to unlink socket %s",
1090 addr->u.q_unix.path);
1094 qapi_free_SocketAddress(addr);
1097 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
1099 int fd;
1102 * TODO SOCKET_ADDRESS_TYPE_FD when fd is AF_INET or AF_INET6
1103 * (although other address families can do SOCK_DGRAM, too)
1105 switch (remote->type) {
1106 case SOCKET_ADDRESS_TYPE_INET:
1107 fd = inet_dgram_saddr(&remote->u.inet,
1108 local ? &local->u.inet : NULL, errp);
1109 break;
1111 default:
1112 error_setg(errp, "socket type unsupported for datagram");
1113 fd = -1;
1115 return fd;
1119 static SocketAddress *
1120 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1121 socklen_t salen,
1122 Error **errp)
1124 char host[NI_MAXHOST];
1125 char serv[NI_MAXSERV];
1126 SocketAddress *addr;
1127 InetSocketAddress *inet;
1128 int ret;
1130 ret = getnameinfo((struct sockaddr *)sa, salen,
1131 host, sizeof(host),
1132 serv, sizeof(serv),
1133 NI_NUMERICHOST | NI_NUMERICSERV);
1134 if (ret != 0) {
1135 error_setg(errp, "Cannot format numeric socket address: %s",
1136 gai_strerror(ret));
1137 return NULL;
1140 addr = g_new0(SocketAddress, 1);
1141 addr->type = SOCKET_ADDRESS_TYPE_INET;
1142 inet = &addr->u.inet;
1143 inet->host = g_strdup(host);
1144 inet->port = g_strdup(serv);
1145 if (sa->ss_family == AF_INET) {
1146 inet->has_ipv4 = inet->ipv4 = true;
1147 } else {
1148 inet->has_ipv6 = inet->ipv6 = true;
1151 return addr;
1155 #ifndef WIN32
1156 static SocketAddress *
1157 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1158 socklen_t salen,
1159 Error **errp)
1161 SocketAddress *addr;
1162 struct sockaddr_un *su = (struct sockaddr_un *)sa;
1164 addr = g_new0(SocketAddress, 1);
1165 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1166 if (su->sun_path[0]) {
1167 addr->u.q_unix.path = g_strndup(su->sun_path, sizeof(su->sun_path));
1170 return addr;
1172 #endif /* WIN32 */
1174 #ifdef CONFIG_AF_VSOCK
1175 static SocketAddress *
1176 socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,
1177 socklen_t salen,
1178 Error **errp)
1180 SocketAddress *addr;
1181 VsockSocketAddress *vaddr;
1182 struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;
1184 addr = g_new0(SocketAddress, 1);
1185 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1186 vaddr = &addr->u.vsock;
1187 vaddr->cid = g_strdup_printf("%u", svm->svm_cid);
1188 vaddr->port = g_strdup_printf("%u", svm->svm_port);
1190 return addr;
1192 #endif /* CONFIG_AF_VSOCK */
1194 SocketAddress *
1195 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1196 socklen_t salen,
1197 Error **errp)
1199 switch (sa->ss_family) {
1200 case AF_INET:
1201 case AF_INET6:
1202 return socket_sockaddr_to_address_inet(sa, salen, errp);
1204 #ifndef WIN32
1205 case AF_UNIX:
1206 return socket_sockaddr_to_address_unix(sa, salen, errp);
1207 #endif /* WIN32 */
1209 #ifdef CONFIG_AF_VSOCK
1210 case AF_VSOCK:
1211 return socket_sockaddr_to_address_vsock(sa, salen, errp);
1212 #endif
1214 default:
1215 error_setg(errp, "socket family %d unsupported",
1216 sa->ss_family);
1217 return NULL;
1219 return 0;
1223 SocketAddress *socket_local_address(int fd, Error **errp)
1225 struct sockaddr_storage ss;
1226 socklen_t sslen = sizeof(ss);
1228 if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1229 error_setg_errno(errp, errno, "%s",
1230 "Unable to query local socket address");
1231 return NULL;
1234 return socket_sockaddr_to_address(&ss, sslen, errp);
1238 SocketAddress *socket_remote_address(int fd, Error **errp)
1240 struct sockaddr_storage ss;
1241 socklen_t sslen = sizeof(ss);
1243 if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1244 error_setg_errno(errp, errno, "%s",
1245 "Unable to query remote socket address");
1246 return NULL;
1249 return socket_sockaddr_to_address(&ss, sslen, errp);
1253 SocketAddress *socket_address_flatten(SocketAddressLegacy *addr_legacy)
1255 SocketAddress *addr;
1257 if (!addr_legacy) {
1258 return NULL;
1261 addr = g_new(SocketAddress, 1);
1263 switch (addr_legacy->type) {
1264 case SOCKET_ADDRESS_LEGACY_KIND_INET:
1265 addr->type = SOCKET_ADDRESS_TYPE_INET;
1266 QAPI_CLONE_MEMBERS(InetSocketAddress, &addr->u.inet,
1267 addr_legacy->u.inet.data);
1268 break;
1269 case SOCKET_ADDRESS_LEGACY_KIND_UNIX:
1270 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1271 QAPI_CLONE_MEMBERS(UnixSocketAddress, &addr->u.q_unix,
1272 addr_legacy->u.q_unix.data);
1273 break;
1274 case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:
1275 addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1276 QAPI_CLONE_MEMBERS(VsockSocketAddress, &addr->u.vsock,
1277 addr_legacy->u.vsock.data);
1278 break;
1279 case SOCKET_ADDRESS_LEGACY_KIND_FD:
1280 addr->type = SOCKET_ADDRESS_TYPE_FD;
1281 QAPI_CLONE_MEMBERS(String, &addr->u.fd, addr_legacy->u.fd.data);
1282 break;
1283 default:
1284 abort();
1287 return addr;