xref: /openbmc/qemu/util/qemu-sockets.c (revision 55bbc861)
1 /*
2  *  inet and unix socket functions for qemu
3  *
4  *  (c) 2008 Gerd Hoffmann <kraxel@redhat.com>
5  *
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.
9  *
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.
14  *
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.
17  */
18 #include "qemu/osdep.h"
19 
20 #ifdef CONFIG_AF_VSOCK
21 #include <linux/vm_sockets.h>
22 #endif /* CONFIG_AF_VSOCK */
23 
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/clone-visitor.h"
30 #include "qapi/qobject-input-visitor.h"
31 #include "qapi/qobject-output-visitor.h"
32 #include "qapi-visit.h"
33 #include "qemu/cutils.h"
34 
35 #ifndef AI_ADDRCONFIG
36 # define AI_ADDRCONFIG 0
37 #endif
38 
39 #ifndef AI_V4MAPPED
40 # define AI_V4MAPPED 0
41 #endif
42 
43 #ifndef AI_NUMERICSERV
44 # define AI_NUMERICSERV 0
45 #endif
46 
47 
48 static int inet_getport(struct addrinfo *e)
49 {
50     struct sockaddr_in *i4;
51     struct sockaddr_in6 *i6;
52 
53     switch (e->ai_family) {
54     case PF_INET6:
55         i6 = (void*)e->ai_addr;
56         return ntohs(i6->sin6_port);
57     case PF_INET:
58         i4 = (void*)e->ai_addr;
59         return ntohs(i4->sin_port);
60     default:
61         return 0;
62     }
63 }
64 
65 static void inet_setport(struct addrinfo *e, int port)
66 {
67     struct sockaddr_in *i4;
68     struct sockaddr_in6 *i6;
69 
70     switch (e->ai_family) {
71     case PF_INET6:
72         i6 = (void*)e->ai_addr;
73         i6->sin6_port = htons(port);
74         break;
75     case PF_INET:
76         i4 = (void*)e->ai_addr;
77         i4->sin_port = htons(port);
78         break;
79     }
80 }
81 
82 NetworkAddressFamily inet_netfamily(int family)
83 {
84     switch (family) {
85     case PF_INET6: return NETWORK_ADDRESS_FAMILY_IPV6;
86     case PF_INET:  return NETWORK_ADDRESS_FAMILY_IPV4;
87     case PF_UNIX:  return NETWORK_ADDRESS_FAMILY_UNIX;
88 #ifdef CONFIG_AF_VSOCK
89     case PF_VSOCK: return NETWORK_ADDRESS_FAMILY_VSOCK;
90 #endif /* CONFIG_AF_VSOCK */
91     }
92     return NETWORK_ADDRESS_FAMILY_UNKNOWN;
93 }
94 
95 /*
96  * Matrix we're trying to apply
97  *
98  *  ipv4  ipv6   family
99  *   -     -       PF_UNSPEC
100  *   -     f       PF_INET
101  *   -     t       PF_INET6
102  *   f     -       PF_INET6
103  *   f     f       <error>
104  *   f     t       PF_INET6
105  *   t     -       PF_INET
106  *   t     f       PF_INET
107  *   t     t       PF_INET6/PF_UNSPEC
108  *
109  * NB, this matrix is only about getting the necessary results
110  * from getaddrinfo(). Some of the cases require further work
111  * after reading results from getaddrinfo in order to fully
112  * apply the logic the end user wants.
113  *
114  * In the first and last cases, we must set IPV6_V6ONLY=0
115  * when binding, to allow a single listener to potentially
116  * accept both IPv4+6 addresses.
117  */
118 int inet_ai_family_from_address(InetSocketAddress *addr,
119                                 Error **errp)
120 {
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;
125     }
126     if ((addr->has_ipv6 && addr->ipv6) && (addr->has_ipv4 && addr->ipv4)) {
127         /*
128          * Some backends can only do a single listener. In that case
129          * we want empty hostname to resolve to "::" and then use the
130          * flag IPV6_V6ONLY==0 to get both protocols on 1 socket. This
131          * doesn't work for addresses other than "", so they're just
132          * inevitably broken until multiple listeners can be used,
133          * and thus we honour getaddrinfo automatic protocol detection
134          * Once all backends do multi-listener, remove the PF_INET6
135          * branch entirely.
136          */
137         if (!addr->host || g_str_equal(addr->host, "")) {
138             return PF_INET6;
139         } else {
140             return PF_UNSPEC;
141         }
142     }
143     if ((addr->has_ipv6 && addr->ipv6) || (addr->has_ipv4 && !addr->ipv4)) {
144         return PF_INET6;
145     }
146     if ((addr->has_ipv4 && addr->ipv4) || (addr->has_ipv6 && !addr->ipv6)) {
147         return PF_INET;
148     }
149     return PF_UNSPEC;
150 }
151 
152 static int create_fast_reuse_socket(struct addrinfo *e)
153 {
154     int slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
155     if (slisten < 0) {
156         return -1;
157     }
158     socket_set_fast_reuse(slisten);
159     return slisten;
160 }
161 
162 static int try_bind(int socket, InetSocketAddress *saddr, struct addrinfo *e)
163 {
164 #ifndef IPV6_V6ONLY
165     return bind(socket, e->ai_addr, e->ai_addrlen);
166 #else
167     /*
168      * Deals with first & last cases in matrix in comment
169      * for inet_ai_family_from_address().
170      */
171     int v6only =
172         ((!saddr->has_ipv4 && !saddr->has_ipv6) ||
173          (saddr->has_ipv4 && saddr->ipv4 &&
174           saddr->has_ipv6 && saddr->ipv6)) ? 0 : 1;
175     int stat;
176 
177  rebind:
178     if (e->ai_family == PF_INET6) {
179         qemu_setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, &v6only,
180                         sizeof(v6only));
181     }
182 
183     stat = bind(socket, e->ai_addr, e->ai_addrlen);
184     if (!stat) {
185         return 0;
186     }
187 
188     /* If we got EADDRINUSE from an IPv6 bind & v6only is unset,
189      * it could be that the IPv4 port is already claimed, so retry
190      * with v6only set
191      */
192     if (e->ai_family == PF_INET6 && errno == EADDRINUSE && !v6only) {
193         v6only = 1;
194         goto rebind;
195     }
196     return stat;
197 #endif
198 }
199 
200 static int inet_listen_saddr(InetSocketAddress *saddr,
201                              int port_offset,
202                              bool update_addr,
203                              Error **errp)
204 {
205     struct addrinfo ai,*res,*e;
206     char port[33];
207     char uaddr[INET6_ADDRSTRLEN+1];
208     char uport[33];
209     int rc, port_min, port_max, p;
210     int slisten = -1;
211     int saved_errno = 0;
212     bool socket_created = false;
213     Error *err = NULL;
214 
215     memset(&ai,0, sizeof(ai));
216     ai.ai_flags = AI_PASSIVE;
217     if (saddr->has_numeric && saddr->numeric) {
218         ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
219     }
220     ai.ai_family = inet_ai_family_from_address(saddr, &err);
221     ai.ai_socktype = SOCK_STREAM;
222 
223     if (err) {
224         error_propagate(errp, err);
225         return -1;
226     }
227 
228     if (saddr->host == NULL) {
229         error_setg(errp, "host not specified");
230         return -1;
231     }
232     if (saddr->port != NULL) {
233         pstrcpy(port, sizeof(port), saddr->port);
234     } else {
235         port[0] = '\0';
236     }
237 
238     /* lookup */
239     if (port_offset) {
240         unsigned long long baseport;
241         if (strlen(port) == 0) {
242             error_setg(errp, "port not specified");
243             return -1;
244         }
245         if (parse_uint_full(port, &baseport, 10) < 0) {
246             error_setg(errp, "can't convert to a number: %s", port);
247             return -1;
248         }
249         if (baseport > 65535 ||
250             baseport + port_offset > 65535) {
251             error_setg(errp, "port %s out of range", port);
252             return -1;
253         }
254         snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
255     }
256     rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,
257                      strlen(port) ? port : NULL, &ai, &res);
258     if (rc != 0) {
259         error_setg(errp, "address resolution failed for %s:%s: %s",
260                    saddr->host, port, gai_strerror(rc));
261         return -1;
262     }
263 
264     /* create socket + bind/listen */
265     for (e = res; e != NULL; e = e->ai_next) {
266         getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
267 		        uaddr,INET6_ADDRSTRLEN,uport,32,
268 		        NI_NUMERICHOST | NI_NUMERICSERV);
269 
270         port_min = inet_getport(e);
271         port_max = saddr->has_to ? saddr->to + port_offset : port_min;
272         for (p = port_min; p <= port_max; p++) {
273             inet_setport(e, p);
274 
275             slisten = create_fast_reuse_socket(e);
276             if (slisten < 0) {
277                 /* First time we expect we might fail to create the socket
278                  * eg if 'e' has AF_INET6 but ipv6 kmod is not loaded.
279                  * Later iterations should always succeed if first iteration
280                  * worked though, so treat that as fatal.
281                  */
282                 if (p == port_min) {
283                     continue;
284                 } else {
285                     error_setg_errno(errp, errno,
286                                      "Failed to recreate failed listening socket");
287                     goto listen_failed;
288                 }
289             }
290             socket_created = true;
291 
292             rc = try_bind(slisten, saddr, e);
293             if (rc < 0) {
294                 if (errno != EADDRINUSE) {
295                     error_setg_errno(errp, errno, "Failed to bind socket");
296                     goto listen_failed;
297                 }
298             } else {
299                 if (!listen(slisten, 1)) {
300                     goto listen_ok;
301                 }
302                 if (errno != EADDRINUSE) {
303                     error_setg_errno(errp, errno, "Failed to listen on socket");
304                     goto listen_failed;
305                 }
306             }
307             /* Someone else managed to bind to the same port and beat us
308              * to listen on it! Socket semantics does not allow us to
309              * recover from this situation, so we need to recreate the
310              * socket to allow bind attempts for subsequent ports:
311              */
312             closesocket(slisten);
313             slisten = -1;
314         }
315     }
316     error_setg_errno(errp, errno,
317                      socket_created ?
318                      "Failed to find an available port" :
319                      "Failed to create a socket");
320 listen_failed:
321     saved_errno = errno;
322     if (slisten >= 0) {
323         closesocket(slisten);
324     }
325     freeaddrinfo(res);
326     errno = saved_errno;
327     return -1;
328 
329 listen_ok:
330     if (update_addr) {
331         g_free(saddr->host);
332         saddr->host = g_strdup(uaddr);
333         g_free(saddr->port);
334         saddr->port = g_strdup_printf("%d",
335                                       inet_getport(e) - port_offset);
336         saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;
337         saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;
338     }
339     freeaddrinfo(res);
340     return slisten;
341 }
342 
343 #ifdef _WIN32
344 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
345     ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
346 #else
347 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
348     ((rc) == -EINPROGRESS)
349 #endif
350 
351 static int inet_connect_addr(struct addrinfo *addr, Error **errp);
352 
353 static int inet_connect_addr(struct addrinfo *addr, Error **errp)
354 {
355     int sock, rc;
356 
357     sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
358     if (sock < 0) {
359         error_setg_errno(errp, errno, "Failed to create socket");
360         return -1;
361     }
362     socket_set_fast_reuse(sock);
363 
364     /* connect to peer */
365     do {
366         rc = 0;
367         if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
368             rc = -errno;
369         }
370     } while (rc == -EINTR);
371 
372     if (rc < 0) {
373         error_setg_errno(errp, errno, "Failed to connect socket");
374         closesocket(sock);
375         return -1;
376     }
377 
378     return sock;
379 }
380 
381 static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,
382                                                  Error **errp)
383 {
384     struct addrinfo ai, *res;
385     int rc;
386     Error *err = NULL;
387     static int useV4Mapped = 1;
388 
389     memset(&ai, 0, sizeof(ai));
390 
391     ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
392     if (atomic_read(&useV4Mapped)) {
393         ai.ai_flags |= AI_V4MAPPED;
394     }
395     ai.ai_family = inet_ai_family_from_address(saddr, &err);
396     ai.ai_socktype = SOCK_STREAM;
397 
398     if (err) {
399         error_propagate(errp, err);
400         return NULL;
401     }
402 
403     if (saddr->host == NULL || saddr->port == NULL) {
404         error_setg(errp, "host and/or port not specified");
405         return NULL;
406     }
407 
408     /* lookup */
409     rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
410 
411     /* At least FreeBSD and OS-X 10.6 declare AI_V4MAPPED but
412      * then don't implement it in their getaddrinfo(). Detect
413      * this and retry without the flag since that's preferrable
414      * to a fatal error
415      */
416     if (rc == EAI_BADFLAGS &&
417         (ai.ai_flags & AI_V4MAPPED)) {
418         atomic_set(&useV4Mapped, 0);
419         ai.ai_flags &= ~AI_V4MAPPED;
420         rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);
421     }
422     if (rc != 0) {
423         error_setg(errp, "address resolution failed for %s:%s: %s",
424                    saddr->host, saddr->port, gai_strerror(rc));
425         return NULL;
426     }
427     return res;
428 }
429 
430 /**
431  * Create a socket and connect it to an address.
432  *
433  * @saddr: Inet socket address specification
434  * @errp: set on error
435  *
436  * Returns: -1 on error, file descriptor on success.
437  */
438 int inet_connect_saddr(InetSocketAddress *saddr, Error **errp)
439 {
440     Error *local_err = NULL;
441     struct addrinfo *res, *e;
442     int sock = -1;
443 
444     res = inet_parse_connect_saddr(saddr, errp);
445     if (!res) {
446         return -1;
447     }
448 
449     for (e = res; e != NULL; e = e->ai_next) {
450         error_free(local_err);
451         local_err = NULL;
452         sock = inet_connect_addr(e, &local_err);
453         if (sock >= 0) {
454             break;
455         }
456     }
457 
458     if (sock < 0) {
459         error_propagate(errp, local_err);
460     }
461 
462     freeaddrinfo(res);
463     return sock;
464 }
465 
466 static int inet_dgram_saddr(InetSocketAddress *sraddr,
467                             InetSocketAddress *sladdr,
468                             Error **errp)
469 {
470     struct addrinfo ai, *peer = NULL, *local = NULL;
471     const char *addr;
472     const char *port;
473     int sock = -1, rc;
474     Error *err = NULL;
475 
476     /* lookup peer addr */
477     memset(&ai,0, sizeof(ai));
478     ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;
479     ai.ai_family = inet_ai_family_from_address(sraddr, &err);
480     ai.ai_socktype = SOCK_DGRAM;
481 
482     if (err) {
483         error_propagate(errp, err);
484         goto err;
485     }
486 
487     addr = sraddr->host;
488     port = sraddr->port;
489     if (addr == NULL || strlen(addr) == 0) {
490         addr = "localhost";
491     }
492     if (port == NULL || strlen(port) == 0) {
493         error_setg(errp, "remote port not specified");
494         goto err;
495     }
496 
497     if ((rc = getaddrinfo(addr, port, &ai, &peer)) != 0) {
498         error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
499                    gai_strerror(rc));
500         goto err;
501     }
502 
503     /* lookup local addr */
504     memset(&ai,0, sizeof(ai));
505     ai.ai_flags = AI_PASSIVE;
506     ai.ai_family = peer->ai_family;
507     ai.ai_socktype = SOCK_DGRAM;
508 
509     if (sladdr) {
510         addr = sladdr->host;
511         port = sladdr->port;
512         if (addr == NULL || strlen(addr) == 0) {
513             addr = NULL;
514         }
515         if (!port || strlen(port) == 0) {
516             port = "0";
517         }
518     } else {
519         addr = NULL;
520         port = "0";
521     }
522 
523     if ((rc = getaddrinfo(addr, port, &ai, &local)) != 0) {
524         error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
525                    gai_strerror(rc));
526         goto err;
527     }
528 
529     /* create socket */
530     sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
531     if (sock < 0) {
532         error_setg_errno(errp, errno, "Failed to create socket");
533         goto err;
534     }
535     socket_set_fast_reuse(sock);
536 
537     /* bind socket */
538     if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
539         error_setg_errno(errp, errno, "Failed to bind socket");
540         goto err;
541     }
542 
543     /* connect to peer */
544     if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
545         error_setg_errno(errp, errno, "Failed to connect socket");
546         goto err;
547     }
548 
549     freeaddrinfo(local);
550     freeaddrinfo(peer);
551     return sock;
552 
553 err:
554     if (sock != -1) {
555         closesocket(sock);
556     }
557     if (local) {
558         freeaddrinfo(local);
559     }
560     if (peer) {
561         freeaddrinfo(peer);
562     }
563 
564     return -1;
565 }
566 
567 /* compatibility wrapper */
568 int inet_parse(InetSocketAddress *addr, const char *str, Error **errp)
569 {
570     const char *optstr, *h;
571     char host[65];
572     char port[33];
573     int to;
574     int pos;
575 
576     memset(addr, 0, sizeof(*addr));
577 
578     /* parse address */
579     if (str[0] == ':') {
580         /* no host given */
581         host[0] = '\0';
582         if (sscanf(str, ":%32[^,]%n", port, &pos) != 1) {
583             error_setg(errp, "error parsing port in address '%s'", str);
584             return -1;
585         }
586     } else if (str[0] == '[') {
587         /* IPv6 addr */
588         if (sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos) != 2) {
589             error_setg(errp, "error parsing IPv6 address '%s'", str);
590             return -1;
591         }
592     } else {
593         /* hostname or IPv4 addr */
594         if (sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos) != 2) {
595             error_setg(errp, "error parsing address '%s'", str);
596             return -1;
597         }
598     }
599 
600     addr->host = g_strdup(host);
601     addr->port = g_strdup(port);
602 
603     /* parse options */
604     optstr = str + pos;
605     h = strstr(optstr, ",to=");
606     if (h) {
607         h += 4;
608         if (sscanf(h, "%d%n", &to, &pos) != 1 ||
609             (h[pos] != '\0' && h[pos] != ',')) {
610             error_setg(errp, "error parsing to= argument");
611             return -1;
612         }
613         addr->has_to = true;
614         addr->to = to;
615     }
616     if (strstr(optstr, ",ipv4")) {
617         addr->ipv4 = addr->has_ipv4 = true;
618     }
619     if (strstr(optstr, ",ipv6")) {
620         addr->ipv6 = addr->has_ipv6 = true;
621     }
622     return 0;
623 }
624 
625 
626 /**
627  * Create a blocking socket and connect it to an address.
628  *
629  * @str: address string
630  * @errp: set in case of an error
631  *
632  * Returns -1 in case of error, file descriptor on success
633  **/
634 int inet_connect(const char *str, Error **errp)
635 {
636     int sock = -1;
637     InetSocketAddress *addr = g_new(InetSocketAddress, 1);
638 
639     if (!inet_parse(addr, str, errp)) {
640         sock = inet_connect_saddr(addr, errp);
641     }
642     qapi_free_InetSocketAddress(addr);
643     return sock;
644 }
645 
646 #ifdef CONFIG_AF_VSOCK
647 static bool vsock_parse_vaddr_to_sockaddr(const VsockSocketAddress *vaddr,
648                                           struct sockaddr_vm *svm,
649                                           Error **errp)
650 {
651     unsigned long long val;
652 
653     memset(svm, 0, sizeof(*svm));
654     svm->svm_family = AF_VSOCK;
655 
656     if (parse_uint_full(vaddr->cid, &val, 10) < 0 ||
657         val > UINT32_MAX) {
658         error_setg(errp, "Failed to parse cid '%s'", vaddr->cid);
659         return false;
660     }
661     svm->svm_cid = val;
662 
663     if (parse_uint_full(vaddr->port, &val, 10) < 0 ||
664         val > UINT32_MAX) {
665         error_setg(errp, "Failed to parse port '%s'", vaddr->port);
666         return false;
667     }
668     svm->svm_port = val;
669 
670     return true;
671 }
672 
673 static int vsock_connect_addr(const struct sockaddr_vm *svm, Error **errp)
674 {
675     int sock, rc;
676 
677     sock = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
678     if (sock < 0) {
679         error_setg_errno(errp, errno, "Failed to create socket");
680         return -1;
681     }
682 
683     /* connect to peer */
684     do {
685         rc = 0;
686         if (connect(sock, (const struct sockaddr *)svm, sizeof(*svm)) < 0) {
687             rc = -errno;
688         }
689     } while (rc == -EINTR);
690 
691     if (rc < 0) {
692         error_setg_errno(errp, errno, "Failed to connect socket");
693         closesocket(sock);
694         return -1;
695     }
696 
697     return sock;
698 }
699 
700 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
701 {
702     struct sockaddr_vm svm;
703     int sock = -1;
704 
705     if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
706         return -1;
707     }
708 
709     sock = vsock_connect_addr(&svm, errp);
710 
711     return sock;
712 }
713 
714 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
715                               Error **errp)
716 {
717     struct sockaddr_vm svm;
718     int slisten;
719 
720     if (!vsock_parse_vaddr_to_sockaddr(vaddr, &svm, errp)) {
721         return -1;
722     }
723 
724     slisten = qemu_socket(AF_VSOCK, SOCK_STREAM, 0);
725     if (slisten < 0) {
726         error_setg_errno(errp, errno, "Failed to create socket");
727         return -1;
728     }
729 
730     if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
731         error_setg_errno(errp, errno, "Failed to bind socket");
732         closesocket(slisten);
733         return -1;
734     }
735 
736     if (listen(slisten, 1) != 0) {
737         error_setg_errno(errp, errno, "Failed to listen on socket");
738         closesocket(slisten);
739         return -1;
740     }
741     return slisten;
742 }
743 
744 static int vsock_parse(VsockSocketAddress *addr, const char *str,
745                        Error **errp)
746 {
747     char cid[33];
748     char port[33];
749     int n;
750 
751     if (sscanf(str, "%32[^:]:%32[^,]%n", cid, port, &n) != 2) {
752         error_setg(errp, "error parsing address '%s'", str);
753         return -1;
754     }
755     if (str[n] != '\0') {
756         error_setg(errp, "trailing characters in address '%s'", str);
757         return -1;
758     }
759 
760     addr->cid = g_strdup(cid);
761     addr->port = g_strdup(port);
762     return 0;
763 }
764 #else
765 static void vsock_unsupported(Error **errp)
766 {
767     error_setg(errp, "socket family AF_VSOCK unsupported");
768 }
769 
770 static int vsock_connect_saddr(VsockSocketAddress *vaddr, Error **errp)
771 {
772     vsock_unsupported(errp);
773     return -1;
774 }
775 
776 static int vsock_listen_saddr(VsockSocketAddress *vaddr,
777                               Error **errp)
778 {
779     vsock_unsupported(errp);
780     return -1;
781 }
782 
783 static int vsock_parse(VsockSocketAddress *addr, const char *str,
784                         Error **errp)
785 {
786     vsock_unsupported(errp);
787     return -1;
788 }
789 #endif /* CONFIG_AF_VSOCK */
790 
791 #ifndef _WIN32
792 
793 static int unix_listen_saddr(UnixSocketAddress *saddr,
794                              bool update_addr,
795                              Error **errp)
796 {
797     struct sockaddr_un un;
798     int sock, fd;
799     char *pathbuf = NULL;
800     const char *path;
801 
802     sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
803     if (sock < 0) {
804         error_setg_errno(errp, errno, "Failed to create Unix socket");
805         return -1;
806     }
807 
808     if (saddr->path && saddr->path[0]) {
809         path = saddr->path;
810     } else {
811         const char *tmpdir = getenv("TMPDIR");
812         tmpdir = tmpdir ? tmpdir : "/tmp";
813         path = pathbuf = g_strdup_printf("%s/qemu-socket-XXXXXX", tmpdir);
814     }
815 
816     if (strlen(path) > sizeof(un.sun_path)) {
817         error_setg(errp, "UNIX socket path '%s' is too long", path);
818         error_append_hint(errp, "Path must be less than %zu bytes\n",
819                           sizeof(un.sun_path));
820         goto err;
821     }
822 
823     if (pathbuf != NULL) {
824         /*
825          * This dummy fd usage silences the mktemp() unsecure warning.
826          * Using mkstemp() doesn't make things more secure here
827          * though.  bind() complains about existing files, so we have
828          * to unlink first and thus re-open the race window.  The
829          * worst case possible is bind() failing, i.e. a DoS attack.
830          */
831         fd = mkstemp(pathbuf);
832         if (fd < 0) {
833             error_setg_errno(errp, errno,
834                              "Failed to make a temporary socket %s", pathbuf);
835             goto err;
836         }
837         close(fd);
838     }
839 
840     if (unlink(path) < 0 && errno != ENOENT) {
841         error_setg_errno(errp, errno,
842                          "Failed to unlink socket %s", path);
843         goto err;
844     }
845 
846     memset(&un, 0, sizeof(un));
847     un.sun_family = AF_UNIX;
848     strncpy(un.sun_path, path, sizeof(un.sun_path));
849 
850     if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
851         error_setg_errno(errp, errno, "Failed to bind socket to %s", path);
852         goto err;
853     }
854     if (listen(sock, 1) < 0) {
855         error_setg_errno(errp, errno, "Failed to listen on socket");
856         goto err;
857     }
858 
859     if (update_addr && pathbuf) {
860         g_free(saddr->path);
861         saddr->path = pathbuf;
862     } else {
863         g_free(pathbuf);
864     }
865     return sock;
866 
867 err:
868     g_free(pathbuf);
869     closesocket(sock);
870     return -1;
871 }
872 
873 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
874 {
875     struct sockaddr_un un;
876     int sock, rc;
877 
878     if (saddr->path == NULL) {
879         error_setg(errp, "unix connect: no path specified");
880         return -1;
881     }
882 
883     sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
884     if (sock < 0) {
885         error_setg_errno(errp, errno, "Failed to create socket");
886         return -1;
887     }
888 
889     if (strlen(saddr->path) > sizeof(un.sun_path)) {
890         error_setg(errp, "UNIX socket path '%s' is too long", saddr->path);
891         error_append_hint(errp, "Path must be less than %zu bytes\n",
892                           sizeof(un.sun_path));
893         goto err;
894     }
895 
896     memset(&un, 0, sizeof(un));
897     un.sun_family = AF_UNIX;
898     strncpy(un.sun_path, saddr->path, sizeof(un.sun_path));
899 
900     /* connect to peer */
901     do {
902         rc = 0;
903         if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
904             rc = -errno;
905         }
906     } while (rc == -EINTR);
907 
908     if (rc < 0) {
909         error_setg_errno(errp, -rc, "Failed to connect socket %s",
910                          saddr->path);
911         goto err;
912     }
913 
914     return sock;
915 
916  err:
917     close(sock);
918     return -1;
919 }
920 
921 #else
922 
923 static int unix_listen_saddr(UnixSocketAddress *saddr,
924                              bool update_addr,
925                              Error **errp)
926 {
927     error_setg(errp, "unix sockets are not available on windows");
928     errno = ENOTSUP;
929     return -1;
930 }
931 
932 static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
933 {
934     error_setg(errp, "unix sockets are not available on windows");
935     errno = ENOTSUP;
936     return -1;
937 }
938 #endif
939 
940 /* compatibility wrapper */
941 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
942 {
943     char *path, *optstr;
944     int sock, len;
945     UnixSocketAddress *saddr;
946 
947     saddr = g_new0(UnixSocketAddress, 1);
948 
949     optstr = strchr(str, ',');
950     if (optstr) {
951         len = optstr - str;
952         if (len) {
953             path = g_malloc(len+1);
954             snprintf(path, len+1, "%.*s", len, str);
955             saddr->path = path;
956         }
957     } else {
958         saddr->path = g_strdup(str);
959     }
960 
961     sock = unix_listen_saddr(saddr, true, errp);
962 
963     if (sock != -1 && ostr) {
964         snprintf(ostr, olen, "%s%s", saddr->path, optstr ? optstr : "");
965     }
966 
967     qapi_free_UnixSocketAddress(saddr);
968     return sock;
969 }
970 
971 int unix_connect(const char *path, Error **errp)
972 {
973     UnixSocketAddress *saddr;
974     int sock;
975 
976     saddr = g_new0(UnixSocketAddress, 1);
977     saddr->path = g_strdup(path);
978     sock = unix_connect_saddr(saddr, errp);
979     qapi_free_UnixSocketAddress(saddr);
980     return sock;
981 }
982 
983 
984 SocketAddress *socket_parse(const char *str, Error **errp)
985 {
986     SocketAddress *addr;
987 
988     addr = g_new0(SocketAddress, 1);
989     if (strstart(str, "unix:", NULL)) {
990         if (str[5] == '\0') {
991             error_setg(errp, "invalid Unix socket address");
992             goto fail;
993         } else {
994             addr->type = SOCKET_ADDRESS_TYPE_UNIX;
995             addr->u.q_unix.path = g_strdup(str + 5);
996         }
997     } else if (strstart(str, "fd:", NULL)) {
998         if (str[3] == '\0') {
999             error_setg(errp, "invalid file descriptor address");
1000             goto fail;
1001         } else {
1002             addr->type = SOCKET_ADDRESS_TYPE_FD;
1003             addr->u.fd.str = g_strdup(str + 3);
1004         }
1005     } else if (strstart(str, "vsock:", NULL)) {
1006         addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1007         if (vsock_parse(&addr->u.vsock, str + strlen("vsock:"), errp)) {
1008             goto fail;
1009         }
1010     } else {
1011         addr->type = SOCKET_ADDRESS_TYPE_INET;
1012         if (inet_parse(&addr->u.inet, str, errp)) {
1013             goto fail;
1014         }
1015     }
1016     return addr;
1017 
1018 fail:
1019     qapi_free_SocketAddress(addr);
1020     return NULL;
1021 }
1022 
1023 int socket_connect(SocketAddress *addr, Error **errp)
1024 {
1025     int fd;
1026 
1027     switch (addr->type) {
1028     case SOCKET_ADDRESS_TYPE_INET:
1029         fd = inet_connect_saddr(&addr->u.inet, errp);
1030         break;
1031 
1032     case SOCKET_ADDRESS_TYPE_UNIX:
1033         fd = unix_connect_saddr(&addr->u.q_unix, errp);
1034         break;
1035 
1036     case SOCKET_ADDRESS_TYPE_FD:
1037         fd = monitor_get_fd(cur_mon, addr->u.fd.str, errp);
1038         break;
1039 
1040     case SOCKET_ADDRESS_TYPE_VSOCK:
1041         fd = vsock_connect_saddr(&addr->u.vsock, errp);
1042         break;
1043 
1044     default:
1045         abort();
1046     }
1047     return fd;
1048 }
1049 
1050 int socket_listen(SocketAddress *addr, Error **errp)
1051 {
1052     int fd;
1053 
1054     switch (addr->type) {
1055     case SOCKET_ADDRESS_TYPE_INET:
1056         fd = inet_listen_saddr(&addr->u.inet, 0, false, errp);
1057         break;
1058 
1059     case SOCKET_ADDRESS_TYPE_UNIX:
1060         fd = unix_listen_saddr(&addr->u.q_unix, false, errp);
1061         break;
1062 
1063     case SOCKET_ADDRESS_TYPE_FD:
1064         fd = monitor_get_fd(cur_mon, addr->u.fd.str, errp);
1065         break;
1066 
1067     case SOCKET_ADDRESS_TYPE_VSOCK:
1068         fd = vsock_listen_saddr(&addr->u.vsock, errp);
1069         break;
1070 
1071     default:
1072         abort();
1073     }
1074     return fd;
1075 }
1076 
1077 void socket_listen_cleanup(int fd, Error **errp)
1078 {
1079     SocketAddress *addr;
1080 
1081     addr = socket_local_address(fd, errp);
1082     if (!addr) {
1083         return;
1084     }
1085 
1086     if (addr->type == SOCKET_ADDRESS_TYPE_UNIX
1087         && addr->u.q_unix.path) {
1088         if (unlink(addr->u.q_unix.path) < 0 && errno != ENOENT) {
1089             error_setg_errno(errp, errno,
1090                              "Failed to unlink socket %s",
1091                              addr->u.q_unix.path);
1092         }
1093     }
1094 
1095     qapi_free_SocketAddress(addr);
1096 }
1097 
1098 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
1099 {
1100     int fd;
1101 
1102     /*
1103      * TODO SOCKET_ADDRESS_TYPE_FD when fd is AF_INET or AF_INET6
1104      * (although other address families can do SOCK_DGRAM, too)
1105      */
1106     switch (remote->type) {
1107     case SOCKET_ADDRESS_TYPE_INET:
1108         fd = inet_dgram_saddr(&remote->u.inet,
1109                               local ? &local->u.inet : NULL, errp);
1110         break;
1111 
1112     default:
1113         error_setg(errp, "socket type unsupported for datagram");
1114         fd = -1;
1115     }
1116     return fd;
1117 }
1118 
1119 
1120 static SocketAddress *
1121 socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,
1122                                 socklen_t salen,
1123                                 Error **errp)
1124 {
1125     char host[NI_MAXHOST];
1126     char serv[NI_MAXSERV];
1127     SocketAddress *addr;
1128     InetSocketAddress *inet;
1129     int ret;
1130 
1131     ret = getnameinfo((struct sockaddr *)sa, salen,
1132                       host, sizeof(host),
1133                       serv, sizeof(serv),
1134                       NI_NUMERICHOST | NI_NUMERICSERV);
1135     if (ret != 0) {
1136         error_setg(errp, "Cannot format numeric socket address: %s",
1137                    gai_strerror(ret));
1138         return NULL;
1139     }
1140 
1141     addr = g_new0(SocketAddress, 1);
1142     addr->type = SOCKET_ADDRESS_TYPE_INET;
1143     inet = &addr->u.inet;
1144     inet->host = g_strdup(host);
1145     inet->port = g_strdup(serv);
1146     if (sa->ss_family == AF_INET) {
1147         inet->has_ipv4 = inet->ipv4 = true;
1148     } else {
1149         inet->has_ipv6 = inet->ipv6 = true;
1150     }
1151 
1152     return addr;
1153 }
1154 
1155 
1156 #ifndef WIN32
1157 static SocketAddress *
1158 socket_sockaddr_to_address_unix(struct sockaddr_storage *sa,
1159                                 socklen_t salen,
1160                                 Error **errp)
1161 {
1162     SocketAddress *addr;
1163     struct sockaddr_un *su = (struct sockaddr_un *)sa;
1164 
1165     addr = g_new0(SocketAddress, 1);
1166     addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1167     if (su->sun_path[0]) {
1168         addr->u.q_unix.path = g_strndup(su->sun_path, sizeof(su->sun_path));
1169     }
1170 
1171     return addr;
1172 }
1173 #endif /* WIN32 */
1174 
1175 #ifdef CONFIG_AF_VSOCK
1176 static SocketAddress *
1177 socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,
1178                                  socklen_t salen,
1179                                  Error **errp)
1180 {
1181     SocketAddress *addr;
1182     VsockSocketAddress *vaddr;
1183     struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;
1184 
1185     addr = g_new0(SocketAddress, 1);
1186     addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1187     vaddr = &addr->u.vsock;
1188     vaddr->cid = g_strdup_printf("%u", svm->svm_cid);
1189     vaddr->port = g_strdup_printf("%u", svm->svm_port);
1190 
1191     return addr;
1192 }
1193 #endif /* CONFIG_AF_VSOCK */
1194 
1195 SocketAddress *
1196 socket_sockaddr_to_address(struct sockaddr_storage *sa,
1197                            socklen_t salen,
1198                            Error **errp)
1199 {
1200     switch (sa->ss_family) {
1201     case AF_INET:
1202     case AF_INET6:
1203         return socket_sockaddr_to_address_inet(sa, salen, errp);
1204 
1205 #ifndef WIN32
1206     case AF_UNIX:
1207         return socket_sockaddr_to_address_unix(sa, salen, errp);
1208 #endif /* WIN32 */
1209 
1210 #ifdef CONFIG_AF_VSOCK
1211     case AF_VSOCK:
1212         return socket_sockaddr_to_address_vsock(sa, salen, errp);
1213 #endif
1214 
1215     default:
1216         error_setg(errp, "socket family %d unsupported",
1217                    sa->ss_family);
1218         return NULL;
1219     }
1220     return 0;
1221 }
1222 
1223 
1224 SocketAddress *socket_local_address(int fd, Error **errp)
1225 {
1226     struct sockaddr_storage ss;
1227     socklen_t sslen = sizeof(ss);
1228 
1229     if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1230         error_setg_errno(errp, errno, "%s",
1231                          "Unable to query local socket address");
1232         return NULL;
1233     }
1234 
1235     return socket_sockaddr_to_address(&ss, sslen, errp);
1236 }
1237 
1238 
1239 SocketAddress *socket_remote_address(int fd, Error **errp)
1240 {
1241     struct sockaddr_storage ss;
1242     socklen_t sslen = sizeof(ss);
1243 
1244     if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
1245         error_setg_errno(errp, errno, "%s",
1246                          "Unable to query remote socket address");
1247         return NULL;
1248     }
1249 
1250     return socket_sockaddr_to_address(&ss, sslen, errp);
1251 }
1252 
1253 
1254 SocketAddress *socket_address_flatten(SocketAddressLegacy *addr_legacy)
1255 {
1256     SocketAddress *addr;
1257 
1258     if (!addr_legacy) {
1259         return NULL;
1260     }
1261 
1262     addr = g_new(SocketAddress, 1);
1263 
1264     switch (addr_legacy->type) {
1265     case SOCKET_ADDRESS_LEGACY_KIND_INET:
1266         addr->type = SOCKET_ADDRESS_TYPE_INET;
1267         QAPI_CLONE_MEMBERS(InetSocketAddress, &addr->u.inet,
1268                            addr_legacy->u.inet.data);
1269         break;
1270     case SOCKET_ADDRESS_LEGACY_KIND_UNIX:
1271         addr->type = SOCKET_ADDRESS_TYPE_UNIX;
1272         QAPI_CLONE_MEMBERS(UnixSocketAddress, &addr->u.q_unix,
1273                            addr_legacy->u.q_unix.data);
1274         break;
1275     case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:
1276         addr->type = SOCKET_ADDRESS_TYPE_VSOCK;
1277         QAPI_CLONE_MEMBERS(VsockSocketAddress, &addr->u.vsock,
1278                            addr_legacy->u.vsock.data);
1279         break;
1280     case SOCKET_ADDRESS_LEGACY_KIND_FD:
1281         addr->type = SOCKET_ADDRESS_TYPE_FD;
1282         QAPI_CLONE_MEMBERS(String, &addr->u.fd, addr_legacy->u.fd.data);
1283         break;
1284     default:
1285         abort();
1286     }
1287 
1288     return addr;
1289 }
1290