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