4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
26 #include "chardev/char.h"
27 #include "io/channel-socket.h"
28 #include "io/channel-tls.h"
29 #include "io/channel-websock.h"
30 #include "io/net-listener.h"
31 #include "qemu/error-report.h"
32 #include "qemu/module.h"
33 #include "qemu/option.h"
34 #include "qapi/error.h"
35 #include "qapi/clone-visitor.h"
36 #include "qapi/qapi-visit-sockets.h"
38 #include "chardev/char-io.h"
40 /***********************************************************/
43 #define TCP_MAX_FDS 16
48 } TCPChardevTelnetInit
;
51 TCP_CHARDEV_STATE_DISCONNECTED
,
52 TCP_CHARDEV_STATE_CONNECTING
,
53 TCP_CHARDEV_STATE_CONNECTED
,
58 QIOChannel
*ioc
; /* Client I/O channel */
59 QIOChannelSocket
*sioc
; /* Client master channel */
60 QIONetListener
*listener
;
62 QCryptoTLSCreds
*tls_creds
;
64 TCPChardevState state
;
69 size_t read_msgfds_num
;
71 size_t write_msgfds_num
;
77 GSource
*telnet_source
;
78 TCPChardevTelnetInit
*telnet_init
;
82 GSource
*reconnect_timer
;
83 int64_t reconnect_time
;
84 bool connect_err_reported
;
86 QIOTask
*connect_task
;
89 #define SOCKET_CHARDEV(obj) \
90 OBJECT_CHECK(SocketChardev, (obj), TYPE_CHARDEV_SOCKET)
92 static gboolean
socket_reconnect_timeout(gpointer opaque
);
93 static void tcp_chr_telnet_init(Chardev
*chr
);
95 static void tcp_chr_change_state(SocketChardev
*s
, TCPChardevState state
)
98 case TCP_CHARDEV_STATE_DISCONNECTED
:
100 case TCP_CHARDEV_STATE_CONNECTING
:
101 assert(s
->state
== TCP_CHARDEV_STATE_DISCONNECTED
);
103 case TCP_CHARDEV_STATE_CONNECTED
:
104 assert(s
->state
== TCP_CHARDEV_STATE_CONNECTING
);
110 static void tcp_chr_reconn_timer_cancel(SocketChardev
*s
)
112 if (s
->reconnect_timer
) {
113 g_source_destroy(s
->reconnect_timer
);
114 g_source_unref(s
->reconnect_timer
);
115 s
->reconnect_timer
= NULL
;
119 static void qemu_chr_socket_restart_timer(Chardev
*chr
)
121 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
124 assert(s
->state
== TCP_CHARDEV_STATE_DISCONNECTED
);
125 assert(!s
->reconnect_timer
);
126 name
= g_strdup_printf("chardev-socket-reconnect-%s", chr
->label
);
127 s
->reconnect_timer
= qemu_chr_timeout_add_ms(chr
,
128 s
->reconnect_time
* 1000,
129 socket_reconnect_timeout
,
131 g_source_set_name(s
->reconnect_timer
, name
);
135 static void check_report_connect_error(Chardev
*chr
,
138 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
140 if (!s
->connect_err_reported
) {
141 error_reportf_err(err
,
142 "Unable to connect character device %s: ",
144 s
->connect_err_reported
= true;
148 qemu_chr_socket_restart_timer(chr
);
151 static void tcp_chr_accept(QIONetListener
*listener
,
152 QIOChannelSocket
*cioc
,
155 static int tcp_chr_read_poll(void *opaque
);
156 static void tcp_chr_disconnect_locked(Chardev
*chr
);
158 /* Called with chr_write_lock held. */
159 static int tcp_chr_write(Chardev
*chr
, const uint8_t *buf
, int len
)
161 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
163 if (s
->state
== TCP_CHARDEV_STATE_CONNECTED
) {
164 int ret
= io_channel_send_full(s
->ioc
, buf
, len
,
166 s
->write_msgfds_num
);
168 /* free the written msgfds in any cases
169 * other than ret < 0 && errno == EAGAIN
171 if (!(ret
< 0 && EAGAIN
== errno
)
172 && s
->write_msgfds_num
) {
173 g_free(s
->write_msgfds
);
175 s
->write_msgfds_num
= 0;
178 if (ret
< 0 && errno
!= EAGAIN
) {
179 if (tcp_chr_read_poll(chr
) <= 0) {
180 /* Perform disconnect and return error. */
181 tcp_chr_disconnect_locked(chr
);
182 } /* else let the read handler finish it properly */
187 /* Indicate an error. */
193 static int tcp_chr_read_poll(void *opaque
)
195 Chardev
*chr
= CHARDEV(opaque
);
196 SocketChardev
*s
= SOCKET_CHARDEV(opaque
);
197 if (s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) {
200 s
->max_size
= qemu_chr_be_can_write(chr
);
204 static void tcp_chr_process_IAC_bytes(Chardev
*chr
,
206 uint8_t *buf
, int *size
)
208 /* Handle any telnet or tn3270 client's basic IAC options.
209 * For telnet options, it satisfies char by char mode with no echo.
210 * For tn3270 options, it satisfies binary mode with EOR.
211 * All IAC options will be removed from the buf and the do_opt
212 * pointer will be used to track the state of the width of the
215 * RFC854: "All TELNET commands consist of at least a two byte sequence.
216 * The commands dealing with option negotiation are three byte sequences,
217 * the third byte being the code for the option referenced."
218 * "IAC BREAK", "IAC IP", "IAC NOP" and the double IAC are two bytes.
219 * "IAC SB", "IAC SE" and "IAC EOR" are saved to split up data boundary
221 * NOP, Break and Interrupt Process(IP) might be encountered during a TN3270
222 * session, and NOP and IP need to be done later.
228 for (i
= 0; i
< *size
; i
++) {
229 if (s
->do_telnetopt
> 1) {
230 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
231 /* Double IAC means send an IAC */
238 if ((unsigned char)buf
[i
] == IAC_BREAK
239 && s
->do_telnetopt
== 2) {
240 /* Handle IAC break commands by sending a serial break */
241 qemu_chr_be_event(chr
, CHR_EVENT_BREAK
);
243 } else if (s
->is_tn3270
&& ((unsigned char)buf
[i
] == IAC_EOR
244 || (unsigned char)buf
[i
] == IAC_SB
245 || (unsigned char)buf
[i
] == IAC_SE
)
246 && s
->do_telnetopt
== 2) {
250 } else if (s
->is_tn3270
&& ((unsigned char)buf
[i
] == IAC_IP
251 || (unsigned char)buf
[i
] == IAC_NOP
)
252 && s
->do_telnetopt
== 2) {
253 /* TODO: IP and NOP need to be implemented later. */
258 if (s
->do_telnetopt
>= 4) {
262 if ((unsigned char)buf
[i
] == IAC
) {
275 static int tcp_get_msgfds(Chardev
*chr
, int *fds
, int num
)
277 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
279 int to_copy
= (s
->read_msgfds_num
< num
) ? s
->read_msgfds_num
: num
;
281 assert(num
<= TCP_MAX_FDS
);
286 memcpy(fds
, s
->read_msgfds
, to_copy
* sizeof(int));
288 /* Close unused fds */
289 for (i
= to_copy
; i
< s
->read_msgfds_num
; i
++) {
290 close(s
->read_msgfds
[i
]);
293 g_free(s
->read_msgfds
);
295 s
->read_msgfds_num
= 0;
301 static int tcp_set_msgfds(Chardev
*chr
, int *fds
, int num
)
303 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
305 /* clear old pending fd array */
306 g_free(s
->write_msgfds
);
307 s
->write_msgfds
= NULL
;
308 s
->write_msgfds_num
= 0;
310 if ((s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) ||
311 !qio_channel_has_feature(s
->ioc
,
312 QIO_CHANNEL_FEATURE_FD_PASS
)) {
317 s
->write_msgfds
= g_new(int, num
);
318 memcpy(s
->write_msgfds
, fds
, num
* sizeof(int));
321 s
->write_msgfds_num
= num
;
326 static ssize_t
tcp_chr_recv(Chardev
*chr
, char *buf
, size_t len
)
328 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
329 struct iovec iov
= { .iov_base
= buf
, .iov_len
= len
};
333 size_t msgfds_num
= 0;
335 if (qio_channel_has_feature(s
->ioc
, QIO_CHANNEL_FEATURE_FD_PASS
)) {
336 ret
= qio_channel_readv_full(s
->ioc
, &iov
, 1,
337 &msgfds
, &msgfds_num
,
340 ret
= qio_channel_readv_full(s
->ioc
, &iov
, 1,
345 if (ret
== QIO_CHANNEL_ERR_BLOCK
) {
348 } else if (ret
== -1) {
353 /* close and clean read_msgfds */
354 for (i
= 0; i
< s
->read_msgfds_num
; i
++) {
355 close(s
->read_msgfds
[i
]);
358 if (s
->read_msgfds_num
) {
359 g_free(s
->read_msgfds
);
362 s
->read_msgfds
= msgfds
;
363 s
->read_msgfds_num
= msgfds_num
;
366 for (i
= 0; i
< s
->read_msgfds_num
; i
++) {
367 int fd
= s
->read_msgfds
[i
];
372 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
375 #ifndef MSG_CMSG_CLOEXEC
376 qemu_set_cloexec(fd
);
383 static GSource
*tcp_chr_add_watch(Chardev
*chr
, GIOCondition cond
)
385 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
386 return qio_channel_create_watch(s
->ioc
, cond
);
389 static void remove_hup_source(SocketChardev
*s
)
391 if (s
->hup_source
!= NULL
) {
392 g_source_destroy(s
->hup_source
);
393 g_source_unref(s
->hup_source
);
394 s
->hup_source
= NULL
;
398 static void tcp_chr_free_connection(Chardev
*chr
)
400 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
403 if (s
->read_msgfds_num
) {
404 for (i
= 0; i
< s
->read_msgfds_num
; i
++) {
405 close(s
->read_msgfds
[i
]);
407 g_free(s
->read_msgfds
);
408 s
->read_msgfds
= NULL
;
409 s
->read_msgfds_num
= 0;
412 remove_hup_source(s
);
414 tcp_set_msgfds(chr
, NULL
, 0);
415 remove_fd_in_watch(chr
);
416 object_unref(OBJECT(s
->sioc
));
418 object_unref(OBJECT(s
->ioc
));
420 g_free(chr
->filename
);
421 chr
->filename
= NULL
;
422 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_DISCONNECTED
);
425 static const char *qemu_chr_socket_protocol(SocketChardev
*s
)
430 return s
->is_websock
? "websocket" : "tcp";
433 static char *qemu_chr_socket_address(SocketChardev
*s
, const char *prefix
)
435 switch (s
->addr
->type
) {
436 case SOCKET_ADDRESS_TYPE_INET
:
437 return g_strdup_printf("%s%s:%s:%s%s", prefix
,
438 qemu_chr_socket_protocol(s
),
439 s
->addr
->u
.inet
.host
,
440 s
->addr
->u
.inet
.port
,
441 s
->is_listen
? ",server" : "");
443 case SOCKET_ADDRESS_TYPE_UNIX
:
444 return g_strdup_printf("%sunix:%s%s", prefix
,
445 s
->addr
->u
.q_unix
.path
,
446 s
->is_listen
? ",server" : "");
448 case SOCKET_ADDRESS_TYPE_FD
:
449 return g_strdup_printf("%sfd:%s%s", prefix
, s
->addr
->u
.fd
.str
,
450 s
->is_listen
? ",server" : "");
452 case SOCKET_ADDRESS_TYPE_VSOCK
:
453 return g_strdup_printf("%svsock:%s:%s", prefix
,
454 s
->addr
->u
.vsock
.cid
,
455 s
->addr
->u
.vsock
.port
);
461 static void update_disconnected_filename(SocketChardev
*s
)
463 Chardev
*chr
= CHARDEV(s
);
465 g_free(chr
->filename
);
467 chr
->filename
= qemu_chr_socket_address(s
, "disconnected:");
469 chr
->filename
= g_strdup("disconnected:socket");
473 /* NB may be called even if tcp_chr_connect has not been
474 * reached, due to TLS or telnet initialization failure,
475 * so can *not* assume s->state == TCP_CHARDEV_STATE_CONNECTED
476 * This must be called with chr->chr_write_lock held.
478 static void tcp_chr_disconnect_locked(Chardev
*chr
)
480 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
481 bool emit_close
= s
->state
== TCP_CHARDEV_STATE_CONNECTED
;
483 tcp_chr_free_connection(chr
);
486 qio_net_listener_set_client_func_full(s
->listener
, tcp_chr_accept
,
487 chr
, NULL
, chr
->gcontext
);
489 update_disconnected_filename(s
);
491 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
493 if (s
->reconnect_time
) {
494 qemu_chr_socket_restart_timer(chr
);
498 static void tcp_chr_disconnect(Chardev
*chr
)
500 qemu_mutex_lock(&chr
->chr_write_lock
);
501 tcp_chr_disconnect_locked(chr
);
502 qemu_mutex_unlock(&chr
->chr_write_lock
);
505 static gboolean
tcp_chr_read(QIOChannel
*chan
, GIOCondition cond
, void *opaque
)
507 Chardev
*chr
= CHARDEV(opaque
);
508 SocketChardev
*s
= SOCKET_CHARDEV(opaque
);
509 uint8_t buf
[CHR_READ_BUF_LEN
];
512 if ((s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) ||
517 if (len
> s
->max_size
) {
520 size
= tcp_chr_recv(chr
, (void *)buf
, len
);
521 if (size
== 0 || (size
== -1 && errno
!= EAGAIN
)) {
522 /* connection closed */
523 tcp_chr_disconnect(chr
);
524 } else if (size
> 0) {
525 if (s
->do_telnetopt
) {
526 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
529 qemu_chr_be_write(chr
, buf
, size
);
536 static gboolean
tcp_chr_hup(QIOChannel
*channel
,
540 Chardev
*chr
= CHARDEV(opaque
);
541 tcp_chr_disconnect(chr
);
542 return G_SOURCE_REMOVE
;
545 static int tcp_chr_sync_read(Chardev
*chr
, const uint8_t *buf
, int len
)
547 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
550 if (s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) {
554 qio_channel_set_blocking(s
->ioc
, true, NULL
);
555 size
= tcp_chr_recv(chr
, (void *) buf
, len
);
556 if (s
->state
!= TCP_CHARDEV_STATE_DISCONNECTED
) {
557 qio_channel_set_blocking(s
->ioc
, false, NULL
);
560 /* connection closed */
561 tcp_chr_disconnect(chr
);
567 static char *qemu_chr_compute_filename(SocketChardev
*s
)
569 struct sockaddr_storage
*ss
= &s
->sioc
->localAddr
;
570 struct sockaddr_storage
*ps
= &s
->sioc
->remoteAddr
;
571 socklen_t ss_len
= s
->sioc
->localAddrLen
;
572 socklen_t ps_len
= s
->sioc
->remoteAddrLen
;
573 char shost
[NI_MAXHOST
], sserv
[NI_MAXSERV
];
574 char phost
[NI_MAXHOST
], pserv
[NI_MAXSERV
];
575 const char *left
= "", *right
= "";
577 switch (ss
->ss_family
) {
580 return g_strdup_printf("unix:%s%s",
581 ((struct sockaddr_un
*)(ss
))->sun_path
,
582 s
->is_listen
? ",server" : "");
589 getnameinfo((struct sockaddr
*) ss
, ss_len
, shost
, sizeof(shost
),
590 sserv
, sizeof(sserv
), NI_NUMERICHOST
| NI_NUMERICSERV
);
591 getnameinfo((struct sockaddr
*) ps
, ps_len
, phost
, sizeof(phost
),
592 pserv
, sizeof(pserv
), NI_NUMERICHOST
| NI_NUMERICSERV
);
593 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
594 qemu_chr_socket_protocol(s
),
595 left
, shost
, right
, sserv
,
596 s
->is_listen
? ",server" : "",
597 left
, phost
, right
, pserv
);
600 return g_strdup_printf("unknown");
604 static void update_ioc_handlers(SocketChardev
*s
)
606 Chardev
*chr
= CHARDEV(s
);
608 if (s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) {
612 remove_fd_in_watch(chr
);
613 chr
->gsource
= io_add_watch_poll(chr
, s
->ioc
,
618 remove_hup_source(s
);
619 s
->hup_source
= qio_channel_create_watch(s
->ioc
, G_IO_HUP
);
620 g_source_set_callback(s
->hup_source
, (GSourceFunc
)tcp_chr_hup
,
622 g_source_attach(s
->hup_source
, chr
->gcontext
);
625 static void tcp_chr_connect(void *opaque
)
627 Chardev
*chr
= CHARDEV(opaque
);
628 SocketChardev
*s
= SOCKET_CHARDEV(opaque
);
630 g_free(chr
->filename
);
631 chr
->filename
= qemu_chr_compute_filename(s
);
633 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTED
);
634 update_ioc_handlers(s
);
635 qemu_chr_be_event(chr
, CHR_EVENT_OPENED
);
638 static void tcp_chr_telnet_destroy(SocketChardev
*s
)
640 if (s
->telnet_source
) {
641 g_source_destroy(s
->telnet_source
);
642 g_source_unref(s
->telnet_source
);
643 s
->telnet_source
= NULL
;
647 static void tcp_chr_update_read_handler(Chardev
*chr
)
649 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
651 if (s
->listener
&& s
->state
== TCP_CHARDEV_STATE_DISCONNECTED
) {
653 * It's possible that chardev context is changed in
654 * qemu_chr_be_update_read_handlers(). Reset it for QIO net
655 * listener if there is.
657 qio_net_listener_set_client_func_full(s
->listener
, tcp_chr_accept
,
658 chr
, NULL
, chr
->gcontext
);
661 if (s
->telnet_source
) {
662 tcp_chr_telnet_init(CHARDEV(s
));
665 update_ioc_handlers(s
);
668 static gboolean
tcp_chr_telnet_init_io(QIOChannel
*ioc
,
669 GIOCondition cond G_GNUC_UNUSED
,
672 SocketChardev
*s
= user_data
;
673 Chardev
*chr
= CHARDEV(s
);
674 TCPChardevTelnetInit
*init
= s
->telnet_init
;
679 ret
= qio_channel_write(ioc
, init
->buf
, init
->buflen
, NULL
);
681 if (ret
== QIO_CHANNEL_ERR_BLOCK
) {
684 tcp_chr_disconnect(chr
);
690 if (init
->buflen
== 0) {
691 tcp_chr_connect(chr
);
695 memmove(init
->buf
, init
->buf
+ ret
, init
->buflen
);
697 return G_SOURCE_CONTINUE
;
700 g_free(s
->telnet_init
);
701 s
->telnet_init
= NULL
;
702 g_source_unref(s
->telnet_source
);
703 s
->telnet_source
= NULL
;
704 return G_SOURCE_REMOVE
;
707 static void tcp_chr_telnet_init(Chardev
*chr
)
709 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
710 TCPChardevTelnetInit
*init
;
713 /* Destroy existing task */
714 tcp_chr_telnet_destroy(s
);
716 if (s
->telnet_init
) {
717 /* We are possibly during a handshake already */
721 s
->telnet_init
= g_new0(TCPChardevTelnetInit
, 1);
722 init
= s
->telnet_init
;
724 #define IACSET(x, a, b, c) \
733 /* Prep the telnet negotion to put telnet in binary,
734 * no echo, single char mode */
735 IACSET(init
->buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
736 IACSET(init
->buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
737 IACSET(init
->buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
738 IACSET(init
->buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
741 /* Prep the TN3270 negotion based on RFC1576 */
742 IACSET(init
->buf
, 0xff, 0xfd, 0x19); /* IAC DO EOR */
743 IACSET(init
->buf
, 0xff, 0xfb, 0x19); /* IAC WILL EOR */
744 IACSET(init
->buf
, 0xff, 0xfd, 0x00); /* IAC DO BINARY */
745 IACSET(init
->buf
, 0xff, 0xfb, 0x00); /* IAC WILL BINARY */
746 IACSET(init
->buf
, 0xff, 0xfd, 0x18); /* IAC DO TERMINAL TYPE */
747 IACSET(init
->buf
, 0xff, 0xfa, 0x18); /* IAC SB TERMINAL TYPE */
748 IACSET(init
->buf
, 0x01, 0xff, 0xf0); /* SEND IAC SE */
754 s
->telnet_source
= qio_channel_add_watch_source(s
->ioc
, G_IO_OUT
,
755 tcp_chr_telnet_init_io
,
761 static void tcp_chr_websock_handshake(QIOTask
*task
, gpointer user_data
)
763 Chardev
*chr
= user_data
;
764 SocketChardev
*s
= user_data
;
766 if (qio_task_propagate_error(task
, NULL
)) {
767 tcp_chr_disconnect(chr
);
769 if (s
->do_telnetopt
) {
770 tcp_chr_telnet_init(chr
);
772 tcp_chr_connect(chr
);
778 static void tcp_chr_websock_init(Chardev
*chr
)
780 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
781 QIOChannelWebsock
*wioc
= NULL
;
784 wioc
= qio_channel_websock_new_server(s
->ioc
);
786 name
= g_strdup_printf("chardev-websocket-server-%s", chr
->label
);
787 qio_channel_set_name(QIO_CHANNEL(wioc
), name
);
789 object_unref(OBJECT(s
->ioc
));
790 s
->ioc
= QIO_CHANNEL(wioc
);
792 qio_channel_websock_handshake(wioc
, tcp_chr_websock_handshake
, chr
, NULL
);
796 static void tcp_chr_tls_handshake(QIOTask
*task
,
799 Chardev
*chr
= user_data
;
800 SocketChardev
*s
= user_data
;
802 if (qio_task_propagate_error(task
, NULL
)) {
803 tcp_chr_disconnect(chr
);
806 tcp_chr_websock_init(chr
);
807 } else if (s
->do_telnetopt
) {
808 tcp_chr_telnet_init(chr
);
810 tcp_chr_connect(chr
);
816 static void tcp_chr_tls_init(Chardev
*chr
)
818 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
823 tioc
= qio_channel_tls_new_server(
824 s
->ioc
, s
->tls_creds
,
828 tioc
= qio_channel_tls_new_client(
829 s
->ioc
, s
->tls_creds
,
830 s
->addr
->u
.inet
.host
,
834 tcp_chr_disconnect(chr
);
837 name
= g_strdup_printf("chardev-tls-%s-%s",
838 s
->is_listen
? "server" : "client",
840 qio_channel_set_name(QIO_CHANNEL(tioc
), name
);
842 object_unref(OBJECT(s
->ioc
));
843 s
->ioc
= QIO_CHANNEL(tioc
);
845 qio_channel_tls_handshake(tioc
,
846 tcp_chr_tls_handshake
,
853 static void tcp_chr_set_client_ioc_name(Chardev
*chr
,
854 QIOChannelSocket
*sioc
)
856 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
858 name
= g_strdup_printf("chardev-tcp-%s-%s",
859 s
->is_listen
? "server" : "client",
861 qio_channel_set_name(QIO_CHANNEL(sioc
), name
);
866 static int tcp_chr_new_client(Chardev
*chr
, QIOChannelSocket
*sioc
)
868 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
870 if (s
->state
!= TCP_CHARDEV_STATE_CONNECTING
) {
874 s
->ioc
= QIO_CHANNEL(sioc
);
875 object_ref(OBJECT(sioc
));
877 object_ref(OBJECT(sioc
));
879 qio_channel_set_blocking(s
->ioc
, false, NULL
);
882 qio_channel_set_delay(s
->ioc
, false);
885 qio_net_listener_set_client_func_full(s
->listener
, NULL
, NULL
,
886 NULL
, chr
->gcontext
);
890 tcp_chr_tls_init(chr
);
891 } else if (s
->is_websock
) {
892 tcp_chr_websock_init(chr
);
893 } else if (s
->do_telnetopt
) {
894 tcp_chr_telnet_init(chr
);
896 tcp_chr_connect(chr
);
903 static int tcp_chr_add_client(Chardev
*chr
, int fd
)
906 QIOChannelSocket
*sioc
;
907 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
909 if (s
->state
!= TCP_CHARDEV_STATE_DISCONNECTED
) {
913 sioc
= qio_channel_socket_new_fd(fd
, NULL
);
917 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
918 tcp_chr_set_client_ioc_name(chr
, sioc
);
919 ret
= tcp_chr_new_client(chr
, sioc
);
920 object_unref(OBJECT(sioc
));
924 static void tcp_chr_accept(QIONetListener
*listener
,
925 QIOChannelSocket
*cioc
,
928 Chardev
*chr
= CHARDEV(opaque
);
929 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
931 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
932 tcp_chr_set_client_ioc_name(chr
, cioc
);
933 tcp_chr_new_client(chr
, cioc
);
937 static int tcp_chr_connect_client_sync(Chardev
*chr
, Error
**errp
)
939 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
940 QIOChannelSocket
*sioc
= qio_channel_socket_new();
941 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
942 tcp_chr_set_client_ioc_name(chr
, sioc
);
943 if (qio_channel_socket_connect_sync(sioc
, s
->addr
, errp
) < 0) {
944 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_DISCONNECTED
);
945 object_unref(OBJECT(sioc
));
948 tcp_chr_new_client(chr
, sioc
);
949 object_unref(OBJECT(sioc
));
954 static void tcp_chr_accept_server_sync(Chardev
*chr
)
956 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
957 QIOChannelSocket
*sioc
;
958 info_report("QEMU waiting for connection on: %s",
960 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
961 sioc
= qio_net_listener_wait_client(s
->listener
);
962 tcp_chr_set_client_ioc_name(chr
, sioc
);
963 tcp_chr_new_client(chr
, sioc
);
964 object_unref(OBJECT(sioc
));
968 static int tcp_chr_wait_connected(Chardev
*chr
, Error
**errp
)
970 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
971 const char *opts
[] = { "telnet", "tn3270", "websock", "tls-creds" };
972 bool optset
[] = { s
->is_telnet
, s
->is_tn3270
, s
->is_websock
, s
->tls_creds
};
975 QEMU_BUILD_BUG_ON(G_N_ELEMENTS(opts
) != G_N_ELEMENTS(optset
));
976 for (i
= 0; i
< G_N_ELEMENTS(opts
); i
++) {
979 "'%s' option is incompatible with waiting for "
980 "connection completion", opts
[i
]);
985 tcp_chr_reconn_timer_cancel(s
);
988 * We expect states to be as follows:
991 * - wait -> CONNECTED
992 * - nowait -> DISCONNECTED
994 * - reconnect == 0 -> CONNECTED
995 * - reconnect != 0 -> CONNECTING
998 if (s
->state
== TCP_CHARDEV_STATE_CONNECTING
) {
999 if (!s
->connect_task
) {
1001 "Unexpected 'connecting' state without connect task "
1002 "while waiting for connection completion");
1006 * tcp_chr_wait_connected should only ever be run from the
1007 * main loop thread associated with chr->gcontext, otherwise
1008 * qio_task_wait_thread has a dangerous race condition with
1009 * free'ing of the s->connect_task object.
1011 * Acquiring the main context doesn't 100% prove we're in
1012 * the main loop thread, but it does at least guarantee
1013 * that the main loop won't be executed by another thread
1014 * avoiding the race condition with the task idle callback.
1016 g_main_context_acquire(chr
->gcontext
);
1017 qio_task_wait_thread(s
->connect_task
);
1018 g_main_context_release(chr
->gcontext
);
1021 * The completion callback (qemu_chr_socket_connected) for
1022 * s->connect_task should have set this to NULL by the time
1023 * qio_task_wait_thread has returned.
1025 assert(!s
->connect_task
);
1028 * NB we are *not* guaranteed to have "s->state == ..CONNECTED"
1029 * at this point as this first connect may be failed, so
1030 * allow the next loop to run regardless.
1034 while (s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) {
1036 tcp_chr_accept_server_sync(chr
);
1039 if (tcp_chr_connect_client_sync(chr
, &err
) < 0) {
1040 if (s
->reconnect_time
) {
1042 g_usleep(s
->reconnect_time
* 1000ULL * 1000ULL);
1044 error_propagate(errp
, err
);
1054 static void char_socket_finalize(Object
*obj
)
1056 Chardev
*chr
= CHARDEV(obj
);
1057 SocketChardev
*s
= SOCKET_CHARDEV(obj
);
1059 tcp_chr_free_connection(chr
);
1060 tcp_chr_reconn_timer_cancel(s
);
1061 qapi_free_SocketAddress(s
->addr
);
1062 tcp_chr_telnet_destroy(s
);
1063 g_free(s
->telnet_init
);
1065 qio_net_listener_set_client_func_full(s
->listener
, NULL
, NULL
,
1066 NULL
, chr
->gcontext
);
1067 object_unref(OBJECT(s
->listener
));
1070 object_unref(OBJECT(s
->tls_creds
));
1072 g_free(s
->tls_authz
);
1074 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
1077 static void qemu_chr_socket_connected(QIOTask
*task
, void *opaque
)
1079 QIOChannelSocket
*sioc
= QIO_CHANNEL_SOCKET(qio_task_get_source(task
));
1080 Chardev
*chr
= CHARDEV(opaque
);
1081 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1084 s
->connect_task
= NULL
;
1086 if (qio_task_propagate_error(task
, &err
)) {
1087 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_DISCONNECTED
);
1088 check_report_connect_error(chr
, err
);
1092 s
->connect_err_reported
= false;
1093 tcp_chr_new_client(chr
, sioc
);
1096 object_unref(OBJECT(sioc
));
1100 static void tcp_chr_connect_client_task(QIOTask
*task
,
1103 QIOChannelSocket
*ioc
= QIO_CHANNEL_SOCKET(qio_task_get_source(task
));
1104 SocketAddress
*addr
= opaque
;
1107 qio_channel_socket_connect_sync(ioc
, addr
, &err
);
1109 qio_task_set_error(task
, err
);
1113 static void tcp_chr_connect_client_async(Chardev
*chr
)
1115 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1116 QIOChannelSocket
*sioc
;
1118 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
1119 sioc
= qio_channel_socket_new();
1120 tcp_chr_set_client_ioc_name(chr
, sioc
);
1122 * Normally code would use the qio_channel_socket_connect_async
1123 * method which uses a QIOTask + qio_task_set_error internally
1124 * to avoid blocking. The tcp_chr_wait_connected method, however,
1125 * needs a way to synchronize with completion of the background
1126 * connect task which can't be done with the QIOChannelSocket
1127 * async APIs. Thus we must use QIOTask directly to implement
1128 * the non-blocking concept locally.
1130 s
->connect_task
= qio_task_new(OBJECT(sioc
),
1131 qemu_chr_socket_connected
,
1133 qio_task_run_in_thread(s
->connect_task
,
1134 tcp_chr_connect_client_task
,
1140 static gboolean
socket_reconnect_timeout(gpointer opaque
)
1142 Chardev
*chr
= CHARDEV(opaque
);
1143 SocketChardev
*s
= SOCKET_CHARDEV(opaque
);
1145 qemu_mutex_lock(&chr
->chr_write_lock
);
1146 g_source_unref(s
->reconnect_timer
);
1147 s
->reconnect_timer
= NULL
;
1148 qemu_mutex_unlock(&chr
->chr_write_lock
);
1154 tcp_chr_connect_client_async(chr
);
1160 static int qmp_chardev_open_socket_server(Chardev
*chr
,
1162 bool is_waitconnect
,
1165 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1168 s
->do_telnetopt
= 1;
1170 s
->listener
= qio_net_listener_new();
1172 name
= g_strdup_printf("chardev-tcp-listener-%s", chr
->label
);
1173 qio_net_listener_set_name(s
->listener
, name
);
1176 if (qio_net_listener_open_sync(s
->listener
, s
->addr
, 1, errp
) < 0) {
1177 object_unref(OBJECT(s
->listener
));
1182 qapi_free_SocketAddress(s
->addr
);
1183 s
->addr
= socket_local_address(s
->listener
->sioc
[0]->fd
, errp
);
1184 update_disconnected_filename(s
);
1186 if (is_waitconnect
) {
1187 tcp_chr_accept_server_sync(chr
);
1189 qio_net_listener_set_client_func_full(s
->listener
,
1199 static int qmp_chardev_open_socket_client(Chardev
*chr
,
1203 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1205 if (reconnect
> 0) {
1206 s
->reconnect_time
= reconnect
;
1207 tcp_chr_connect_client_async(chr
);
1210 return tcp_chr_connect_client_sync(chr
, errp
);
1215 static bool qmp_chardev_validate_socket(ChardevSocket
*sock
,
1216 SocketAddress
*addr
,
1219 /* Validate any options which have a dependency on address type */
1220 switch (addr
->type
) {
1221 case SOCKET_ADDRESS_TYPE_FD
:
1222 if (sock
->has_reconnect
) {
1224 "'reconnect' option is incompatible with "
1225 "'fd' address type");
1228 if (sock
->has_tls_creds
&&
1229 !(sock
->has_server
&& sock
->server
)) {
1231 "'tls_creds' option is incompatible with "
1232 "'fd' address type as client");
1237 case SOCKET_ADDRESS_TYPE_UNIX
:
1238 if (sock
->has_tls_creds
) {
1240 "'tls_creds' option is incompatible with "
1241 "'unix' address type");
1246 case SOCKET_ADDRESS_TYPE_INET
:
1249 case SOCKET_ADDRESS_TYPE_VSOCK
:
1250 if (sock
->has_tls_creds
) {
1252 "'tls_creds' option is incompatible with "
1253 "'vsock' address type");
1261 if (sock
->has_tls_authz
&& !sock
->has_tls_creds
) {
1262 error_setg(errp
, "'tls_authz' option requires 'tls_creds' option");
1266 /* Validate any options which have a dependancy on client vs server */
1267 if (!sock
->has_server
|| sock
->server
) {
1268 if (sock
->has_reconnect
) {
1270 "'reconnect' option is incompatible with "
1271 "socket in server listen mode");
1275 if (sock
->has_websocket
&& sock
->websocket
) {
1276 error_setg(errp
, "%s", "Websocket client is not implemented");
1279 if (sock
->has_wait
) {
1280 warn_report("'wait' option is deprecated with "
1281 "socket in client connect mode");
1283 error_setg(errp
, "%s",
1284 "'wait' option is incompatible with "
1285 "socket in client connect mode");
1295 static void qmp_chardev_open_socket(Chardev
*chr
,
1296 ChardevBackend
*backend
,
1300 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1301 ChardevSocket
*sock
= backend
->u
.socket
.data
;
1302 bool do_nodelay
= sock
->has_nodelay
? sock
->nodelay
: false;
1303 bool is_listen
= sock
->has_server
? sock
->server
: true;
1304 bool is_telnet
= sock
->has_telnet
? sock
->telnet
: false;
1305 bool is_tn3270
= sock
->has_tn3270
? sock
->tn3270
: false;
1306 bool is_waitconnect
= sock
->has_wait
? sock
->wait
: false;
1307 bool is_websock
= sock
->has_websocket
? sock
->websocket
: false;
1308 int64_t reconnect
= sock
->has_reconnect
? sock
->reconnect
: 0;
1309 SocketAddress
*addr
;
1311 s
->is_listen
= is_listen
;
1312 s
->is_telnet
= is_telnet
;
1313 s
->is_tn3270
= is_tn3270
;
1314 s
->is_websock
= is_websock
;
1315 s
->do_nodelay
= do_nodelay
;
1316 if (sock
->tls_creds
) {
1318 creds
= object_resolve_path_component(
1319 object_get_objects_root(), sock
->tls_creds
);
1321 error_setg(errp
, "No TLS credentials with id '%s'",
1325 s
->tls_creds
= (QCryptoTLSCreds
*)
1326 object_dynamic_cast(creds
,
1327 TYPE_QCRYPTO_TLS_CREDS
);
1328 if (!s
->tls_creds
) {
1329 error_setg(errp
, "Object with id '%s' is not TLS credentials",
1333 object_ref(OBJECT(s
->tls_creds
));
1335 if (s
->tls_creds
->endpoint
!= QCRYPTO_TLS_CREDS_ENDPOINT_SERVER
) {
1336 error_setg(errp
, "%s",
1337 "Expected TLS credentials for server endpoint");
1341 if (s
->tls_creds
->endpoint
!= QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
) {
1342 error_setg(errp
, "%s",
1343 "Expected TLS credentials for client endpoint");
1348 s
->tls_authz
= g_strdup(sock
->tls_authz
);
1350 s
->addr
= addr
= socket_address_flatten(sock
->addr
);
1352 if (!qmp_chardev_validate_socket(sock
, addr
, errp
)) {
1356 qemu_chr_set_feature(chr
, QEMU_CHAR_FEATURE_RECONNECTABLE
);
1357 /* TODO SOCKET_ADDRESS_FD where fd has AF_UNIX */
1358 if (addr
->type
== SOCKET_ADDRESS_TYPE_UNIX
) {
1359 qemu_chr_set_feature(chr
, QEMU_CHAR_FEATURE_FD_PASS
);
1362 /* be isn't opened until we get a connection */
1365 update_disconnected_filename(s
);
1368 if (qmp_chardev_open_socket_server(chr
, is_telnet
|| is_tn3270
,
1369 is_waitconnect
, errp
) < 0) {
1373 if (qmp_chardev_open_socket_client(chr
, reconnect
, errp
) < 0) {
1379 static void qemu_chr_parse_socket(QemuOpts
*opts
, ChardevBackend
*backend
,
1382 const char *path
= qemu_opt_get(opts
, "path");
1383 const char *host
= qemu_opt_get(opts
, "host");
1384 const char *port
= qemu_opt_get(opts
, "port");
1385 const char *fd
= qemu_opt_get(opts
, "fd");
1386 bool tight
= qemu_opt_get_bool(opts
, "tight", true);
1387 bool abstract
= qemu_opt_get_bool(opts
, "abstract", false);
1388 SocketAddressLegacy
*addr
;
1389 ChardevSocket
*sock
;
1391 if ((!!path
+ !!fd
+ !!host
) != 1) {
1393 "Exactly one of 'path', 'fd' or 'host' required");
1397 if (host
&& !port
) {
1398 error_setg(errp
, "chardev: socket: no port given");
1402 backend
->type
= CHARDEV_BACKEND_KIND_SOCKET
;
1403 sock
= backend
->u
.socket
.data
= g_new0(ChardevSocket
, 1);
1404 qemu_chr_parse_common(opts
, qapi_ChardevSocket_base(sock
));
1406 sock
->has_nodelay
= qemu_opt_get(opts
, "delay");
1407 sock
->nodelay
= !qemu_opt_get_bool(opts
, "delay", true);
1409 * We have different default to QMP for 'server', hence
1410 * we can't just check for existence of 'server'
1412 sock
->has_server
= true;
1413 sock
->server
= qemu_opt_get_bool(opts
, "server", false);
1414 sock
->has_telnet
= qemu_opt_get(opts
, "telnet");
1415 sock
->telnet
= qemu_opt_get_bool(opts
, "telnet", false);
1416 sock
->has_tn3270
= qemu_opt_get(opts
, "tn3270");
1417 sock
->tn3270
= qemu_opt_get_bool(opts
, "tn3270", false);
1418 sock
->has_websocket
= qemu_opt_get(opts
, "websocket");
1419 sock
->websocket
= qemu_opt_get_bool(opts
, "websocket", false);
1421 * We have different default to QMP for 'wait' when 'server'
1422 * is set, hence we can't just check for existence of 'wait'
1424 sock
->has_wait
= qemu_opt_find(opts
, "wait") || sock
->server
;
1425 sock
->wait
= qemu_opt_get_bool(opts
, "wait", true);
1426 sock
->has_reconnect
= qemu_opt_find(opts
, "reconnect");
1427 sock
->reconnect
= qemu_opt_get_number(opts
, "reconnect", 0);
1428 sock
->has_tls_creds
= qemu_opt_get(opts
, "tls-creds");
1429 sock
->tls_creds
= g_strdup(qemu_opt_get(opts
, "tls-creds"));
1430 sock
->has_tls_authz
= qemu_opt_get(opts
, "tls-authz");
1431 sock
->tls_authz
= g_strdup(qemu_opt_get(opts
, "tls-authz"));
1433 addr
= g_new0(SocketAddressLegacy
, 1);
1435 UnixSocketAddress
*q_unix
;
1436 addr
->type
= SOCKET_ADDRESS_LEGACY_KIND_UNIX
;
1437 q_unix
= addr
->u
.q_unix
.data
= g_new0(UnixSocketAddress
, 1);
1438 q_unix
->path
= g_strdup(path
);
1439 q_unix
->tight
= tight
;
1440 q_unix
->abstract
= abstract
;
1442 addr
->type
= SOCKET_ADDRESS_LEGACY_KIND_INET
;
1443 addr
->u
.inet
.data
= g_new(InetSocketAddress
, 1);
1444 *addr
->u
.inet
.data
= (InetSocketAddress
) {
1445 .host
= g_strdup(host
),
1446 .port
= g_strdup(port
),
1447 .has_to
= qemu_opt_get(opts
, "to"),
1448 .to
= qemu_opt_get_number(opts
, "to", 0),
1449 .has_ipv4
= qemu_opt_get(opts
, "ipv4"),
1450 .ipv4
= qemu_opt_get_bool(opts
, "ipv4", 0),
1451 .has_ipv6
= qemu_opt_get(opts
, "ipv6"),
1452 .ipv6
= qemu_opt_get_bool(opts
, "ipv6", 0),
1455 addr
->type
= SOCKET_ADDRESS_LEGACY_KIND_FD
;
1456 addr
->u
.fd
.data
= g_new(String
, 1);
1457 addr
->u
.fd
.data
->str
= g_strdup(fd
);
1459 g_assert_not_reached();
1465 char_socket_get_addr(Object
*obj
, Visitor
*v
, const char *name
,
1466 void *opaque
, Error
**errp
)
1468 SocketChardev
*s
= SOCKET_CHARDEV(obj
);
1470 visit_type_SocketAddress(v
, name
, &s
->addr
, errp
);
1474 char_socket_get_connected(Object
*obj
, Error
**errp
)
1476 SocketChardev
*s
= SOCKET_CHARDEV(obj
);
1478 return s
->state
== TCP_CHARDEV_STATE_CONNECTED
;
1481 static void char_socket_class_init(ObjectClass
*oc
, void *data
)
1483 ChardevClass
*cc
= CHARDEV_CLASS(oc
);
1485 cc
->parse
= qemu_chr_parse_socket
;
1486 cc
->open
= qmp_chardev_open_socket
;
1487 cc
->chr_wait_connected
= tcp_chr_wait_connected
;
1488 cc
->chr_write
= tcp_chr_write
;
1489 cc
->chr_sync_read
= tcp_chr_sync_read
;
1490 cc
->chr_disconnect
= tcp_chr_disconnect
;
1491 cc
->get_msgfds
= tcp_get_msgfds
;
1492 cc
->set_msgfds
= tcp_set_msgfds
;
1493 cc
->chr_add_client
= tcp_chr_add_client
;
1494 cc
->chr_add_watch
= tcp_chr_add_watch
;
1495 cc
->chr_update_read_handler
= tcp_chr_update_read_handler
;
1497 object_class_property_add(oc
, "addr", "SocketAddress",
1498 char_socket_get_addr
, NULL
,
1501 object_class_property_add_bool(oc
, "connected", char_socket_get_connected
,
1505 static const TypeInfo char_socket_type_info
= {
1506 .name
= TYPE_CHARDEV_SOCKET
,
1507 .parent
= TYPE_CHARDEV
,
1508 .instance_size
= sizeof(SocketChardev
),
1509 .instance_finalize
= char_socket_finalize
,
1510 .class_init
= char_socket_class_init
,
1513 static void register_types(void)
1515 type_register_static(&char_socket_type_info
);
1518 type_init(register_types
);