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