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 "qemu_socket.h"
26 #include "qemu-common.h" /* for qemu_isdigit */
27 #include "main-loop.h"
30 # define AI_ADDRCONFIG 0
33 static const int on
=1, off
=0;
35 /* used temporarely until all users are converted to QemuOpts */
36 static QemuOptsList dummy_opts
= {
38 .head
= QTAILQ_HEAD_INITIALIZER(dummy_opts
.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 setsockopt(slisten
,SOL_SOCKET
,SO_REUSEADDR
,(void*)&on
,sizeof(on
));
160 if (e
->ai_family
== PF_INET6
) {
161 /* listen on both ipv4 and ipv6 */
162 setsockopt(slisten
,IPPROTO_IPV6
,IPV6_V6ONLY
,(void*)&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
= getsockopt(s
->fd
, SOL_SOCKET
, SO_ERROR
, (void *) &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 socket_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 rc
= getaddrinfo(addr
, port
, &ai
, &res
);
332 error_setg(errp
, "address resolution failed for %s:%s: %s", addr
, port
,
340 * Create a socket and connect it to an address.
342 * @opts: QEMU options, recognized parameters strings "host" and "port",
343 * bools "ipv4" and "ipv6".
344 * @errp: set on error
345 * @callback: callback function for non-blocking connect
346 * @opaque: opaque for callback function
348 * Returns: -1 on error, file descriptor on success.
350 * If @callback is non-null, the connect is non-blocking. If this
351 * function succeeds, callback will be called when the connection
352 * completes, with the file descriptor on success, or -1 on error.
354 int inet_connect_opts(QemuOpts
*opts
, Error
**errp
,
355 NonBlockingConnectHandler
*callback
, void *opaque
)
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 if (connect_state
!= NULL
) {
376 connect_state
->current_addr
= e
;
378 sock
= inet_connect_addr(e
, &in_progress
, connect_state
, errp
);
381 } else if (sock
>= 0) {
382 /* non blocking socket immediate success, call callback */
383 if (callback
!= NULL
) {
384 callback(sock
, opaque
);
389 g_free(connect_state
);
394 int inet_dgram_opts(QemuOpts
*opts
, Error
**errp
)
396 struct addrinfo ai
, *peer
= NULL
, *local
= NULL
;
401 /* lookup peer addr */
402 memset(&ai
,0, sizeof(ai
));
403 ai
.ai_flags
= AI_CANONNAME
| AI_ADDRCONFIG
;
404 ai
.ai_family
= PF_UNSPEC
;
405 ai
.ai_socktype
= SOCK_DGRAM
;
407 addr
= qemu_opt_get(opts
, "host");
408 port
= qemu_opt_get(opts
, "port");
409 if (addr
== NULL
|| strlen(addr
) == 0) {
412 if (port
== NULL
|| strlen(port
) == 0) {
413 error_setg(errp
, "remote port not specified");
417 if (qemu_opt_get_bool(opts
, "ipv4", 0))
418 ai
.ai_family
= PF_INET
;
419 if (qemu_opt_get_bool(opts
, "ipv6", 0))
420 ai
.ai_family
= PF_INET6
;
422 if (0 != (rc
= getaddrinfo(addr
, port
, &ai
, &peer
))) {
423 error_setg(errp
, "address resolution failed for %s:%s: %s", addr
, port
,
428 /* lookup local addr */
429 memset(&ai
,0, sizeof(ai
));
430 ai
.ai_flags
= AI_PASSIVE
;
431 ai
.ai_family
= peer
->ai_family
;
432 ai
.ai_socktype
= SOCK_DGRAM
;
434 addr
= qemu_opt_get(opts
, "localaddr");
435 port
= qemu_opt_get(opts
, "localport");
436 if (addr
== NULL
|| strlen(addr
) == 0) {
439 if (!port
|| strlen(port
) == 0)
442 if (0 != (rc
= getaddrinfo(addr
, port
, &ai
, &local
))) {
443 error_setg(errp
, "address resolution failed for %s:%s: %s", addr
, port
,
449 sock
= qemu_socket(peer
->ai_family
, peer
->ai_socktype
, peer
->ai_protocol
);
451 error_set_errno(errp
, errno
, QERR_SOCKET_CREATE_FAILED
);
454 setsockopt(sock
,SOL_SOCKET
,SO_REUSEADDR
,(void*)&on
,sizeof(on
));
457 if (bind(sock
, local
->ai_addr
, local
->ai_addrlen
) < 0) {
458 error_set_errno(errp
, errno
, QERR_SOCKET_BIND_FAILED
);
462 /* connect to peer */
463 if (connect(sock
,peer
->ai_addr
,peer
->ai_addrlen
) < 0) {
464 error_set_errno(errp
, errno
, QERR_SOCKET_CONNECT_FAILED
);
482 /* compatibility wrapper */
483 static int inet_parse(QemuOpts
*opts
, const char *str
)
485 const char *optstr
, *h
;
494 if (1 != sscanf(str
,":%32[^,]%n",port
,&pos
)) {
495 fprintf(stderr
, "%s: portonly parse error (%s)\n",
499 } else if (str
[0] == '[') {
501 if (2 != sscanf(str
,"[%64[^]]]:%32[^,]%n",addr
,port
,&pos
)) {
502 fprintf(stderr
, "%s: ipv6 parse error (%s)\n",
506 qemu_opt_set(opts
, "ipv6", "on");
507 } else if (qemu_isdigit(str
[0])) {
509 if (2 != sscanf(str
,"%64[0-9.]:%32[^,]%n",addr
,port
,&pos
)) {
510 fprintf(stderr
, "%s: ipv4 parse error (%s)\n",
514 qemu_opt_set(opts
, "ipv4", "on");
517 if (2 != sscanf(str
,"%64[^:]:%32[^,]%n",addr
,port
,&pos
)) {
518 fprintf(stderr
, "%s: hostname parse error (%s)\n",
523 qemu_opt_set(opts
, "host", addr
);
524 qemu_opt_set(opts
, "port", port
);
528 h
= strstr(optstr
, ",to=");
530 qemu_opt_set(opts
, "to", h
+4);
531 if (strstr(optstr
, ",ipv4"))
532 qemu_opt_set(opts
, "ipv4", "on");
533 if (strstr(optstr
, ",ipv6"))
534 qemu_opt_set(opts
, "ipv6", "on");
538 int inet_listen(const char *str
, char *ostr
, int olen
,
539 int socktype
, int port_offset
, Error
**errp
)
545 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
546 if (inet_parse(opts
, str
) == 0) {
547 sock
= inet_listen_opts(opts
, port_offset
, errp
);
548 if (sock
!= -1 && ostr
) {
549 optstr
= strchr(str
, ',');
550 if (qemu_opt_get_bool(opts
, "ipv6", 0)) {
551 snprintf(ostr
, olen
, "[%s]:%s%s",
552 qemu_opt_get(opts
, "host"),
553 qemu_opt_get(opts
, "port"),
554 optstr
? optstr
: "");
556 snprintf(ostr
, olen
, "%s:%s%s",
557 qemu_opt_get(opts
, "host"),
558 qemu_opt_get(opts
, "port"),
559 optstr
? optstr
: "");
563 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
570 * Create a blocking socket and connect it to an address.
572 * @str: address string
573 * @errp: set in case of an error
575 * Returns -1 in case of error, file descriptor on success
577 int inet_connect(const char *str
, Error
**errp
)
582 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
583 if (inet_parse(opts
, str
) == 0) {
584 sock
= inet_connect_opts(opts
, errp
, NULL
, NULL
);
586 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
593 * Create a non-blocking socket and connect it to an address.
594 * Calls the callback function with fd in case of success or -1 in case of
597 * @str: address string
598 * @callback: callback function that is called when connect completes,
600 * @opaque: opaque for callback function
601 * @errp: set in case of an error
603 * Returns: -1 on immediate error, file descriptor on success.
605 int inet_nonblocking_connect(const char *str
,
606 NonBlockingConnectHandler
*callback
,
607 void *opaque
, Error
**errp
)
612 g_assert(callback
!= NULL
);
614 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
615 if (inet_parse(opts
, str
) == 0) {
616 sock
= inet_connect_opts(opts
, errp
, callback
, opaque
);
618 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
626 int unix_listen_opts(QemuOpts
*opts
, Error
**errp
)
628 struct sockaddr_un un
;
629 const char *path
= qemu_opt_get(opts
, "path");
632 sock
= qemu_socket(PF_UNIX
, SOCK_STREAM
, 0);
634 perror("socket(unix)");
638 memset(&un
, 0, sizeof(un
));
639 un
.sun_family
= AF_UNIX
;
640 if (path
&& strlen(path
)) {
641 snprintf(un
.sun_path
, sizeof(un
.sun_path
), "%s", path
);
643 char *tmpdir
= getenv("TMPDIR");
644 snprintf(un
.sun_path
, sizeof(un
.sun_path
), "%s/qemu-socket-XXXXXX",
645 tmpdir
? tmpdir
: "/tmp");
647 * This dummy fd usage silences the mktemp() unsecure warning.
648 * Using mkstemp() doesn't make things more secure here
649 * though. bind() complains about existing files, so we have
650 * to unlink first and thus re-open the race window. The
651 * worst case possible is bind() failing, i.e. a DoS attack.
653 fd
= mkstemp(un
.sun_path
); close(fd
);
654 qemu_opt_set(opts
, "path", un
.sun_path
);
658 if (bind(sock
, (struct sockaddr
*) &un
, sizeof(un
)) < 0) {
659 fprintf(stderr
, "bind(unix:%s): %s\n", un
.sun_path
, strerror(errno
));
662 if (listen(sock
, 1) < 0) {
663 fprintf(stderr
, "listen(unix:%s): %s\n", un
.sun_path
, strerror(errno
));
674 int unix_connect_opts(QemuOpts
*opts
, Error
**errp
,
675 NonBlockingConnectHandler
*callback
, void *opaque
)
677 struct sockaddr_un un
;
678 const char *path
= qemu_opt_get(opts
, "path");
679 ConnectState
*connect_state
= NULL
;
683 fprintf(stderr
, "unix connect: no path specified\n");
687 sock
= qemu_socket(PF_UNIX
, SOCK_STREAM
, 0);
689 perror("socket(unix)");
692 if (callback
!= NULL
) {
693 connect_state
= g_malloc0(sizeof(*connect_state
));
694 connect_state
->callback
= callback
;
695 connect_state
->opaque
= opaque
;
696 socket_set_nonblock(sock
);
699 memset(&un
, 0, sizeof(un
));
700 un
.sun_family
= AF_UNIX
;
701 snprintf(un
.sun_path
, sizeof(un
.sun_path
), "%s", path
);
703 /* connect to peer */
706 if (connect(sock
, (struct sockaddr
*) &un
, sizeof(un
)) < 0) {
707 rc
= -socket_error();
709 } while (rc
== -EINTR
);
711 if (connect_state
!= NULL
&& QEMU_SOCKET_RC_INPROGRESS(rc
)) {
712 connect_state
->fd
= sock
;
713 qemu_set_fd_handler2(sock
, NULL
, NULL
, wait_for_connect
,
716 } else if (rc
>= 0) {
717 /* non blocking socket immediate success, call callback */
718 if (callback
!= NULL
) {
719 callback(sock
, opaque
);
724 fprintf(stderr
, "connect(unix:%s): %s\n", path
, strerror(errno
));
729 g_free(connect_state
);
735 int unix_listen_opts(QemuOpts
*opts
, Error
**errp
)
737 fprintf(stderr
, "unix sockets are not available on windows\n");
742 int unix_connect_opts(QemuOpts
*opts
, Error
**errp
,
743 NonBlockingConnectHandler
*callback
, void *opaque
)
745 fprintf(stderr
, "unix sockets are not available on windows\n");
751 /* compatibility wrapper */
752 int unix_listen(const char *str
, char *ostr
, int olen
, Error
**errp
)
758 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
760 optstr
= strchr(str
, ',');
764 path
= g_malloc(len
+1);
765 snprintf(path
, len
+1, "%.*s", len
, str
);
766 qemu_opt_set(opts
, "path", path
);
770 qemu_opt_set(opts
, "path", str
);
773 sock
= unix_listen_opts(opts
, errp
);
775 if (sock
!= -1 && ostr
)
776 snprintf(ostr
, olen
, "%s%s", qemu_opt_get(opts
, "path"), optstr
? optstr
: "");
781 int unix_connect(const char *path
, Error
**errp
)
786 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
787 qemu_opt_set(opts
, "path", path
);
788 sock
= unix_connect_opts(opts
, errp
, NULL
, NULL
);
794 int unix_nonblocking_connect(const char *path
,
795 NonBlockingConnectHandler
*callback
,
796 void *opaque
, Error
**errp
)
801 g_assert(callback
!= NULL
);
803 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
804 qemu_opt_set(opts
, "path", path
);
805 sock
= unix_connect_opts(opts
, errp
, callback
, opaque
);
811 static void socket_cleanup(void)
817 int socket_init(void)
823 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
825 err
= WSAGetLastError();
826 fprintf(stderr
, "WSAStartup: %d\n", err
);
829 atexit(socket_cleanup
);