dev-hid: convert init to realize
[qemu/ar7.git] / util / qemu-sockets.c
blob4a25585b2ef295df1c07e277bacaa67c1e327b12
1 /*
2 * inet and unix socket functions for qemu
4 * (c) 2008 Gerd Hoffmann <kraxel@redhat.com>
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.
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.
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.
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <unistd.h>
25 #include "monitor/monitor.h"
26 #include "qemu/sockets.h"
27 #include "qemu/main-loop.h"
29 #ifndef AI_ADDRCONFIG
30 # define AI_ADDRCONFIG 0
31 #endif
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 = {
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,
57 { /* end if list */ }
61 static int inet_getport(struct addrinfo *e)
63 struct sockaddr_in *i4;
64 struct sockaddr_in6 *i6;
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;
78 static void inet_setport(struct addrinfo *e, int port)
80 struct sockaddr_in *i4;
81 struct sockaddr_in6 *i6;
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;
95 NetworkAddressFamily inet_netfamily(int family)
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;
102 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
105 int inet_listen_opts(QemuOpts *opts, int port_offset, Error **errp)
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;
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;
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;
124 pstrcpy(port, sizeof(port), qemu_opt_get(opts, "port"));
125 addr = qemu_opt_get(opts, "host");
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;
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;
140 if (baseport > 65535 ||
141 baseport + port_offset > 65535) {
142 error_setg(errp, "port %s out of range", port);
143 return -1;
145 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
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;
154 /* create socket + bind */
155 for (e = res; e != NULL; e = e->ai_next) {
156 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
157 uaddr,INET6_ADDRSTRLEN,uport,32,
158 NI_NUMERICHOST | NI_NUMERICSERV);
159 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
160 if (slisten < 0) {
161 if (!e->ai_next) {
162 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
164 continue;
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));
175 #endif
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;
184 if (p == port_max) {
185 if (!e->ai_next) {
186 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
190 closesocket(slisten);
192 freeaddrinfo(res);
193 return -1;
195 listen:
196 if (listen(slisten,1) != 0) {
197 error_set_errno(errp, errno, QERR_SOCKET_LISTEN_FAILED);
198 closesocket(slisten);
199 freeaddrinfo(res);
200 return -1;
202 snprintf(uport, sizeof(uport), "%d", inet_getport(e) - port_offset);
203 qemu_opt_set(opts, "host", uaddr);
204 qemu_opt_set(opts, "port", uport);
205 qemu_opt_set(opts, "ipv6", (e->ai_family == PF_INET6) ? "on" : "off");
206 qemu_opt_set(opts, "ipv4", (e->ai_family != PF_INET6) ? "on" : "off");
207 freeaddrinfo(res);
208 return slisten;
211 #ifdef _WIN32
212 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
213 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
214 #else
215 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
216 ((rc) == -EINPROGRESS)
217 #endif
219 /* Struct to store connect state for non blocking connect */
220 typedef struct ConnectState {
221 int fd;
222 struct addrinfo *addr_list;
223 struct addrinfo *current_addr;
224 NonBlockingConnectHandler *callback;
225 void *opaque;
226 } ConnectState;
228 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
229 ConnectState *connect_state, Error **errp);
231 static void wait_for_connect(void *opaque)
233 ConnectState *s = opaque;
234 int val = 0, rc = 0;
235 socklen_t valsize = sizeof(val);
236 bool in_progress;
238 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
240 do {
241 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
242 } while (rc == -1 && socket_error() == EINTR);
244 /* update rc to contain error */
245 if (!rc && val) {
246 rc = -1;
249 /* connect error */
250 if (rc < 0) {
251 closesocket(s->fd);
252 s->fd = rc;
255 /* try to connect to the next address on the list */
256 if (s->current_addr) {
257 while (s->current_addr->ai_next != NULL && s->fd < 0) {
258 s->current_addr = s->current_addr->ai_next;
259 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
260 /* connect in progress */
261 if (in_progress) {
262 return;
266 freeaddrinfo(s->addr_list);
269 if (s->callback) {
270 s->callback(s->fd, s->opaque);
272 g_free(s);
275 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
276 ConnectState *connect_state, Error **errp)
278 int sock, rc;
280 *in_progress = false;
282 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
283 if (sock < 0) {
284 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
285 return -1;
287 socket_set_fast_reuse(sock);
288 if (connect_state != NULL) {
289 qemu_set_nonblock(sock);
291 /* connect to peer */
292 do {
293 rc = 0;
294 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
295 rc = -socket_error();
297 } while (rc == -EINTR);
299 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
300 connect_state->fd = sock;
301 qemu_set_fd_handler2(sock, NULL, NULL, wait_for_connect,
302 connect_state);
303 *in_progress = true;
304 } else if (rc < 0) {
305 error_set_errno(errp, errno, QERR_SOCKET_CONNECT_FAILED);
306 closesocket(sock);
307 return -1;
309 return sock;
312 static struct addrinfo *inet_parse_connect_opts(QemuOpts *opts, Error **errp)
314 struct addrinfo ai, *res;
315 int rc;
316 const char *addr;
317 const char *port;
319 memset(&ai, 0, sizeof(ai));
321 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
322 ai.ai_family = PF_UNSPEC;
323 ai.ai_socktype = SOCK_STREAM;
325 addr = qemu_opt_get(opts, "host");
326 port = qemu_opt_get(opts, "port");
327 if (addr == NULL || port == NULL) {
328 error_setg(errp, "host and/or port not specified");
329 return NULL;
332 if (qemu_opt_get_bool(opts, "ipv4", 0)) {
333 ai.ai_family = PF_INET;
335 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
336 ai.ai_family = PF_INET6;
339 /* lookup */
340 rc = getaddrinfo(addr, port, &ai, &res);
341 if (rc != 0) {
342 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
343 gai_strerror(rc));
344 return NULL;
346 return res;
350 * Create a socket and connect it to an address.
352 * @opts: QEMU options, recognized parameters strings "host" and "port",
353 * bools "ipv4" and "ipv6".
354 * @errp: set on error
355 * @callback: callback function for non-blocking connect
356 * @opaque: opaque for callback function
358 * Returns: -1 on error, file descriptor on success.
360 * If @callback is non-null, the connect is non-blocking. If this
361 * function succeeds, callback will be called when the connection
362 * completes, with the file descriptor on success, or -1 on error.
364 int inet_connect_opts(QemuOpts *opts, Error **errp,
365 NonBlockingConnectHandler *callback, void *opaque)
367 Error *local_err = NULL;
368 struct addrinfo *res, *e;
369 int sock = -1;
370 bool in_progress;
371 ConnectState *connect_state = NULL;
373 res = inet_parse_connect_opts(opts, errp);
374 if (!res) {
375 return -1;
378 if (callback != NULL) {
379 connect_state = g_malloc0(sizeof(*connect_state));
380 connect_state->addr_list = res;
381 connect_state->callback = callback;
382 connect_state->opaque = opaque;
385 for (e = res; e != NULL; e = e->ai_next) {
386 error_free(local_err);
387 local_err = NULL;
388 if (connect_state != NULL) {
389 connect_state->current_addr = e;
391 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
392 if (sock >= 0) {
393 break;
397 if (sock < 0) {
398 error_propagate(errp, local_err);
399 } else if (in_progress) {
400 /* wait_for_connect() will do the rest */
401 return sock;
402 } else {
403 if (callback) {
404 callback(sock, opaque);
407 g_free(connect_state);
408 freeaddrinfo(res);
409 return sock;
412 int inet_dgram_opts(QemuOpts *opts, Error **errp)
414 struct addrinfo ai, *peer = NULL, *local = NULL;
415 const char *addr;
416 const char *port;
417 int sock = -1, rc;
419 /* lookup peer addr */
420 memset(&ai,0, sizeof(ai));
421 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
422 ai.ai_family = PF_UNSPEC;
423 ai.ai_socktype = SOCK_DGRAM;
425 addr = qemu_opt_get(opts, "host");
426 port = qemu_opt_get(opts, "port");
427 if (addr == NULL || strlen(addr) == 0) {
428 addr = "localhost";
430 if (port == NULL || strlen(port) == 0) {
431 error_setg(errp, "remote port not specified");
432 return -1;
435 if (qemu_opt_get_bool(opts, "ipv4", 0))
436 ai.ai_family = PF_INET;
437 if (qemu_opt_get_bool(opts, "ipv6", 0))
438 ai.ai_family = PF_INET6;
440 if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
441 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
442 gai_strerror(rc));
443 return -1;
446 /* lookup local addr */
447 memset(&ai,0, sizeof(ai));
448 ai.ai_flags = AI_PASSIVE;
449 ai.ai_family = peer->ai_family;
450 ai.ai_socktype = SOCK_DGRAM;
452 addr = qemu_opt_get(opts, "localaddr");
453 port = qemu_opt_get(opts, "localport");
454 if (addr == NULL || strlen(addr) == 0) {
455 addr = NULL;
457 if (!port || strlen(port) == 0)
458 port = "0";
460 if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
461 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
462 gai_strerror(rc));
463 goto err;
466 /* create socket */
467 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
468 if (sock < 0) {
469 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
470 goto err;
472 socket_set_fast_reuse(sock);
474 /* bind socket */
475 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
476 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
477 goto err;
480 /* connect to peer */
481 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
482 error_set_errno(errp, errno, QERR_SOCKET_CONNECT_FAILED);
483 goto err;
486 freeaddrinfo(local);
487 freeaddrinfo(peer);
488 return sock;
490 err:
491 if (-1 != sock)
492 closesocket(sock);
493 if (local)
494 freeaddrinfo(local);
495 if (peer)
496 freeaddrinfo(peer);
497 return -1;
500 /* compatibility wrapper */
501 InetSocketAddress *inet_parse(const char *str, Error **errp)
503 InetSocketAddress *addr;
504 const char *optstr, *h;
505 char host[64];
506 char port[33];
507 int to;
508 int pos;
510 addr = g_new0(InetSocketAddress, 1);
512 /* parse address */
513 if (str[0] == ':') {
514 /* no host given */
515 host[0] = '\0';
516 if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
517 error_setg(errp, "error parsing port in address '%s'", str);
518 goto fail;
520 } else if (str[0] == '[') {
521 /* IPv6 addr */
522 if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
523 error_setg(errp, "error parsing IPv6 address '%s'", str);
524 goto fail;
526 addr->ipv6 = addr->has_ipv6 = true;
527 } else {
528 /* hostname or IPv4 addr */
529 if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
530 error_setg(errp, "error parsing address '%s'", str);
531 goto fail;
533 if (host[strspn(host, "0123456789.")] == '\0') {
534 addr->ipv4 = addr->has_ipv4 = true;
538 addr->host = g_strdup(host);
539 addr->port = g_strdup(port);
541 /* parse options */
542 optstr = str + pos;
543 h = strstr(optstr, ",to=");
544 if (h) {
545 h += 4;
546 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
547 (h[pos] != '\0' && h[pos] != ',')) {
548 error_setg(errp, "error parsing to= argument");
549 goto fail;
551 addr->has_to = true;
552 addr->to = to;
554 if (strstr(optstr, ",ipv4")) {
555 addr->ipv4 = addr->has_ipv4 = true;
557 if (strstr(optstr, ",ipv6")) {
558 addr->ipv6 = addr->has_ipv6 = true;
560 return addr;
562 fail:
563 qapi_free_InetSocketAddress(addr);
564 return NULL;
567 static void inet_addr_to_opts(QemuOpts *opts, const InetSocketAddress *addr)
569 bool ipv4 = addr->ipv4 || !addr->has_ipv4;
570 bool ipv6 = addr->ipv6 || !addr->has_ipv6;
572 if (!ipv4 || !ipv6) {
573 qemu_opt_set_bool(opts, "ipv4", ipv4);
574 qemu_opt_set_bool(opts, "ipv6", ipv6);
576 if (addr->has_to) {
577 char to[20];
578 snprintf(to, sizeof(to), "%d", addr->to);
579 qemu_opt_set(opts, "to", to);
581 qemu_opt_set(opts, "host", addr->host);
582 qemu_opt_set(opts, "port", addr->port);
585 int inet_listen(const char *str, char *ostr, int olen,
586 int socktype, int port_offset, Error **errp)
588 QemuOpts *opts;
589 char *optstr;
590 int sock = -1;
591 InetSocketAddress *addr;
593 addr = inet_parse(str, errp);
594 if (addr != NULL) {
595 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
596 inet_addr_to_opts(opts, addr);
597 qapi_free_InetSocketAddress(addr);
598 sock = inet_listen_opts(opts, port_offset, errp);
599 if (sock != -1 && ostr) {
600 optstr = strchr(str, ',');
601 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
602 snprintf(ostr, olen, "[%s]:%s%s",
603 qemu_opt_get(opts, "host"),
604 qemu_opt_get(opts, "port"),
605 optstr ? optstr : "");
606 } else {
607 snprintf(ostr, olen, "%s:%s%s",
608 qemu_opt_get(opts, "host"),
609 qemu_opt_get(opts, "port"),
610 optstr ? optstr : "");
613 qemu_opts_del(opts);
615 return sock;
619 * Create a blocking socket and connect it to an address.
621 * @str: address string
622 * @errp: set in case of an error
624 * Returns -1 in case of error, file descriptor on success
626 int inet_connect(const char *str, Error **errp)
628 QemuOpts *opts;
629 int sock = -1;
630 InetSocketAddress *addr;
632 addr = inet_parse(str, errp);
633 if (addr != NULL) {
634 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
635 inet_addr_to_opts(opts, addr);
636 qapi_free_InetSocketAddress(addr);
637 sock = inet_connect_opts(opts, errp, NULL, NULL);
638 qemu_opts_del(opts);
640 return sock;
644 * Create a non-blocking socket and connect it to an address.
645 * Calls the callback function with fd in case of success or -1 in case of
646 * error.
648 * @str: address string
649 * @callback: callback function that is called when connect completes,
650 * cannot be NULL.
651 * @opaque: opaque for callback function
652 * @errp: set in case of an error
654 * Returns: -1 on immediate error, file descriptor on success.
656 int inet_nonblocking_connect(const char *str,
657 NonBlockingConnectHandler *callback,
658 void *opaque, Error **errp)
660 QemuOpts *opts;
661 int sock = -1;
662 InetSocketAddress *addr;
664 g_assert(callback != NULL);
666 addr = inet_parse(str, errp);
667 if (addr != NULL) {
668 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
669 inet_addr_to_opts(opts, addr);
670 qapi_free_InetSocketAddress(addr);
671 sock = inet_connect_opts(opts, errp, callback, opaque);
672 qemu_opts_del(opts);
674 return sock;
677 #ifndef _WIN32
679 int unix_listen_opts(QemuOpts *opts, Error **errp)
681 struct sockaddr_un un;
682 const char *path = qemu_opt_get(opts, "path");
683 int sock, fd;
685 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
686 if (sock < 0) {
687 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
688 return -1;
691 memset(&un, 0, sizeof(un));
692 un.sun_family = AF_UNIX;
693 if (path && strlen(path)) {
694 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
695 } else {
696 char *tmpdir = getenv("TMPDIR");
697 snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
698 tmpdir ? tmpdir : "/tmp");
700 * This dummy fd usage silences the mktemp() unsecure warning.
701 * Using mkstemp() doesn't make things more secure here
702 * though. bind() complains about existing files, so we have
703 * to unlink first and thus re-open the race window. The
704 * worst case possible is bind() failing, i.e. a DoS attack.
706 fd = mkstemp(un.sun_path); close(fd);
707 qemu_opt_set(opts, "path", un.sun_path);
710 unlink(un.sun_path);
711 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
712 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
713 goto err;
715 if (listen(sock, 1) < 0) {
716 error_set_errno(errp, errno, QERR_SOCKET_LISTEN_FAILED);
717 goto err;
720 return sock;
722 err:
723 closesocket(sock);
724 return -1;
727 int unix_connect_opts(QemuOpts *opts, Error **errp,
728 NonBlockingConnectHandler *callback, void *opaque)
730 struct sockaddr_un un;
731 const char *path = qemu_opt_get(opts, "path");
732 ConnectState *connect_state = NULL;
733 int sock, rc;
735 if (path == NULL) {
736 error_setg(errp, "unix connect: no path specified");
737 return -1;
740 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
741 if (sock < 0) {
742 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
743 return -1;
745 if (callback != NULL) {
746 connect_state = g_malloc0(sizeof(*connect_state));
747 connect_state->callback = callback;
748 connect_state->opaque = opaque;
749 qemu_set_nonblock(sock);
752 memset(&un, 0, sizeof(un));
753 un.sun_family = AF_UNIX;
754 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
756 /* connect to peer */
757 do {
758 rc = 0;
759 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
760 rc = -socket_error();
762 } while (rc == -EINTR);
764 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
765 connect_state->fd = sock;
766 qemu_set_fd_handler2(sock, NULL, NULL, wait_for_connect,
767 connect_state);
768 return sock;
769 } else if (rc >= 0) {
770 /* non blocking socket immediate success, call callback */
771 if (callback != NULL) {
772 callback(sock, opaque);
776 if (rc < 0) {
777 error_set_errno(errp, -rc, QERR_SOCKET_CONNECT_FAILED);
778 close(sock);
779 sock = -1;
782 g_free(connect_state);
783 return sock;
786 #else
788 int unix_listen_opts(QemuOpts *opts, Error **errp)
790 error_setg(errp, "unix sockets are not available on windows");
791 errno = ENOTSUP;
792 return -1;
795 int unix_connect_opts(QemuOpts *opts, Error **errp,
796 NonBlockingConnectHandler *callback, void *opaque)
798 error_setg(errp, "unix sockets are not available on windows");
799 errno = ENOTSUP;
800 return -1;
802 #endif
804 /* compatibility wrapper */
805 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
807 QemuOpts *opts;
808 char *path, *optstr;
809 int sock, len;
811 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
813 optstr = strchr(str, ',');
814 if (optstr) {
815 len = optstr - str;
816 if (len) {
817 path = g_malloc(len+1);
818 snprintf(path, len+1, "%.*s", len, str);
819 qemu_opt_set(opts, "path", path);
820 g_free(path);
822 } else {
823 qemu_opt_set(opts, "path", str);
826 sock = unix_listen_opts(opts, errp);
828 if (sock != -1 && ostr)
829 snprintf(ostr, olen, "%s%s", qemu_opt_get(opts, "path"), optstr ? optstr : "");
830 qemu_opts_del(opts);
831 return sock;
834 int unix_connect(const char *path, Error **errp)
836 QemuOpts *opts;
837 int sock;
839 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
840 qemu_opt_set(opts, "path", path);
841 sock = unix_connect_opts(opts, errp, NULL, NULL);
842 qemu_opts_del(opts);
843 return sock;
847 int unix_nonblocking_connect(const char *path,
848 NonBlockingConnectHandler *callback,
849 void *opaque, Error **errp)
851 QemuOpts *opts;
852 int sock = -1;
854 g_assert(callback != NULL);
856 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
857 qemu_opt_set(opts, "path", path);
858 sock = unix_connect_opts(opts, errp, callback, opaque);
859 qemu_opts_del(opts);
860 return sock;
863 SocketAddress *socket_parse(const char *str, Error **errp)
865 SocketAddress *addr;
867 addr = g_new0(SocketAddress, 1);
868 if (strstart(str, "unix:", NULL)) {
869 if (str[5] == '\0') {
870 error_setg(errp, "invalid Unix socket address");
871 goto fail;
872 } else {
873 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
874 addr->q_unix = g_new(UnixSocketAddress, 1);
875 addr->q_unix->path = g_strdup(str + 5);
877 } else if (strstart(str, "fd:", NULL)) {
878 if (str[3] == '\0') {
879 error_setg(errp, "invalid file descriptor address");
880 goto fail;
881 } else {
882 addr->kind = SOCKET_ADDRESS_KIND_FD;
883 addr->fd = g_new(String, 1);
884 addr->fd->str = g_strdup(str + 3);
886 } else {
887 addr->kind = SOCKET_ADDRESS_KIND_INET;
888 addr->inet = inet_parse(str, errp);
889 if (addr->inet == NULL) {
890 goto fail;
893 return addr;
895 fail:
896 qapi_free_SocketAddress(addr);
897 return NULL;
900 int socket_connect(SocketAddress *addr, Error **errp,
901 NonBlockingConnectHandler *callback, void *opaque)
903 QemuOpts *opts;
904 int fd;
906 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
907 switch (addr->kind) {
908 case SOCKET_ADDRESS_KIND_INET:
909 inet_addr_to_opts(opts, addr->inet);
910 fd = inet_connect_opts(opts, errp, callback, opaque);
911 break;
913 case SOCKET_ADDRESS_KIND_UNIX:
914 qemu_opt_set(opts, "path", addr->q_unix->path);
915 fd = unix_connect_opts(opts, errp, callback, opaque);
916 break;
918 case SOCKET_ADDRESS_KIND_FD:
919 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
920 if (fd >= 0 && callback) {
921 qemu_set_nonblock(fd);
922 callback(fd, opaque);
924 break;
926 default:
927 abort();
929 qemu_opts_del(opts);
930 return fd;
933 int socket_listen(SocketAddress *addr, Error **errp)
935 QemuOpts *opts;
936 int fd;
938 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
939 switch (addr->kind) {
940 case SOCKET_ADDRESS_KIND_INET:
941 inet_addr_to_opts(opts, addr->inet);
942 fd = inet_listen_opts(opts, 0, errp);
943 break;
945 case SOCKET_ADDRESS_KIND_UNIX:
946 qemu_opt_set(opts, "path", addr->q_unix->path);
947 fd = unix_listen_opts(opts, errp);
948 break;
950 case SOCKET_ADDRESS_KIND_FD:
951 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
952 break;
954 default:
955 abort();
957 qemu_opts_del(opts);
958 return fd;
961 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
963 QemuOpts *opts;
964 int fd;
966 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
967 switch (remote->kind) {
968 case SOCKET_ADDRESS_KIND_INET:
969 inet_addr_to_opts(opts, remote->inet);
970 if (local) {
971 qemu_opt_set(opts, "localaddr", local->inet->host);
972 qemu_opt_set(opts, "localport", local->inet->port);
974 fd = inet_dgram_opts(opts, errp);
975 break;
977 default:
978 error_setg(errp, "socket type unsupported for datagram");
979 fd = -1;
981 qemu_opts_del(opts);
982 return fd;