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.
25 #include "monitor/monitor.h"
26 #include "qemu/sockets.h"
27 #include "qemu/main-loop.h"
30 # define AI_ADDRCONFIG 0
33 static const int on=1, off=0;
35 /* used temporarily until all users are converted to QemuOpts */
36 QemuOptsList socket_optslist = {
38 .head = QTAILQ_HEAD_INITIALIZER(socket_optslist.head),
42 .type = QEMU_OPT_STRING,
45 .type = QEMU_OPT_STRING,
48 .type = QEMU_OPT_STRING,
51 .type = QEMU_OPT_NUMBER,
54 .type = QEMU_OPT_BOOL,
57 .type = QEMU_OPT_BOOL,
63 static int inet_getport(struct addrinfo *e)
65 struct sockaddr_in *i4;
66 struct sockaddr_in6 *i6;
68 switch (e->ai_family) {
70 i6 = (void*)e->ai_addr;
71 return ntohs(i6->sin6_port);
73 i4 = (void*)e->ai_addr;
74 return ntohs(i4->sin_port);
80 static void inet_setport(struct addrinfo *e, int port)
82 struct sockaddr_in *i4;
83 struct sockaddr_in6 *i6;
85 switch (e->ai_family) {
87 i6 = (void*)e->ai_addr;
88 i6->sin6_port = htons(port);
91 i4 = (void*)e->ai_addr;
92 i4->sin_port = htons(port);
97 const char *inet_strfamily(int family)
100 case PF_INET6: return "ipv6";
101 case PF_INET: return "ipv4";
102 case PF_UNIX: return "unix";
107 int inet_listen_opts(QemuOpts *opts, int port_offset, Error **errp)
109 struct addrinfo ai,*res,*e;
112 char uaddr[INET6_ADDRSTRLEN+1];
114 int slisten, rc, to, port_min, port_max, p;
116 memset(&ai,0, sizeof(ai));
117 ai.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
118 ai.ai_family = PF_UNSPEC;
119 ai.ai_socktype = SOCK_STREAM;
121 if ((qemu_opt_get(opts, "host") == NULL) ||
122 (qemu_opt_get(opts, "port") == NULL)) {
123 error_setg(errp, "host and/or port not specified");
126 pstrcpy(port, sizeof(port), qemu_opt_get(opts, "port"));
127 addr = qemu_opt_get(opts, "host");
129 to = qemu_opt_get_number(opts, "to", 0);
130 if (qemu_opt_get_bool(opts, "ipv4", 0))
131 ai.ai_family = PF_INET;
132 if (qemu_opt_get_bool(opts, "ipv6", 0))
133 ai.ai_family = PF_INET6;
137 snprintf(port, sizeof(port), "%d", atoi(port) + port_offset);
138 rc = getaddrinfo(strlen(addr) ? addr : NULL, port, &ai, &res);
140 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
145 /* create socket + bind */
146 for (e = res; e != NULL; e = e->ai_next) {
147 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
148 uaddr,INET6_ADDRSTRLEN,uport,32,
149 NI_NUMERICHOST | NI_NUMERICSERV);
150 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
153 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
158 qemu_setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
160 if (e->ai_family == PF_INET6) {
161 /* listen on both ipv4 and ipv6 */
162 qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,
167 port_min = inet_getport(e);
168 port_max = to ? to + port_offset : port_min;
169 for (p = port_min; p <= port_max; p++) {
171 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
176 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
180 closesocket(slisten);
186 if (listen(slisten,1) != 0) {
187 error_set_errno(errp, errno, QERR_SOCKET_LISTEN_FAILED);
188 closesocket(slisten);
192 snprintf(uport, sizeof(uport), "%d", inet_getport(e) - port_offset);
193 qemu_opt_set(opts, "host", uaddr);
194 qemu_opt_set(opts, "port", uport);
195 qemu_opt_set(opts, "ipv6", (e->ai_family == PF_INET6) ? "on" : "off");
196 qemu_opt_set(opts, "ipv4", (e->ai_family != PF_INET6) ? "on" : "off");
202 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
203 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
205 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
206 ((rc) == -EINPROGRESS)
209 /* Struct to store connect state for non blocking connect */
210 typedef struct ConnectState {
212 struct addrinfo *addr_list;
213 struct addrinfo *current_addr;
214 NonBlockingConnectHandler *callback;
218 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
219 ConnectState *connect_state, Error **errp);
221 static void wait_for_connect(void *opaque)
223 ConnectState *s = opaque;
225 socklen_t valsize = sizeof(val);
228 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
231 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
232 } while (rc == -1 && socket_error() == EINTR);
234 /* update rc to contain error */
245 /* try to connect to the next address on the list */
246 if (s->current_addr) {
247 while (s->current_addr->ai_next != NULL && s->fd < 0) {
248 s->current_addr = s->current_addr->ai_next;
249 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
250 /* connect in progress */
256 freeaddrinfo(s->addr_list);
260 s->callback(s->fd, s->opaque);
265 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
266 ConnectState *connect_state, Error **errp)
270 *in_progress = false;
272 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
274 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
277 qemu_setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
278 if (connect_state != NULL) {
279 qemu_set_nonblock(sock);
281 /* connect to peer */
284 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
285 rc = -socket_error();
287 } while (rc == -EINTR);
289 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
290 connect_state->fd = sock;
291 qemu_set_fd_handler2(sock, NULL, NULL, wait_for_connect,
295 error_set_errno(errp, errno, QERR_SOCKET_CONNECT_FAILED);
302 static struct addrinfo *inet_parse_connect_opts(QemuOpts *opts, Error **errp)
304 struct addrinfo ai, *res;
309 memset(&ai, 0, sizeof(ai));
311 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
312 ai.ai_family = PF_UNSPEC;
313 ai.ai_socktype = SOCK_STREAM;
315 addr = qemu_opt_get(opts, "host");
316 port = qemu_opt_get(opts, "port");
317 if (addr == NULL || port == NULL) {
318 error_setg(errp, "host and/or port not specified");
322 if (qemu_opt_get_bool(opts, "ipv4", 0)) {
323 ai.ai_family = PF_INET;
325 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
326 ai.ai_family = PF_INET6;
330 // for lookup loopback interface...
331 if (addr[0] == '\0') {
338 rc = getaddrinfo(addr, port, &ai, &res);
340 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
348 * Create a socket and connect it to an address.
350 * @opts: QEMU options, recognized parameters strings "host" and "port",
351 * bools "ipv4" and "ipv6".
352 * @errp: set on error
353 * @callback: callback function for non-blocking connect
354 * @opaque: opaque for callback function
356 * Returns: -1 on error, file descriptor on success.
358 * If @callback is non-null, the connect is non-blocking. If this
359 * function succeeds, callback will be called when the connection
360 * completes, with the file descriptor on success, or -1 on error.
362 int inet_connect_opts(QemuOpts *opts, Error **errp,
363 NonBlockingConnectHandler *callback, void *opaque)
365 struct addrinfo *res, *e;
368 ConnectState *connect_state = NULL;
370 res = inet_parse_connect_opts(opts, errp);
375 if (callback != NULL) {
376 connect_state = g_malloc0(sizeof(*connect_state));
377 connect_state->addr_list = res;
378 connect_state->callback = callback;
379 connect_state->opaque = opaque;
382 for (e = res; e != NULL; e = e->ai_next) {
383 if (error_is_set(errp)) {
387 if (connect_state != NULL) {
388 connect_state->current_addr = e;
390 sock = inet_connect_addr(e, &in_progress, connect_state, errp);
393 } else if (sock >= 0) {
394 /* non blocking socket immediate success, call callback */
395 if (callback != NULL) {
396 callback(sock, opaque);
401 g_free(connect_state);
406 int inet_dgram_opts(QemuOpts *opts, Error **errp)
408 struct addrinfo ai, *peer = NULL, *local = NULL;
413 /* lookup peer addr */
414 memset(&ai,0, sizeof(ai));
415 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
416 ai.ai_family = PF_UNSPEC;
417 ai.ai_socktype = SOCK_DGRAM;
419 addr = qemu_opt_get(opts, "host");
420 port = qemu_opt_get(opts, "port");
421 if (addr == NULL || strlen(addr) == 0) {
424 if (port == NULL || strlen(port) == 0) {
425 error_setg(errp, "remote port not specified");
429 if (qemu_opt_get_bool(opts, "ipv4", 0))
430 ai.ai_family = PF_INET;
431 if (qemu_opt_get_bool(opts, "ipv6", 0))
432 ai.ai_family = PF_INET6;
434 if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
435 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
440 /* lookup local addr */
441 memset(&ai,0, sizeof(ai));
442 ai.ai_flags = AI_PASSIVE;
443 ai.ai_family = peer->ai_family;
444 ai.ai_socktype = SOCK_DGRAM;
446 addr = qemu_opt_get(opts, "localaddr");
447 port = qemu_opt_get(opts, "localport");
448 if (addr == NULL || strlen(addr) == 0) {
451 if (!port || strlen(port) == 0)
454 if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
455 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
461 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
463 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
466 qemu_setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
469 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
470 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
474 /* connect to peer */
475 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
476 error_set_errno(errp, errno, QERR_SOCKET_CONNECT_FAILED);
494 /* compatibility wrapper */
495 InetSocketAddress *inet_parse(const char *str, Error **errp)
497 InetSocketAddress *addr;
498 const char *optstr, *h;
504 addr = g_new0(InetSocketAddress, 1);
510 if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
511 error_setg(errp, "error parsing port in address '%s'", str);
514 } else if (str[0] == '[') {
516 if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
517 error_setg(errp, "error parsing IPv6 address '%s'", str);
520 addr->ipv6 = addr->has_ipv6 = true;
522 /* hostname or IPv4 addr */
523 if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
524 error_setg(errp, "error parsing address '%s'", str);
527 if (host[strspn(host, "0123456789.")] == '\0') {
528 addr->ipv4 = addr->has_ipv4 = true;
532 addr->host = g_strdup(host);
533 addr->port = g_strdup(port);
537 h = strstr(optstr, ",to=");
540 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
541 (h[pos] != '\0' && h[pos] != ',')) {
542 error_setg(errp, "error parsing to= argument");
548 if (strstr(optstr, ",ipv4")) {
549 addr->ipv4 = addr->has_ipv4 = true;
551 if (strstr(optstr, ",ipv6")) {
552 addr->ipv6 = addr->has_ipv6 = true;
557 qapi_free_InetSocketAddress(addr);
561 static void inet_addr_to_opts(QemuOpts *opts, const InetSocketAddress *addr)
563 bool ipv4 = addr->ipv4 || !addr->has_ipv4;
564 bool ipv6 = addr->ipv6 || !addr->has_ipv6;
566 if (!ipv4 || !ipv6) {
567 qemu_opt_set_bool(opts, "ipv4", ipv4);
568 qemu_opt_set_bool(opts, "ipv6", ipv6);
572 snprintf(to, sizeof(to), "%d", addr->to);
573 qemu_opt_set(opts, "to", to);
575 qemu_opt_set(opts, "host", addr->host);
576 qemu_opt_set(opts, "port", addr->port);
579 int inet_listen(const char *str, char *ostr, int olen,
580 int socktype, int port_offset, Error **errp)
585 InetSocketAddress *addr;
587 addr = inet_parse(str, errp);
589 opts = qemu_opts_create_nofail(&socket_optslist);
590 inet_addr_to_opts(opts, addr);
591 qapi_free_InetSocketAddress(addr);
592 sock = inet_listen_opts(opts, port_offset, errp);
593 if (sock != -1 && ostr) {
594 optstr = strchr(str, ',');
595 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
596 snprintf(ostr, olen, "[%s]:%s%s",
597 qemu_opt_get(opts, "host"),
598 qemu_opt_get(opts, "port"),
599 optstr ? optstr : "");
601 snprintf(ostr, olen, "%s:%s%s",
602 qemu_opt_get(opts, "host"),
603 qemu_opt_get(opts, "port"),
604 optstr ? optstr : "");
613 * Create a blocking socket and connect it to an address.
615 * @str: address string
616 * @errp: set in case of an error
618 * Returns -1 in case of error, file descriptor on success
620 int inet_connect(const char *str, Error **errp)
624 InetSocketAddress *addr;
626 addr = inet_parse(str, errp);
628 opts = qemu_opts_create_nofail(&socket_optslist);
629 inet_addr_to_opts(opts, addr);
630 qapi_free_InetSocketAddress(addr);
631 sock = inet_connect_opts(opts, errp, NULL, NULL);
638 * Create a non-blocking socket and connect it to an address.
639 * Calls the callback function with fd in case of success or -1 in case of
642 * @str: address string
643 * @callback: callback function that is called when connect completes,
645 * @opaque: opaque for callback function
646 * @errp: set in case of an error
648 * Returns: -1 on immediate error, file descriptor on success.
650 int inet_nonblocking_connect(const char *str,
651 NonBlockingConnectHandler *callback,
652 void *opaque, Error **errp)
656 InetSocketAddress *addr;
658 g_assert(callback != NULL);
660 addr = inet_parse(str, errp);
662 opts = qemu_opts_create_nofail(&socket_optslist);
663 inet_addr_to_opts(opts, addr);
664 qapi_free_InetSocketAddress(addr);
665 sock = inet_connect_opts(opts, errp, callback, opaque);
673 int unix_listen_opts(QemuOpts *opts, Error **errp)
675 struct sockaddr_un un;
676 const char *path = qemu_opt_get(opts, "path");
679 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
681 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
685 memset(&un, 0, sizeof(un));
686 un.sun_family = AF_UNIX;
687 if (path && strlen(path)) {
688 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
690 char *tmpdir = getenv("TMPDIR");
691 snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
692 tmpdir ? tmpdir : "/tmp");
694 * This dummy fd usage silences the mktemp() unsecure warning.
695 * Using mkstemp() doesn't make things more secure here
696 * though. bind() complains about existing files, so we have
697 * to unlink first and thus re-open the race window. The
698 * worst case possible is bind() failing, i.e. a DoS attack.
700 fd = mkstemp(un.sun_path); close(fd);
701 qemu_opt_set(opts, "path", un.sun_path);
705 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
706 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
709 if (listen(sock, 1) < 0) {
710 error_set_errno(errp, errno, QERR_SOCKET_LISTEN_FAILED);
721 int unix_connect_opts(QemuOpts *opts, Error **errp,
722 NonBlockingConnectHandler *callback, void *opaque)
724 struct sockaddr_un un;
725 const char *path = qemu_opt_get(opts, "path");
726 ConnectState *connect_state = NULL;
730 error_setg(errp, "unix connect: no path specified");
734 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
736 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
739 if (callback != NULL) {
740 connect_state = g_malloc0(sizeof(*connect_state));
741 connect_state->callback = callback;
742 connect_state->opaque = opaque;
743 qemu_set_nonblock(sock);
746 memset(&un, 0, sizeof(un));
747 un.sun_family = AF_UNIX;
748 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
750 /* connect to peer */
753 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
754 rc = -socket_error();
756 } while (rc == -EINTR);
758 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
759 connect_state->fd = sock;
760 qemu_set_fd_handler2(sock, NULL, NULL, wait_for_connect,
763 } else if (rc >= 0) {
764 /* non blocking socket immediate success, call callback */
765 if (callback != NULL) {
766 callback(sock, opaque);
771 error_set_errno(errp, -rc, QERR_SOCKET_CONNECT_FAILED);
776 g_free(connect_state);
782 int unix_listen_opts(QemuOpts *opts, Error **errp)
784 error_setg(errp, "unix sockets are not available on windows");
789 int unix_connect_opts(QemuOpts *opts, Error **errp,
790 NonBlockingConnectHandler *callback, void *opaque)
792 error_setg(errp, "unix sockets are not available on windows");
798 /* compatibility wrapper */
799 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
805 opts = qemu_opts_create_nofail(&socket_optslist);
807 optstr = strchr(str, ',');
811 path = g_malloc(len+1);
812 snprintf(path, len+1, "%.*s", len, str);
813 qemu_opt_set(opts, "path", path);
817 qemu_opt_set(opts, "path", str);
820 sock = unix_listen_opts(opts, errp);
822 if (sock != -1 && ostr)
823 snprintf(ostr, olen, "%s%s", qemu_opt_get(opts, "path"), optstr ? optstr : "");
828 int unix_connect(const char *path, Error **errp)
833 opts = qemu_opts_create_nofail(&socket_optslist);
834 qemu_opt_set(opts, "path", path);
835 sock = unix_connect_opts(opts, errp, NULL, NULL);
841 int unix_nonblocking_connect(const char *path,
842 NonBlockingConnectHandler *callback,
843 void *opaque, Error **errp)
848 g_assert(callback != NULL);
850 opts = qemu_opts_create_nofail(&socket_optslist);
851 qemu_opt_set(opts, "path", path);
852 sock = unix_connect_opts(opts, errp, callback, opaque);
857 SocketAddress *socket_parse(const char *str, Error **errp)
859 SocketAddress *addr = NULL;
861 addr = g_new(SocketAddress, 1);
862 if (strstart(str, "unix:", NULL)) {
863 if (str[5] == '\0') {
864 error_setg(errp, "invalid Unix socket address");
867 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
868 addr->q_unix = g_new(UnixSocketAddress, 1);
869 addr->q_unix->path = g_strdup(str + 5);
871 } else if (strstart(str, "fd:", NULL)) {
872 if (str[3] == '\0') {
873 error_setg(errp, "invalid file descriptor address");
876 addr->kind = SOCKET_ADDRESS_KIND_FD;
877 addr->fd = g_new(String, 1);
878 addr->fd->str = g_strdup(str + 3);
881 addr->kind = SOCKET_ADDRESS_KIND_INET;
882 addr->inet = g_new(InetSocketAddress, 1);
883 addr->inet = inet_parse(str, errp);
884 if (addr->inet == NULL) {
891 qapi_free_SocketAddress(addr);
895 int socket_connect(SocketAddress *addr, Error **errp,
896 NonBlockingConnectHandler *callback, void *opaque)
901 opts = qemu_opts_create_nofail(&socket_optslist);
902 switch (addr->kind) {
903 case SOCKET_ADDRESS_KIND_INET:
904 inet_addr_to_opts(opts, addr->inet);
905 fd = inet_connect_opts(opts, errp, callback, opaque);
908 case SOCKET_ADDRESS_KIND_UNIX:
909 qemu_opt_set(opts, "path", addr->q_unix->path);
910 fd = unix_connect_opts(opts, errp, callback, opaque);
913 case SOCKET_ADDRESS_KIND_FD:
914 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
916 qemu_set_nonblock(fd);
917 callback(fd, opaque);
928 int socket_listen(SocketAddress *addr, Error **errp)
933 opts = qemu_opts_create_nofail(&socket_optslist);
934 switch (addr->kind) {
935 case SOCKET_ADDRESS_KIND_INET:
936 inet_addr_to_opts(opts, addr->inet);
937 fd = inet_listen_opts(opts, 0, errp);
940 case SOCKET_ADDRESS_KIND_UNIX:
941 qemu_opt_set(opts, "path", addr->q_unix->path);
942 fd = unix_listen_opts(opts, errp);
945 case SOCKET_ADDRESS_KIND_FD:
946 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
956 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
961 opts = qemu_opts_create_nofail(&socket_optslist);
962 switch (remote->kind) {
963 case SOCKET_ADDRESS_KIND_INET:
964 qemu_opt_set(opts, "host", remote->inet->host);
965 qemu_opt_set(opts, "port", remote->inet->port);
967 qemu_opt_set(opts, "localaddr", local->inet->host);
968 qemu_opt_set(opts, "localport", local->inet->port);
970 fd = inet_dgram_opts(opts, errp);
974 error_setg(errp, "socket type unsupported for datagram");