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