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