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