Makefile: Fix "make cscope TAGS"
[qemu/kevin.git] / util / qemu-sockets.c
blob4026314435a109dfcaab0130f8233d65bcfb7264
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 = "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,
63 { /* end if list */ }
67 static int inet_getport(struct addrinfo *e)
69 struct sockaddr_in *i4;
70 struct sockaddr_in6 *i6;
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;
84 static void inet_setport(struct addrinfo *e, int port)
86 struct sockaddr_in *i4;
87 struct sockaddr_in6 *i6;
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;
101 NetworkAddressFamily inet_netfamily(int family)
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;
108 return NETWORK_ADDRESS_FAMILY_UNKNOWN;
111 int inet_listen_opts(QemuOpts *opts, int port_offset, Error **errp)
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;
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;
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;
130 pstrcpy(port, sizeof(port), qemu_opt_get(opts, "port"));
131 addr = qemu_opt_get(opts, "host");
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;
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;
146 if (baseport > 65535 ||
147 baseport + port_offset > 65535) {
148 error_setg(errp, "port %s out of range", port);
149 return -1;
151 snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);
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;
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");
170 continue;
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));
181 #endif
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;
190 if (p == port_max) {
191 if (!e->ai_next) {
192 error_setg_errno(errp, errno, "Failed to bind socket");
196 closesocket(slisten);
198 freeaddrinfo(res);
199 return -1;
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;
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;
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
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;
236 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
237 ConnectState *connect_state, Error **errp);
239 static void wait_for_connect(void *opaque)
241 ConnectState *s = opaque;
242 int val = 0, rc = 0;
243 socklen_t valsize = sizeof(val);
244 bool in_progress;
245 Error *err = NULL;
247 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
249 do {
250 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
251 } while (rc == -1 && socket_error() == EINTR);
253 /* update rc to contain error */
254 if (!rc && val) {
255 rc = -1;
256 errno = val;
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;
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");
276 /* connect in progress */
277 if (in_progress) {
278 goto out;
282 freeaddrinfo(s->addr_list);
285 if (s->callback) {
286 s->callback(s->fd, err, s->opaque);
288 g_free(s);
289 out:
290 error_free(err);
293 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
294 ConnectState *connect_state, Error **errp)
296 int sock, rc;
298 *in_progress = false;
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;
305 socket_set_fast_reuse(sock);
306 if (connect_state != NULL) {
307 qemu_set_nonblock(sock);
309 /* connect to peer */
310 do {
311 rc = 0;
312 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
313 rc = -socket_error();
315 } while (rc == -EINTR);
317 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
318 connect_state->fd = sock;
319 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
320 *in_progress = true;
321 } else if (rc < 0) {
322 error_setg_errno(errp, errno, "Failed to connect socket");
323 closesocket(sock);
324 return -1;
326 return sock;
329 static struct addrinfo *inet_parse_connect_opts(QemuOpts *opts, Error **errp)
331 struct addrinfo ai, *res;
332 int rc;
333 const char *addr;
334 const char *port;
336 memset(&ai, 0, sizeof(ai));
338 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
339 ai.ai_family = PF_UNSPEC;
340 ai.ai_socktype = SOCK_STREAM;
342 addr = qemu_opt_get(opts, "host");
343 port = qemu_opt_get(opts, "port");
344 if (addr == NULL || port == NULL) {
345 error_setg(errp, "host and/or port not specified");
346 return NULL;
349 if (qemu_opt_get_bool(opts, "ipv4", 0)) {
350 ai.ai_family = PF_INET;
352 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
353 ai.ai_family = PF_INET6;
356 /* lookup */
357 rc = getaddrinfo(addr, port, &ai, &res);
358 if (rc != 0) {
359 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
360 gai_strerror(rc));
361 return NULL;
363 return res;
367 * Create a socket and connect it to an address.
369 * @opts: QEMU options, recognized parameters strings "host" and "port",
370 * bools "ipv4" and "ipv6".
371 * @errp: set on error
372 * @callback: callback function for non-blocking connect
373 * @opaque: opaque for callback function
375 * Returns: -1 on error, file descriptor on success.
377 * If @callback is non-null, the connect is non-blocking. If this
378 * function succeeds, callback will be called when the connection
379 * completes, with the file descriptor on success, or -1 on error.
381 int inet_connect_opts(QemuOpts *opts, Error **errp,
382 NonBlockingConnectHandler *callback, void *opaque)
384 Error *local_err = NULL;
385 struct addrinfo *res, *e;
386 int sock = -1;
387 bool in_progress;
388 ConnectState *connect_state = NULL;
390 res = inet_parse_connect_opts(opts, errp);
391 if (!res) {
392 return -1;
395 if (callback != NULL) {
396 connect_state = g_malloc0(sizeof(*connect_state));
397 connect_state->addr_list = res;
398 connect_state->callback = callback;
399 connect_state->opaque = opaque;
402 for (e = res; e != NULL; e = e->ai_next) {
403 error_free(local_err);
404 local_err = NULL;
405 if (connect_state != NULL) {
406 connect_state->current_addr = e;
408 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
409 if (sock >= 0) {
410 break;
414 if (sock < 0) {
415 error_propagate(errp, local_err);
416 } else if (in_progress) {
417 /* wait_for_connect() will do the rest */
418 return sock;
419 } else {
420 if (callback) {
421 callback(sock, NULL, opaque);
424 g_free(connect_state);
425 freeaddrinfo(res);
426 return sock;
429 int inet_dgram_opts(QemuOpts *opts, Error **errp)
431 struct addrinfo ai, *peer = NULL, *local = NULL;
432 const char *addr;
433 const char *port;
434 int sock = -1, rc;
436 /* lookup peer addr */
437 memset(&ai,0, sizeof(ai));
438 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
439 ai.ai_family = PF_UNSPEC;
440 ai.ai_socktype = SOCK_DGRAM;
442 addr = qemu_opt_get(opts, "host");
443 port = qemu_opt_get(opts, "port");
444 if (addr == NULL || strlen(addr) == 0) {
445 addr = "localhost";
447 if (port == NULL || strlen(port) == 0) {
448 error_setg(errp, "remote port not specified");
449 return -1;
452 if (qemu_opt_get_bool(opts, "ipv4", 0))
453 ai.ai_family = PF_INET;
454 if (qemu_opt_get_bool(opts, "ipv6", 0))
455 ai.ai_family = PF_INET6;
457 if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
458 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
459 gai_strerror(rc));
460 return -1;
463 /* lookup local addr */
464 memset(&ai,0, sizeof(ai));
465 ai.ai_flags = AI_PASSIVE;
466 ai.ai_family = peer->ai_family;
467 ai.ai_socktype = SOCK_DGRAM;
469 addr = qemu_opt_get(opts, "localaddr");
470 port = qemu_opt_get(opts, "localport");
471 if (addr == NULL || strlen(addr) == 0) {
472 addr = NULL;
474 if (!port || strlen(port) == 0)
475 port = "0";
477 if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
478 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
479 gai_strerror(rc));
480 goto err;
483 /* create socket */
484 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
485 if (sock < 0) {
486 error_setg_errno(errp, errno, "Failed to create socket");
487 goto err;
489 socket_set_fast_reuse(sock);
491 /* bind socket */
492 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
493 error_setg_errno(errp, errno, "Failed to bind socket");
494 goto err;
497 /* connect to peer */
498 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
499 error_setg_errno(errp, errno, "Failed to connect socket");
500 goto err;
503 freeaddrinfo(local);
504 freeaddrinfo(peer);
505 return sock;
507 err:
508 if (-1 != sock)
509 closesocket(sock);
510 if (local)
511 freeaddrinfo(local);
512 if (peer)
513 freeaddrinfo(peer);
514 return -1;
517 /* compatibility wrapper */
518 InetSocketAddress *inet_parse(const char *str, Error **errp)
520 InetSocketAddress *addr;
521 const char *optstr, *h;
522 char host[65];
523 char port[33];
524 int to;
525 int pos;
527 addr = g_new0(InetSocketAddress, 1);
529 /* parse address */
530 if (str[0] == ':') {
531 /* no host given */
532 host[0] = '\0';
533 if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
534 error_setg(errp, "error parsing port in address '%s'", str);
535 goto fail;
537 } else if (str[0] == '[') {
538 /* IPv6 addr */
539 if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
540 error_setg(errp, "error parsing IPv6 address '%s'", str);
541 goto fail;
543 addr->ipv6 = addr->has_ipv6 = true;
544 } else {
545 /* hostname or IPv4 addr */
546 if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
547 error_setg(errp, "error parsing address '%s'", str);
548 goto fail;
550 if (host[strspn(host, "0123456789.")] == '\0') {
551 addr->ipv4 = addr->has_ipv4 = true;
555 addr->host = g_strdup(host);
556 addr->port = g_strdup(port);
558 /* parse options */
559 optstr = str + pos;
560 h = strstr(optstr, ",to=");
561 if (h) {
562 h += 4;
563 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
564 (h[pos] != '\0' && h[pos] != ',')) {
565 error_setg(errp, "error parsing to= argument");
566 goto fail;
568 addr->has_to = true;
569 addr->to = to;
571 if (strstr(optstr, ",ipv4")) {
572 addr->ipv4 = addr->has_ipv4 = true;
574 if (strstr(optstr, ",ipv6")) {
575 addr->ipv6 = addr->has_ipv6 = true;
577 return addr;
579 fail:
580 qapi_free_InetSocketAddress(addr);
581 return NULL;
584 static void inet_addr_to_opts(QemuOpts *opts, const InetSocketAddress *addr)
586 bool ipv4 = addr->ipv4 || !addr->has_ipv4;
587 bool ipv6 = addr->ipv6 || !addr->has_ipv6;
589 if (!ipv4 || !ipv6) {
590 qemu_opt_set_bool(opts, "ipv4", ipv4, &error_abort);
591 qemu_opt_set_bool(opts, "ipv6", ipv6, &error_abort);
593 if (addr->has_to) {
594 qemu_opt_set_number(opts, "to", addr->to, &error_abort);
596 qemu_opt_set(opts, "host", addr->host, &error_abort);
597 qemu_opt_set(opts, "port", addr->port, &error_abort);
600 int inet_listen(const char *str, char *ostr, int olen,
601 int socktype, int port_offset, Error **errp)
603 QemuOpts *opts;
604 char *optstr;
605 int sock = -1;
606 InetSocketAddress *addr;
608 addr = inet_parse(str, errp);
609 if (addr != NULL) {
610 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
611 inet_addr_to_opts(opts, addr);
612 qapi_free_InetSocketAddress(addr);
613 sock = inet_listen_opts(opts, port_offset, errp);
614 if (sock != -1 && ostr) {
615 optstr = strchr(str, ',');
616 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
617 snprintf(ostr, olen, "[%s]:%s%s",
618 qemu_opt_get(opts, "host"),
619 qemu_opt_get(opts, "port"),
620 optstr ? optstr : "");
621 } else {
622 snprintf(ostr, olen, "%s:%s%s",
623 qemu_opt_get(opts, "host"),
624 qemu_opt_get(opts, "port"),
625 optstr ? optstr : "");
628 qemu_opts_del(opts);
630 return sock;
634 * Create a blocking socket and connect it to an address.
636 * @str: address string
637 * @errp: set in case of an error
639 * Returns -1 in case of error, file descriptor on success
641 int inet_connect(const char *str, Error **errp)
643 QemuOpts *opts;
644 int sock = -1;
645 InetSocketAddress *addr;
647 addr = inet_parse(str, errp);
648 if (addr != NULL) {
649 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
650 inet_addr_to_opts(opts, addr);
651 qapi_free_InetSocketAddress(addr);
652 sock = inet_connect_opts(opts, errp, NULL, NULL);
653 qemu_opts_del(opts);
655 return sock;
659 * Create a non-blocking socket and connect it to an address.
660 * Calls the callback function with fd in case of success or -1 in case of
661 * error.
663 * @str: address string
664 * @callback: callback function that is called when connect completes,
665 * cannot be NULL.
666 * @opaque: opaque for callback function
667 * @errp: set in case of an error
669 * Returns: -1 on immediate error, file descriptor on success.
671 int inet_nonblocking_connect(const char *str,
672 NonBlockingConnectHandler *callback,
673 void *opaque, Error **errp)
675 QemuOpts *opts;
676 int sock = -1;
677 InetSocketAddress *addr;
679 g_assert(callback != NULL);
681 addr = inet_parse(str, errp);
682 if (addr != NULL) {
683 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
684 inet_addr_to_opts(opts, addr);
685 qapi_free_InetSocketAddress(addr);
686 sock = inet_connect_opts(opts, errp, callback, opaque);
687 qemu_opts_del(opts);
689 return sock;
692 #ifndef _WIN32
694 int unix_listen_opts(QemuOpts *opts, Error **errp)
696 struct sockaddr_un un;
697 const char *path = qemu_opt_get(opts, "path");
698 int sock, fd;
700 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
701 if (sock < 0) {
702 error_setg_errno(errp, errno, "Failed to create Unix socket");
703 return -1;
706 memset(&un, 0, sizeof(un));
707 un.sun_family = AF_UNIX;
708 if (path && strlen(path)) {
709 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
710 } else {
711 const char *tmpdir = getenv("TMPDIR");
712 tmpdir = tmpdir ? tmpdir : "/tmp";
713 if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
714 tmpdir) >= sizeof(un.sun_path)) {
715 error_setg_errno(errp, errno,
716 "TMPDIR environment variable (%s) too large", tmpdir);
717 goto err;
721 * This dummy fd usage silences the mktemp() unsecure warning.
722 * Using mkstemp() doesn't make things more secure here
723 * though. bind() complains about existing files, so we have
724 * to unlink first and thus re-open the race window. The
725 * worst case possible is bind() failing, i.e. a DoS attack.
727 fd = mkstemp(un.sun_path);
728 if (fd < 0) {
729 error_setg_errno(errp, errno,
730 "Failed to make a temporary socket name in %s", tmpdir);
731 goto err;
733 close(fd);
734 qemu_opt_set(opts, "path", un.sun_path, &error_abort);
737 if ((access(un.sun_path, F_OK) == 0) &&
738 unlink(un.sun_path) < 0) {
739 error_setg_errno(errp, errno,
740 "Failed to unlink socket %s", un.sun_path);
741 goto err;
743 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
744 error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);
745 goto err;
747 if (listen(sock, 1) < 0) {
748 error_setg_errno(errp, errno, "Failed to listen on socket");
749 goto err;
752 return sock;
754 err:
755 closesocket(sock);
756 return -1;
759 int unix_connect_opts(QemuOpts *opts, Error **errp,
760 NonBlockingConnectHandler *callback, void *opaque)
762 struct sockaddr_un un;
763 const char *path = qemu_opt_get(opts, "path");
764 ConnectState *connect_state = NULL;
765 int sock, rc;
767 if (path == NULL) {
768 error_setg(errp, "unix connect: no path specified");
769 return -1;
772 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
773 if (sock < 0) {
774 error_setg_errno(errp, errno, "Failed to create socket");
775 return -1;
777 if (callback != NULL) {
778 connect_state = g_malloc0(sizeof(*connect_state));
779 connect_state->callback = callback;
780 connect_state->opaque = opaque;
781 qemu_set_nonblock(sock);
784 memset(&un, 0, sizeof(un));
785 un.sun_family = AF_UNIX;
786 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
788 /* connect to peer */
789 do {
790 rc = 0;
791 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
792 rc = -socket_error();
794 } while (rc == -EINTR);
796 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
797 connect_state->fd = sock;
798 qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);
799 return sock;
800 } else if (rc >= 0) {
801 /* non blocking socket immediate success, call callback */
802 if (callback != NULL) {
803 callback(sock, NULL, opaque);
807 if (rc < 0) {
808 error_setg_errno(errp, -rc, "Failed to connect socket");
809 close(sock);
810 sock = -1;
813 g_free(connect_state);
814 return sock;
817 #else
819 int unix_listen_opts(QemuOpts *opts, Error **errp)
821 error_setg(errp, "unix sockets are not available on windows");
822 errno = ENOTSUP;
823 return -1;
826 int unix_connect_opts(QemuOpts *opts, Error **errp,
827 NonBlockingConnectHandler *callback, void *opaque)
829 error_setg(errp, "unix sockets are not available on windows");
830 errno = ENOTSUP;
831 return -1;
833 #endif
835 /* compatibility wrapper */
836 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
838 QemuOpts *opts;
839 char *path, *optstr;
840 int sock, len;
842 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
844 optstr = strchr(str, ',');
845 if (optstr) {
846 len = optstr - str;
847 if (len) {
848 path = g_malloc(len+1);
849 snprintf(path, len+1, "%.*s", len, str);
850 qemu_opt_set(opts, "path", path, &error_abort);
851 g_free(path);
853 } else {
854 qemu_opt_set(opts, "path", str, &error_abort);
857 sock = unix_listen_opts(opts, errp);
859 if (sock != -1 && ostr)
860 snprintf(ostr, olen, "%s%s", qemu_opt_get(opts, "path"), optstr ? optstr : "");
861 qemu_opts_del(opts);
862 return sock;
865 int unix_connect(const char *path, Error **errp)
867 QemuOpts *opts;
868 int sock;
870 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
871 qemu_opt_set(opts, "path", path, &error_abort);
872 sock = unix_connect_opts(opts, errp, NULL, NULL);
873 qemu_opts_del(opts);
874 return sock;
878 int unix_nonblocking_connect(const char *path,
879 NonBlockingConnectHandler *callback,
880 void *opaque, Error **errp)
882 QemuOpts *opts;
883 int sock = -1;
885 g_assert(callback != NULL);
887 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
888 qemu_opt_set(opts, "path", path, &error_abort);
889 sock = unix_connect_opts(opts, errp, callback, opaque);
890 qemu_opts_del(opts);
891 return sock;
894 SocketAddress *socket_parse(const char *str, Error **errp)
896 SocketAddress *addr;
898 addr = g_new0(SocketAddress, 1);
899 if (strstart(str, "unix:", NULL)) {
900 if (str[5] == '\0') {
901 error_setg(errp, "invalid Unix socket address");
902 goto fail;
903 } else {
904 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
905 addr->q_unix = g_new(UnixSocketAddress, 1);
906 addr->q_unix->path = g_strdup(str + 5);
908 } else if (strstart(str, "fd:", NULL)) {
909 if (str[3] == '\0') {
910 error_setg(errp, "invalid file descriptor address");
911 goto fail;
912 } else {
913 addr->kind = SOCKET_ADDRESS_KIND_FD;
914 addr->fd = g_new(String, 1);
915 addr->fd->str = g_strdup(str + 3);
917 } else {
918 addr->kind = SOCKET_ADDRESS_KIND_INET;
919 addr->inet = inet_parse(str, errp);
920 if (addr->inet == NULL) {
921 goto fail;
924 return addr;
926 fail:
927 qapi_free_SocketAddress(addr);
928 return NULL;
931 int socket_connect(SocketAddress *addr, Error **errp,
932 NonBlockingConnectHandler *callback, void *opaque)
934 QemuOpts *opts;
935 int fd;
937 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
938 switch (addr->kind) {
939 case SOCKET_ADDRESS_KIND_INET:
940 inet_addr_to_opts(opts, addr->inet);
941 fd = inet_connect_opts(opts, errp, callback, opaque);
942 break;
944 case SOCKET_ADDRESS_KIND_UNIX:
945 qemu_opt_set(opts, "path", addr->q_unix->path, &error_abort);
946 fd = unix_connect_opts(opts, errp, callback, opaque);
947 break;
949 case SOCKET_ADDRESS_KIND_FD:
950 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
951 if (fd >= 0 && callback) {
952 qemu_set_nonblock(fd);
953 callback(fd, NULL, opaque);
955 break;
957 default:
958 abort();
960 qemu_opts_del(opts);
961 return fd;
964 int socket_listen(SocketAddress *addr, Error **errp)
966 QemuOpts *opts;
967 int fd;
969 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
970 switch (addr->kind) {
971 case SOCKET_ADDRESS_KIND_INET:
972 inet_addr_to_opts(opts, addr->inet);
973 fd = inet_listen_opts(opts, 0, errp);
974 break;
976 case SOCKET_ADDRESS_KIND_UNIX:
977 qemu_opt_set(opts, "path", addr->q_unix->path, &error_abort);
978 fd = unix_listen_opts(opts, errp);
979 break;
981 case SOCKET_ADDRESS_KIND_FD:
982 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
983 break;
985 default:
986 abort();
988 qemu_opts_del(opts);
989 return fd;
992 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
994 QemuOpts *opts;
995 int fd;
997 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
998 switch (remote->kind) {
999 case SOCKET_ADDRESS_KIND_INET:
1000 inet_addr_to_opts(opts, remote->inet);
1001 if (local) {
1002 qemu_opt_set(opts, "localaddr", local->inet->host, &error_abort);
1003 qemu_opt_set(opts, "localport", local->inet->port, &error_abort);
1005 fd = inet_dgram_opts(opts, errp);
1006 break;
1008 default:
1009 error_setg(errp, "socket type unsupported for datagram");
1010 fd = -1;
1012 qemu_opts_del(opts);
1013 return fd;