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