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