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"
39 #include "qom/object.h"
41 /***********************************************************/
44 #define TCP_MAX_FDS 16
49 } TCPChardevTelnetInit
;
52 TCP_CHARDEV_STATE_DISCONNECTED
,
53 TCP_CHARDEV_STATE_CONNECTING
,
54 TCP_CHARDEV_STATE_CONNECTED
,
57 struct SocketChardev
{
59 QIOChannel
*ioc
; /* Client I/O channel */
60 QIOChannelSocket
*sioc
; /* Client master channel */
61 QIONetListener
*listener
;
63 QCryptoTLSCreds
*tls_creds
;
65 TCPChardevState state
;
70 size_t read_msgfds_num
;
72 size_t write_msgfds_num
;
78 GSource
*telnet_source
;
79 TCPChardevTelnetInit
*telnet_init
;
83 GSource
*reconnect_timer
;
84 int64_t reconnect_time
;
85 bool connect_err_reported
;
87 QIOTask
*connect_task
;
89 typedef struct SocketChardev SocketChardev
;
91 DECLARE_INSTANCE_CHECKER(SocketChardev
, SOCKET_CHARDEV
,
94 static gboolean
socket_reconnect_timeout(gpointer opaque
);
95 static void tcp_chr_telnet_init(Chardev
*chr
);
97 static void tcp_chr_change_state(SocketChardev
*s
, TCPChardevState state
)
100 case TCP_CHARDEV_STATE_DISCONNECTED
:
102 case TCP_CHARDEV_STATE_CONNECTING
:
103 assert(s
->state
== TCP_CHARDEV_STATE_DISCONNECTED
);
105 case TCP_CHARDEV_STATE_CONNECTED
:
106 assert(s
->state
== TCP_CHARDEV_STATE_CONNECTING
);
112 static void tcp_chr_reconn_timer_cancel(SocketChardev
*s
)
114 if (s
->reconnect_timer
) {
115 g_source_destroy(s
->reconnect_timer
);
116 g_source_unref(s
->reconnect_timer
);
117 s
->reconnect_timer
= NULL
;
121 static void qemu_chr_socket_restart_timer(Chardev
*chr
)
123 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
126 assert(s
->state
== TCP_CHARDEV_STATE_DISCONNECTED
);
127 assert(!s
->reconnect_timer
);
128 name
= g_strdup_printf("chardev-socket-reconnect-%s", chr
->label
);
129 s
->reconnect_timer
= qemu_chr_timeout_add_ms(chr
,
130 s
->reconnect_time
* 1000,
131 socket_reconnect_timeout
,
133 g_source_set_name(s
->reconnect_timer
, name
);
137 static void check_report_connect_error(Chardev
*chr
,
140 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
142 if (!s
->connect_err_reported
) {
143 error_reportf_err(err
,
144 "Unable to connect character device %s: ",
146 s
->connect_err_reported
= true;
150 qemu_chr_socket_restart_timer(chr
);
153 static void tcp_chr_accept(QIONetListener
*listener
,
154 QIOChannelSocket
*cioc
,
157 static int tcp_chr_read_poll(void *opaque
);
158 static void tcp_chr_disconnect_locked(Chardev
*chr
);
160 /* Called with chr_write_lock held. */
161 static int tcp_chr_write(Chardev
*chr
, const uint8_t *buf
, int len
)
163 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
165 if (s
->state
== TCP_CHARDEV_STATE_CONNECTED
) {
166 int ret
= io_channel_send_full(s
->ioc
, buf
, len
,
168 s
->write_msgfds_num
);
170 /* free the written msgfds in any cases
171 * other than ret < 0 && errno == EAGAIN
173 if (!(ret
< 0 && EAGAIN
== errno
)
174 && s
->write_msgfds_num
) {
175 g_free(s
->write_msgfds
);
177 s
->write_msgfds_num
= 0;
180 if (ret
< 0 && errno
!= EAGAIN
) {
181 if (tcp_chr_read_poll(chr
) <= 0) {
182 /* Perform disconnect and return error. */
183 tcp_chr_disconnect_locked(chr
);
184 } /* else let the read handler finish it properly */
189 /* Indicate an error. */
195 static int tcp_chr_read_poll(void *opaque
)
197 Chardev
*chr
= CHARDEV(opaque
);
198 SocketChardev
*s
= SOCKET_CHARDEV(opaque
);
199 if (s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) {
202 s
->max_size
= qemu_chr_be_can_write(chr
);
206 static void tcp_chr_process_IAC_bytes(Chardev
*chr
,
208 uint8_t *buf
, int *size
)
210 /* Handle any telnet or tn3270 client's basic IAC options.
211 * For telnet options, it satisfies char by char mode with no echo.
212 * For tn3270 options, it satisfies binary mode with EOR.
213 * All IAC options will be removed from the buf and the do_opt
214 * pointer will be used to track the state of the width of the
217 * RFC854: "All TELNET commands consist of at least a two byte sequence.
218 * The commands dealing with option negotiation are three byte sequences,
219 * the third byte being the code for the option referenced."
220 * "IAC BREAK", "IAC IP", "IAC NOP" and the double IAC are two bytes.
221 * "IAC SB", "IAC SE" and "IAC EOR" are saved to split up data boundary
223 * NOP, Break and Interrupt Process(IP) might be encountered during a TN3270
224 * session, and NOP and IP need to be done later.
230 for (i
= 0; i
< *size
; i
++) {
231 if (s
->do_telnetopt
> 1) {
232 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
233 /* Double IAC means send an IAC */
240 if ((unsigned char)buf
[i
] == IAC_BREAK
241 && s
->do_telnetopt
== 2) {
242 /* Handle IAC break commands by sending a serial break */
243 qemu_chr_be_event(chr
, CHR_EVENT_BREAK
);
245 } else if (s
->is_tn3270
&& ((unsigned char)buf
[i
] == IAC_EOR
246 || (unsigned char)buf
[i
] == IAC_SB
247 || (unsigned char)buf
[i
] == IAC_SE
)
248 && s
->do_telnetopt
== 2) {
252 } else if (s
->is_tn3270
&& ((unsigned char)buf
[i
] == IAC_IP
253 || (unsigned char)buf
[i
] == IAC_NOP
)
254 && s
->do_telnetopt
== 2) {
255 /* TODO: IP and NOP need to be implemented later. */
260 if (s
->do_telnetopt
>= 4) {
264 if ((unsigned char)buf
[i
] == IAC
) {
277 static int tcp_get_msgfds(Chardev
*chr
, int *fds
, int num
)
279 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
281 int to_copy
= (s
->read_msgfds_num
< num
) ? s
->read_msgfds_num
: num
;
283 assert(num
<= TCP_MAX_FDS
);
288 memcpy(fds
, s
->read_msgfds
, to_copy
* sizeof(int));
290 /* Close unused fds */
291 for (i
= to_copy
; i
< s
->read_msgfds_num
; i
++) {
292 close(s
->read_msgfds
[i
]);
295 g_free(s
->read_msgfds
);
297 s
->read_msgfds_num
= 0;
303 static int tcp_set_msgfds(Chardev
*chr
, int *fds
, int num
)
305 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
307 /* clear old pending fd array */
308 g_free(s
->write_msgfds
);
309 s
->write_msgfds
= NULL
;
310 s
->write_msgfds_num
= 0;
312 if ((s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) ||
313 !qio_channel_has_feature(s
->ioc
,
314 QIO_CHANNEL_FEATURE_FD_PASS
)) {
319 s
->write_msgfds
= g_new(int, num
);
320 memcpy(s
->write_msgfds
, fds
, num
* sizeof(int));
323 s
->write_msgfds_num
= num
;
328 static ssize_t
tcp_chr_recv(Chardev
*chr
, char *buf
, size_t len
)
330 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
331 struct iovec iov
= { .iov_base
= buf
, .iov_len
= len
};
335 size_t msgfds_num
= 0;
337 if (qio_channel_has_feature(s
->ioc
, QIO_CHANNEL_FEATURE_FD_PASS
)) {
338 ret
= qio_channel_readv_full(s
->ioc
, &iov
, 1,
339 &msgfds
, &msgfds_num
,
342 ret
= qio_channel_readv_full(s
->ioc
, &iov
, 1,
347 if (ret
== QIO_CHANNEL_ERR_BLOCK
) {
350 } else if (ret
== -1) {
355 /* close and clean read_msgfds */
356 for (i
= 0; i
< s
->read_msgfds_num
; i
++) {
357 close(s
->read_msgfds
[i
]);
360 if (s
->read_msgfds_num
) {
361 g_free(s
->read_msgfds
);
364 s
->read_msgfds
= msgfds
;
365 s
->read_msgfds_num
= msgfds_num
;
368 for (i
= 0; i
< s
->read_msgfds_num
; i
++) {
369 int fd
= s
->read_msgfds
[i
];
374 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
377 #ifndef MSG_CMSG_CLOEXEC
378 qemu_set_cloexec(fd
);
385 static GSource
*tcp_chr_add_watch(Chardev
*chr
, GIOCondition cond
)
387 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
388 return qio_channel_create_watch(s
->ioc
, cond
);
391 static void remove_hup_source(SocketChardev
*s
)
393 if (s
->hup_source
!= NULL
) {
394 g_source_destroy(s
->hup_source
);
395 g_source_unref(s
->hup_source
);
396 s
->hup_source
= NULL
;
400 static void tcp_chr_free_connection(Chardev
*chr
)
402 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
405 if (s
->read_msgfds_num
) {
406 for (i
= 0; i
< s
->read_msgfds_num
; i
++) {
407 close(s
->read_msgfds
[i
]);
409 g_free(s
->read_msgfds
);
410 s
->read_msgfds
= NULL
;
411 s
->read_msgfds_num
= 0;
414 remove_hup_source(s
);
416 tcp_set_msgfds(chr
, NULL
, 0);
417 remove_fd_in_watch(chr
);
418 object_unref(OBJECT(s
->sioc
));
420 object_unref(OBJECT(s
->ioc
));
422 g_free(chr
->filename
);
423 chr
->filename
= NULL
;
424 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_DISCONNECTED
);
427 static const char *qemu_chr_socket_protocol(SocketChardev
*s
)
432 return s
->is_websock
? "websocket" : "tcp";
435 static char *qemu_chr_socket_address(SocketChardev
*s
, const char *prefix
)
437 switch (s
->addr
->type
) {
438 case SOCKET_ADDRESS_TYPE_INET
:
439 return g_strdup_printf("%s%s:%s:%s%s", prefix
,
440 qemu_chr_socket_protocol(s
),
441 s
->addr
->u
.inet
.host
,
442 s
->addr
->u
.inet
.port
,
443 s
->is_listen
? ",server" : "");
445 case SOCKET_ADDRESS_TYPE_UNIX
:
447 const char *tight
= "", *abstract
= "";
448 UnixSocketAddress
*sa
= &s
->addr
->u
.q_unix
;
451 if (sa
->has_abstract
&& sa
->abstract
) {
452 abstract
= ",abstract";
453 if (sa
->has_tight
&& sa
->tight
) {
459 return g_strdup_printf("%sunix:%s%s%s%s", prefix
, sa
->path
,
461 s
->is_listen
? ",server" : "");
464 case SOCKET_ADDRESS_TYPE_FD
:
465 return g_strdup_printf("%sfd:%s%s", prefix
, s
->addr
->u
.fd
.str
,
466 s
->is_listen
? ",server" : "");
468 case SOCKET_ADDRESS_TYPE_VSOCK
:
469 return g_strdup_printf("%svsock:%s:%s", prefix
,
470 s
->addr
->u
.vsock
.cid
,
471 s
->addr
->u
.vsock
.port
);
477 static void update_disconnected_filename(SocketChardev
*s
)
479 Chardev
*chr
= CHARDEV(s
);
481 g_free(chr
->filename
);
483 chr
->filename
= qemu_chr_socket_address(s
, "disconnected:");
485 chr
->filename
= g_strdup("disconnected:socket");
489 /* NB may be called even if tcp_chr_connect has not been
490 * reached, due to TLS or telnet initialization failure,
491 * so can *not* assume s->state == TCP_CHARDEV_STATE_CONNECTED
492 * This must be called with chr->chr_write_lock held.
494 static void tcp_chr_disconnect_locked(Chardev
*chr
)
496 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
497 bool emit_close
= s
->state
== TCP_CHARDEV_STATE_CONNECTED
;
499 tcp_chr_free_connection(chr
);
502 qio_net_listener_set_client_func_full(s
->listener
, tcp_chr_accept
,
503 chr
, NULL
, chr
->gcontext
);
505 update_disconnected_filename(s
);
507 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
509 if (s
->reconnect_time
&& !s
->reconnect_timer
) {
510 qemu_chr_socket_restart_timer(chr
);
514 static void tcp_chr_disconnect(Chardev
*chr
)
516 qemu_mutex_lock(&chr
->chr_write_lock
);
517 tcp_chr_disconnect_locked(chr
);
518 qemu_mutex_unlock(&chr
->chr_write_lock
);
521 static gboolean
tcp_chr_read(QIOChannel
*chan
, GIOCondition cond
, void *opaque
)
523 Chardev
*chr
= CHARDEV(opaque
);
524 SocketChardev
*s
= SOCKET_CHARDEV(opaque
);
525 uint8_t buf
[CHR_READ_BUF_LEN
];
528 if ((s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) ||
533 if (len
> s
->max_size
) {
536 size
= tcp_chr_recv(chr
, (void *)buf
, len
);
537 if (size
== 0 || (size
== -1 && errno
!= EAGAIN
)) {
538 /* connection closed */
539 tcp_chr_disconnect(chr
);
540 } else if (size
> 0) {
541 if (s
->do_telnetopt
) {
542 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
545 qemu_chr_be_write(chr
, buf
, size
);
552 static gboolean
tcp_chr_hup(QIOChannel
*channel
,
556 Chardev
*chr
= CHARDEV(opaque
);
557 tcp_chr_disconnect(chr
);
558 return G_SOURCE_REMOVE
;
561 static int tcp_chr_sync_read(Chardev
*chr
, const uint8_t *buf
, int len
)
563 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
566 if (s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) {
570 qio_channel_set_blocking(s
->ioc
, true, NULL
);
571 size
= tcp_chr_recv(chr
, (void *) buf
, len
);
572 if (s
->state
!= TCP_CHARDEV_STATE_DISCONNECTED
) {
573 qio_channel_set_blocking(s
->ioc
, false, NULL
);
576 /* connection closed */
577 tcp_chr_disconnect(chr
);
583 static char *qemu_chr_compute_filename(SocketChardev
*s
)
585 struct sockaddr_storage
*ss
= &s
->sioc
->localAddr
;
586 struct sockaddr_storage
*ps
= &s
->sioc
->remoteAddr
;
587 socklen_t ss_len
= s
->sioc
->localAddrLen
;
588 socklen_t ps_len
= s
->sioc
->remoteAddrLen
;
589 char shost
[NI_MAXHOST
], sserv
[NI_MAXSERV
];
590 char phost
[NI_MAXHOST
], pserv
[NI_MAXSERV
];
591 const char *left
= "", *right
= "";
593 switch (ss
->ss_family
) {
596 return g_strdup_printf("unix:%s%s",
597 ((struct sockaddr_un
*)(ss
))->sun_path
,
598 s
->is_listen
? ",server" : "");
605 getnameinfo((struct sockaddr
*) ss
, ss_len
, shost
, sizeof(shost
),
606 sserv
, sizeof(sserv
), NI_NUMERICHOST
| NI_NUMERICSERV
);
607 getnameinfo((struct sockaddr
*) ps
, ps_len
, phost
, sizeof(phost
),
608 pserv
, sizeof(pserv
), NI_NUMERICHOST
| NI_NUMERICSERV
);
609 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
610 qemu_chr_socket_protocol(s
),
611 left
, shost
, right
, sserv
,
612 s
->is_listen
? ",server" : "",
613 left
, phost
, right
, pserv
);
616 return g_strdup_printf("unknown");
620 static void update_ioc_handlers(SocketChardev
*s
)
622 Chardev
*chr
= CHARDEV(s
);
624 if (s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) {
628 remove_fd_in_watch(chr
);
629 chr
->gsource
= io_add_watch_poll(chr
, s
->ioc
,
634 remove_hup_source(s
);
635 s
->hup_source
= qio_channel_create_watch(s
->ioc
, G_IO_HUP
);
636 g_source_set_callback(s
->hup_source
, (GSourceFunc
)tcp_chr_hup
,
638 g_source_attach(s
->hup_source
, chr
->gcontext
);
641 static void tcp_chr_connect(void *opaque
)
643 Chardev
*chr
= CHARDEV(opaque
);
644 SocketChardev
*s
= SOCKET_CHARDEV(opaque
);
646 g_free(chr
->filename
);
647 chr
->filename
= qemu_chr_compute_filename(s
);
649 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTED
);
650 update_ioc_handlers(s
);
651 qemu_chr_be_event(chr
, CHR_EVENT_OPENED
);
654 static void tcp_chr_telnet_destroy(SocketChardev
*s
)
656 if (s
->telnet_source
) {
657 g_source_destroy(s
->telnet_source
);
658 g_source_unref(s
->telnet_source
);
659 s
->telnet_source
= NULL
;
663 static void tcp_chr_update_read_handler(Chardev
*chr
)
665 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
667 if (s
->listener
&& s
->state
== TCP_CHARDEV_STATE_DISCONNECTED
) {
669 * It's possible that chardev context is changed in
670 * qemu_chr_be_update_read_handlers(). Reset it for QIO net
671 * listener if there is.
673 qio_net_listener_set_client_func_full(s
->listener
, tcp_chr_accept
,
674 chr
, NULL
, chr
->gcontext
);
677 if (s
->telnet_source
) {
678 tcp_chr_telnet_init(CHARDEV(s
));
681 update_ioc_handlers(s
);
684 static gboolean
tcp_chr_telnet_init_io(QIOChannel
*ioc
,
685 GIOCondition cond G_GNUC_UNUSED
,
688 SocketChardev
*s
= user_data
;
689 Chardev
*chr
= CHARDEV(s
);
690 TCPChardevTelnetInit
*init
= s
->telnet_init
;
695 ret
= qio_channel_write(ioc
, init
->buf
, init
->buflen
, NULL
);
697 if (ret
== QIO_CHANNEL_ERR_BLOCK
) {
700 tcp_chr_disconnect(chr
);
706 if (init
->buflen
== 0) {
707 tcp_chr_connect(chr
);
711 memmove(init
->buf
, init
->buf
+ ret
, init
->buflen
);
713 return G_SOURCE_CONTINUE
;
716 g_free(s
->telnet_init
);
717 s
->telnet_init
= NULL
;
718 g_source_unref(s
->telnet_source
);
719 s
->telnet_source
= NULL
;
720 return G_SOURCE_REMOVE
;
723 static void tcp_chr_telnet_init(Chardev
*chr
)
725 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
726 TCPChardevTelnetInit
*init
;
729 /* Destroy existing task */
730 tcp_chr_telnet_destroy(s
);
732 if (s
->telnet_init
) {
733 /* We are possibly during a handshake already */
737 s
->telnet_init
= g_new0(TCPChardevTelnetInit
, 1);
738 init
= s
->telnet_init
;
740 #define IACSET(x, a, b, c) \
749 /* Prep the telnet negotion to put telnet in binary,
750 * no echo, single char mode */
751 IACSET(init
->buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
752 IACSET(init
->buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
753 IACSET(init
->buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
754 IACSET(init
->buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
757 /* Prep the TN3270 negotion based on RFC1576 */
758 IACSET(init
->buf
, 0xff, 0xfd, 0x19); /* IAC DO EOR */
759 IACSET(init
->buf
, 0xff, 0xfb, 0x19); /* IAC WILL EOR */
760 IACSET(init
->buf
, 0xff, 0xfd, 0x00); /* IAC DO BINARY */
761 IACSET(init
->buf
, 0xff, 0xfb, 0x00); /* IAC WILL BINARY */
762 IACSET(init
->buf
, 0xff, 0xfd, 0x18); /* IAC DO TERMINAL TYPE */
763 IACSET(init
->buf
, 0xff, 0xfa, 0x18); /* IAC SB TERMINAL TYPE */
764 IACSET(init
->buf
, 0x01, 0xff, 0xf0); /* SEND IAC SE */
770 s
->telnet_source
= qio_channel_add_watch_source(s
->ioc
, G_IO_OUT
,
771 tcp_chr_telnet_init_io
,
777 static void tcp_chr_websock_handshake(QIOTask
*task
, gpointer user_data
)
779 Chardev
*chr
= user_data
;
780 SocketChardev
*s
= user_data
;
782 if (qio_task_propagate_error(task
, NULL
)) {
783 tcp_chr_disconnect(chr
);
785 if (s
->do_telnetopt
) {
786 tcp_chr_telnet_init(chr
);
788 tcp_chr_connect(chr
);
794 static void tcp_chr_websock_init(Chardev
*chr
)
796 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
797 QIOChannelWebsock
*wioc
= NULL
;
800 wioc
= qio_channel_websock_new_server(s
->ioc
);
802 name
= g_strdup_printf("chardev-websocket-server-%s", chr
->label
);
803 qio_channel_set_name(QIO_CHANNEL(wioc
), name
);
805 object_unref(OBJECT(s
->ioc
));
806 s
->ioc
= QIO_CHANNEL(wioc
);
808 qio_channel_websock_handshake(wioc
, tcp_chr_websock_handshake
, chr
, NULL
);
812 static void tcp_chr_tls_handshake(QIOTask
*task
,
815 Chardev
*chr
= user_data
;
816 SocketChardev
*s
= user_data
;
818 if (qio_task_propagate_error(task
, NULL
)) {
819 tcp_chr_disconnect(chr
);
822 tcp_chr_websock_init(chr
);
823 } else if (s
->do_telnetopt
) {
824 tcp_chr_telnet_init(chr
);
826 tcp_chr_connect(chr
);
832 static void tcp_chr_tls_init(Chardev
*chr
)
834 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
839 tioc
= qio_channel_tls_new_server(
840 s
->ioc
, s
->tls_creds
,
844 tioc
= qio_channel_tls_new_client(
845 s
->ioc
, s
->tls_creds
,
846 s
->addr
->u
.inet
.host
,
850 tcp_chr_disconnect(chr
);
853 name
= g_strdup_printf("chardev-tls-%s-%s",
854 s
->is_listen
? "server" : "client",
856 qio_channel_set_name(QIO_CHANNEL(tioc
), name
);
858 object_unref(OBJECT(s
->ioc
));
859 s
->ioc
= QIO_CHANNEL(tioc
);
861 qio_channel_tls_handshake(tioc
,
862 tcp_chr_tls_handshake
,
869 static void tcp_chr_set_client_ioc_name(Chardev
*chr
,
870 QIOChannelSocket
*sioc
)
872 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
874 name
= g_strdup_printf("chardev-tcp-%s-%s",
875 s
->is_listen
? "server" : "client",
877 qio_channel_set_name(QIO_CHANNEL(sioc
), name
);
882 static int tcp_chr_new_client(Chardev
*chr
, QIOChannelSocket
*sioc
)
884 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
886 if (s
->state
!= TCP_CHARDEV_STATE_CONNECTING
) {
890 s
->ioc
= QIO_CHANNEL(sioc
);
891 object_ref(OBJECT(sioc
));
893 object_ref(OBJECT(sioc
));
895 qio_channel_set_blocking(s
->ioc
, false, NULL
);
898 qio_channel_set_delay(s
->ioc
, false);
901 qio_net_listener_set_client_func_full(s
->listener
, NULL
, NULL
,
902 NULL
, chr
->gcontext
);
906 tcp_chr_tls_init(chr
);
907 } else if (s
->is_websock
) {
908 tcp_chr_websock_init(chr
);
909 } else if (s
->do_telnetopt
) {
910 tcp_chr_telnet_init(chr
);
912 tcp_chr_connect(chr
);
919 static int tcp_chr_add_client(Chardev
*chr
, int fd
)
922 QIOChannelSocket
*sioc
;
923 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
925 if (s
->state
!= TCP_CHARDEV_STATE_DISCONNECTED
) {
929 sioc
= qio_channel_socket_new_fd(fd
, NULL
);
933 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
934 tcp_chr_set_client_ioc_name(chr
, sioc
);
935 ret
= tcp_chr_new_client(chr
, sioc
);
936 object_unref(OBJECT(sioc
));
940 static void tcp_chr_accept(QIONetListener
*listener
,
941 QIOChannelSocket
*cioc
,
944 Chardev
*chr
= CHARDEV(opaque
);
945 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
947 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
948 tcp_chr_set_client_ioc_name(chr
, cioc
);
949 tcp_chr_new_client(chr
, cioc
);
953 static int tcp_chr_connect_client_sync(Chardev
*chr
, Error
**errp
)
955 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
956 QIOChannelSocket
*sioc
= qio_channel_socket_new();
957 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
958 tcp_chr_set_client_ioc_name(chr
, sioc
);
959 if (qio_channel_socket_connect_sync(sioc
, s
->addr
, errp
) < 0) {
960 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_DISCONNECTED
);
961 object_unref(OBJECT(sioc
));
964 tcp_chr_new_client(chr
, sioc
);
965 object_unref(OBJECT(sioc
));
970 static void tcp_chr_accept_server_sync(Chardev
*chr
)
972 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
973 QIOChannelSocket
*sioc
;
974 info_report("QEMU waiting for connection on: %s",
976 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
977 sioc
= qio_net_listener_wait_client(s
->listener
);
978 tcp_chr_set_client_ioc_name(chr
, sioc
);
979 tcp_chr_new_client(chr
, sioc
);
980 object_unref(OBJECT(sioc
));
984 static int tcp_chr_wait_connected(Chardev
*chr
, Error
**errp
)
986 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
987 const char *opts
[] = { "telnet", "tn3270", "websock", "tls-creds" };
988 bool optset
[] = { s
->is_telnet
, s
->is_tn3270
, s
->is_websock
, s
->tls_creds
};
991 QEMU_BUILD_BUG_ON(G_N_ELEMENTS(opts
) != G_N_ELEMENTS(optset
));
992 for (i
= 0; i
< G_N_ELEMENTS(opts
); i
++) {
995 "'%s' option is incompatible with waiting for "
996 "connection completion", opts
[i
]);
1001 tcp_chr_reconn_timer_cancel(s
);
1004 * We expect states to be as follows:
1007 * - wait -> CONNECTED
1008 * - nowait -> DISCONNECTED
1010 * - reconnect == 0 -> CONNECTED
1011 * - reconnect != 0 -> CONNECTING
1014 if (s
->state
== TCP_CHARDEV_STATE_CONNECTING
) {
1015 if (!s
->connect_task
) {
1017 "Unexpected 'connecting' state without connect task "
1018 "while waiting for connection completion");
1022 * tcp_chr_wait_connected should only ever be run from the
1023 * main loop thread associated with chr->gcontext, otherwise
1024 * qio_task_wait_thread has a dangerous race condition with
1025 * free'ing of the s->connect_task object.
1027 * Acquiring the main context doesn't 100% prove we're in
1028 * the main loop thread, but it does at least guarantee
1029 * that the main loop won't be executed by another thread
1030 * avoiding the race condition with the task idle callback.
1032 g_main_context_acquire(chr
->gcontext
);
1033 qio_task_wait_thread(s
->connect_task
);
1034 g_main_context_release(chr
->gcontext
);
1037 * The completion callback (qemu_chr_socket_connected) for
1038 * s->connect_task should have set this to NULL by the time
1039 * qio_task_wait_thread has returned.
1041 assert(!s
->connect_task
);
1044 * NB we are *not* guaranteed to have "s->state == ..CONNECTED"
1045 * at this point as this first connect may be failed, so
1046 * allow the next loop to run regardless.
1050 while (s
->state
!= TCP_CHARDEV_STATE_CONNECTED
) {
1052 tcp_chr_accept_server_sync(chr
);
1055 if (tcp_chr_connect_client_sync(chr
, &err
) < 0) {
1056 if (s
->reconnect_time
) {
1058 g_usleep(s
->reconnect_time
* 1000ULL * 1000ULL);
1060 error_propagate(errp
, err
);
1070 static void char_socket_finalize(Object
*obj
)
1072 Chardev
*chr
= CHARDEV(obj
);
1073 SocketChardev
*s
= SOCKET_CHARDEV(obj
);
1075 tcp_chr_free_connection(chr
);
1076 tcp_chr_reconn_timer_cancel(s
);
1077 qapi_free_SocketAddress(s
->addr
);
1078 tcp_chr_telnet_destroy(s
);
1079 g_free(s
->telnet_init
);
1081 qio_net_listener_set_client_func_full(s
->listener
, NULL
, NULL
,
1082 NULL
, chr
->gcontext
);
1083 object_unref(OBJECT(s
->listener
));
1086 object_unref(OBJECT(s
->tls_creds
));
1088 g_free(s
->tls_authz
);
1090 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
1093 static void qemu_chr_socket_connected(QIOTask
*task
, void *opaque
)
1095 QIOChannelSocket
*sioc
= QIO_CHANNEL_SOCKET(qio_task_get_source(task
));
1096 Chardev
*chr
= CHARDEV(opaque
);
1097 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1100 s
->connect_task
= NULL
;
1102 if (qio_task_propagate_error(task
, &err
)) {
1103 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_DISCONNECTED
);
1104 check_report_connect_error(chr
, err
);
1108 s
->connect_err_reported
= false;
1109 tcp_chr_new_client(chr
, sioc
);
1112 object_unref(OBJECT(sioc
));
1116 static void tcp_chr_connect_client_task(QIOTask
*task
,
1119 QIOChannelSocket
*ioc
= QIO_CHANNEL_SOCKET(qio_task_get_source(task
));
1120 SocketAddress
*addr
= opaque
;
1123 qio_channel_socket_connect_sync(ioc
, addr
, &err
);
1125 qio_task_set_error(task
, err
);
1129 static void tcp_chr_connect_client_async(Chardev
*chr
)
1131 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1132 QIOChannelSocket
*sioc
;
1134 tcp_chr_change_state(s
, TCP_CHARDEV_STATE_CONNECTING
);
1135 sioc
= qio_channel_socket_new();
1136 tcp_chr_set_client_ioc_name(chr
, sioc
);
1138 * Normally code would use the qio_channel_socket_connect_async
1139 * method which uses a QIOTask + qio_task_set_error internally
1140 * to avoid blocking. The tcp_chr_wait_connected method, however,
1141 * needs a way to synchronize with completion of the background
1142 * connect task which can't be done with the QIOChannelSocket
1143 * async APIs. Thus we must use QIOTask directly to implement
1144 * the non-blocking concept locally.
1146 s
->connect_task
= qio_task_new(OBJECT(sioc
),
1147 qemu_chr_socket_connected
,
1148 object_ref(OBJECT(chr
)),
1149 (GDestroyNotify
)object_unref
);
1150 qio_task_run_in_thread(s
->connect_task
,
1151 tcp_chr_connect_client_task
,
1157 static gboolean
socket_reconnect_timeout(gpointer opaque
)
1159 Chardev
*chr
= CHARDEV(opaque
);
1160 SocketChardev
*s
= SOCKET_CHARDEV(opaque
);
1162 qemu_mutex_lock(&chr
->chr_write_lock
);
1163 g_source_unref(s
->reconnect_timer
);
1164 s
->reconnect_timer
= NULL
;
1165 qemu_mutex_unlock(&chr
->chr_write_lock
);
1171 tcp_chr_connect_client_async(chr
);
1177 static int qmp_chardev_open_socket_server(Chardev
*chr
,
1179 bool is_waitconnect
,
1182 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1185 s
->do_telnetopt
= 1;
1187 s
->listener
= qio_net_listener_new();
1189 name
= g_strdup_printf("chardev-tcp-listener-%s", chr
->label
);
1190 qio_net_listener_set_name(s
->listener
, name
);
1193 if (qio_net_listener_open_sync(s
->listener
, s
->addr
, 1, errp
) < 0) {
1194 object_unref(OBJECT(s
->listener
));
1199 qapi_free_SocketAddress(s
->addr
);
1200 s
->addr
= socket_local_address(s
->listener
->sioc
[0]->fd
, errp
);
1201 update_disconnected_filename(s
);
1203 if (is_waitconnect
) {
1204 tcp_chr_accept_server_sync(chr
);
1206 qio_net_listener_set_client_func_full(s
->listener
,
1216 static int qmp_chardev_open_socket_client(Chardev
*chr
,
1220 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1222 if (reconnect
> 0) {
1223 s
->reconnect_time
= reconnect
;
1224 tcp_chr_connect_client_async(chr
);
1227 return tcp_chr_connect_client_sync(chr
, errp
);
1232 static bool qmp_chardev_validate_socket(ChardevSocket
*sock
,
1233 SocketAddress
*addr
,
1236 /* Validate any options which have a dependency on address type */
1237 switch (addr
->type
) {
1238 case SOCKET_ADDRESS_TYPE_FD
:
1239 if (sock
->has_reconnect
) {
1241 "'reconnect' option is incompatible with "
1242 "'fd' address type");
1245 if (sock
->has_tls_creds
&&
1246 !(sock
->has_server
&& sock
->server
)) {
1248 "'tls_creds' option is incompatible with "
1249 "'fd' address type as client");
1254 case SOCKET_ADDRESS_TYPE_UNIX
:
1255 if (sock
->has_tls_creds
) {
1257 "'tls_creds' option is incompatible with "
1258 "'unix' address type");
1263 case SOCKET_ADDRESS_TYPE_INET
:
1266 case SOCKET_ADDRESS_TYPE_VSOCK
:
1267 if (sock
->has_tls_creds
) {
1269 "'tls_creds' option is incompatible with "
1270 "'vsock' address type");
1278 if (sock
->has_tls_authz
&& !sock
->has_tls_creds
) {
1279 error_setg(errp
, "'tls_authz' option requires 'tls_creds' option");
1283 /* Validate any options which have a dependancy on client vs server */
1284 if (!sock
->has_server
|| sock
->server
) {
1285 if (sock
->has_reconnect
) {
1287 "'reconnect' option is incompatible with "
1288 "socket in server listen mode");
1292 if (sock
->has_websocket
&& sock
->websocket
) {
1293 error_setg(errp
, "%s", "Websocket client is not implemented");
1296 if (sock
->has_wait
) {
1297 warn_report("'wait' option is deprecated with "
1298 "socket in client connect mode");
1300 error_setg(errp
, "%s",
1301 "'wait' option is incompatible with "
1302 "socket in client connect mode");
1312 static void qmp_chardev_open_socket(Chardev
*chr
,
1313 ChardevBackend
*backend
,
1317 SocketChardev
*s
= SOCKET_CHARDEV(chr
);
1318 ChardevSocket
*sock
= backend
->u
.socket
.data
;
1319 bool do_nodelay
= sock
->has_nodelay
? sock
->nodelay
: false;
1320 bool is_listen
= sock
->has_server
? sock
->server
: true;
1321 bool is_telnet
= sock
->has_telnet
? sock
->telnet
: false;
1322 bool is_tn3270
= sock
->has_tn3270
? sock
->tn3270
: false;
1323 bool is_waitconnect
= sock
->has_wait
? sock
->wait
: false;
1324 bool is_websock
= sock
->has_websocket
? sock
->websocket
: false;
1325 int64_t reconnect
= sock
->has_reconnect
? sock
->reconnect
: 0;
1326 SocketAddress
*addr
;
1328 s
->is_listen
= is_listen
;
1329 s
->is_telnet
= is_telnet
;
1330 s
->is_tn3270
= is_tn3270
;
1331 s
->is_websock
= is_websock
;
1332 s
->do_nodelay
= do_nodelay
;
1333 if (sock
->tls_creds
) {
1335 creds
= object_resolve_path_component(
1336 object_get_objects_root(), sock
->tls_creds
);
1338 error_setg(errp
, "No TLS credentials with id '%s'",
1342 s
->tls_creds
= (QCryptoTLSCreds
*)
1343 object_dynamic_cast(creds
,
1344 TYPE_QCRYPTO_TLS_CREDS
);
1345 if (!s
->tls_creds
) {
1346 error_setg(errp
, "Object with id '%s' is not TLS credentials",
1350 object_ref(OBJECT(s
->tls_creds
));
1352 if (s
->tls_creds
->endpoint
!= QCRYPTO_TLS_CREDS_ENDPOINT_SERVER
) {
1353 error_setg(errp
, "%s",
1354 "Expected TLS credentials for server endpoint");
1358 if (s
->tls_creds
->endpoint
!= QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
) {
1359 error_setg(errp
, "%s",
1360 "Expected TLS credentials for client endpoint");
1365 s
->tls_authz
= g_strdup(sock
->tls_authz
);
1367 s
->addr
= addr
= socket_address_flatten(sock
->addr
);
1369 if (!qmp_chardev_validate_socket(sock
, addr
, errp
)) {
1373 qemu_chr_set_feature(chr
, QEMU_CHAR_FEATURE_RECONNECTABLE
);
1374 /* TODO SOCKET_ADDRESS_FD where fd has AF_UNIX */
1375 if (addr
->type
== SOCKET_ADDRESS_TYPE_UNIX
) {
1376 qemu_chr_set_feature(chr
, QEMU_CHAR_FEATURE_FD_PASS
);
1379 /* be isn't opened until we get a connection */
1382 update_disconnected_filename(s
);
1385 if (qmp_chardev_open_socket_server(chr
, is_telnet
|| is_tn3270
,
1386 is_waitconnect
, errp
) < 0) {
1390 if (qmp_chardev_open_socket_client(chr
, reconnect
, errp
) < 0) {
1396 static void qemu_chr_parse_socket(QemuOpts
*opts
, ChardevBackend
*backend
,
1399 const char *path
= qemu_opt_get(opts
, "path");
1400 const char *host
= qemu_opt_get(opts
, "host");
1401 const char *port
= qemu_opt_get(opts
, "port");
1402 const char *fd
= qemu_opt_get(opts
, "fd");
1404 bool tight
= qemu_opt_get_bool(opts
, "tight", true);
1405 bool abstract
= qemu_opt_get_bool(opts
, "abstract", false);
1407 SocketAddressLegacy
*addr
;
1408 ChardevSocket
*sock
;
1410 if ((!!path
+ !!fd
+ !!host
) != 1) {
1412 "Exactly one of 'path', 'fd' or 'host' required");
1416 if (host
&& !port
) {
1417 error_setg(errp
, "chardev: socket: no port given");
1421 backend
->type
= CHARDEV_BACKEND_KIND_SOCKET
;
1422 sock
= backend
->u
.socket
.data
= g_new0(ChardevSocket
, 1);
1423 qemu_chr_parse_common(opts
, qapi_ChardevSocket_base(sock
));
1425 sock
->has_nodelay
= qemu_opt_get(opts
, "delay");
1426 sock
->nodelay
= !qemu_opt_get_bool(opts
, "delay", true);
1428 * We have different default to QMP for 'server', hence
1429 * we can't just check for existence of 'server'
1431 sock
->has_server
= true;
1432 sock
->server
= qemu_opt_get_bool(opts
, "server", false);
1433 sock
->has_telnet
= qemu_opt_get(opts
, "telnet");
1434 sock
->telnet
= qemu_opt_get_bool(opts
, "telnet", false);
1435 sock
->has_tn3270
= qemu_opt_get(opts
, "tn3270");
1436 sock
->tn3270
= qemu_opt_get_bool(opts
, "tn3270", false);
1437 sock
->has_websocket
= qemu_opt_get(opts
, "websocket");
1438 sock
->websocket
= qemu_opt_get_bool(opts
, "websocket", false);
1440 * We have different default to QMP for 'wait' when 'server'
1441 * is set, hence we can't just check for existence of 'wait'
1443 sock
->has_wait
= qemu_opt_find(opts
, "wait") || sock
->server
;
1444 sock
->wait
= qemu_opt_get_bool(opts
, "wait", true);
1445 sock
->has_reconnect
= qemu_opt_find(opts
, "reconnect");
1446 sock
->reconnect
= qemu_opt_get_number(opts
, "reconnect", 0);
1447 sock
->has_tls_creds
= qemu_opt_get(opts
, "tls-creds");
1448 sock
->tls_creds
= g_strdup(qemu_opt_get(opts
, "tls-creds"));
1449 sock
->has_tls_authz
= qemu_opt_get(opts
, "tls-authz");
1450 sock
->tls_authz
= g_strdup(qemu_opt_get(opts
, "tls-authz"));
1452 addr
= g_new0(SocketAddressLegacy
, 1);
1454 UnixSocketAddress
*q_unix
;
1455 addr
->type
= SOCKET_ADDRESS_LEGACY_KIND_UNIX
;
1456 q_unix
= addr
->u
.q_unix
.data
= g_new0(UnixSocketAddress
, 1);
1457 q_unix
->path
= g_strdup(path
);
1459 q_unix
->has_tight
= true;
1460 q_unix
->tight
= tight
;
1461 q_unix
->has_abstract
= true;
1462 q_unix
->abstract
= abstract
;
1465 addr
->type
= SOCKET_ADDRESS_LEGACY_KIND_INET
;
1466 addr
->u
.inet
.data
= g_new(InetSocketAddress
, 1);
1467 *addr
->u
.inet
.data
= (InetSocketAddress
) {
1468 .host
= g_strdup(host
),
1469 .port
= g_strdup(port
),
1470 .has_to
= qemu_opt_get(opts
, "to"),
1471 .to
= qemu_opt_get_number(opts
, "to", 0),
1472 .has_ipv4
= qemu_opt_get(opts
, "ipv4"),
1473 .ipv4
= qemu_opt_get_bool(opts
, "ipv4", 0),
1474 .has_ipv6
= qemu_opt_get(opts
, "ipv6"),
1475 .ipv6
= qemu_opt_get_bool(opts
, "ipv6", 0),
1478 addr
->type
= SOCKET_ADDRESS_LEGACY_KIND_FD
;
1479 addr
->u
.fd
.data
= g_new(String
, 1);
1480 addr
->u
.fd
.data
->str
= g_strdup(fd
);
1482 g_assert_not_reached();
1488 char_socket_get_addr(Object
*obj
, Visitor
*v
, const char *name
,
1489 void *opaque
, Error
**errp
)
1491 SocketChardev
*s
= SOCKET_CHARDEV(obj
);
1493 visit_type_SocketAddress(v
, name
, &s
->addr
, errp
);
1497 char_socket_get_connected(Object
*obj
, Error
**errp
)
1499 SocketChardev
*s
= SOCKET_CHARDEV(obj
);
1501 return s
->state
== TCP_CHARDEV_STATE_CONNECTED
;
1504 static void char_socket_class_init(ObjectClass
*oc
, void *data
)
1506 ChardevClass
*cc
= CHARDEV_CLASS(oc
);
1508 cc
->parse
= qemu_chr_parse_socket
;
1509 cc
->open
= qmp_chardev_open_socket
;
1510 cc
->chr_wait_connected
= tcp_chr_wait_connected
;
1511 cc
->chr_write
= tcp_chr_write
;
1512 cc
->chr_sync_read
= tcp_chr_sync_read
;
1513 cc
->chr_disconnect
= tcp_chr_disconnect
;
1514 cc
->get_msgfds
= tcp_get_msgfds
;
1515 cc
->set_msgfds
= tcp_set_msgfds
;
1516 cc
->chr_add_client
= tcp_chr_add_client
;
1517 cc
->chr_add_watch
= tcp_chr_add_watch
;
1518 cc
->chr_update_read_handler
= tcp_chr_update_read_handler
;
1520 object_class_property_add(oc
, "addr", "SocketAddress",
1521 char_socket_get_addr
, NULL
,
1524 object_class_property_add_bool(oc
, "connected", char_socket_get_connected
,
1528 static const TypeInfo char_socket_type_info
= {
1529 .name
= TYPE_CHARDEV_SOCKET
,
1530 .parent
= TYPE_CHARDEV
,
1531 .instance_size
= sizeof(SocketChardev
),
1532 .instance_finalize
= char_socket_finalize
,
1533 .class_init
= char_socket_class_init
,
1536 static void register_types(void)
1538 type_register_static(&char_socket_type_info
);
1541 type_init(register_types
);