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