2 * inet and unix socket functions for qemu
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 /* used temporarily until all users are converted to QemuOpts */
34 QemuOptsList socket_optslist = {
36 .head = QTAILQ_HEAD_INITIALIZER(socket_optslist.head),
40 .type = QEMU_OPT_STRING,
43 .type = QEMU_OPT_STRING,
46 .type = QEMU_OPT_STRING,
49 .type = QEMU_OPT_NUMBER,
52 .type = QEMU_OPT_BOOL,
55 .type = QEMU_OPT_BOOL,
61 static int inet_getport(struct addrinfo *e)
63 struct sockaddr_in *i4;
64 struct sockaddr_in6 *i6;
66 switch (e->ai_family) {
68 i6 = (void*)e->ai_addr;
69 return ntohs(i6->sin6_port);
71 i4 = (void*)e->ai_addr;
72 return ntohs(i4->sin_port);
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) {
85 i6 = (void*)e->ai_addr;
86 i6->sin6_port = htons(port);
89 i4 = (void*)e->ai_addr;
90 i4->sin_port = htons(port);
95 const char *inet_strfamily(int family)
98 case PF_INET6: return "ipv6";
99 case PF_INET: return "ipv4";
100 case PF_UNIX: return "unix";
105 int inet_listen_opts(QemuOpts *opts, int port_offset, Error **errp)
107 struct addrinfo ai,*res,*e;
110 char uaddr[INET6_ADDRSTRLEN+1];
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");
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;
135 snprintf(port, sizeof(port), "%d", atoi(port) + port_offset);
136 rc = getaddrinfo(strlen(addr) ? addr : NULL, port, &ai, &res);
138 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
143 /* create socket + bind */
144 for (e = res; e != NULL; e = e->ai_next) {
145 getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
146 uaddr,INET6_ADDRSTRLEN,uport,32,
147 NI_NUMERICHOST | NI_NUMERICSERV);
148 slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);
151 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
156 socket_set_fast_reuse(slisten);
158 if (e->ai_family == PF_INET6) {
159 /* listen on both ipv4 and ipv6 */
161 qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,
166 port_min = inet_getport(e);
167 port_max = to ? to + port_offset : port_min;
168 for (p = port_min; p <= port_max; p++) {
170 if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
175 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
179 closesocket(slisten);
185 if (listen(slisten,1) != 0) {
186 error_set_errno(errp, errno, QERR_SOCKET_LISTEN_FAILED);
187 closesocket(slisten);
191 snprintf(uport, sizeof(uport), "%d", inet_getport(e) - port_offset);
192 qemu_opt_set(opts, "host", uaddr);
193 qemu_opt_set(opts, "port", uport);
194 qemu_opt_set(opts, "ipv6", (e->ai_family == PF_INET6) ? "on" : "off");
195 qemu_opt_set(opts, "ipv4", (e->ai_family != PF_INET6) ? "on" : "off");
201 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
202 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
204 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
205 ((rc) == -EINPROGRESS)
208 /* Struct to store connect state for non blocking connect */
209 typedef struct ConnectState {
211 struct addrinfo *addr_list;
212 struct addrinfo *current_addr;
213 NonBlockingConnectHandler *callback;
217 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
218 ConnectState *connect_state, Error **errp);
220 static void wait_for_connect(void *opaque)
222 ConnectState *s = opaque;
224 socklen_t valsize = sizeof(val);
227 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
230 rc = qemu_getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &val, &valsize);
231 } while (rc == -1 && socket_error() == EINTR);
233 /* update rc to contain error */
244 /* try to connect to the next address on the list */
245 if (s->current_addr) {
246 while (s->current_addr->ai_next != NULL && s->fd < 0) {
247 s->current_addr = s->current_addr->ai_next;
248 s->fd = inet_connect_addr(s->current_addr, &in_progress, s, NULL);
249 /* connect in progress */
255 freeaddrinfo(s->addr_list);
259 s->callback(s->fd, s->opaque);
264 static int inet_connect_addr(struct addrinfo *addr, bool *in_progress,
265 ConnectState *connect_state, Error **errp)
269 *in_progress = false;
271 sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
273 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
276 socket_set_fast_reuse(sock);
277 if (connect_state != NULL) {
278 qemu_set_nonblock(sock);
280 /* connect to peer */
283 if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {
284 rc = -socket_error();
286 } while (rc == -EINTR);
288 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
289 connect_state->fd = sock;
290 qemu_set_fd_handler2(sock, NULL, NULL, wait_for_connect,
294 error_set_errno(errp, errno, QERR_SOCKET_CONNECT_FAILED);
301 static struct addrinfo *inet_parse_connect_opts(QemuOpts *opts, Error **errp)
303 struct addrinfo ai, *res;
308 memset(&ai, 0, sizeof(ai));
310 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
311 ai.ai_family = PF_UNSPEC;
312 ai.ai_socktype = SOCK_STREAM;
314 addr = qemu_opt_get(opts, "host");
315 port = qemu_opt_get(opts, "port");
316 if (addr == NULL || port == NULL) {
317 error_setg(errp, "host and/or port not specified");
321 if (qemu_opt_get_bool(opts, "ipv4", 0)) {
322 ai.ai_family = PF_INET;
324 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
325 ai.ai_family = PF_INET6;
329 rc = getaddrinfo(addr, port, &ai, &res);
331 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
339 * Create a socket and connect it to an address.
341 * @opts: QEMU options, recognized parameters strings "host" and "port",
342 * bools "ipv4" and "ipv6".
343 * @errp: set on error
344 * @callback: callback function for non-blocking connect
345 * @opaque: opaque for callback function
347 * Returns: -1 on error, file descriptor on success.
349 * If @callback is non-null, the connect is non-blocking. If this
350 * function succeeds, callback will be called when the connection
351 * completes, with the file descriptor on success, or -1 on error.
353 int inet_connect_opts(QemuOpts *opts, Error **errp,
354 NonBlockingConnectHandler *callback, void *opaque)
356 Error *local_err = NULL;
357 struct addrinfo *res, *e;
360 ConnectState *connect_state = NULL;
362 res = inet_parse_connect_opts(opts, errp);
367 if (callback != NULL) {
368 connect_state = g_malloc0(sizeof(*connect_state));
369 connect_state->addr_list = res;
370 connect_state->callback = callback;
371 connect_state->opaque = opaque;
374 for (e = res; e != NULL; e = e->ai_next) {
375 error_free(local_err);
377 if (connect_state != NULL) {
378 connect_state->current_addr = e;
380 sock = inet_connect_addr(e, &in_progress, connect_state, &local_err);
387 error_propagate(errp, local_err);
388 } else if (in_progress) {
389 /* wait_for_connect() will do the rest */
393 callback(sock, opaque);
396 g_free(connect_state);
401 int inet_dgram_opts(QemuOpts *opts, Error **errp)
403 struct addrinfo ai, *peer = NULL, *local = NULL;
408 /* lookup peer addr */
409 memset(&ai,0, sizeof(ai));
410 ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
411 ai.ai_family = PF_UNSPEC;
412 ai.ai_socktype = SOCK_DGRAM;
414 addr = qemu_opt_get(opts, "host");
415 port = qemu_opt_get(opts, "port");
416 if (addr == NULL || strlen(addr) == 0) {
419 if (port == NULL || strlen(port) == 0) {
420 error_setg(errp, "remote port not specified");
424 if (qemu_opt_get_bool(opts, "ipv4", 0))
425 ai.ai_family = PF_INET;
426 if (qemu_opt_get_bool(opts, "ipv6", 0))
427 ai.ai_family = PF_INET6;
429 if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {
430 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
435 /* lookup local addr */
436 memset(&ai,0, sizeof(ai));
437 ai.ai_flags = AI_PASSIVE;
438 ai.ai_family = peer->ai_family;
439 ai.ai_socktype = SOCK_DGRAM;
441 addr = qemu_opt_get(opts, "localaddr");
442 port = qemu_opt_get(opts, "localport");
443 if (addr == NULL || strlen(addr) == 0) {
446 if (!port || strlen(port) == 0)
449 if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {
450 error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,
456 sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);
458 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
461 socket_set_fast_reuse(sock);
464 if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {
465 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
469 /* connect to peer */
470 if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {
471 error_set_errno(errp, errno, QERR_SOCKET_CONNECT_FAILED);
489 /* compatibility wrapper */
490 InetSocketAddress *inet_parse(const char *str, Error **errp)
492 InetSocketAddress *addr;
493 const char *optstr, *h;
499 addr = g_new0(InetSocketAddress, 1);
505 if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {
506 error_setg(errp, "error parsing port in address '%s'", str);
509 } else if (str[0] == '[') {
511 if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {
512 error_setg(errp, "error parsing IPv6 address '%s'", str);
515 addr->ipv6 = addr->has_ipv6 = true;
517 /* hostname or IPv4 addr */
518 if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {
519 error_setg(errp, "error parsing address '%s'", str);
522 if (host[strspn(host, "0123456789.")] == '\0') {
523 addr->ipv4 = addr->has_ipv4 = true;
527 addr->host = g_strdup(host);
528 addr->port = g_strdup(port);
532 h = strstr(optstr, ",to=");
535 if (sscanf(h, "%d%n", &to, &pos) != 1 ||
536 (h[pos] != '\0' && h[pos] != ',')) {
537 error_setg(errp, "error parsing to= argument");
543 if (strstr(optstr, ",ipv4")) {
544 addr->ipv4 = addr->has_ipv4 = true;
546 if (strstr(optstr, ",ipv6")) {
547 addr->ipv6 = addr->has_ipv6 = true;
552 qapi_free_InetSocketAddress(addr);
556 static void inet_addr_to_opts(QemuOpts *opts, const InetSocketAddress *addr)
558 bool ipv4 = addr->ipv4 || !addr->has_ipv4;
559 bool ipv6 = addr->ipv6 || !addr->has_ipv6;
561 if (!ipv4 || !ipv6) {
562 qemu_opt_set_bool(opts, "ipv4", ipv4);
563 qemu_opt_set_bool(opts, "ipv6", ipv6);
567 snprintf(to, sizeof(to), "%d", addr->to);
568 qemu_opt_set(opts, "to", to);
570 qemu_opt_set(opts, "host", addr->host);
571 qemu_opt_set(opts, "port", addr->port);
574 int inet_listen(const char *str, char *ostr, int olen,
575 int socktype, int port_offset, Error **errp)
580 InetSocketAddress *addr;
582 addr = inet_parse(str, errp);
584 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
585 inet_addr_to_opts(opts, addr);
586 qapi_free_InetSocketAddress(addr);
587 sock = inet_listen_opts(opts, port_offset, errp);
588 if (sock != -1 && ostr) {
589 optstr = strchr(str, ',');
590 if (qemu_opt_get_bool(opts, "ipv6", 0)) {
591 snprintf(ostr, olen, "[%s]:%s%s",
592 qemu_opt_get(opts, "host"),
593 qemu_opt_get(opts, "port"),
594 optstr ? optstr : "");
596 snprintf(ostr, olen, "%s:%s%s",
597 qemu_opt_get(opts, "host"),
598 qemu_opt_get(opts, "port"),
599 optstr ? optstr : "");
608 * Create a blocking socket and connect it to an address.
610 * @str: address string
611 * @errp: set in case of an error
613 * Returns -1 in case of error, file descriptor on success
615 int inet_connect(const char *str, Error **errp)
619 InetSocketAddress *addr;
621 addr = inet_parse(str, errp);
623 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
624 inet_addr_to_opts(opts, addr);
625 qapi_free_InetSocketAddress(addr);
626 sock = inet_connect_opts(opts, errp, NULL, NULL);
633 * Create a non-blocking socket and connect it to an address.
634 * Calls the callback function with fd in case of success or -1 in case of
637 * @str: address string
638 * @callback: callback function that is called when connect completes,
640 * @opaque: opaque for callback function
641 * @errp: set in case of an error
643 * Returns: -1 on immediate error, file descriptor on success.
645 int inet_nonblocking_connect(const char *str,
646 NonBlockingConnectHandler *callback,
647 void *opaque, Error **errp)
651 InetSocketAddress *addr;
653 g_assert(callback != NULL);
655 addr = inet_parse(str, errp);
657 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
658 inet_addr_to_opts(opts, addr);
659 qapi_free_InetSocketAddress(addr);
660 sock = inet_connect_opts(opts, errp, callback, opaque);
668 int unix_listen_opts(QemuOpts *opts, Error **errp)
670 struct sockaddr_un un;
671 const char *path = qemu_opt_get(opts, "path");
674 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
676 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
680 memset(&un, 0, sizeof(un));
681 un.sun_family = AF_UNIX;
682 if (path && strlen(path)) {
683 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
685 char *tmpdir = getenv("TMPDIR");
686 snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",
687 tmpdir ? tmpdir : "/tmp");
689 * This dummy fd usage silences the mktemp() unsecure warning.
690 * Using mkstemp() doesn't make things more secure here
691 * though. bind() complains about existing files, so we have
692 * to unlink first and thus re-open the race window. The
693 * worst case possible is bind() failing, i.e. a DoS attack.
695 fd = mkstemp(un.sun_path); close(fd);
696 qemu_opt_set(opts, "path", un.sun_path);
700 if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {
701 error_set_errno(errp, errno, QERR_SOCKET_BIND_FAILED);
704 if (listen(sock, 1) < 0) {
705 error_set_errno(errp, errno, QERR_SOCKET_LISTEN_FAILED);
716 int unix_connect_opts(QemuOpts *opts, Error **errp,
717 NonBlockingConnectHandler *callback, void *opaque)
719 struct sockaddr_un un;
720 const char *path = qemu_opt_get(opts, "path");
721 ConnectState *connect_state = NULL;
725 error_setg(errp, "unix connect: no path specified");
729 sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);
731 error_set_errno(errp, errno, QERR_SOCKET_CREATE_FAILED);
734 if (callback != NULL) {
735 connect_state = g_malloc0(sizeof(*connect_state));
736 connect_state->callback = callback;
737 connect_state->opaque = opaque;
738 qemu_set_nonblock(sock);
741 memset(&un, 0, sizeof(un));
742 un.sun_family = AF_UNIX;
743 snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);
745 /* connect to peer */
748 if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {
749 rc = -socket_error();
751 } while (rc == -EINTR);
753 if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {
754 connect_state->fd = sock;
755 qemu_set_fd_handler2(sock, NULL, NULL, wait_for_connect,
758 } else if (rc >= 0) {
759 /* non blocking socket immediate success, call callback */
760 if (callback != NULL) {
761 callback(sock, opaque);
766 error_set_errno(errp, -rc, QERR_SOCKET_CONNECT_FAILED);
771 g_free(connect_state);
777 int unix_listen_opts(QemuOpts *opts, Error **errp)
779 error_setg(errp, "unix sockets are not available on windows");
784 int unix_connect_opts(QemuOpts *opts, Error **errp,
785 NonBlockingConnectHandler *callback, void *opaque)
787 error_setg(errp, "unix sockets are not available on windows");
793 /* compatibility wrapper */
794 int unix_listen(const char *str, char *ostr, int olen, Error **errp)
800 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
802 optstr = strchr(str, ',');
806 path = g_malloc(len+1);
807 snprintf(path, len+1, "%.*s", len, str);
808 qemu_opt_set(opts, "path", path);
812 qemu_opt_set(opts, "path", str);
815 sock = unix_listen_opts(opts, errp);
817 if (sock != -1 && ostr)
818 snprintf(ostr, olen, "%s%s", qemu_opt_get(opts, "path"), optstr ? optstr : "");
823 int unix_connect(const char *path, Error **errp)
828 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
829 qemu_opt_set(opts, "path", path);
830 sock = unix_connect_opts(opts, errp, NULL, NULL);
836 int unix_nonblocking_connect(const char *path,
837 NonBlockingConnectHandler *callback,
838 void *opaque, Error **errp)
843 g_assert(callback != NULL);
845 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
846 qemu_opt_set(opts, "path", path);
847 sock = unix_connect_opts(opts, errp, callback, opaque);
852 SocketAddress *socket_parse(const char *str, Error **errp)
856 addr = g_new0(SocketAddress, 1);
857 if (strstart(str, "unix:", NULL)) {
858 if (str[5] == '\0') {
859 error_setg(errp, "invalid Unix socket address");
862 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
863 addr->q_unix = g_new(UnixSocketAddress, 1);
864 addr->q_unix->path = g_strdup(str + 5);
866 } else if (strstart(str, "fd:", NULL)) {
867 if (str[3] == '\0') {
868 error_setg(errp, "invalid file descriptor address");
871 addr->kind = SOCKET_ADDRESS_KIND_FD;
872 addr->fd = g_new(String, 1);
873 addr->fd->str = g_strdup(str + 3);
876 addr->kind = SOCKET_ADDRESS_KIND_INET;
877 addr->inet = inet_parse(str, errp);
878 if (addr->inet == NULL) {
885 qapi_free_SocketAddress(addr);
889 int socket_connect(SocketAddress *addr, Error **errp,
890 NonBlockingConnectHandler *callback, void *opaque)
895 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
896 switch (addr->kind) {
897 case SOCKET_ADDRESS_KIND_INET:
898 inet_addr_to_opts(opts, addr->inet);
899 fd = inet_connect_opts(opts, errp, callback, opaque);
902 case SOCKET_ADDRESS_KIND_UNIX:
903 qemu_opt_set(opts, "path", addr->q_unix->path);
904 fd = unix_connect_opts(opts, errp, callback, opaque);
907 case SOCKET_ADDRESS_KIND_FD:
908 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
909 if (fd >= 0 && callback) {
910 qemu_set_nonblock(fd);
911 callback(fd, opaque);
922 int socket_listen(SocketAddress *addr, Error **errp)
927 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
928 switch (addr->kind) {
929 case SOCKET_ADDRESS_KIND_INET:
930 inet_addr_to_opts(opts, addr->inet);
931 fd = inet_listen_opts(opts, 0, errp);
934 case SOCKET_ADDRESS_KIND_UNIX:
935 qemu_opt_set(opts, "path", addr->q_unix->path);
936 fd = unix_listen_opts(opts, errp);
939 case SOCKET_ADDRESS_KIND_FD:
940 fd = monitor_get_fd(cur_mon, addr->fd->str, errp);
950 int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)
955 opts = qemu_opts_create(&socket_optslist, NULL, 0, &error_abort);
956 switch (remote->kind) {
957 case SOCKET_ADDRESS_KIND_INET:
958 qemu_opt_set(opts, "host", remote->inet->host);
959 qemu_opt_set(opts, "port", remote->inet->port);
961 qemu_opt_set(opts, "localaddr", local->inet->host);
962 qemu_opt_set(opts, "localport", local->inet->port);
964 fd = inet_dgram_opts(opts, errp);
968 error_setg(errp, "socket type unsupported for datagram");