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