qemu-fsdev-dummy.c: Include module.h
[qemu.git] / qemu-sockets.c
blobabcd791cb687520a485f9e751ead736db9c59815
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.h"
26 #include "qemu_socket.h"
27 #include "qemu-common.h" /* for qemu_isdigit */
28 #include "main-loop.h"
30 #ifndef AI_ADDRCONFIG
31 # define AI_ADDRCONFIG 0
32 #endif
34 static const int on=1, off=0;
36 /* used temporarely until all users are converted to QemuOpts */
37 static QemuOptsList dummy_opts = {
38 .name = "dummy",
39 .head = QTAILQ_HEAD_INITIALIZER(dummy_opts.head),
40 .desc = {
42 .name = "path",
43 .type = QEMU_OPT_STRING,
44 },{
45 .name = "host",
46 .type = QEMU_OPT_STRING,
47 },{
48 .name = "port",
49 .type = QEMU_OPT_STRING,
50 },{
51 .name = "to",
52 .type = QEMU_OPT_NUMBER,
53 },{
54 .name = "ipv4",
55 .type = QEMU_OPT_BOOL,
56 },{
57 .name = "ipv6",
58 .type = QEMU_OPT_BOOL,
60 { /* end if list */ }
64 static int default_monitor_get_fd(Monitor *mon, const char *name, Error **errp)
66 error_setg(errp, "only QEMU supports file descriptor passing");
67 return -1;
69 QEMU_WEAK_ALIAS(monitor_get_fd, default_monitor_get_fd);
70 #define monitor_get_fd \
71 QEMU_WEAK_REF(monitor_get_fd, default_monitor_get_fd)
73 static int default_qemu_set_fd_handler2(int fd,
74 IOCanReadHandler *fd_read_poll,
75 IOHandler *fd_read,
76 IOHandler *fd_write,
77 void *opaque)
80 abort();
82 QEMU_WEAK_ALIAS(qemu_set_fd_handler2, default_qemu_set_fd_handler2);
83 #define qemu_set_fd_handler2 \
84 QEMU_WEAK_REF(qemu_set_fd_handler2, default_qemu_set_fd_handler2)
86 static int inet_getport(struct addrinfo *e)
88 struct sockaddr_in *i4;
89 struct sockaddr_in6 *i6;
91 switch (e->ai_family) {
92 case PF_INET6:
93 i6 = (void*)e->ai_addr;
94 return ntohs(i6->sin6_port);
95 case PF_INET:
96 i4 = (void*)e->ai_addr;
97 return ntohs(i4->sin_port);
98 default:
99 return 0;
103 static void inet_setport(struct addrinfo *e, int port)
105 struct sockaddr_in *i4;
106 struct sockaddr_in6 *i6;
108 switch (e->ai_family) {
109 case PF_INET6:
110 i6 = (void*)e->ai_addr;
111 i6->sin6_port = htons(port);
112 break;
113 case PF_INET:
114 i4 = (void*)e->ai_addr;
115 i4->sin_port = htons(port);
116 break;
120 const char *inet_strfamily(int family)
122 switch (family) {
123 case PF_INET6: return "ipv6";
124 case PF_INET: return "ipv4";
125 case PF_UNIX: return "unix";
127 return "unknown";
130 int inet_listen_opts(QemuOpts *opts, int port_offset, Error **errp)
132 struct addrinfo ai,*res,*e;
133 const char *addr;
134 char port[33];
135 char uaddr[INET6_ADDRSTRLEN+1];
136 char uport[33];
137 int slisten, rc, to, port_min, port_max, p;
139 memset(&ai,0, sizeof(ai));
140 ai.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
141 ai.ai_family = PF_UNSPEC;
142 ai.ai_socktype = SOCK_STREAM;
144 if ((qemu_opt_get(opts, "host") == NULL) ||
145 (qemu_opt_get(opts, "port") == NULL)) {
146 error_setg(errp, "host and/or port not specified");
147 return -1;
149 pstrcpy(port, sizeof(port), qemu_opt_get(opts, "port"));
150 addr = qemu_opt_get(opts, "host");
152 to = qemu_opt_get_number(opts, "to", 0);
153 if (qemu_opt_get_bool(opts, "ipv4", 0))
154 ai.ai_family = PF_INET;
155 if (qemu_opt_get_bool(opts, "ipv6", 0))
156 ai.ai_family = PF_INET6;
158 /* lookup */
159 if (port_offset)
160 snprintf(port, sizeof(port), "%d", atoi(port) + port_offset);
161 rc = getaddrinfo(strlen(addr) ? addr : NULL, port, &ai, &res);
162 if (rc != 0) {
163 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
164 gai_strerror(rc));
165 return -1;
168 /* create socket + bind */
169 for (e = res; e != NULL; e = e->ai_next) {
170 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
171 uaddr,INET6_ADDRSTRLEN,uport,32,
172 NI_NUMERICHOST | NI_NUMERICSERV);
173 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
174 if (slisten < 0) {
175 if (!e->ai_next) {
176 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
178 continue;
181 setsockopt(slisten,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on));
182 #ifdef IPV6_V6ONLY
183 if (e->ai_family == PF_INET6) {
184 /* listen on both ipv4 and ipv6 */
185 setsockopt(slisten,IPPROTO_IPV6,IPV6_V6ONLY,(void*)&off,
186 sizeof(off));
188 #endif
190 port_min = inet_getport(e);
191 port_max = to ? to + port_offset : port_min;
192 for (p = port_min; p <= port_max; p++) {
193 inet_setport(e, p);
194 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
195 goto listen;
197 if (p == port_max) {
198 if (!e->ai_next) {
199 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
203 closesocket(slisten);
205 freeaddrinfo(res);
206 return -1;
208 listen:
209 if (listen(slisten,1) != 0) {
210 error_set_errno(errp, errno, QERR_SOCKET_LISTEN_FAILED);
211 closesocket(slisten);
212 freeaddrinfo(res);
213 return -1;
215 snprintf(uport, sizeof(uport), "%d", inet_getport(e) - port_offset);
216 qemu_opt_set(opts, "host", uaddr);
217 qemu_opt_set(opts, "port", uport);
218 qemu_opt_set(opts, "ipv6", (e->ai_family == PF_INET6) ? "on" : "off");
219 qemu_opt_set(opts, "ipv4", (e->ai_family != PF_INET6) ? "on" : "off");
220 freeaddrinfo(res);
221 return slisten;
224 #ifdef _WIN32
225 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
226 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
227 #else
228 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
229 ((rc) == -EINPROGRESS)
230 #endif
232 /* Struct to store connect state for non blocking connect */
233 typedef struct ConnectState {
234 int fd;
235 struct addrinfo *addr_list;
236 struct addrinfo *current_addr;
237 NonBlockingConnectHandler *callback;
238 void *opaque;
239 } ConnectState;
241 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
242 ConnectState *connect_state, Error **errp);
244 static void wait_for_connect(void *opaque)
246 ConnectState *s = opaque;
247 int val = 0, rc = 0;
248 socklen_t valsize = sizeof(val);
249 bool in_progress;
251 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
253 do {
254 rc = getsockopt(s->fd, SOL_SOCKET, SO_ERROR, (void *) &val, &valsize);
255 } while (rc == -1 && socket_error() == EINTR);
257 /* update rc to contain error */
258 if (!rc && val) {
259 rc = -1;
262 /* connect error */
263 if (rc < 0) {
264 closesocket(s->fd);
265 s->fd = rc;
268 /* try to connect to the next address on the list */
269 if (s->current_addr) {
270 while (s->current_addr->ai_next != NULL && s->fd < 0) {
271 s->current_addr = s->current_addr->ai_next;
272 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
273 /* connect in progress */
274 if (in_progress) {
275 return;
279 freeaddrinfo(s->addr_list);
282 if (s->callback) {
283 s->callback(s->fd, s->opaque);
285 g_free(s);
288 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
289 ConnectState *connect_state, Error **errp)
291 int sock, rc;
293 *in_progress = false;
295 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
296 if (sock < 0) {
297 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
298 return -1;
300 qemu_setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
301 if (connect_state != NULL) {
302 socket_set_nonblock(sock);
304 /* connect to peer */
305 do {
306 rc = 0;
307 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
308 rc = -socket_error();
310 } while (rc == -EINTR);
312 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
313 connect_state->fd = sock;
314 qemu_set_fd_handler2(sock, NULL, NULL, wait_for_connect,
315 connect_state);
316 *in_progress = true;
317 } else if (rc < 0) {
318 error_set_errno(errp, errno, QERR_SOCKET_CONNECT_FAILED);
319 closesocket(sock);
320 return -1;
322 return sock;
325 static struct addrinfo *inet_parse_connect_opts(QemuOpts *opts, Error **errp)
327 struct addrinfo ai, *res;
328 int rc;
329 const char *addr;
330 const char *port;
332 memset(&ai, 0, sizeof(ai));
334 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
335 ai.ai_family = PF_UNSPEC;
336 ai.ai_socktype = SOCK_STREAM;
338 addr = qemu_opt_get(opts, "host");
339 port = qemu_opt_get(opts, "port");
340 if (addr == NULL || port == NULL) {
341 error_setg(errp, "host and/or port not specified");
342 return NULL;
345 if (qemu_opt_get_bool(opts, "ipv4", 0)) {
346 ai.ai_family = PF_INET;
348 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
349 ai.ai_family = PF_INET6;
352 /* lookup */
353 rc = getaddrinfo(addr, port, &ai, &res);
354 if (rc != 0) {
355 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
356 gai_strerror(rc));
357 return NULL;
359 return res;
363 * Create a socket and connect it to an address.
365 * @opts: QEMU options, recognized parameters strings "host" and "port",
366 * bools "ipv4" and "ipv6".
367 * @errp: set on error
368 * @callback: callback function for non-blocking connect
369 * @opaque: opaque for callback function
371 * Returns: -1 on error, file descriptor on success.
373 * If @callback is non-null, the connect is non-blocking. If this
374 * function succeeds, callback will be called when the connection
375 * completes, with the file descriptor on success, or -1 on error.
377 int inet_connect_opts(QemuOpts *opts, Error **errp,
378 NonBlockingConnectHandler *callback, void *opaque)
380 struct addrinfo *res, *e;
381 int sock = -1;
382 bool in_progress;
383 ConnectState *connect_state = NULL;
385 res = inet_parse_connect_opts(opts, errp);
386 if (!res) {
387 return -1;
390 if (callback != NULL) {
391 connect_state = g_malloc0(sizeof(*connect_state));
392 connect_state->addr_list = res;
393 connect_state->callback = callback;
394 connect_state->opaque = opaque;
397 for (e = res; e != NULL; e = e->ai_next) {
398 if (connect_state != NULL) {
399 connect_state->current_addr = e;
401 sock = inet_connect_addr(e, &in_progress, connect_state, errp);
402 if (in_progress) {
403 return sock;
404 } else if (sock >= 0) {
405 /* non blocking socket immediate success, call callback */
406 if (callback != NULL) {
407 callback(sock, opaque);
409 break;
412 g_free(connect_state);
413 freeaddrinfo(res);
414 return sock;
417 int inet_dgram_opts(QemuOpts *opts, Error **errp)
419 struct addrinfo ai, *peer = NULL, *local = NULL;
420 const char *addr;
421 const char *port;
422 int sock = -1, rc;
424 /* lookup peer addr */
425 memset(&ai,0, sizeof(ai));
426 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
427 ai.ai_family = PF_UNSPEC;
428 ai.ai_socktype = SOCK_DGRAM;
430 addr = qemu_opt_get(opts, "host");
431 port = qemu_opt_get(opts, "port");
432 if (addr == NULL || strlen(addr) == 0) {
433 addr = "localhost";
435 if (port == NULL || strlen(port) == 0) {
436 error_setg(errp, "remote port not specified");
437 return -1;
440 if (qemu_opt_get_bool(opts, "ipv4", 0))
441 ai.ai_family = PF_INET;
442 if (qemu_opt_get_bool(opts, "ipv6", 0))
443 ai.ai_family = PF_INET6;
445 if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
446 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
447 gai_strerror(rc));
448 return -1;
451 /* lookup local addr */
452 memset(&ai,0, sizeof(ai));
453 ai.ai_flags = AI_PASSIVE;
454 ai.ai_family = peer->ai_family;
455 ai.ai_socktype = SOCK_DGRAM;
457 addr = qemu_opt_get(opts, "localaddr");
458 port = qemu_opt_get(opts, "localport");
459 if (addr == NULL || strlen(addr) == 0) {
460 addr = NULL;
462 if (!port || strlen(port) == 0)
463 port = "0";
465 if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
466 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
467 gai_strerror(rc));
468 goto err;
471 /* create socket */
472 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
473 if (sock < 0) {
474 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
475 goto err;
477 setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on));
479 /* bind socket */
480 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
481 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
482 goto err;
485 /* connect to peer */
486 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
487 error_set_errno(errp, errno, QERR_SOCKET_CONNECT_FAILED);
488 goto err;
491 freeaddrinfo(local);
492 freeaddrinfo(peer);
493 return sock;
495 err:
496 if (-1 != sock)
497 closesocket(sock);
498 if (local)
499 freeaddrinfo(local);
500 if (peer)
501 freeaddrinfo(peer);
502 return -1;
505 /* compatibility wrapper */
506 static InetSocketAddress *inet_parse(const char *str, Error **errp)
508 InetSocketAddress *addr;
509 const char *optstr, *h;
510 char host[64];
511 char port[33];
512 int to;
513 int pos;
515 addr = g_new0(InetSocketAddress, 1);
517 /* parse address */
518 if (str[0] == ':') {
519 /* no host given */
520 host[0] = '\0';
521 if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
522 error_setg(errp, "error parsing port in address '%s'", str);
523 goto fail;
525 } else if (str[0] == '[') {
526 /* IPv6 addr */
527 if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
528 error_setg(errp, "error parsing IPv6 address '%s'", str);
529 goto fail;
531 addr->ipv6 = addr->has_ipv6 = true;
532 } else if (qemu_isdigit(str[0])) {
533 /* IPv4 addr */
534 if (2 != sscanf(str, "%64[0-9.]:%32[^,]%n", host, port, &pos)) {
535 error_setg(errp, "error parsing IPv4 address '%s'", str);
536 goto fail;
538 addr->ipv4 = addr->has_ipv4 = true;
539 } else {
540 /* hostname */
541 if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
542 error_setg(errp, "error parsing address '%s'", str);
543 goto fail;
547 addr->host = g_strdup(host);
548 addr->port = g_strdup(port);
550 /* parse options */
551 optstr = str + pos;
552 h = strstr(optstr, ",to=");
553 if (h) {
554 if (1 != sscanf(str, "%d%n", &to, &pos) ||
555 (str[pos] != '\0' && str[pos] != ',')) {
556 error_setg(errp, "error parsing to= argument");
557 goto fail;
559 addr->has_to = true;
560 addr->to = to;
562 if (strstr(optstr, ",ipv4")) {
563 addr->ipv4 = addr->has_ipv4 = true;
565 if (strstr(optstr, ",ipv6")) {
566 addr->ipv6 = addr->has_ipv6 = true;
568 return addr;
570 fail:
571 qapi_free_InetSocketAddress(addr);
572 return NULL;
575 static void inet_addr_to_opts(QemuOpts *opts, InetSocketAddress *addr)
577 bool ipv4 = addr->ipv4 || !addr->has_ipv4;
578 bool ipv6 = addr->ipv6 || !addr->has_ipv6;
580 if (!ipv4 || !ipv6) {
581 qemu_opt_set_bool(opts, "ipv4", ipv4);
582 qemu_opt_set_bool(opts, "ipv6", ipv6);
584 if (addr->has_to) {
585 char to[20];
586 snprintf(to, sizeof(to), "%d", addr->to);
587 qemu_opt_set(opts, "to", to);
589 qemu_opt_set(opts, "host", addr->host);
590 qemu_opt_set(opts, "port", addr->port);
593 int inet_listen(const char *str, char *ostr, int olen,
594 int socktype, int port_offset, Error **errp)
596 QemuOpts *opts;
597 char *optstr;
598 int sock = -1;
599 InetSocketAddress *addr;
601 addr = inet_parse(str, errp);
602 if (addr != NULL) {
603 opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);
604 inet_addr_to_opts(opts, addr);
605 qapi_free_InetSocketAddress(addr);
606 sock = inet_listen_opts(opts, port_offset, errp);
607 if (sock != -1 && ostr) {
608 optstr = strchr(str, ',');
609 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
610 snprintf(ostr, olen, "[%s]:%s%s",
611 qemu_opt_get(opts, "host"),
612 qemu_opt_get(opts, "port"),
613 optstr ? optstr : "");
614 } else {
615 snprintf(ostr, olen, "%s:%s%s",
616 qemu_opt_get(opts, "host"),
617 qemu_opt_get(opts, "port"),
618 optstr ? optstr : "");
621 qemu_opts_del(opts);
623 return sock;
627 * Create a blocking socket and connect it to an address.
629 * @str: address string
630 * @errp: set in case of an error
632 * Returns -1 in case of error, file descriptor on success
634 int inet_connect(const char *str, Error **errp)
636 QemuOpts *opts;
637 int sock = -1;
638 InetSocketAddress *addr;
640 addr = inet_parse(str, errp);
641 if (addr != NULL) {
642 opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);
643 inet_addr_to_opts(opts, addr);
644 qapi_free_InetSocketAddress(addr);
645 sock = inet_connect_opts(opts, errp, NULL, NULL);
646 qemu_opts_del(opts);
648 return sock;
652 * Create a non-blocking socket and connect it to an address.
653 * Calls the callback function with fd in case of success or -1 in case of
654 * error.
656 * @str: address string
657 * @callback: callback function that is called when connect completes,
658 * cannot be NULL.
659 * @opaque: opaque for callback function
660 * @errp: set in case of an error
662 * Returns: -1 on immediate error, file descriptor on success.
664 int inet_nonblocking_connect(const char *str,
665 NonBlockingConnectHandler *callback,
666 void *opaque, Error **errp)
668 QemuOpts *opts;
669 int sock = -1;
670 InetSocketAddress *addr;
672 g_assert(callback != NULL);
674 addr = inet_parse(str, errp);
675 if (addr != NULL) {
676 opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);
677 inet_addr_to_opts(opts, addr);
678 qapi_free_InetSocketAddress(addr);
679 sock = inet_connect_opts(opts, errp, callback, opaque);
680 qemu_opts_del(opts);
682 return sock;
685 #ifndef _WIN32
687 int unix_listen_opts(QemuOpts *opts, Error **errp)
689 struct sockaddr_un un;
690 const char *path = qemu_opt_get(opts, "path");
691 int sock, fd;
693 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
694 if (sock < 0) {
695 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
696 return -1;
699 memset(&un, 0, sizeof(un));
700 un.sun_family = AF_UNIX;
701 if (path && strlen(path)) {
702 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
703 } else {
704 char *tmpdir = getenv("TMPDIR");
705 snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
706 tmpdir ? tmpdir : "/tmp");
708 * This dummy fd usage silences the mktemp() unsecure warning.
709 * Using mkstemp() doesn't make things more secure here
710 * though. bind() complains about existing files, so we have
711 * to unlink first and thus re-open the race window. The
712 * worst case possible is bind() failing, i.e. a DoS attack.
714 fd = mkstemp(un.sun_path); close(fd);
715 qemu_opt_set(opts, "path", un.sun_path);
718 unlink(un.sun_path);
719 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
720 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
721 goto err;
723 if (listen(sock, 1) < 0) {
724 error_set_errno(errp, errno, QERR_SOCKET_LISTEN_FAILED);
725 goto err;
728 return sock;
730 err:
731 closesocket(sock);
732 return -1;
735 int unix_connect_opts(QemuOpts *opts, Error **errp,
736 NonBlockingConnectHandler *callback, void *opaque)
738 struct sockaddr_un un;
739 const char *path = qemu_opt_get(opts, "path");
740 ConnectState *connect_state = NULL;
741 int sock, rc;
743 if (NULL == path) {
744 error_setg(errp, "unix connect: no path specified\n");
745 return -1;
748 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
749 if (sock < 0) {
750 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
751 return -1;
753 if (callback != NULL) {
754 connect_state = g_malloc0(sizeof(*connect_state));
755 connect_state->callback = callback;
756 connect_state->opaque = opaque;
757 socket_set_nonblock(sock);
760 memset(&un, 0, sizeof(un));
761 un.sun_family = AF_UNIX;
762 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
764 /* connect to peer */
765 do {
766 rc = 0;
767 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
768 rc = -socket_error();
770 } while (rc == -EINTR);
772 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
773 connect_state->fd = sock;
774 qemu_set_fd_handler2(sock, NULL, NULL, wait_for_connect,
775 connect_state);
776 return sock;
777 } else if (rc >= 0) {
778 /* non blocking socket immediate success, call callback */
779 if (callback != NULL) {
780 callback(sock, opaque);
784 if (rc < 0) {
785 error_set_errno(errp, -rc, QERR_SOCKET_CONNECT_FAILED);
786 close(sock);
787 sock = -1;
790 g_free(connect_state);
791 return sock;
794 #else
796 int unix_listen_opts(QemuOpts *opts, Error **errp)
798 error_setg(errp, "unix sockets are not available on windows");
799 errno = ENOTSUP;
800 return -1;
803 int unix_connect_opts(QemuOpts *opts, Error **errp,
804 NonBlockingConnectHandler *callback, void *opaque)
806 error_setg(errp, "unix sockets are not available on windows");
807 errno = ENOTSUP;
808 return -1;
810 #endif
812 /* compatibility wrapper */
813 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
815 QemuOpts *opts;
816 char *path, *optstr;
817 int sock, len;
819 opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);
821 optstr = strchr(str, ',');
822 if (optstr) {
823 len = optstr - str;
824 if (len) {
825 path = g_malloc(len+1);
826 snprintf(path, len+1, "%.*s", len, str);
827 qemu_opt_set(opts, "path", path);
828 g_free(path);
830 } else {
831 qemu_opt_set(opts, "path", str);
834 sock = unix_listen_opts(opts, errp);
836 if (sock != -1 && ostr)
837 snprintf(ostr, olen, "%s%s", qemu_opt_get(opts, "path"), optstr ? optstr : "");
838 qemu_opts_del(opts);
839 return sock;
842 int unix_connect(const char *path, Error **errp)
844 QemuOpts *opts;
845 int sock;
847 opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);
848 qemu_opt_set(opts, "path", path);
849 sock = unix_connect_opts(opts, errp, NULL, NULL);
850 qemu_opts_del(opts);
851 return sock;
855 int unix_nonblocking_connect(const char *path,
856 NonBlockingConnectHandler *callback,
857 void *opaque, Error **errp)
859 QemuOpts *opts;
860 int sock = -1;
862 g_assert(callback != NULL);
864 opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);
865 qemu_opt_set(opts, "path", path);
866 sock = unix_connect_opts(opts, errp, callback, opaque);
867 qemu_opts_del(opts);
868 return sock;
871 SocketAddress *socket_parse(const char *str, Error **errp)
873 SocketAddress *addr = NULL;
875 addr = g_new(SocketAddress, 1);
876 if (strstart(str, "unix:", NULL)) {
877 if (str[5] == '\0') {
878 error_setg(errp, "invalid Unix socket address\n");
879 goto fail;
880 } else {
881 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
882 addr->q_unix = g_new(UnixSocketAddress, 1);
883 addr->q_unix->path = g_strdup(str + 5);
885 } else if (strstart(str, "fd:", NULL)) {
886 if (str[3] == '\0') {
887 error_setg(errp, "invalid file descriptor address\n");
888 goto fail;
889 } else {
890 addr->kind = SOCKET_ADDRESS_KIND_FD;
891 addr->fd = g_new(String, 1);
892 addr->fd->str = g_strdup(str + 3);
894 } else {
895 addr->kind = SOCKET_ADDRESS_KIND_INET;
896 addr->inet = g_new(InetSocketAddress, 1);
897 addr->inet = inet_parse(str, errp);
898 if (addr->inet == NULL) {
899 goto fail;
902 return addr;
904 fail:
905 qapi_free_SocketAddress(addr);
906 return NULL;
909 int socket_connect(SocketAddress *addr, Error **errp,
910 NonBlockingConnectHandler *callback, void *opaque)
912 QemuOpts *opts;
913 int fd;
915 opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);
916 switch (addr->kind) {
917 case SOCKET_ADDRESS_KIND_INET:
918 inet_addr_to_opts(opts, addr->inet);
919 fd = inet_connect_opts(opts, errp, callback, opaque);
920 break;
922 case SOCKET_ADDRESS_KIND_UNIX:
923 qemu_opt_set(opts, "path", addr->q_unix->path);
924 fd = unix_connect_opts(opts, errp, callback, opaque);
925 break;
927 case SOCKET_ADDRESS_KIND_FD:
928 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
929 if (callback) {
930 callback(fd, opaque);
932 break;
934 default:
935 abort();
937 qemu_opts_del(opts);
938 return fd;
941 int socket_listen(SocketAddress *addr, Error **errp)
943 QemuOpts *opts;
944 int fd;
946 opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);
947 switch (addr->kind) {
948 case SOCKET_ADDRESS_KIND_INET:
949 inet_addr_to_opts(opts, addr->inet);
950 fd = inet_listen_opts(opts, 0, errp);
951 break;
953 case SOCKET_ADDRESS_KIND_UNIX:
954 qemu_opt_set(opts, "path", addr->q_unix->path);
955 fd = unix_listen_opts(opts, errp);
956 break;
958 case SOCKET_ADDRESS_KIND_FD:
959 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
960 break;
962 default:
963 abort();
965 qemu_opts_del(opts);
966 return fd;
969 #ifdef _WIN32
970 static void socket_cleanup(void)
972 WSACleanup();
974 #endif
976 int socket_init(void)
978 #ifdef _WIN32
979 WSADATA Data;
980 int ret, err;
982 ret = WSAStartup(MAKEWORD(2,2), &Data);
983 if (ret != 0) {
984 err = WSAGetLastError();
985 fprintf(stderr, "WSAStartup: %d\n", err);
986 return -1;
988 atexit(socket_cleanup);
989 #endif
990 return 0;