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