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