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 fprintf(stderr
, "%s: host and/or port not specified\n", __FUNCTION__
);
124 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
127 pstrcpy(port
, sizeof(port
), qemu_opt_get(opts
, "port"));
128 addr
= qemu_opt_get(opts
, "host");
130 to
= qemu_opt_get_number(opts
, "to", 0);
131 if (qemu_opt_get_bool(opts
, "ipv4", 0))
132 ai
.ai_family
= PF_INET
;
133 if (qemu_opt_get_bool(opts
, "ipv6", 0))
134 ai
.ai_family
= PF_INET6
;
138 snprintf(port
, sizeof(port
), "%d", atoi(port
) + port_offset
);
139 rc
= getaddrinfo(strlen(addr
) ? addr
: NULL
, port
, &ai
, &res
);
141 fprintf(stderr
,"getaddrinfo(%s,%s): %s\n", addr
, port
,
143 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
147 /* create socket + bind */
148 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
149 getnameinfo((struct sockaddr
*)e
->ai_addr
,e
->ai_addrlen
,
150 uaddr
,INET6_ADDRSTRLEN
,uport
,32,
151 NI_NUMERICHOST
| NI_NUMERICSERV
);
152 slisten
= qemu_socket(e
->ai_family
, e
->ai_socktype
, e
->ai_protocol
);
154 fprintf(stderr
,"%s: socket(%s): %s\n", __FUNCTION__
,
155 inet_strfamily(e
->ai_family
), strerror(errno
));
157 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
162 setsockopt(slisten
,SOL_SOCKET
,SO_REUSEADDR
,(void*)&on
,sizeof(on
));
164 if (e
->ai_family
== PF_INET6
) {
165 /* listen on both ipv4 and ipv6 */
166 setsockopt(slisten
,IPPROTO_IPV6
,IPV6_V6ONLY
,(void*)&off
,
171 port_min
= inet_getport(e
);
172 port_max
= to
? to
+ port_offset
: port_min
;
173 for (p
= port_min
; p
<= port_max
; p
++) {
175 if (bind(slisten
, e
->ai_addr
, e
->ai_addrlen
) == 0) {
179 fprintf(stderr
,"%s: bind(%s,%s,%d): %s\n", __FUNCTION__
,
180 inet_strfamily(e
->ai_family
), uaddr
, inet_getport(e
),
183 error_set(errp
, QERR_SOCKET_BIND_FAILED
);
187 closesocket(slisten
);
189 fprintf(stderr
, "%s: FAILED\n", __FUNCTION__
);
194 if (listen(slisten
,1) != 0) {
195 error_set(errp
, QERR_SOCKET_LISTEN_FAILED
);
197 closesocket(slisten
);
201 snprintf(uport
, sizeof(uport
), "%d", inet_getport(e
) - port_offset
);
202 qemu_opt_set(opts
, "host", uaddr
);
203 qemu_opt_set(opts
, "port", uport
);
204 qemu_opt_set(opts
, "ipv6", (e
->ai_family
== PF_INET6
) ? "on" : "off");
205 qemu_opt_set(opts
, "ipv4", (e
->ai_family
!= PF_INET6
) ? "on" : "off");
211 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
212 ((rc) == -EINPROGRESS || (rc) == -EWOULDBLOCK || (rc) == -WSAEALREADY)
214 #define QEMU_SOCKET_RC_INPROGRESS(rc) \
215 ((rc) == -EINPROGRESS)
218 /* Struct to store connect state for non blocking connect */
219 typedef struct ConnectState
{
221 struct addrinfo
*addr_list
;
222 struct addrinfo
*current_addr
;
223 NonBlockingConnectHandler
*callback
;
227 static int inet_connect_addr(struct addrinfo
*addr
, bool *in_progress
,
228 ConnectState
*connect_state
);
230 static void wait_for_connect(void *opaque
)
232 ConnectState
*s
= opaque
;
234 socklen_t valsize
= sizeof(val
);
237 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
240 rc
= getsockopt(s
->fd
, SOL_SOCKET
, SO_ERROR
, (void *) &val
, &valsize
);
241 } while (rc
== -1 && socket_error() == EINTR
);
243 /* update rc to contain error */
254 /* try to connect to the next address on the list */
255 while (s
->current_addr
->ai_next
!= NULL
&& s
->fd
< 0) {
256 s
->current_addr
= s
->current_addr
->ai_next
;
257 s
->fd
= inet_connect_addr(s
->current_addr
, &in_progress
, s
);
258 /* connect in progress */
264 freeaddrinfo(s
->addr_list
);
266 s
->callback(s
->fd
, s
->opaque
);
271 static int inet_connect_addr(struct addrinfo
*addr
, bool *in_progress
,
272 ConnectState
*connect_state
)
276 *in_progress
= false;
278 sock
= qemu_socket(addr
->ai_family
, addr
->ai_socktype
, addr
->ai_protocol
);
280 fprintf(stderr
, "%s: socket(%s): %s\n", __func__
,
281 inet_strfamily(addr
->ai_family
), strerror(errno
));
284 qemu_setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
285 if (connect_state
!= NULL
) {
286 socket_set_nonblock(sock
);
288 /* connect to peer */
291 if (connect(sock
, addr
->ai_addr
, addr
->ai_addrlen
) < 0) {
292 rc
= -socket_error();
294 } while (rc
== -EINTR
);
296 if (connect_state
!= NULL
&& QEMU_SOCKET_RC_INPROGRESS(rc
)) {
297 connect_state
->fd
= sock
;
298 qemu_set_fd_handler2(sock
, NULL
, NULL
, wait_for_connect
,
308 static struct addrinfo
*inet_parse_connect_opts(QemuOpts
*opts
, Error
**errp
)
310 struct addrinfo ai
, *res
;
315 memset(&ai
, 0, sizeof(ai
));
317 ai
.ai_flags
= AI_CANONNAME
| AI_ADDRCONFIG
;
318 ai
.ai_family
= PF_UNSPEC
;
319 ai
.ai_socktype
= SOCK_STREAM
;
321 addr
= qemu_opt_get(opts
, "host");
322 port
= qemu_opt_get(opts
, "port");
323 if (addr
== NULL
|| port
== NULL
) {
325 "inet_parse_connect_opts: host and/or port not specified\n");
326 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
330 if (qemu_opt_get_bool(opts
, "ipv4", 0)) {
331 ai
.ai_family
= PF_INET
;
333 if (qemu_opt_get_bool(opts
, "ipv6", 0)) {
334 ai
.ai_family
= PF_INET6
;
338 rc
= getaddrinfo(addr
, port
, &ai
, &res
);
340 fprintf(stderr
, "getaddrinfo(%s,%s): %s\n", addr
, port
,
342 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
349 * Create a socket and connect it to an address.
351 * @opts: QEMU options, recognized parameters strings "host" and "port",
352 * bools "ipv4" and "ipv6".
353 * @errp: set on error
354 * @callback: callback function for non-blocking connect
355 * @opaque: opaque for callback function
357 * Returns: -1 on error, file descriptor on success.
359 * If @callback is non-null, the connect is non-blocking. If this
360 * function succeeds, callback will be called when the connection
361 * completes, with the file descriptor on success, or -1 on error.
363 int inet_connect_opts(QemuOpts
*opts
, Error
**errp
,
364 NonBlockingConnectHandler
*callback
, void *opaque
)
366 struct addrinfo
*res
, *e
;
369 ConnectState
*connect_state
= NULL
;
371 res
= inet_parse_connect_opts(opts
, errp
);
376 if (callback
!= NULL
) {
377 connect_state
= g_malloc0(sizeof(*connect_state
));
378 connect_state
->addr_list
= res
;
379 connect_state
->callback
= callback
;
380 connect_state
->opaque
= opaque
;
383 for (e
= res
; e
!= NULL
; e
= e
->ai_next
) {
384 if (connect_state
!= NULL
) {
385 connect_state
->current_addr
= e
;
387 sock
= inet_connect_addr(e
, &in_progress
, connect_state
);
390 } else if (sock
>= 0) {
391 /* non blocking socket immediate success, call callback */
392 if (callback
!= NULL
) {
393 callback(sock
, opaque
);
399 error_set(errp
, QERR_SOCKET_CONNECT_FAILED
);
401 g_free(connect_state
);
406 int inet_dgram_opts(QemuOpts
*opts
, Error
**errp
)
408 struct addrinfo ai
, *peer
= NULL
, *local
= NULL
;
411 char uaddr
[INET6_ADDRSTRLEN
+1];
415 /* lookup peer addr */
416 memset(&ai
,0, sizeof(ai
));
417 ai
.ai_flags
= AI_CANONNAME
| AI_ADDRCONFIG
;
418 ai
.ai_family
= PF_UNSPEC
;
419 ai
.ai_socktype
= SOCK_DGRAM
;
421 addr
= qemu_opt_get(opts
, "host");
422 port
= qemu_opt_get(opts
, "port");
423 if (addr
== NULL
|| strlen(addr
) == 0) {
426 if (port
== NULL
|| strlen(port
) == 0) {
427 fprintf(stderr
, "inet_dgram: port not specified\n");
431 if (qemu_opt_get_bool(opts
, "ipv4", 0))
432 ai
.ai_family
= PF_INET
;
433 if (qemu_opt_get_bool(opts
, "ipv6", 0))
434 ai
.ai_family
= PF_INET6
;
436 if (0 != (rc
= getaddrinfo(addr
, port
, &ai
, &peer
))) {
437 fprintf(stderr
,"getaddrinfo(%s,%s): %s\n", addr
, port
,
442 /* lookup local addr */
443 memset(&ai
,0, sizeof(ai
));
444 ai
.ai_flags
= AI_PASSIVE
;
445 ai
.ai_family
= peer
->ai_family
;
446 ai
.ai_socktype
= SOCK_DGRAM
;
448 addr
= qemu_opt_get(opts
, "localaddr");
449 port
= qemu_opt_get(opts
, "localport");
450 if (addr
== NULL
|| strlen(addr
) == 0) {
453 if (!port
|| strlen(port
) == 0)
456 if (0 != (rc
= getaddrinfo(addr
, port
, &ai
, &local
))) {
457 fprintf(stderr
,"getaddrinfo(%s,%s): %s\n", addr
, port
,
463 sock
= qemu_socket(peer
->ai_family
, peer
->ai_socktype
, peer
->ai_protocol
);
465 fprintf(stderr
,"%s: socket(%s): %s\n", __FUNCTION__
,
466 inet_strfamily(peer
->ai_family
), strerror(errno
));
469 setsockopt(sock
,SOL_SOCKET
,SO_REUSEADDR
,(void*)&on
,sizeof(on
));
472 if (getnameinfo((struct sockaddr
*)local
->ai_addr
,local
->ai_addrlen
,
473 uaddr
,INET6_ADDRSTRLEN
,uport
,32,
474 NI_NUMERICHOST
| NI_NUMERICSERV
) != 0) {
475 fprintf(stderr
, "%s: getnameinfo: oops\n", __FUNCTION__
);
478 if (bind(sock
, local
->ai_addr
, local
->ai_addrlen
) < 0) {
479 fprintf(stderr
,"%s: bind(%s,%s,%d): OK\n", __FUNCTION__
,
480 inet_strfamily(local
->ai_family
), uaddr
, inet_getport(local
));
484 /* connect to peer */
485 if (getnameinfo((struct sockaddr
*)peer
->ai_addr
, peer
->ai_addrlen
,
486 uaddr
, INET6_ADDRSTRLEN
, uport
, 32,
487 NI_NUMERICHOST
| NI_NUMERICSERV
) != 0) {
488 fprintf(stderr
, "%s: getnameinfo: oops\n", __FUNCTION__
);
491 if (connect(sock
,peer
->ai_addr
,peer
->ai_addrlen
) < 0) {
492 fprintf(stderr
, "%s: connect(%s,%s,%s,%s): %s\n", __FUNCTION__
,
493 inet_strfamily(peer
->ai_family
),
494 peer
->ai_canonname
, uaddr
, uport
, strerror(errno
));
512 /* compatibility wrapper */
513 static int inet_parse(QemuOpts
*opts
, const char *str
)
515 const char *optstr
, *h
;
524 if (1 != sscanf(str
,":%32[^,]%n",port
,&pos
)) {
525 fprintf(stderr
, "%s: portonly parse error (%s)\n",
529 } else if (str
[0] == '[') {
531 if (2 != sscanf(str
,"[%64[^]]]:%32[^,]%n",addr
,port
,&pos
)) {
532 fprintf(stderr
, "%s: ipv6 parse error (%s)\n",
536 qemu_opt_set(opts
, "ipv6", "on");
537 } else if (qemu_isdigit(str
[0])) {
539 if (2 != sscanf(str
,"%64[0-9.]:%32[^,]%n",addr
,port
,&pos
)) {
540 fprintf(stderr
, "%s: ipv4 parse error (%s)\n",
544 qemu_opt_set(opts
, "ipv4", "on");
547 if (2 != sscanf(str
,"%64[^:]:%32[^,]%n",addr
,port
,&pos
)) {
548 fprintf(stderr
, "%s: hostname parse error (%s)\n",
553 qemu_opt_set(opts
, "host", addr
);
554 qemu_opt_set(opts
, "port", port
);
558 h
= strstr(optstr
, ",to=");
560 qemu_opt_set(opts
, "to", h
+4);
561 if (strstr(optstr
, ",ipv4"))
562 qemu_opt_set(opts
, "ipv4", "on");
563 if (strstr(optstr
, ",ipv6"))
564 qemu_opt_set(opts
, "ipv6", "on");
568 int inet_listen(const char *str
, char *ostr
, int olen
,
569 int socktype
, int port_offset
, Error
**errp
)
575 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
576 if (inet_parse(opts
, str
) == 0) {
577 sock
= inet_listen_opts(opts
, port_offset
, errp
);
578 if (sock
!= -1 && ostr
) {
579 optstr
= strchr(str
, ',');
580 if (qemu_opt_get_bool(opts
, "ipv6", 0)) {
581 snprintf(ostr
, olen
, "[%s]:%s%s",
582 qemu_opt_get(opts
, "host"),
583 qemu_opt_get(opts
, "port"),
584 optstr
? optstr
: "");
586 snprintf(ostr
, olen
, "%s:%s%s",
587 qemu_opt_get(opts
, "host"),
588 qemu_opt_get(opts
, "port"),
589 optstr
? optstr
: "");
593 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
600 * Create a blocking socket and connect it to an address.
602 * @str: address string
603 * @errp: set in case of an error
605 * Returns -1 in case of error, file descriptor on success
607 int inet_connect(const char *str
, Error
**errp
)
612 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
613 if (inet_parse(opts
, str
) == 0) {
614 sock
= inet_connect_opts(opts
, errp
, NULL
, NULL
);
616 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
623 * Create a non-blocking socket and connect it to an address.
624 * Calls the callback function with fd in case of success or -1 in case of
627 * @str: address string
628 * @callback: callback function that is called when connect completes,
630 * @opaque: opaque for callback function
631 * @errp: set in case of an error
633 * Returns: -1 on immediate error, file descriptor on success.
635 int inet_nonblocking_connect(const char *str
,
636 NonBlockingConnectHandler
*callback
,
637 void *opaque
, Error
**errp
)
642 g_assert(callback
!= NULL
);
644 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
645 if (inet_parse(opts
, str
) == 0) {
646 sock
= inet_connect_opts(opts
, errp
, callback
, opaque
);
648 error_set(errp
, QERR_SOCKET_CREATE_FAILED
);
656 int unix_listen_opts(QemuOpts
*opts
, Error
**errp
)
658 struct sockaddr_un un
;
659 const char *path
= qemu_opt_get(opts
, "path");
662 sock
= qemu_socket(PF_UNIX
, SOCK_STREAM
, 0);
664 perror("socket(unix)");
668 memset(&un
, 0, sizeof(un
));
669 un
.sun_family
= AF_UNIX
;
670 if (path
&& strlen(path
)) {
671 snprintf(un
.sun_path
, sizeof(un
.sun_path
), "%s", path
);
673 char *tmpdir
= getenv("TMPDIR");
674 snprintf(un
.sun_path
, sizeof(un
.sun_path
), "%s/qemu-socket-XXXXXX",
675 tmpdir
? tmpdir
: "/tmp");
677 * This dummy fd usage silences the mktemp() unsecure warning.
678 * Using mkstemp() doesn't make things more secure here
679 * though. bind() complains about existing files, so we have
680 * to unlink first and thus re-open the race window. The
681 * worst case possible is bind() failing, i.e. a DoS attack.
683 fd
= mkstemp(un
.sun_path
); close(fd
);
684 qemu_opt_set(opts
, "path", un
.sun_path
);
688 if (bind(sock
, (struct sockaddr
*) &un
, sizeof(un
)) < 0) {
689 fprintf(stderr
, "bind(unix:%s): %s\n", un
.sun_path
, strerror(errno
));
692 if (listen(sock
, 1) < 0) {
693 fprintf(stderr
, "listen(unix:%s): %s\n", un
.sun_path
, strerror(errno
));
704 int unix_connect_opts(QemuOpts
*opts
, Error
**errp
)
706 struct sockaddr_un un
;
707 const char *path
= qemu_opt_get(opts
, "path");
711 fprintf(stderr
, "unix connect: no path specified\n");
715 sock
= qemu_socket(PF_UNIX
, SOCK_STREAM
, 0);
717 perror("socket(unix)");
721 memset(&un
, 0, sizeof(un
));
722 un
.sun_family
= AF_UNIX
;
723 snprintf(un
.sun_path
, sizeof(un
.sun_path
), "%s", path
);
724 if (connect(sock
, (struct sockaddr
*) &un
, sizeof(un
)) < 0) {
725 fprintf(stderr
, "connect(unix:%s): %s\n", path
, strerror(errno
));
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
)
744 fprintf(stderr
, "unix sockets are not available on windows\n");
750 /* compatibility wrapper */
751 int unix_listen(const char *str
, char *ostr
, int olen
, Error
**errp
)
757 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
759 optstr
= strchr(str
, ',');
763 path
= g_malloc(len
+1);
764 snprintf(path
, len
+1, "%.*s", len
, str
);
765 qemu_opt_set(opts
, "path", path
);
769 qemu_opt_set(opts
, "path", str
);
772 sock
= unix_listen_opts(opts
, errp
);
774 if (sock
!= -1 && ostr
)
775 snprintf(ostr
, olen
, "%s%s", qemu_opt_get(opts
, "path"), optstr
? optstr
: "");
780 int unix_connect(const char *path
, Error
**errp
)
785 opts
= qemu_opts_create(&dummy_opts
, NULL
, 0, NULL
);
786 qemu_opt_set(opts
, "path", path
);
787 sock
= unix_connect_opts(opts
, errp
);
793 static void socket_cleanup(void)
799 int socket_init(void)
805 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
807 err
= WSAGetLastError();
808 fprintf(stderr
, "WSAStartup: %d\n", err
);
811 atexit(socket_cleanup
);