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
24 #include "qemu-common.h"
25 #include "monitor/monitor.h"
26 #include "sysemu/sysemu.h"
27 #include "qemu/timer.h"
28 #include "sysemu/char.h"
30 #include "qmp-commands.h"
31 #include "qapi/qmp-input-visitor.h"
32 #include "qapi/qmp-output-visitor.h"
33 #include "qapi-visit.h"
43 #include <sys/times.h>
47 #include <sys/ioctl.h>
48 #include <sys/resource.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
52 #include <arpa/inet.h>
55 #include <sys/select.h>
58 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
59 #include <dev/ppbus/ppi.h>
60 #include <dev/ppbus/ppbconf.h>
61 #elif defined(__DragonFly__)
62 #include <dev/misc/ppi/ppi.h>
63 #include <bus/ppbus/ppbconf.h>
67 #include <linux/ppdev.h>
68 #include <linux/parport.h>
72 #include <sys/ethernet.h>
73 #include <sys/sockio.h>
74 #include <netinet/arp.h>
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_icmp.h> // must come after ip.h
79 #include <netinet/udp.h>
80 #include <netinet/tcp.h>
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
89 #define READ_RETRIES 10
90 #define CHR_MAX_FILENAME_SIZE 256
92 /***********************************************************/
93 /* Socket address helpers */
94 static void qapi_copy_SocketAddress(SocketAddress
**p_dest
,
97 QmpOutputVisitor
*qov
;
104 qov
= qmp_output_visitor_new();
105 ov
= qmp_output_get_visitor(qov
);
106 visit_type_SocketAddress(ov
, &src
, NULL
, &error_abort
);
107 obj
= qmp_output_get_qobject(qov
);
108 qmp_output_visitor_cleanup(qov
);
113 qiv
= qmp_input_visitor_new(obj
);
114 iv
= qmp_input_get_visitor(qiv
);
115 visit_type_SocketAddress(iv
, p_dest
, NULL
, &error_abort
);
116 qmp_input_visitor_cleanup(qiv
);
120 static int SocketAddress_to_str(char *dest
, int max_len
,
121 const char *prefix
, SocketAddress
*addr
,
122 bool is_listen
, bool is_telnet
)
124 switch (addr
->kind
) {
125 case SOCKET_ADDRESS_KIND_INET
:
126 return snprintf(dest
, max_len
, "%s%s:%s:%s%s", prefix
,
127 is_telnet
? "telnet" : "tcp", addr
->inet
->host
,
128 addr
->inet
->port
, is_listen
? ",server" : "");
130 case SOCKET_ADDRESS_KIND_UNIX
:
131 return snprintf(dest
, max_len
, "%sunix:%s%s", prefix
,
132 addr
->q_unix
->path
, is_listen
? ",server" : "");
134 case SOCKET_ADDRESS_KIND_FD
:
135 return snprintf(dest
, max_len
, "%sfd:%s%s", prefix
, addr
->fd
->str
,
136 is_listen
? ",server" : "");
143 static int sockaddr_to_str(char *dest
, int max_len
,
144 struct sockaddr_storage
*ss
, socklen_t ss_len
,
145 struct sockaddr_storage
*ps
, socklen_t ps_len
,
146 bool is_listen
, bool is_telnet
)
148 char shost
[NI_MAXHOST
], sserv
[NI_MAXSERV
];
149 char phost
[NI_MAXHOST
], pserv
[NI_MAXSERV
];
150 const char *left
= "", *right
= "";
152 switch (ss
->ss_family
) {
155 return snprintf(dest
, max_len
, "unix:%s%s",
156 ((struct sockaddr_un
*)(ss
))->sun_path
,
157 is_listen
? ",server" : "");
164 getnameinfo((struct sockaddr
*) ss
, ss_len
, shost
, sizeof(shost
),
165 sserv
, sizeof(sserv
), NI_NUMERICHOST
| NI_NUMERICSERV
);
166 getnameinfo((struct sockaddr
*) ps
, ps_len
, phost
, sizeof(phost
),
167 pserv
, sizeof(pserv
), NI_NUMERICHOST
| NI_NUMERICSERV
);
168 return snprintf(dest
, max_len
, "%s:%s%s%s:%s%s <-> %s%s%s:%s",
169 is_telnet
? "telnet" : "tcp",
170 left
, shost
, right
, sserv
,
171 is_listen
? ",server" : "",
172 left
, phost
, right
, pserv
);
175 return snprintf(dest
, max_len
, "unknown");
179 /***********************************************************/
180 /* character device */
182 static QTAILQ_HEAD(CharDriverStateHead
, CharDriverState
) chardevs
=
183 QTAILQ_HEAD_INITIALIZER(chardevs
);
185 CharDriverState
*qemu_chr_alloc(void)
187 CharDriverState
*chr
= g_malloc0(sizeof(CharDriverState
));
188 qemu_mutex_init(&chr
->chr_write_lock
);
192 void qemu_chr_be_event(CharDriverState
*s
, int event
)
194 /* Keep track if the char device is open */
196 case CHR_EVENT_OPENED
:
199 case CHR_EVENT_CLOSED
:
206 s
->chr_event(s
->handler_opaque
, event
);
209 void qemu_chr_be_generic_open(CharDriverState
*s
)
211 qemu_chr_be_event(s
, CHR_EVENT_OPENED
);
214 int qemu_chr_fe_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
218 qemu_mutex_lock(&s
->chr_write_lock
);
219 ret
= s
->chr_write(s
, buf
, len
);
220 qemu_mutex_unlock(&s
->chr_write_lock
);
224 int qemu_chr_fe_write_all(CharDriverState
*s
, const uint8_t *buf
, int len
)
229 qemu_mutex_lock(&s
->chr_write_lock
);
230 while (offset
< len
) {
232 res
= s
->chr_write(s
, buf
+ offset
, len
- offset
);
233 if (res
== -1 && errno
== EAGAIN
) {
236 } while (res
== -1 && errno
== EAGAIN
);
244 qemu_mutex_unlock(&s
->chr_write_lock
);
252 int qemu_chr_fe_read_all(CharDriverState
*s
, uint8_t *buf
, int len
)
254 int offset
= 0, counter
= 10;
257 if (!s
->chr_sync_read
) {
261 while (offset
< len
) {
263 res
= s
->chr_sync_read(s
, buf
+ offset
, len
- offset
);
264 if (res
== -1 && errno
== EAGAIN
) {
267 } while (res
== -1 && errno
== EAGAIN
);
287 int qemu_chr_fe_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
291 return s
->chr_ioctl(s
, cmd
, arg
);
294 int qemu_chr_be_can_write(CharDriverState
*s
)
296 if (!s
->chr_can_read
)
298 return s
->chr_can_read(s
->handler_opaque
);
301 void qemu_chr_be_write(CharDriverState
*s
, uint8_t *buf
, int len
)
304 s
->chr_read(s
->handler_opaque
, buf
, len
);
308 int qemu_chr_fe_get_msgfd(CharDriverState
*s
)
311 return (qemu_chr_fe_get_msgfds(s
, &fd
, 1) == 1) ? fd
: -1;
314 int qemu_chr_fe_get_msgfds(CharDriverState
*s
, int *fds
, int len
)
316 return s
->get_msgfds
? s
->get_msgfds(s
, fds
, len
) : -1;
319 int qemu_chr_fe_set_msgfds(CharDriverState
*s
, int *fds
, int num
)
321 return s
->set_msgfds
? s
->set_msgfds(s
, fds
, num
) : -1;
324 int qemu_chr_add_client(CharDriverState
*s
, int fd
)
326 return s
->chr_add_client
? s
->chr_add_client(s
, fd
) : -1;
329 void qemu_chr_accept_input(CharDriverState
*s
)
331 if (s
->chr_accept_input
)
332 s
->chr_accept_input(s
);
336 void qemu_chr_fe_printf(CharDriverState
*s
, const char *fmt
, ...)
338 char buf
[READ_BUF_LEN
];
341 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
342 qemu_chr_fe_write(s
, (uint8_t *)buf
, strlen(buf
));
346 static void remove_fd_in_watch(CharDriverState
*chr
);
348 void qemu_chr_add_handlers(CharDriverState
*s
,
349 IOCanReadHandler
*fd_can_read
,
350 IOReadHandler
*fd_read
,
351 IOEventHandler
*fd_event
,
356 if (!opaque
&& !fd_can_read
&& !fd_read
&& !fd_event
) {
358 remove_fd_in_watch(s
);
362 s
->chr_can_read
= fd_can_read
;
363 s
->chr_read
= fd_read
;
364 s
->chr_event
= fd_event
;
365 s
->handler_opaque
= opaque
;
366 if (fe_open
&& s
->chr_update_read_handler
)
367 s
->chr_update_read_handler(s
);
369 if (!s
->explicit_fe_open
) {
370 qemu_chr_fe_set_open(s
, fe_open
);
373 /* We're connecting to an already opened device, so let's make sure we
374 also get the open event */
375 if (fe_open
&& s
->be_open
) {
376 qemu_chr_be_generic_open(s
);
380 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
385 static CharDriverState
*qemu_chr_open_null(void)
387 CharDriverState
*chr
;
389 chr
= qemu_chr_alloc();
390 chr
->chr_write
= null_chr_write
;
391 chr
->explicit_be_open
= true;
395 /* MUX driver for serial I/O splitting */
397 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
398 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
400 IOCanReadHandler
*chr_can_read
[MAX_MUX
];
401 IOReadHandler
*chr_read
[MAX_MUX
];
402 IOEventHandler
*chr_event
[MAX_MUX
];
403 void *ext_opaque
[MAX_MUX
];
404 CharDriverState
*drv
;
409 /* Intermediate input buffer allows to catch escape sequences even if the
410 currently active device is not accepting any input - but only until it
412 unsigned char buffer
[MAX_MUX
][MUX_BUFFER_SIZE
];
417 /* Protected by the CharDriverState chr_write_lock. */
419 int64_t timestamps_start
;
423 /* Called with chr_write_lock held. */
424 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
426 MuxDriver
*d
= chr
->opaque
;
428 if (!d
->timestamps
) {
429 ret
= qemu_chr_fe_write(d
->drv
, buf
, len
);
434 for (i
= 0; i
< len
; i
++) {
440 ti
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
441 if (d
->timestamps_start
== -1)
442 d
->timestamps_start
= ti
;
443 ti
-= d
->timestamps_start
;
445 snprintf(buf1
, sizeof(buf1
),
446 "[%02d:%02d:%02d.%03d] ",
451 qemu_chr_fe_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
454 ret
+= qemu_chr_fe_write(d
->drv
, buf
+i
, 1);
455 if (buf
[i
] == '\n') {
463 static const char * const mux_help
[] = {
464 "% h print this help\n\r",
465 "% x exit emulator\n\r",
466 "% s save disk data back to file (if -snapshot)\n\r",
467 "% t toggle console timestamps\n\r"
468 "% b send break (magic sysrq)\n\r",
469 "% c switch between console and monitor\n\r",
474 int term_escape_char
= 0x01; /* ctrl-a is used for escape */
475 static void mux_print_help(CharDriverState
*chr
)
478 char ebuf
[15] = "Escape-Char";
479 char cbuf
[50] = "\n\r";
481 if (term_escape_char
> 0 && term_escape_char
< 26) {
482 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
483 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
485 snprintf(cbuf
, sizeof(cbuf
),
486 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
489 qemu_chr_fe_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
490 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
491 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
492 if (mux_help
[i
][j
] == '%')
493 qemu_chr_fe_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
495 qemu_chr_fe_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
500 static void mux_chr_send_event(MuxDriver
*d
, int mux_nr
, int event
)
502 if (d
->chr_event
[mux_nr
])
503 d
->chr_event
[mux_nr
](d
->ext_opaque
[mux_nr
], event
);
506 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
508 if (d
->term_got_escape
) {
509 d
->term_got_escape
= 0;
510 if (ch
== term_escape_char
)
519 const char *term
= "QEMU: Terminated\n\r";
520 qemu_chr_fe_write(chr
, (uint8_t *)term
, strlen(term
));
528 qemu_chr_be_event(chr
, CHR_EVENT_BREAK
);
531 /* Switch to the next registered device */
532 mux_chr_send_event(d
, d
->focus
, CHR_EVENT_MUX_OUT
);
534 if (d
->focus
>= d
->mux_cnt
)
536 mux_chr_send_event(d
, d
->focus
, CHR_EVENT_MUX_IN
);
539 d
->timestamps
= !d
->timestamps
;
540 d
->timestamps_start
= -1;
544 } else if (ch
== term_escape_char
) {
545 d
->term_got_escape
= 1;
553 static void mux_chr_accept_input(CharDriverState
*chr
)
555 MuxDriver
*d
= chr
->opaque
;
558 while (d
->prod
[m
] != d
->cons
[m
] &&
559 d
->chr_can_read
[m
] &&
560 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
561 d
->chr_read
[m
](d
->ext_opaque
[m
],
562 &d
->buffer
[m
][d
->cons
[m
]++ & MUX_BUFFER_MASK
], 1);
566 static int mux_chr_can_read(void *opaque
)
568 CharDriverState
*chr
= opaque
;
569 MuxDriver
*d
= chr
->opaque
;
572 if ((d
->prod
[m
] - d
->cons
[m
]) < MUX_BUFFER_SIZE
)
574 if (d
->chr_can_read
[m
])
575 return d
->chr_can_read
[m
](d
->ext_opaque
[m
]);
579 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
581 CharDriverState
*chr
= opaque
;
582 MuxDriver
*d
= chr
->opaque
;
586 mux_chr_accept_input (opaque
);
588 for(i
= 0; i
< size
; i
++)
589 if (mux_proc_byte(chr
, d
, buf
[i
])) {
590 if (d
->prod
[m
] == d
->cons
[m
] &&
591 d
->chr_can_read
[m
] &&
592 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
593 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
595 d
->buffer
[m
][d
->prod
[m
]++ & MUX_BUFFER_MASK
] = buf
[i
];
599 static void mux_chr_event(void *opaque
, int event
)
601 CharDriverState
*chr
= opaque
;
602 MuxDriver
*d
= chr
->opaque
;
605 /* Send the event to all registered listeners */
606 for (i
= 0; i
< d
->mux_cnt
; i
++)
607 mux_chr_send_event(d
, i
, event
);
610 static void mux_chr_update_read_handler(CharDriverState
*chr
)
612 MuxDriver
*d
= chr
->opaque
;
614 if (d
->mux_cnt
>= MAX_MUX
) {
615 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
618 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
619 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
620 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
621 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
622 /* Fix up the real driver with mux routines */
623 if (d
->mux_cnt
== 0) {
624 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
627 if (d
->focus
!= -1) {
628 mux_chr_send_event(d
, d
->focus
, CHR_EVENT_MUX_OUT
);
630 d
->focus
= d
->mux_cnt
;
632 mux_chr_send_event(d
, d
->focus
, CHR_EVENT_MUX_IN
);
635 static bool muxes_realized
;
638 * Called after processing of default and command-line-specified
639 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
640 * to a mux chardev. This is done here to ensure that
641 * output/prompts/banners are only displayed for the FE that has
642 * focus when initial command-line processing/machine init is
645 * After this point, any new FE attached to any new or existing
646 * mux will receive CHR_EVENT_OPENED notifications for the BE
649 static void muxes_realize_done(Notifier
*notifier
, void *unused
)
651 CharDriverState
*chr
;
653 QTAILQ_FOREACH(chr
, &chardevs
, next
) {
655 MuxDriver
*d
= chr
->opaque
;
658 /* send OPENED to all already-attached FEs */
659 for (i
= 0; i
< d
->mux_cnt
; i
++) {
660 mux_chr_send_event(d
, i
, CHR_EVENT_OPENED
);
662 /* mark mux as OPENED so any new FEs will immediately receive
665 qemu_chr_be_generic_open(chr
);
668 muxes_realized
= true;
671 static Notifier muxes_realize_notify
= {
672 .notify
= muxes_realize_done
,
675 static GSource
*mux_chr_add_watch(CharDriverState
*s
, GIOCondition cond
)
677 MuxDriver
*d
= s
->opaque
;
678 return d
->drv
->chr_add_watch(d
->drv
, cond
);
681 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
683 CharDriverState
*chr
;
686 chr
= qemu_chr_alloc();
687 d
= g_malloc0(sizeof(MuxDriver
));
692 chr
->chr_write
= mux_chr_write
;
693 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
694 chr
->chr_accept_input
= mux_chr_accept_input
;
695 /* Frontend guest-open / -close notification is not support with muxes */
696 chr
->chr_set_fe_open
= NULL
;
697 if (drv
->chr_add_watch
) {
698 chr
->chr_add_watch
= mux_chr_add_watch
;
700 /* only default to opened state if we've realized the initial
703 chr
->explicit_be_open
= muxes_realized
? 0 : 1;
711 int send_all(int fd
, const void *buf
, int len1
)
717 ret
= send(fd
, buf
, len
, 0);
719 errno
= WSAGetLastError();
720 if (errno
!= WSAEWOULDBLOCK
) {
723 } else if (ret
== 0) {
735 int send_all(int fd
, const void *_buf
, int len1
)
738 const uint8_t *buf
= _buf
;
742 ret
= write(fd
, buf
, len
);
744 if (errno
!= EINTR
&& errno
!= EAGAIN
)
746 } else if (ret
== 0) {
756 int recv_all(int fd
, void *_buf
, int len1
, bool single_read
)
762 while ((len
> 0) && (ret
= read(fd
, buf
, len
)) != 0) {
764 if (errno
!= EINTR
&& errno
!= EAGAIN
) {
781 typedef struct IOWatchPoll
788 IOCanReadHandler
*fd_can_read
;
793 static IOWatchPoll
*io_watch_poll_from_source(GSource
*source
)
795 return container_of(source
, IOWatchPoll
, parent
);
798 static gboolean
io_watch_poll_prepare(GSource
*source
, gint
*timeout_
)
800 IOWatchPoll
*iwp
= io_watch_poll_from_source(source
);
801 bool now_active
= iwp
->fd_can_read(iwp
->opaque
) > 0;
802 bool was_active
= iwp
->src
!= NULL
;
803 if (was_active
== now_active
) {
808 iwp
->src
= g_io_create_watch(iwp
->channel
, G_IO_IN
| G_IO_ERR
| G_IO_HUP
);
809 g_source_set_callback(iwp
->src
, iwp
->fd_read
, iwp
->opaque
, NULL
);
810 g_source_attach(iwp
->src
, NULL
);
812 g_source_destroy(iwp
->src
);
813 g_source_unref(iwp
->src
);
819 static gboolean
io_watch_poll_check(GSource
*source
)
824 static gboolean
io_watch_poll_dispatch(GSource
*source
, GSourceFunc callback
,
830 static void io_watch_poll_finalize(GSource
*source
)
832 /* Due to a glib bug, removing the last reference to a source
833 * inside a finalize callback causes recursive locking (and a
834 * deadlock). This is not a problem inside other callbacks,
835 * including dispatch callbacks, so we call io_remove_watch_poll
836 * to remove this source. At this point, iwp->src must
837 * be NULL, or we would leak it.
839 * This would be solved much more elegantly by child sources,
840 * but we support older glib versions that do not have them.
842 IOWatchPoll
*iwp
= io_watch_poll_from_source(source
);
843 assert(iwp
->src
== NULL
);
846 static GSourceFuncs io_watch_poll_funcs
= {
847 .prepare
= io_watch_poll_prepare
,
848 .check
= io_watch_poll_check
,
849 .dispatch
= io_watch_poll_dispatch
,
850 .finalize
= io_watch_poll_finalize
,
853 /* Can only be used for read */
854 static guint
io_add_watch_poll(GIOChannel
*channel
,
855 IOCanReadHandler
*fd_can_read
,
862 iwp
= (IOWatchPoll
*) g_source_new(&io_watch_poll_funcs
, sizeof(IOWatchPoll
));
863 iwp
->fd_can_read
= fd_can_read
;
864 iwp
->opaque
= user_data
;
865 iwp
->channel
= channel
;
866 iwp
->fd_read
= (GSourceFunc
) fd_read
;
869 tag
= g_source_attach(&iwp
->parent
, NULL
);
870 g_source_unref(&iwp
->parent
);
874 static void io_remove_watch_poll(guint tag
)
879 g_return_if_fail (tag
> 0);
881 source
= g_main_context_find_source_by_id(NULL
, tag
);
882 g_return_if_fail (source
!= NULL
);
884 iwp
= io_watch_poll_from_source(source
);
886 g_source_destroy(iwp
->src
);
887 g_source_unref(iwp
->src
);
890 g_source_destroy(&iwp
->parent
);
893 static void remove_fd_in_watch(CharDriverState
*chr
)
895 if (chr
->fd_in_tag
) {
896 io_remove_watch_poll(chr
->fd_in_tag
);
902 static GIOChannel
*io_channel_from_fd(int fd
)
910 chan
= g_io_channel_unix_new(fd
);
912 g_io_channel_set_encoding(chan
, NULL
, NULL
);
913 g_io_channel_set_buffered(chan
, FALSE
);
919 static GIOChannel
*io_channel_from_socket(int fd
)
928 chan
= g_io_channel_win32_new_socket(fd
);
930 chan
= g_io_channel_unix_new(fd
);
933 g_io_channel_set_encoding(chan
, NULL
, NULL
);
934 g_io_channel_set_buffered(chan
, FALSE
);
939 static int io_channel_send(GIOChannel
*fd
, const void *buf
, size_t len
)
942 GIOStatus status
= G_IO_STATUS_NORMAL
;
944 while (offset
< len
&& status
== G_IO_STATUS_NORMAL
) {
945 gsize bytes_written
= 0;
947 status
= g_io_channel_write_chars(fd
, buf
+ offset
, len
- offset
,
948 &bytes_written
, NULL
);
949 offset
+= bytes_written
;
956 case G_IO_STATUS_NORMAL
:
959 case G_IO_STATUS_AGAIN
:
971 typedef struct FDCharDriver
{
972 CharDriverState
*chr
;
973 GIOChannel
*fd_in
, *fd_out
;
975 QTAILQ_ENTRY(FDCharDriver
) node
;
978 /* Called with chr_write_lock held. */
979 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
981 FDCharDriver
*s
= chr
->opaque
;
983 return io_channel_send(s
->fd_out
, buf
, len
);
986 static gboolean
fd_chr_read(GIOChannel
*chan
, GIOCondition cond
, void *opaque
)
988 CharDriverState
*chr
= opaque
;
989 FDCharDriver
*s
= chr
->opaque
;
991 uint8_t buf
[READ_BUF_LEN
];
996 if (len
> s
->max_size
) {
1003 status
= g_io_channel_read_chars(chan
, (gchar
*)buf
,
1004 len
, &bytes_read
, NULL
);
1005 if (status
== G_IO_STATUS_EOF
) {
1006 remove_fd_in_watch(chr
);
1007 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
1010 if (status
== G_IO_STATUS_NORMAL
) {
1011 qemu_chr_be_write(chr
, buf
, bytes_read
);
1017 static int fd_chr_read_poll(void *opaque
)
1019 CharDriverState
*chr
= opaque
;
1020 FDCharDriver
*s
= chr
->opaque
;
1022 s
->max_size
= qemu_chr_be_can_write(chr
);
1026 static GSource
*fd_chr_add_watch(CharDriverState
*chr
, GIOCondition cond
)
1028 FDCharDriver
*s
= chr
->opaque
;
1029 return g_io_create_watch(s
->fd_out
, cond
);
1032 static void fd_chr_update_read_handler(CharDriverState
*chr
)
1034 FDCharDriver
*s
= chr
->opaque
;
1036 remove_fd_in_watch(chr
);
1038 chr
->fd_in_tag
= io_add_watch_poll(s
->fd_in
, fd_chr_read_poll
,
1043 static void fd_chr_close(struct CharDriverState
*chr
)
1045 FDCharDriver
*s
= chr
->opaque
;
1047 remove_fd_in_watch(chr
);
1049 g_io_channel_unref(s
->fd_in
);
1052 g_io_channel_unref(s
->fd_out
);
1056 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
1059 /* open a character device to a unix fd */
1060 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1062 CharDriverState
*chr
;
1065 chr
= qemu_chr_alloc();
1066 s
= g_malloc0(sizeof(FDCharDriver
));
1067 s
->fd_in
= io_channel_from_fd(fd_in
);
1068 s
->fd_out
= io_channel_from_fd(fd_out
);
1069 qemu_set_nonblock(fd_out
);
1072 chr
->chr_add_watch
= fd_chr_add_watch
;
1073 chr
->chr_write
= fd_chr_write
;
1074 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
1075 chr
->chr_close
= fd_chr_close
;
1080 static CharDriverState
*qemu_chr_open_pipe(ChardevHostdev
*opts
)
1083 char filename_in
[CHR_MAX_FILENAME_SIZE
];
1084 char filename_out
[CHR_MAX_FILENAME_SIZE
];
1085 const char *filename
= opts
->device
;
1087 if (filename
== NULL
) {
1088 fprintf(stderr
, "chardev: pipe: no filename given\n");
1092 snprintf(filename_in
, CHR_MAX_FILENAME_SIZE
, "%s.in", filename
);
1093 snprintf(filename_out
, CHR_MAX_FILENAME_SIZE
, "%s.out", filename
);
1094 TFR(fd_in
= qemu_open(filename_in
, O_RDWR
| O_BINARY
));
1095 TFR(fd_out
= qemu_open(filename_out
, O_RDWR
| O_BINARY
));
1096 if (fd_in
< 0 || fd_out
< 0) {
1101 TFR(fd_in
= fd_out
= qemu_open(filename
, O_RDWR
| O_BINARY
));
1106 return qemu_chr_open_fd(fd_in
, fd_out
);
1109 /* init terminal so that we can grab keys */
1110 static struct termios oldtty
;
1111 static int old_fd0_flags
;
1112 static bool stdio_in_use
;
1113 static bool stdio_allow_signal
;
1115 static void term_exit(void)
1117 tcsetattr (0, TCSANOW
, &oldtty
);
1118 fcntl(0, F_SETFL
, old_fd0_flags
);
1121 static void qemu_chr_set_echo_stdio(CharDriverState
*chr
, bool echo
)
1127 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1128 |INLCR
|IGNCR
|ICRNL
|IXON
);
1129 tty
.c_oflag
|= OPOST
;
1130 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1131 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1134 tty
.c_cc
[VTIME
] = 0;
1136 if (!stdio_allow_signal
)
1137 tty
.c_lflag
&= ~ISIG
;
1139 tcsetattr (0, TCSANOW
, &tty
);
1142 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
1148 static CharDriverState
*qemu_chr_open_stdio(ChardevStdio
*opts
)
1150 CharDriverState
*chr
;
1152 if (is_daemonized()) {
1153 error_report("cannot use stdio with -daemonize");
1158 error_report("cannot use stdio by multiple character devices");
1162 stdio_in_use
= true;
1163 old_fd0_flags
= fcntl(0, F_GETFL
);
1164 tcgetattr(0, &oldtty
);
1165 qemu_set_nonblock(0);
1168 chr
= qemu_chr_open_fd(0, 1);
1169 chr
->chr_close
= qemu_chr_close_stdio
;
1170 chr
->chr_set_echo
= qemu_chr_set_echo_stdio
;
1171 if (opts
->has_signal
) {
1172 stdio_allow_signal
= opts
->signal
;
1174 qemu_chr_fe_set_echo(chr
, false);
1179 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1180 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1181 || defined(__GLIBC__)
1183 #define HAVE_CHARDEV_TTY 1
1189 /* Protected by the CharDriverState chr_write_lock. */
1195 static void pty_chr_update_read_handler_locked(CharDriverState
*chr
);
1196 static void pty_chr_state(CharDriverState
*chr
, int connected
);
1198 static gboolean
pty_chr_timer(gpointer opaque
)
1200 struct CharDriverState
*chr
= opaque
;
1201 PtyCharDriver
*s
= chr
->opaque
;
1203 qemu_mutex_lock(&chr
->chr_write_lock
);
1206 if (!s
->connected
) {
1208 pty_chr_update_read_handler_locked(chr
);
1210 qemu_mutex_unlock(&chr
->chr_write_lock
);
1214 /* Called with chr_write_lock held. */
1215 static void pty_chr_rearm_timer(CharDriverState
*chr
, int ms
)
1217 PtyCharDriver
*s
= chr
->opaque
;
1220 g_source_remove(s
->timer_tag
);
1225 s
->timer_tag
= g_timeout_add_seconds(1, pty_chr_timer
, chr
);
1227 s
->timer_tag
= g_timeout_add(ms
, pty_chr_timer
, chr
);
1231 /* Called with chr_write_lock held. */
1232 static void pty_chr_update_read_handler_locked(CharDriverState
*chr
)
1234 PtyCharDriver
*s
= chr
->opaque
;
1237 pfd
.fd
= g_io_channel_unix_get_fd(s
->fd
);
1238 pfd
.events
= G_IO_OUT
;
1241 if (pfd
.revents
& G_IO_HUP
) {
1242 pty_chr_state(chr
, 0);
1244 pty_chr_state(chr
, 1);
1248 static void pty_chr_update_read_handler(CharDriverState
*chr
)
1250 qemu_mutex_lock(&chr
->chr_write_lock
);
1251 pty_chr_update_read_handler_locked(chr
);
1252 qemu_mutex_unlock(&chr
->chr_write_lock
);
1255 /* Called with chr_write_lock held. */
1256 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1258 PtyCharDriver
*s
= chr
->opaque
;
1260 if (!s
->connected
) {
1261 /* guest sends data, check for (re-)connect */
1262 pty_chr_update_read_handler_locked(chr
);
1263 if (!s
->connected
) {
1267 return io_channel_send(s
->fd
, buf
, len
);
1270 static GSource
*pty_chr_add_watch(CharDriverState
*chr
, GIOCondition cond
)
1272 PtyCharDriver
*s
= chr
->opaque
;
1273 if (!s
->connected
) {
1276 return g_io_create_watch(s
->fd
, cond
);
1279 static int pty_chr_read_poll(void *opaque
)
1281 CharDriverState
*chr
= opaque
;
1282 PtyCharDriver
*s
= chr
->opaque
;
1284 s
->read_bytes
= qemu_chr_be_can_write(chr
);
1285 return s
->read_bytes
;
1288 static gboolean
pty_chr_read(GIOChannel
*chan
, GIOCondition cond
, void *opaque
)
1290 CharDriverState
*chr
= opaque
;
1291 PtyCharDriver
*s
= chr
->opaque
;
1293 uint8_t buf
[READ_BUF_LEN
];
1297 if (len
> s
->read_bytes
)
1298 len
= s
->read_bytes
;
1302 status
= g_io_channel_read_chars(s
->fd
, (gchar
*)buf
, len
, &size
, NULL
);
1303 if (status
!= G_IO_STATUS_NORMAL
) {
1304 pty_chr_state(chr
, 0);
1307 pty_chr_state(chr
, 1);
1308 qemu_chr_be_write(chr
, buf
, size
);
1313 static gboolean
qemu_chr_be_generic_open_func(gpointer opaque
)
1315 CharDriverState
*chr
= opaque
;
1316 PtyCharDriver
*s
= chr
->opaque
;
1319 qemu_chr_be_generic_open(chr
);
1323 /* Called with chr_write_lock held. */
1324 static void pty_chr_state(CharDriverState
*chr
, int connected
)
1326 PtyCharDriver
*s
= chr
->opaque
;
1330 g_source_remove(s
->open_tag
);
1333 remove_fd_in_watch(chr
);
1335 /* (re-)connect poll interval for idle guests: once per second.
1336 * We check more frequently in case the guests sends data to
1337 * the virtual device linked to our pty. */
1338 pty_chr_rearm_timer(chr
, 1000);
1341 g_source_remove(s
->timer_tag
);
1344 if (!s
->connected
) {
1345 g_assert(s
->open_tag
== 0);
1347 s
->open_tag
= g_idle_add(qemu_chr_be_generic_open_func
, chr
);
1349 if (!chr
->fd_in_tag
) {
1350 chr
->fd_in_tag
= io_add_watch_poll(s
->fd
, pty_chr_read_poll
,
1356 static void pty_chr_close(struct CharDriverState
*chr
)
1358 PtyCharDriver
*s
= chr
->opaque
;
1361 qemu_mutex_lock(&chr
->chr_write_lock
);
1362 pty_chr_state(chr
, 0);
1363 fd
= g_io_channel_unix_get_fd(s
->fd
);
1364 g_io_channel_unref(s
->fd
);
1367 g_source_remove(s
->timer_tag
);
1370 qemu_mutex_unlock(&chr
->chr_write_lock
);
1372 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
1375 static CharDriverState
*qemu_chr_open_pty(const char *id
,
1378 CharDriverState
*chr
;
1380 int master_fd
, slave_fd
;
1381 char pty_name
[PATH_MAX
];
1383 master_fd
= qemu_openpty_raw(&slave_fd
, pty_name
);
1384 if (master_fd
< 0) {
1390 chr
= qemu_chr_alloc();
1392 chr
->filename
= g_strdup_printf("pty:%s", pty_name
);
1393 ret
->pty
= g_strdup(pty_name
);
1394 ret
->has_pty
= true;
1396 fprintf(stderr
, "char device redirected to %s (label %s)\n",
1399 s
= g_malloc0(sizeof(PtyCharDriver
));
1401 chr
->chr_write
= pty_chr_write
;
1402 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
1403 chr
->chr_close
= pty_chr_close
;
1404 chr
->chr_add_watch
= pty_chr_add_watch
;
1405 chr
->explicit_be_open
= true;
1407 s
->fd
= io_channel_from_fd(master_fd
);
1413 static void tty_serial_init(int fd
, int speed
,
1414 int parity
, int data_bits
, int stop_bits
)
1420 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1421 speed
, parity
, data_bits
, stop_bits
);
1423 tcgetattr (fd
, &tty
);
1425 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1426 speed
= speed
* 10 / 11;
1443 /* Non-Posix values follow. They may be unsupported on some systems. */
1445 check_speed(115200);
1447 check_speed(230400);
1450 check_speed(460800);
1453 check_speed(500000);
1456 check_speed(576000);
1459 check_speed(921600);
1462 check_speed(1000000);
1465 check_speed(1152000);
1468 check_speed(1500000);
1471 check_speed(2000000);
1474 check_speed(2500000);
1477 check_speed(3000000);
1480 check_speed(3500000);
1483 check_speed(4000000);
1488 cfsetispeed(&tty
, spd
);
1489 cfsetospeed(&tty
, spd
);
1491 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1492 |INLCR
|IGNCR
|ICRNL
|IXON
);
1493 tty
.c_oflag
|= OPOST
;
1494 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1495 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
1516 tty
.c_cflag
|= PARENB
;
1519 tty
.c_cflag
|= PARENB
| PARODD
;
1523 tty
.c_cflag
|= CSTOPB
;
1525 tcsetattr (fd
, TCSANOW
, &tty
);
1528 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1530 FDCharDriver
*s
= chr
->opaque
;
1533 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1535 QEMUSerialSetParams
*ssp
= arg
;
1536 tty_serial_init(g_io_channel_unix_get_fd(s
->fd_in
),
1537 ssp
->speed
, ssp
->parity
,
1538 ssp
->data_bits
, ssp
->stop_bits
);
1541 case CHR_IOCTL_SERIAL_SET_BREAK
:
1543 int enable
= *(int *)arg
;
1545 tcsendbreak(g_io_channel_unix_get_fd(s
->fd_in
), 1);
1549 case CHR_IOCTL_SERIAL_GET_TIOCM
:
1552 int *targ
= (int *)arg
;
1553 ioctl(g_io_channel_unix_get_fd(s
->fd_in
), TIOCMGET
, &sarg
);
1555 if (sarg
& TIOCM_CTS
)
1556 *targ
|= CHR_TIOCM_CTS
;
1557 if (sarg
& TIOCM_CAR
)
1558 *targ
|= CHR_TIOCM_CAR
;
1559 if (sarg
& TIOCM_DSR
)
1560 *targ
|= CHR_TIOCM_DSR
;
1561 if (sarg
& TIOCM_RI
)
1562 *targ
|= CHR_TIOCM_RI
;
1563 if (sarg
& TIOCM_DTR
)
1564 *targ
|= CHR_TIOCM_DTR
;
1565 if (sarg
& TIOCM_RTS
)
1566 *targ
|= CHR_TIOCM_RTS
;
1569 case CHR_IOCTL_SERIAL_SET_TIOCM
:
1571 int sarg
= *(int *)arg
;
1573 ioctl(g_io_channel_unix_get_fd(s
->fd_in
), TIOCMGET
, &targ
);
1574 targ
&= ~(CHR_TIOCM_CTS
| CHR_TIOCM_CAR
| CHR_TIOCM_DSR
1575 | CHR_TIOCM_RI
| CHR_TIOCM_DTR
| CHR_TIOCM_RTS
);
1576 if (sarg
& CHR_TIOCM_CTS
)
1578 if (sarg
& CHR_TIOCM_CAR
)
1580 if (sarg
& CHR_TIOCM_DSR
)
1582 if (sarg
& CHR_TIOCM_RI
)
1584 if (sarg
& CHR_TIOCM_DTR
)
1586 if (sarg
& CHR_TIOCM_RTS
)
1588 ioctl(g_io_channel_unix_get_fd(s
->fd_in
), TIOCMSET
, &targ
);
1597 static void qemu_chr_close_tty(CharDriverState
*chr
)
1599 FDCharDriver
*s
= chr
->opaque
;
1603 fd
= g_io_channel_unix_get_fd(s
->fd_in
);
1613 static CharDriverState
*qemu_chr_open_tty_fd(int fd
)
1615 CharDriverState
*chr
;
1617 tty_serial_init(fd
, 115200, 'N', 8, 1);
1618 chr
= qemu_chr_open_fd(fd
, fd
);
1619 chr
->chr_ioctl
= tty_serial_ioctl
;
1620 chr
->chr_close
= qemu_chr_close_tty
;
1623 #endif /* __linux__ || __sun__ */
1625 #if defined(__linux__)
1627 #define HAVE_CHARDEV_PARPORT 1
1632 } ParallelCharDriver
;
1634 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
1636 if (s
->mode
!= mode
) {
1638 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
1645 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1647 ParallelCharDriver
*drv
= chr
->opaque
;
1652 case CHR_IOCTL_PP_READ_DATA
:
1653 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1655 *(uint8_t *)arg
= b
;
1657 case CHR_IOCTL_PP_WRITE_DATA
:
1658 b
= *(uint8_t *)arg
;
1659 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1662 case CHR_IOCTL_PP_READ_CONTROL
:
1663 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1665 /* Linux gives only the lowest bits, and no way to know data
1666 direction! For better compatibility set the fixed upper
1668 *(uint8_t *)arg
= b
| 0xc0;
1670 case CHR_IOCTL_PP_WRITE_CONTROL
:
1671 b
= *(uint8_t *)arg
;
1672 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1675 case CHR_IOCTL_PP_READ_STATUS
:
1676 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1678 *(uint8_t *)arg
= b
;
1680 case CHR_IOCTL_PP_DATA_DIR
:
1681 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
1684 case CHR_IOCTL_PP_EPP_READ_ADDR
:
1685 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1686 struct ParallelIOArg
*parg
= arg
;
1687 int n
= read(fd
, parg
->buffer
, parg
->count
);
1688 if (n
!= parg
->count
) {
1693 case CHR_IOCTL_PP_EPP_READ
:
1694 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1695 struct ParallelIOArg
*parg
= arg
;
1696 int n
= read(fd
, parg
->buffer
, parg
->count
);
1697 if (n
!= parg
->count
) {
1702 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
1703 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1704 struct ParallelIOArg
*parg
= arg
;
1705 int n
= write(fd
, parg
->buffer
, parg
->count
);
1706 if (n
!= parg
->count
) {
1711 case CHR_IOCTL_PP_EPP_WRITE
:
1712 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1713 struct ParallelIOArg
*parg
= arg
;
1714 int n
= write(fd
, parg
->buffer
, parg
->count
);
1715 if (n
!= parg
->count
) {
1726 static void pp_close(CharDriverState
*chr
)
1728 ParallelCharDriver
*drv
= chr
->opaque
;
1731 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
1732 ioctl(fd
, PPRELEASE
);
1735 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
1738 static CharDriverState
*qemu_chr_open_pp_fd(int fd
)
1740 CharDriverState
*chr
;
1741 ParallelCharDriver
*drv
;
1743 if (ioctl(fd
, PPCLAIM
) < 0) {
1748 drv
= g_malloc0(sizeof(ParallelCharDriver
));
1750 drv
->mode
= IEEE1284_MODE_COMPAT
;
1752 chr
= qemu_chr_alloc();
1753 chr
->chr_write
= null_chr_write
;
1754 chr
->chr_ioctl
= pp_ioctl
;
1755 chr
->chr_close
= pp_close
;
1760 #endif /* __linux__ */
1762 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1764 #define HAVE_CHARDEV_PARPORT 1
1766 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1768 int fd
= (int)(intptr_t)chr
->opaque
;
1772 case CHR_IOCTL_PP_READ_DATA
:
1773 if (ioctl(fd
, PPIGDATA
, &b
) < 0)
1775 *(uint8_t *)arg
= b
;
1777 case CHR_IOCTL_PP_WRITE_DATA
:
1778 b
= *(uint8_t *)arg
;
1779 if (ioctl(fd
, PPISDATA
, &b
) < 0)
1782 case CHR_IOCTL_PP_READ_CONTROL
:
1783 if (ioctl(fd
, PPIGCTRL
, &b
) < 0)
1785 *(uint8_t *)arg
= b
;
1787 case CHR_IOCTL_PP_WRITE_CONTROL
:
1788 b
= *(uint8_t *)arg
;
1789 if (ioctl(fd
, PPISCTRL
, &b
) < 0)
1792 case CHR_IOCTL_PP_READ_STATUS
:
1793 if (ioctl(fd
, PPIGSTATUS
, &b
) < 0)
1795 *(uint8_t *)arg
= b
;
1803 static CharDriverState
*qemu_chr_open_pp_fd(int fd
)
1805 CharDriverState
*chr
;
1807 chr
= qemu_chr_alloc();
1808 chr
->opaque
= (void *)(intptr_t)fd
;
1809 chr
->chr_write
= null_chr_write
;
1810 chr
->chr_ioctl
= pp_ioctl
;
1811 chr
->explicit_be_open
= true;
1820 HANDLE hcom
, hrecv
, hsend
;
1825 /* Protected by the CharDriverState chr_write_lock. */
1831 HANDLE hInputReadyEvent
;
1832 HANDLE hInputDoneEvent
;
1833 HANDLE hInputThread
;
1834 uint8_t win_stdio_buf
;
1835 } WinStdioCharState
;
1837 #define NSENDBUF 2048
1838 #define NRECVBUF 2048
1839 #define MAXCONNECT 1
1840 #define NTIMEOUT 5000
1842 static int win_chr_poll(void *opaque
);
1843 static int win_chr_pipe_poll(void *opaque
);
1845 static void win_chr_close(CharDriverState
*chr
)
1847 WinCharState
*s
= chr
->opaque
;
1850 CloseHandle(s
->hsend
);
1854 CloseHandle(s
->hrecv
);
1858 CloseHandle(s
->hcom
);
1862 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
1864 qemu_del_polling_cb(win_chr_poll
, chr
);
1866 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
1869 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
1871 WinCharState
*s
= chr
->opaque
;
1873 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
1878 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1880 fprintf(stderr
, "Failed CreateEvent\n");
1883 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1885 fprintf(stderr
, "Failed CreateEvent\n");
1889 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
1890 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
1891 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
1892 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
1897 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
1898 fprintf(stderr
, "Failed SetupComm\n");
1902 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
1903 size
= sizeof(COMMCONFIG
);
1904 GetDefaultCommConfig(filename
, &comcfg
, &size
);
1905 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
1906 CommConfigDialog(filename
, NULL
, &comcfg
);
1908 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
1909 fprintf(stderr
, "Failed SetCommState\n");
1913 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
1914 fprintf(stderr
, "Failed SetCommMask\n");
1918 cto
.ReadIntervalTimeout
= MAXDWORD
;
1919 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
1920 fprintf(stderr
, "Failed SetCommTimeouts\n");
1924 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
1925 fprintf(stderr
, "Failed ClearCommError\n");
1928 qemu_add_polling_cb(win_chr_poll
, chr
);
1936 /* Called with chr_write_lock held. */
1937 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
1939 WinCharState
*s
= chr
->opaque
;
1940 DWORD len
, ret
, size
, err
;
1943 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
1944 s
->osend
.hEvent
= s
->hsend
;
1947 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
1949 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
1951 err
= GetLastError();
1952 if (err
== ERROR_IO_PENDING
) {
1953 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
1971 static int win_chr_read_poll(CharDriverState
*chr
)
1973 WinCharState
*s
= chr
->opaque
;
1975 s
->max_size
= qemu_chr_be_can_write(chr
);
1979 static void win_chr_readfile(CharDriverState
*chr
)
1981 WinCharState
*s
= chr
->opaque
;
1983 uint8_t buf
[READ_BUF_LEN
];
1986 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
1987 s
->orecv
.hEvent
= s
->hrecv
;
1988 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
1990 err
= GetLastError();
1991 if (err
== ERROR_IO_PENDING
) {
1992 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
1997 qemu_chr_be_write(chr
, buf
, size
);
2001 static void win_chr_read(CharDriverState
*chr
)
2003 WinCharState
*s
= chr
->opaque
;
2005 if (s
->len
> s
->max_size
)
2006 s
->len
= s
->max_size
;
2010 win_chr_readfile(chr
);
2013 static int win_chr_poll(void *opaque
)
2015 CharDriverState
*chr
= opaque
;
2016 WinCharState
*s
= chr
->opaque
;
2020 ClearCommError(s
->hcom
, &comerr
, &status
);
2021 if (status
.cbInQue
> 0) {
2022 s
->len
= status
.cbInQue
;
2023 win_chr_read_poll(chr
);
2030 static CharDriverState
*qemu_chr_open_win_path(const char *filename
)
2032 CharDriverState
*chr
;
2035 chr
= qemu_chr_alloc();
2036 s
= g_malloc0(sizeof(WinCharState
));
2038 chr
->chr_write
= win_chr_write
;
2039 chr
->chr_close
= win_chr_close
;
2041 if (win_chr_init(chr
, filename
) < 0) {
2049 static int win_chr_pipe_poll(void *opaque
)
2051 CharDriverState
*chr
= opaque
;
2052 WinCharState
*s
= chr
->opaque
;
2055 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2058 win_chr_read_poll(chr
);
2065 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
2067 WinCharState
*s
= chr
->opaque
;
2071 char openname
[CHR_MAX_FILENAME_SIZE
];
2075 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2077 fprintf(stderr
, "Failed CreateEvent\n");
2080 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2082 fprintf(stderr
, "Failed CreateEvent\n");
2086 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2087 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2088 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2090 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2091 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2092 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2097 ZeroMemory(&ov
, sizeof(ov
));
2098 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2099 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2101 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2105 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2107 fprintf(stderr
, "Failed GetOverlappedResult\n");
2109 CloseHandle(ov
.hEvent
);
2116 CloseHandle(ov
.hEvent
);
2119 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
2128 static CharDriverState
*qemu_chr_open_pipe(ChardevHostdev
*opts
)
2130 const char *filename
= opts
->device
;
2131 CharDriverState
*chr
;
2134 chr
= qemu_chr_alloc();
2135 s
= g_malloc0(sizeof(WinCharState
));
2137 chr
->chr_write
= win_chr_write
;
2138 chr
->chr_close
= win_chr_close
;
2140 if (win_chr_pipe_init(chr
, filename
) < 0) {
2148 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2150 CharDriverState
*chr
;
2153 chr
= qemu_chr_alloc();
2154 s
= g_malloc0(sizeof(WinCharState
));
2157 chr
->chr_write
= win_chr_write
;
2161 static CharDriverState
*qemu_chr_open_win_con(void)
2163 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
2166 static int win_stdio_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2168 HANDLE hStdOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
2175 if (!WriteFile(hStdOut
, buf
, len1
, &dwSize
, NULL
)) {
2185 static void win_stdio_wait_func(void *opaque
)
2187 CharDriverState
*chr
= opaque
;
2188 WinStdioCharState
*stdio
= chr
->opaque
;
2189 INPUT_RECORD buf
[4];
2194 ret
= ReadConsoleInput(stdio
->hStdIn
, buf
, ARRAY_SIZE(buf
), &dwSize
);
2197 /* Avoid error storm */
2198 qemu_del_wait_object(stdio
->hStdIn
, NULL
, NULL
);
2202 for (i
= 0; i
< dwSize
; i
++) {
2203 KEY_EVENT_RECORD
*kev
= &buf
[i
].Event
.KeyEvent
;
2205 if (buf
[i
].EventType
== KEY_EVENT
&& kev
->bKeyDown
) {
2207 if (kev
->uChar
.AsciiChar
!= 0) {
2208 for (j
= 0; j
< kev
->wRepeatCount
; j
++) {
2209 if (qemu_chr_be_can_write(chr
)) {
2210 uint8_t c
= kev
->uChar
.AsciiChar
;
2211 qemu_chr_be_write(chr
, &c
, 1);
2219 static DWORD WINAPI
win_stdio_thread(LPVOID param
)
2221 CharDriverState
*chr
= param
;
2222 WinStdioCharState
*stdio
= chr
->opaque
;
2228 /* Wait for one byte */
2229 ret
= ReadFile(stdio
->hStdIn
, &stdio
->win_stdio_buf
, 1, &dwSize
, NULL
);
2231 /* Exit in case of error, continue if nothing read */
2239 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2240 if (stdio
->win_stdio_buf
== '\r') {
2244 /* Signal the main thread and wait until the byte was eaten */
2245 if (!SetEvent(stdio
->hInputReadyEvent
)) {
2248 if (WaitForSingleObject(stdio
->hInputDoneEvent
, INFINITE
)
2254 qemu_del_wait_object(stdio
->hInputReadyEvent
, NULL
, NULL
);
2258 static void win_stdio_thread_wait_func(void *opaque
)
2260 CharDriverState
*chr
= opaque
;
2261 WinStdioCharState
*stdio
= chr
->opaque
;
2263 if (qemu_chr_be_can_write(chr
)) {
2264 qemu_chr_be_write(chr
, &stdio
->win_stdio_buf
, 1);
2267 SetEvent(stdio
->hInputDoneEvent
);
2270 static void qemu_chr_set_echo_win_stdio(CharDriverState
*chr
, bool echo
)
2272 WinStdioCharState
*stdio
= chr
->opaque
;
2275 GetConsoleMode(stdio
->hStdIn
, &dwMode
);
2278 SetConsoleMode(stdio
->hStdIn
, dwMode
| ENABLE_ECHO_INPUT
);
2280 SetConsoleMode(stdio
->hStdIn
, dwMode
& ~ENABLE_ECHO_INPUT
);
2284 static void win_stdio_close(CharDriverState
*chr
)
2286 WinStdioCharState
*stdio
= chr
->opaque
;
2288 if (stdio
->hInputReadyEvent
!= INVALID_HANDLE_VALUE
) {
2289 CloseHandle(stdio
->hInputReadyEvent
);
2291 if (stdio
->hInputDoneEvent
!= INVALID_HANDLE_VALUE
) {
2292 CloseHandle(stdio
->hInputDoneEvent
);
2294 if (stdio
->hInputThread
!= INVALID_HANDLE_VALUE
) {
2295 TerminateThread(stdio
->hInputThread
, 0);
2298 g_free(chr
->opaque
);
2302 static CharDriverState
*qemu_chr_open_stdio(ChardevStdio
*opts
)
2304 CharDriverState
*chr
;
2305 WinStdioCharState
*stdio
;
2309 chr
= qemu_chr_alloc();
2310 stdio
= g_malloc0(sizeof(WinStdioCharState
));
2312 stdio
->hStdIn
= GetStdHandle(STD_INPUT_HANDLE
);
2313 if (stdio
->hStdIn
== INVALID_HANDLE_VALUE
) {
2314 fprintf(stderr
, "cannot open stdio: invalid handle\n");
2318 is_console
= GetConsoleMode(stdio
->hStdIn
, &dwMode
) != 0;
2320 chr
->opaque
= stdio
;
2321 chr
->chr_write
= win_stdio_write
;
2322 chr
->chr_close
= win_stdio_close
;
2325 if (qemu_add_wait_object(stdio
->hStdIn
,
2326 win_stdio_wait_func
, chr
)) {
2327 fprintf(stderr
, "qemu_add_wait_object: failed\n");
2332 stdio
->hInputReadyEvent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2333 stdio
->hInputDoneEvent
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
2334 stdio
->hInputThread
= CreateThread(NULL
, 0, win_stdio_thread
,
2337 if (stdio
->hInputThread
== INVALID_HANDLE_VALUE
2338 || stdio
->hInputReadyEvent
== INVALID_HANDLE_VALUE
2339 || stdio
->hInputDoneEvent
== INVALID_HANDLE_VALUE
) {
2340 fprintf(stderr
, "cannot create stdio thread or event\n");
2343 if (qemu_add_wait_object(stdio
->hInputReadyEvent
,
2344 win_stdio_thread_wait_func
, chr
)) {
2345 fprintf(stderr
, "qemu_add_wait_object: failed\n");
2349 dwMode
|= ENABLE_LINE_INPUT
;
2352 /* set the terminal in raw mode */
2353 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2354 dwMode
|= ENABLE_PROCESSED_INPUT
;
2357 SetConsoleMode(stdio
->hStdIn
, dwMode
);
2359 chr
->chr_set_echo
= qemu_chr_set_echo_win_stdio
;
2360 qemu_chr_fe_set_echo(chr
, false);
2364 #endif /* !_WIN32 */
2367 /***********************************************************/
2368 /* UDP Net console */
2373 uint8_t buf
[READ_BUF_LEN
];
2379 /* Called with chr_write_lock held. */
2380 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2382 NetCharDriver
*s
= chr
->opaque
;
2383 gsize bytes_written
;
2386 status
= g_io_channel_write_chars(s
->chan
, (const gchar
*)buf
, len
, &bytes_written
, NULL
);
2387 if (status
== G_IO_STATUS_EOF
) {
2389 } else if (status
!= G_IO_STATUS_NORMAL
) {
2393 return bytes_written
;
2396 static int udp_chr_read_poll(void *opaque
)
2398 CharDriverState
*chr
= opaque
;
2399 NetCharDriver
*s
= chr
->opaque
;
2401 s
->max_size
= qemu_chr_be_can_write(chr
);
2403 /* If there were any stray characters in the queue process them
2406 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2407 qemu_chr_be_write(chr
, &s
->buf
[s
->bufptr
], 1);
2409 s
->max_size
= qemu_chr_be_can_write(chr
);
2414 static gboolean
udp_chr_read(GIOChannel
*chan
, GIOCondition cond
, void *opaque
)
2416 CharDriverState
*chr
= opaque
;
2417 NetCharDriver
*s
= chr
->opaque
;
2418 gsize bytes_read
= 0;
2421 if (s
->max_size
== 0) {
2424 status
= g_io_channel_read_chars(s
->chan
, (gchar
*)s
->buf
, sizeof(s
->buf
),
2426 s
->bufcnt
= bytes_read
;
2427 s
->bufptr
= s
->bufcnt
;
2428 if (status
!= G_IO_STATUS_NORMAL
) {
2429 remove_fd_in_watch(chr
);
2434 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2435 qemu_chr_be_write(chr
, &s
->buf
[s
->bufptr
], 1);
2437 s
->max_size
= qemu_chr_be_can_write(chr
);
2443 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2445 NetCharDriver
*s
= chr
->opaque
;
2447 remove_fd_in_watch(chr
);
2449 chr
->fd_in_tag
= io_add_watch_poll(s
->chan
, udp_chr_read_poll
,
2454 static void udp_chr_close(CharDriverState
*chr
)
2456 NetCharDriver
*s
= chr
->opaque
;
2458 remove_fd_in_watch(chr
);
2460 g_io_channel_unref(s
->chan
);
2464 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
2467 static CharDriverState
*qemu_chr_open_udp_fd(int fd
)
2469 CharDriverState
*chr
= NULL
;
2470 NetCharDriver
*s
= NULL
;
2472 chr
= qemu_chr_alloc();
2473 s
= g_malloc0(sizeof(NetCharDriver
));
2476 s
->chan
= io_channel_from_socket(s
->fd
);
2480 chr
->chr_write
= udp_chr_write
;
2481 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
2482 chr
->chr_close
= udp_chr_close
;
2483 /* be isn't opened until we get a connection */
2484 chr
->explicit_be_open
= true;
2488 /***********************************************************/
2489 /* TCP Net console */
2493 GIOChannel
*chan
, *listen_chan
;
2502 int read_msgfds_num
;
2504 int write_msgfds_num
;
2506 SocketAddress
*addr
;
2510 guint reconnect_timer
;
2511 int64_t reconnect_time
;
2512 bool connect_err_reported
;
2515 static gboolean
socket_reconnect_timeout(gpointer opaque
);
2517 static void qemu_chr_socket_restart_timer(CharDriverState
*chr
)
2519 TCPCharDriver
*s
= chr
->opaque
;
2520 assert(s
->connected
== 0);
2521 s
->reconnect_timer
= g_timeout_add_seconds(s
->reconnect_time
,
2522 socket_reconnect_timeout
, chr
);
2525 static void check_report_connect_error(CharDriverState
*chr
,
2528 TCPCharDriver
*s
= chr
->opaque
;
2530 if (!s
->connect_err_reported
) {
2531 error_report("Unable to connect character device %s: %s",
2532 chr
->label
, error_get_pretty(err
));
2533 s
->connect_err_reported
= true;
2535 qemu_chr_socket_restart_timer(chr
);
2538 static gboolean
tcp_chr_accept(GIOChannel
*chan
, GIOCondition cond
, void *opaque
);
2541 static int unix_send_msgfds(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2543 TCPCharDriver
*s
= chr
->opaque
;
2548 size_t fd_size
= s
->write_msgfds_num
* sizeof(int);
2549 char control
[CMSG_SPACE(fd_size
)];
2550 struct cmsghdr
*cmsg
;
2552 memset(&msgh
, 0, sizeof(msgh
));
2553 memset(control
, 0, sizeof(control
));
2555 /* set the payload */
2556 iov
.iov_base
= (uint8_t *) buf
;
2559 msgh
.msg_iov
= &iov
;
2560 msgh
.msg_iovlen
= 1;
2562 msgh
.msg_control
= control
;
2563 msgh
.msg_controllen
= sizeof(control
);
2565 cmsg
= CMSG_FIRSTHDR(&msgh
);
2567 cmsg
->cmsg_len
= CMSG_LEN(fd_size
);
2568 cmsg
->cmsg_level
= SOL_SOCKET
;
2569 cmsg
->cmsg_type
= SCM_RIGHTS
;
2570 memcpy(CMSG_DATA(cmsg
), s
->write_msgfds
, fd_size
);
2573 r
= sendmsg(s
->fd
, &msgh
, 0);
2574 } while (r
< 0 && errno
== EINTR
);
2576 /* free the written msgfds, no matter what */
2577 if (s
->write_msgfds_num
) {
2578 g_free(s
->write_msgfds
);
2579 s
->write_msgfds
= 0;
2580 s
->write_msgfds_num
= 0;
2587 /* Called with chr_write_lock held. */
2588 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2590 TCPCharDriver
*s
= chr
->opaque
;
2593 if (s
->is_unix
&& s
->write_msgfds_num
) {
2594 return unix_send_msgfds(chr
, buf
, len
);
2598 return io_channel_send(s
->chan
, buf
, len
);
2601 /* XXX: indicate an error ? */
2606 static int tcp_chr_read_poll(void *opaque
)
2608 CharDriverState
*chr
= opaque
;
2609 TCPCharDriver
*s
= chr
->opaque
;
2612 s
->max_size
= qemu_chr_be_can_write(chr
);
2617 #define IAC_BREAK 243
2618 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2620 uint8_t *buf
, int *size
)
2622 /* Handle any telnet client's basic IAC options to satisfy char by
2623 * char mode with no echo. All IAC options will be removed from
2624 * the buf and the do_telnetopt variable will be used to track the
2625 * state of the width of the IAC information.
2627 * IAC commands come in sets of 3 bytes with the exception of the
2628 * "IAC BREAK" command and the double IAC.
2634 for (i
= 0; i
< *size
; i
++) {
2635 if (s
->do_telnetopt
> 1) {
2636 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2637 /* Double IAC means send an IAC */
2641 s
->do_telnetopt
= 1;
2643 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2644 /* Handle IAC break commands by sending a serial break */
2645 qemu_chr_be_event(chr
, CHR_EVENT_BREAK
);
2650 if (s
->do_telnetopt
>= 4) {
2651 s
->do_telnetopt
= 1;
2654 if ((unsigned char)buf
[i
] == IAC
) {
2655 s
->do_telnetopt
= 2;
2666 static int tcp_get_msgfds(CharDriverState
*chr
, int *fds
, int num
)
2668 TCPCharDriver
*s
= chr
->opaque
;
2669 int to_copy
= (s
->read_msgfds_num
< num
) ? s
->read_msgfds_num
: num
;
2674 memcpy(fds
, s
->read_msgfds
, to_copy
* sizeof(int));
2676 /* Close unused fds */
2677 for (i
= to_copy
; i
< s
->read_msgfds_num
; i
++) {
2678 close(s
->read_msgfds
[i
]);
2681 g_free(s
->read_msgfds
);
2683 s
->read_msgfds_num
= 0;
2689 static int tcp_set_msgfds(CharDriverState
*chr
, int *fds
, int num
)
2691 TCPCharDriver
*s
= chr
->opaque
;
2693 /* clear old pending fd array */
2694 if (s
->write_msgfds
) {
2695 g_free(s
->write_msgfds
);
2699 s
->write_msgfds
= g_malloc(num
* sizeof(int));
2700 memcpy(s
->write_msgfds
, fds
, num
* sizeof(int));
2703 s
->write_msgfds_num
= num
;
2709 static void unix_process_msgfd(CharDriverState
*chr
, struct msghdr
*msg
)
2711 TCPCharDriver
*s
= chr
->opaque
;
2712 struct cmsghdr
*cmsg
;
2714 for (cmsg
= CMSG_FIRSTHDR(msg
); cmsg
; cmsg
= CMSG_NXTHDR(msg
, cmsg
)) {
2717 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(int)) ||
2718 cmsg
->cmsg_level
!= SOL_SOCKET
||
2719 cmsg
->cmsg_type
!= SCM_RIGHTS
) {
2723 fd_size
= cmsg
->cmsg_len
- CMSG_LEN(0);
2729 /* close and clean read_msgfds */
2730 for (i
= 0; i
< s
->read_msgfds_num
; i
++) {
2731 close(s
->read_msgfds
[i
]);
2734 if (s
->read_msgfds_num
) {
2735 g_free(s
->read_msgfds
);
2738 s
->read_msgfds_num
= fd_size
/ sizeof(int);
2739 s
->read_msgfds
= g_malloc(fd_size
);
2740 memcpy(s
->read_msgfds
, CMSG_DATA(cmsg
), fd_size
);
2742 for (i
= 0; i
< s
->read_msgfds_num
; i
++) {
2743 int fd
= s
->read_msgfds
[i
];
2748 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2751 #ifndef MSG_CMSG_CLOEXEC
2752 qemu_set_cloexec(fd
);
2758 static ssize_t
tcp_chr_recv(CharDriverState
*chr
, char *buf
, size_t len
)
2760 TCPCharDriver
*s
= chr
->opaque
;
2761 struct msghdr msg
= { NULL
, };
2762 struct iovec iov
[1];
2764 struct cmsghdr cmsg
;
2765 char control
[CMSG_SPACE(sizeof(int))];
2770 iov
[0].iov_base
= buf
;
2771 iov
[0].iov_len
= len
;
2775 msg
.msg_control
= &msg_control
;
2776 msg
.msg_controllen
= sizeof(msg_control
);
2778 #ifdef MSG_CMSG_CLOEXEC
2779 flags
|= MSG_CMSG_CLOEXEC
;
2781 ret
= recvmsg(s
->fd
, &msg
, flags
);
2782 if (ret
> 0 && s
->is_unix
) {
2783 unix_process_msgfd(chr
, &msg
);
2789 static ssize_t
tcp_chr_recv(CharDriverState
*chr
, char *buf
, size_t len
)
2791 TCPCharDriver
*s
= chr
->opaque
;
2792 return qemu_recv(s
->fd
, buf
, len
, 0);
2796 static GSource
*tcp_chr_add_watch(CharDriverState
*chr
, GIOCondition cond
)
2798 TCPCharDriver
*s
= chr
->opaque
;
2799 return g_io_create_watch(s
->chan
, cond
);
2802 static void tcp_chr_disconnect(CharDriverState
*chr
)
2804 TCPCharDriver
*s
= chr
->opaque
;
2807 if (s
->listen_chan
) {
2808 s
->listen_tag
= g_io_add_watch(s
->listen_chan
, G_IO_IN
,
2809 tcp_chr_accept
, chr
);
2811 remove_fd_in_watch(chr
);
2812 g_io_channel_unref(s
->chan
);
2816 SocketAddress_to_str(chr
->filename
, CHR_MAX_FILENAME_SIZE
,
2817 "disconnected:", s
->addr
, s
->is_listen
, s
->is_telnet
);
2818 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
2819 if (s
->reconnect_time
) {
2820 qemu_chr_socket_restart_timer(chr
);
2824 static gboolean
tcp_chr_read(GIOChannel
*chan
, GIOCondition cond
, void *opaque
)
2826 CharDriverState
*chr
= opaque
;
2827 TCPCharDriver
*s
= chr
->opaque
;
2828 uint8_t buf
[READ_BUF_LEN
];
2831 if (cond
& G_IO_HUP
) {
2832 /* connection closed */
2833 tcp_chr_disconnect(chr
);
2837 if (!s
->connected
|| s
->max_size
<= 0) {
2841 if (len
> s
->max_size
)
2843 size
= tcp_chr_recv(chr
, (void *)buf
, len
);
2845 /* connection closed */
2846 tcp_chr_disconnect(chr
);
2847 } else if (size
> 0) {
2848 if (s
->do_telnetopt
)
2849 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2851 qemu_chr_be_write(chr
, buf
, size
);
2857 static int tcp_chr_sync_read(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2859 TCPCharDriver
*s
= chr
->opaque
;
2862 if (!s
->connected
) {
2866 size
= tcp_chr_recv(chr
, (void *) buf
, len
);
2868 /* connection closed */
2869 tcp_chr_disconnect(chr
);
2876 CharDriverState
*qemu_chr_open_eventfd(int eventfd
)
2878 CharDriverState
*chr
= qemu_chr_open_fd(eventfd
, eventfd
);
2881 chr
->avail_connections
= 1;
2888 static void tcp_chr_connect(void *opaque
)
2890 CharDriverState
*chr
= opaque
;
2891 TCPCharDriver
*s
= chr
->opaque
;
2892 struct sockaddr_storage ss
, ps
;
2893 socklen_t ss_len
= sizeof(ss
), ps_len
= sizeof(ps
);
2895 memset(&ss
, 0, ss_len
);
2896 if (getsockname(s
->fd
, (struct sockaddr
*) &ss
, &ss_len
) != 0) {
2897 snprintf(chr
->filename
, CHR_MAX_FILENAME_SIZE
,
2898 "Error in getsockname: %s\n", strerror(errno
));
2899 } else if (getpeername(s
->fd
, (struct sockaddr
*) &ps
, &ps_len
) != 0) {
2900 snprintf(chr
->filename
, CHR_MAX_FILENAME_SIZE
,
2901 "Error in getpeername: %s\n", strerror(errno
));
2903 sockaddr_to_str(chr
->filename
, CHR_MAX_FILENAME_SIZE
,
2904 &ss
, ss_len
, &ps
, ps_len
,
2905 s
->is_listen
, s
->is_telnet
);
2910 chr
->fd_in_tag
= io_add_watch_poll(s
->chan
, tcp_chr_read_poll
,
2913 qemu_chr_be_generic_open(chr
);
2916 static void tcp_chr_update_read_handler(CharDriverState
*chr
)
2918 TCPCharDriver
*s
= chr
->opaque
;
2920 remove_fd_in_watch(chr
);
2922 chr
->fd_in_tag
= io_add_watch_poll(s
->chan
, tcp_chr_read_poll
,
2927 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2928 static void tcp_chr_telnet_init(int fd
)
2931 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2932 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2933 send(fd
, (char *)buf
, 3, 0);
2934 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2935 send(fd
, (char *)buf
, 3, 0);
2936 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2937 send(fd
, (char *)buf
, 3, 0);
2938 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2939 send(fd
, (char *)buf
, 3, 0);
2942 static int tcp_chr_add_client(CharDriverState
*chr
, int fd
)
2944 TCPCharDriver
*s
= chr
->opaque
;
2948 qemu_set_nonblock(fd
);
2950 socket_set_nodelay(fd
);
2952 s
->chan
= io_channel_from_socket(fd
);
2953 if (s
->listen_tag
) {
2954 g_source_remove(s
->listen_tag
);
2957 tcp_chr_connect(chr
);
2962 static gboolean
tcp_chr_accept(GIOChannel
*channel
, GIOCondition cond
, void *opaque
)
2964 CharDriverState
*chr
= opaque
;
2965 TCPCharDriver
*s
= chr
->opaque
;
2966 struct sockaddr_in saddr
;
2968 struct sockaddr_un uaddr
;
2970 struct sockaddr
*addr
;
2977 len
= sizeof(uaddr
);
2978 addr
= (struct sockaddr
*)&uaddr
;
2982 len
= sizeof(saddr
);
2983 addr
= (struct sockaddr
*)&saddr
;
2985 fd
= qemu_accept(s
->listen_fd
, addr
, &len
);
2986 if (fd
< 0 && errno
!= EINTR
) {
2989 } else if (fd
>= 0) {
2990 if (s
->do_telnetopt
)
2991 tcp_chr_telnet_init(fd
);
2995 if (tcp_chr_add_client(chr
, fd
) < 0)
3001 static void tcp_chr_close(CharDriverState
*chr
)
3003 TCPCharDriver
*s
= chr
->opaque
;
3006 if (s
->reconnect_timer
) {
3007 g_source_remove(s
->reconnect_timer
);
3008 s
->reconnect_timer
= 0;
3010 qapi_free_SocketAddress(s
->addr
);
3012 remove_fd_in_watch(chr
);
3014 g_io_channel_unref(s
->chan
);
3018 if (s
->listen_fd
>= 0) {
3019 if (s
->listen_tag
) {
3020 g_source_remove(s
->listen_tag
);
3023 if (s
->listen_chan
) {
3024 g_io_channel_unref(s
->listen_chan
);
3026 closesocket(s
->listen_fd
);
3028 if (s
->read_msgfds_num
) {
3029 for (i
= 0; i
< s
->read_msgfds_num
; i
++) {
3030 close(s
->read_msgfds
[i
]);
3032 g_free(s
->read_msgfds
);
3034 if (s
->write_msgfds_num
) {
3035 g_free(s
->write_msgfds
);
3038 qemu_chr_be_event(chr
, CHR_EVENT_CLOSED
);
3041 static void qemu_chr_finish_socket_connection(CharDriverState
*chr
, int fd
)
3043 TCPCharDriver
*s
= chr
->opaque
;
3047 s
->listen_chan
= io_channel_from_socket(s
->listen_fd
);
3048 s
->listen_tag
= g_io_add_watch(s
->listen_chan
, G_IO_IN
,
3049 tcp_chr_accept
, chr
);
3053 socket_set_nodelay(fd
);
3054 s
->chan
= io_channel_from_socket(s
->fd
);
3055 tcp_chr_connect(chr
);
3059 static void qemu_chr_socket_connected(int fd
, Error
*err
, void *opaque
)
3061 CharDriverState
*chr
= opaque
;
3062 TCPCharDriver
*s
= chr
->opaque
;
3065 check_report_connect_error(chr
, err
);
3069 s
->connect_err_reported
= false;
3070 qemu_chr_finish_socket_connection(chr
, fd
);
3073 static bool qemu_chr_open_socket_fd(CharDriverState
*chr
, Error
**errp
)
3075 TCPCharDriver
*s
= chr
->opaque
;
3079 fd
= socket_listen(s
->addr
, errp
);
3080 } else if (s
->reconnect_time
) {
3081 fd
= socket_connect(s
->addr
, errp
, qemu_chr_socket_connected
, chr
);
3084 fd
= socket_connect(s
->addr
, errp
, NULL
, NULL
);
3090 qemu_chr_finish_socket_connection(chr
, fd
);
3094 /*********************************************************/
3095 /* Ring buffer chardev */
3102 } RingBufCharDriver
;
3104 static size_t ringbuf_count(const CharDriverState
*chr
)
3106 const RingBufCharDriver
*d
= chr
->opaque
;
3108 return d
->prod
- d
->cons
;
3111 /* Called with chr_write_lock held. */
3112 static int ringbuf_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3114 RingBufCharDriver
*d
= chr
->opaque
;
3117 if (!buf
|| (len
< 0)) {
3121 for (i
= 0; i
< len
; i
++ ) {
3122 d
->cbuf
[d
->prod
++ & (d
->size
- 1)] = buf
[i
];
3123 if (d
->prod
- d
->cons
> d
->size
) {
3124 d
->cons
= d
->prod
- d
->size
;
3131 static int ringbuf_chr_read(CharDriverState
*chr
, uint8_t *buf
, int len
)
3133 RingBufCharDriver
*d
= chr
->opaque
;
3136 qemu_mutex_lock(&chr
->chr_write_lock
);
3137 for (i
= 0; i
< len
&& d
->cons
!= d
->prod
; i
++) {
3138 buf
[i
] = d
->cbuf
[d
->cons
++ & (d
->size
- 1)];
3140 qemu_mutex_unlock(&chr
->chr_write_lock
);
3145 static void ringbuf_chr_close(struct CharDriverState
*chr
)
3147 RingBufCharDriver
*d
= chr
->opaque
;
3154 static CharDriverState
*qemu_chr_open_ringbuf(ChardevRingbuf
*opts
,
3157 CharDriverState
*chr
;
3158 RingBufCharDriver
*d
;
3160 chr
= qemu_chr_alloc();
3161 d
= g_malloc(sizeof(*d
));
3163 d
->size
= opts
->has_size
? opts
->size
: 65536;
3165 /* The size must be power of 2 */
3166 if (d
->size
& (d
->size
- 1)) {
3167 error_setg(errp
, "size of ringbuf chardev must be power of two");
3173 d
->cbuf
= g_malloc0(d
->size
);
3176 chr
->chr_write
= ringbuf_chr_write
;
3177 chr
->chr_close
= ringbuf_chr_close
;
3187 bool chr_is_ringbuf(const CharDriverState
*chr
)
3189 return chr
->chr_write
== ringbuf_chr_write
;
3192 void qmp_ringbuf_write(const char *device
, const char *data
,
3193 bool has_format
, enum DataFormat format
,
3196 CharDriverState
*chr
;
3197 const uint8_t *write_data
;
3201 chr
= qemu_chr_find(device
);
3203 error_setg(errp
, "Device '%s' not found", device
);
3207 if (!chr_is_ringbuf(chr
)) {
3208 error_setg(errp
,"%s is not a ringbuf device", device
);
3212 if (has_format
&& (format
== DATA_FORMAT_BASE64
)) {
3213 write_data
= g_base64_decode(data
, &write_count
);
3215 write_data
= (uint8_t *)data
;
3216 write_count
= strlen(data
);
3219 ret
= ringbuf_chr_write(chr
, write_data
, write_count
);
3221 if (write_data
!= (uint8_t *)data
) {
3222 g_free((void *)write_data
);
3226 error_setg(errp
, "Failed to write to device %s", device
);
3231 char *qmp_ringbuf_read(const char *device
, int64_t size
,
3232 bool has_format
, enum DataFormat format
,
3235 CharDriverState
*chr
;
3240 chr
= qemu_chr_find(device
);
3242 error_setg(errp
, "Device '%s' not found", device
);
3246 if (!chr_is_ringbuf(chr
)) {
3247 error_setg(errp
,"%s is not a ringbuf device", device
);
3252 error_setg(errp
, "size must be greater than zero");
3256 count
= ringbuf_count(chr
);
3257 size
= size
> count
? count
: size
;
3258 read_data
= g_malloc(size
+ 1);
3260 ringbuf_chr_read(chr
, read_data
, size
);
3262 if (has_format
&& (format
== DATA_FORMAT_BASE64
)) {
3263 data
= g_base64_encode(read_data
, size
);
3267 * FIXME should read only complete, valid UTF-8 characters up
3268 * to @size bytes. Invalid sequences should be replaced by a
3269 * suitable replacement character. Except when (and only
3270 * when) ring buffer lost characters since last read, initial
3271 * continuation characters should be dropped.
3273 read_data
[size
] = 0;
3274 data
= (char *)read_data
;
3280 QemuOpts
*qemu_chr_parse_compat(const char *label
, const char *filename
)
3282 char host
[65], port
[33], width
[8], height
[8];
3286 Error
*local_err
= NULL
;
3288 opts
= qemu_opts_create(qemu_find_opts("chardev"), label
, 1, &local_err
);
3290 qerror_report_err(local_err
);
3291 error_free(local_err
);
3295 if (strstart(filename
, "mon:", &p
)) {
3297 qemu_opt_set(opts
, "mux", "on");
3298 if (strcmp(filename
, "stdio") == 0) {
3299 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3300 * but pass it to the guest. Handle this only for compat syntax,
3301 * for -chardev syntax we have special option for this.
3302 * This is what -nographic did, redirecting+muxing serial+monitor
3303 * to stdio causing Ctrl+C to be passed to guest. */
3304 qemu_opt_set(opts
, "signal", "off");
3308 if (strcmp(filename
, "null") == 0 ||
3309 strcmp(filename
, "pty") == 0 ||
3310 strcmp(filename
, "msmouse") == 0 ||
3311 strcmp(filename
, "braille") == 0 ||
3312 strcmp(filename
, "testdev") == 0 ||
3313 strcmp(filename
, "stdio") == 0) {
3314 qemu_opt_set(opts
, "backend", filename
);
3317 if (strstart(filename
, "vc", &p
)) {
3318 qemu_opt_set(opts
, "backend", "vc");
3320 if (sscanf(p
+1, "%7[0-9]x%7[0-9]", width
, height
) == 2) {
3322 qemu_opt_set(opts
, "width", width
);
3323 qemu_opt_set(opts
, "height", height
);
3324 } else if (sscanf(p
+1, "%7[0-9]Cx%7[0-9]C", width
, height
) == 2) {
3326 qemu_opt_set(opts
, "cols", width
);
3327 qemu_opt_set(opts
, "rows", height
);
3334 if (strcmp(filename
, "con:") == 0) {
3335 qemu_opt_set(opts
, "backend", "console");
3338 if (strstart(filename
, "COM", NULL
)) {
3339 qemu_opt_set(opts
, "backend", "serial");
3340 qemu_opt_set(opts
, "path", filename
);
3343 if (strstart(filename
, "file:", &p
)) {
3344 qemu_opt_set(opts
, "backend", "file");
3345 qemu_opt_set(opts
, "path", p
);
3348 if (strstart(filename
, "pipe:", &p
)) {
3349 qemu_opt_set(opts
, "backend", "pipe");
3350 qemu_opt_set(opts
, "path", p
);
3353 if (strstart(filename
, "tcp:", &p
) ||
3354 strstart(filename
, "telnet:", &p
)) {
3355 if (sscanf(p
, "%64[^:]:%32[^,]%n", host
, port
, &pos
) < 2) {
3357 if (sscanf(p
, ":%32[^,]%n", port
, &pos
) < 1)
3360 qemu_opt_set(opts
, "backend", "socket");
3361 qemu_opt_set(opts
, "host", host
);
3362 qemu_opt_set(opts
, "port", port
);
3363 if (p
[pos
] == ',') {
3364 if (qemu_opts_do_parse(opts
, p
+pos
+1, NULL
) != 0)
3367 if (strstart(filename
, "telnet:", &p
))
3368 qemu_opt_set(opts
, "telnet", "on");
3371 if (strstart(filename
, "udp:", &p
)) {
3372 qemu_opt_set(opts
, "backend", "udp");
3373 if (sscanf(p
, "%64[^:]:%32[^@,]%n", host
, port
, &pos
) < 2) {
3375 if (sscanf(p
, ":%32[^@,]%n", port
, &pos
) < 1) {
3379 qemu_opt_set(opts
, "host", host
);
3380 qemu_opt_set(opts
, "port", port
);
3381 if (p
[pos
] == '@') {
3383 if (sscanf(p
, "%64[^:]:%32[^,]%n", host
, port
, &pos
) < 2) {
3385 if (sscanf(p
, ":%32[^,]%n", port
, &pos
) < 1) {
3389 qemu_opt_set(opts
, "localaddr", host
);
3390 qemu_opt_set(opts
, "localport", port
);
3394 if (strstart(filename
, "unix:", &p
)) {
3395 qemu_opt_set(opts
, "backend", "socket");
3396 if (qemu_opts_do_parse(opts
, p
, "path") != 0)
3400 if (strstart(filename
, "/dev/parport", NULL
) ||
3401 strstart(filename
, "/dev/ppi", NULL
)) {
3402 qemu_opt_set(opts
, "backend", "parport");
3403 qemu_opt_set(opts
, "path", filename
);
3406 if (strstart(filename
, "/dev/", NULL
)) {
3407 qemu_opt_set(opts
, "backend", "tty");
3408 qemu_opt_set(opts
, "path", filename
);
3413 qemu_opts_del(opts
);
3417 static void qemu_chr_parse_file_out(QemuOpts
*opts
, ChardevBackend
*backend
,
3420 const char *path
= qemu_opt_get(opts
, "path");
3423 error_setg(errp
, "chardev: file: no filename given");
3426 backend
->file
= g_new0(ChardevFile
, 1);
3427 backend
->file
->out
= g_strdup(path
);
3430 static void qemu_chr_parse_stdio(QemuOpts
*opts
, ChardevBackend
*backend
,
3433 backend
->stdio
= g_new0(ChardevStdio
, 1);
3434 backend
->stdio
->has_signal
= true;
3435 backend
->stdio
->signal
= qemu_opt_get_bool(opts
, "signal", true);
3438 static void qemu_chr_parse_serial(QemuOpts
*opts
, ChardevBackend
*backend
,
3441 const char *device
= qemu_opt_get(opts
, "path");
3443 if (device
== NULL
) {
3444 error_setg(errp
, "chardev: serial/tty: no device path given");
3447 backend
->serial
= g_new0(ChardevHostdev
, 1);
3448 backend
->serial
->device
= g_strdup(device
);
3451 static void qemu_chr_parse_parallel(QemuOpts
*opts
, ChardevBackend
*backend
,
3454 const char *device
= qemu_opt_get(opts
, "path");
3456 if (device
== NULL
) {
3457 error_setg(errp
, "chardev: parallel: no device path given");
3460 backend
->parallel
= g_new0(ChardevHostdev
, 1);
3461 backend
->parallel
->device
= g_strdup(device
);
3464 static void qemu_chr_parse_pipe(QemuOpts
*opts
, ChardevBackend
*backend
,
3467 const char *device
= qemu_opt_get(opts
, "path");
3469 if (device
== NULL
) {
3470 error_setg(errp
, "chardev: pipe: no device path given");
3473 backend
->pipe
= g_new0(ChardevHostdev
, 1);
3474 backend
->pipe
->device
= g_strdup(device
);
3477 static void qemu_chr_parse_ringbuf(QemuOpts
*opts
, ChardevBackend
*backend
,
3482 backend
->ringbuf
= g_new0(ChardevRingbuf
, 1);
3484 val
= qemu_opt_get_size(opts
, "size", 0);
3486 backend
->ringbuf
->has_size
= true;
3487 backend
->ringbuf
->size
= val
;
3491 static void qemu_chr_parse_mux(QemuOpts
*opts
, ChardevBackend
*backend
,
3494 const char *chardev
= qemu_opt_get(opts
, "chardev");
3496 if (chardev
== NULL
) {
3497 error_setg(errp
, "chardev: mux: no chardev given");
3500 backend
->mux
= g_new0(ChardevMux
, 1);
3501 backend
->mux
->chardev
= g_strdup(chardev
);
3504 static void qemu_chr_parse_socket(QemuOpts
*opts
, ChardevBackend
*backend
,
3507 bool is_listen
= qemu_opt_get_bool(opts
, "server", false);
3508 bool is_waitconnect
= is_listen
&& qemu_opt_get_bool(opts
, "wait", true);
3509 bool is_telnet
= qemu_opt_get_bool(opts
, "telnet", false);
3510 bool do_nodelay
= !qemu_opt_get_bool(opts
, "delay", true);
3511 int64_t reconnect
= qemu_opt_get_number(opts
, "reconnect", 0);
3512 const char *path
= qemu_opt_get(opts
, "path");
3513 const char *host
= qemu_opt_get(opts
, "host");
3514 const char *port
= qemu_opt_get(opts
, "port");
3515 SocketAddress
*addr
;
3519 error_setg(errp
, "chardev: socket: no host given");
3523 error_setg(errp
, "chardev: socket: no port given");
3528 backend
->socket
= g_new0(ChardevSocket
, 1);
3530 backend
->socket
->has_nodelay
= true;
3531 backend
->socket
->nodelay
= do_nodelay
;
3532 backend
->socket
->has_server
= true;
3533 backend
->socket
->server
= is_listen
;
3534 backend
->socket
->has_telnet
= true;
3535 backend
->socket
->telnet
= is_telnet
;
3536 backend
->socket
->has_wait
= true;
3537 backend
->socket
->wait
= is_waitconnect
;
3538 backend
->socket
->has_reconnect
= true;
3539 backend
->socket
->reconnect
= reconnect
;
3541 addr
= g_new0(SocketAddress
, 1);
3543 addr
->kind
= SOCKET_ADDRESS_KIND_UNIX
;
3544 addr
->q_unix
= g_new0(UnixSocketAddress
, 1);
3545 addr
->q_unix
->path
= g_strdup(path
);
3547 addr
->kind
= SOCKET_ADDRESS_KIND_INET
;
3548 addr
->inet
= g_new0(InetSocketAddress
, 1);
3549 addr
->inet
->host
= g_strdup(host
);
3550 addr
->inet
->port
= g_strdup(port
);
3551 addr
->inet
->has_to
= qemu_opt_get(opts
, "to");
3552 addr
->inet
->to
= qemu_opt_get_number(opts
, "to", 0);
3553 addr
->inet
->has_ipv4
= qemu_opt_get(opts
, "ipv4");
3554 addr
->inet
->ipv4
= qemu_opt_get_bool(opts
, "ipv4", 0);
3555 addr
->inet
->has_ipv6
= qemu_opt_get(opts
, "ipv6");
3556 addr
->inet
->ipv6
= qemu_opt_get_bool(opts
, "ipv6", 0);
3558 backend
->socket
->addr
= addr
;
3561 static void qemu_chr_parse_udp(QemuOpts
*opts
, ChardevBackend
*backend
,
3564 const char *host
= qemu_opt_get(opts
, "host");
3565 const char *port
= qemu_opt_get(opts
, "port");
3566 const char *localaddr
= qemu_opt_get(opts
, "localaddr");
3567 const char *localport
= qemu_opt_get(opts
, "localport");
3568 bool has_local
= false;
3569 SocketAddress
*addr
;
3571 if (host
== NULL
|| strlen(host
) == 0) {
3574 if (port
== NULL
|| strlen(port
) == 0) {
3575 error_setg(errp
, "chardev: udp: remote port not specified");
3578 if (localport
== NULL
|| strlen(localport
) == 0) {
3583 if (localaddr
== NULL
|| strlen(localaddr
) == 0) {
3589 backend
->udp
= g_new0(ChardevUdp
, 1);
3591 addr
= g_new0(SocketAddress
, 1);
3592 addr
->kind
= SOCKET_ADDRESS_KIND_INET
;
3593 addr
->inet
= g_new0(InetSocketAddress
, 1);
3594 addr
->inet
->host
= g_strdup(host
);
3595 addr
->inet
->port
= g_strdup(port
);
3596 addr
->inet
->has_ipv4
= qemu_opt_get(opts
, "ipv4");
3597 addr
->inet
->ipv4
= qemu_opt_get_bool(opts
, "ipv4", 0);
3598 addr
->inet
->has_ipv6
= qemu_opt_get(opts
, "ipv6");
3599 addr
->inet
->ipv6
= qemu_opt_get_bool(opts
, "ipv6", 0);
3600 backend
->udp
->remote
= addr
;
3603 backend
->udp
->has_local
= true;
3604 addr
= g_new0(SocketAddress
, 1);
3605 addr
->kind
= SOCKET_ADDRESS_KIND_INET
;
3606 addr
->inet
= g_new0(InetSocketAddress
, 1);
3607 addr
->inet
->host
= g_strdup(localaddr
);
3608 addr
->inet
->port
= g_strdup(localport
);
3609 backend
->udp
->local
= addr
;
3613 typedef struct CharDriver
{
3615 ChardevBackendKind kind
;
3616 void (*parse
)(QemuOpts
*opts
, ChardevBackend
*backend
, Error
**errp
);
3619 static GSList
*backends
;
3621 void register_char_driver(const char *name
, ChardevBackendKind kind
,
3622 void (*parse
)(QemuOpts
*opts
, ChardevBackend
*backend
, Error
**errp
))
3626 s
= g_malloc0(sizeof(*s
));
3627 s
->name
= g_strdup(name
);
3631 backends
= g_slist_append(backends
, s
);
3634 CharDriverState
*qemu_chr_new_from_opts(QemuOpts
*opts
,
3635 void (*init
)(struct CharDriverState
*s
),
3638 Error
*local_err
= NULL
;
3640 CharDriverState
*chr
;
3642 ChardevReturn
*ret
= NULL
;
3643 ChardevBackend
*backend
;
3644 const char *id
= qemu_opts_id(opts
);
3648 error_setg(errp
, "chardev: no id specified");
3652 if (qemu_opt_get(opts
, "backend") == NULL
) {
3653 error_setg(errp
, "chardev: \"%s\" missing backend",
3654 qemu_opts_id(opts
));
3657 for (i
= backends
; i
; i
= i
->next
) {
3660 if (strcmp(cd
->name
, qemu_opt_get(opts
, "backend")) == 0) {
3665 error_setg(errp
, "chardev: backend \"%s\" not found",
3666 qemu_opt_get(opts
, "backend"));
3670 backend
= g_new0(ChardevBackend
, 1);
3672 if (qemu_opt_get_bool(opts
, "mux", 0)) {
3673 bid
= g_strdup_printf("%s-base", id
);
3677 backend
->kind
= cd
->kind
;
3679 cd
->parse(opts
, backend
, &local_err
);
3681 error_propagate(errp
, local_err
);
3685 ret
= qmp_chardev_add(bid
? bid
: id
, backend
, errp
);
3691 qapi_free_ChardevBackend(backend
);
3692 qapi_free_ChardevReturn(ret
);
3693 backend
= g_new0(ChardevBackend
, 1);
3694 backend
->mux
= g_new0(ChardevMux
, 1);
3695 backend
->kind
= CHARDEV_BACKEND_KIND_MUX
;
3696 backend
->mux
->chardev
= g_strdup(bid
);
3697 ret
= qmp_chardev_add(id
, backend
, errp
);
3699 chr
= qemu_chr_find(bid
);
3700 qemu_chr_delete(chr
);
3706 chr
= qemu_chr_find(id
);
3710 qapi_free_ChardevBackend(backend
);
3711 qapi_free_ChardevReturn(ret
);
3716 qemu_opts_del(opts
);
3720 CharDriverState
*qemu_chr_new(const char *label
, const char *filename
, void (*init
)(struct CharDriverState
*s
))
3723 CharDriverState
*chr
;
3727 if (strstart(filename
, "chardev:", &p
)) {
3728 return qemu_chr_find(p
);
3731 opts
= qemu_chr_parse_compat(label
, filename
);
3735 chr
= qemu_chr_new_from_opts(opts
, init
, &err
);
3737 error_report("%s", error_get_pretty(err
));
3740 if (chr
&& qemu_opt_get_bool(opts
, "mux", 0)) {
3741 qemu_chr_fe_claim_no_fail(chr
);
3742 monitor_init(chr
, MONITOR_USE_READLINE
);
3747 void qemu_chr_fe_set_echo(struct CharDriverState
*chr
, bool echo
)
3749 if (chr
->chr_set_echo
) {
3750 chr
->chr_set_echo(chr
, echo
);
3754 void qemu_chr_fe_set_open(struct CharDriverState
*chr
, int fe_open
)
3756 if (chr
->fe_open
== fe_open
) {
3759 chr
->fe_open
= fe_open
;
3760 if (chr
->chr_set_fe_open
) {
3761 chr
->chr_set_fe_open(chr
, fe_open
);
3765 void qemu_chr_fe_event(struct CharDriverState
*chr
, int event
)
3767 if (chr
->chr_fe_event
) {
3768 chr
->chr_fe_event(chr
, event
);
3772 int qemu_chr_fe_add_watch(CharDriverState
*s
, GIOCondition cond
,
3773 GIOFunc func
, void *user_data
)
3778 if (s
->chr_add_watch
== NULL
) {
3782 src
= s
->chr_add_watch(s
, cond
);
3787 g_source_set_callback(src
, (GSourceFunc
)func
, user_data
, NULL
);
3788 tag
= g_source_attach(src
, NULL
);
3789 g_source_unref(src
);
3794 int qemu_chr_fe_claim(CharDriverState
*s
)
3796 if (s
->avail_connections
< 1) {
3799 s
->avail_connections
--;
3803 void qemu_chr_fe_claim_no_fail(CharDriverState
*s
)
3805 if (qemu_chr_fe_claim(s
) != 0) {
3806 fprintf(stderr
, "%s: error chardev \"%s\" already used\n",
3807 __func__
, s
->label
);
3812 void qemu_chr_fe_release(CharDriverState
*s
)
3814 s
->avail_connections
++;
3817 void qemu_chr_delete(CharDriverState
*chr
)
3819 QTAILQ_REMOVE(&chardevs
, chr
, next
);
3820 if (chr
->chr_close
) {
3821 chr
->chr_close(chr
);
3823 g_free(chr
->filename
);
3826 qemu_opts_del(chr
->opts
);
3831 ChardevInfoList
*qmp_query_chardev(Error
**errp
)
3833 ChardevInfoList
*chr_list
= NULL
;
3834 CharDriverState
*chr
;
3836 QTAILQ_FOREACH(chr
, &chardevs
, next
) {
3837 ChardevInfoList
*info
= g_malloc0(sizeof(*info
));
3838 info
->value
= g_malloc0(sizeof(*info
->value
));
3839 info
->value
->label
= g_strdup(chr
->label
);
3840 info
->value
->filename
= g_strdup(chr
->filename
);
3841 info
->value
->frontend_open
= chr
->fe_open
;
3843 info
->next
= chr_list
;
3850 ChardevBackendInfoList
*qmp_query_chardev_backends(Error
**errp
)
3852 ChardevBackendInfoList
*backend_list
= NULL
;
3853 CharDriver
*c
= NULL
;
3856 for (i
= backends
; i
; i
= i
->next
) {
3857 ChardevBackendInfoList
*info
= g_malloc0(sizeof(*info
));
3859 info
->value
= g_malloc0(sizeof(*info
->value
));
3860 info
->value
->name
= g_strdup(c
->name
);
3862 info
->next
= backend_list
;
3863 backend_list
= info
;
3866 return backend_list
;
3869 CharDriverState
*qemu_chr_find(const char *name
)
3871 CharDriverState
*chr
;
3873 QTAILQ_FOREACH(chr
, &chardevs
, next
) {
3874 if (strcmp(chr
->label
, name
) != 0)
3881 /* Get a character (serial) device interface. */
3882 CharDriverState
*qemu_char_get_next_serial(void)
3884 static int next_serial
;
3885 CharDriverState
*chr
;
3887 /* FIXME: This function needs to go away: use chardev properties! */
3889 while (next_serial
< MAX_SERIAL_PORTS
&& serial_hds
[next_serial
]) {
3890 chr
= serial_hds
[next_serial
++];
3891 qemu_chr_fe_claim_no_fail(chr
);
3897 QemuOptsList qemu_chardev_opts
= {
3899 .implied_opt_name
= "backend",
3900 .head
= QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts
.head
),
3904 .type
= QEMU_OPT_STRING
,
3907 .type
= QEMU_OPT_STRING
,
3910 .type
= QEMU_OPT_STRING
,
3913 .type
= QEMU_OPT_STRING
,
3915 .name
= "localaddr",
3916 .type
= QEMU_OPT_STRING
,
3918 .name
= "localport",
3919 .type
= QEMU_OPT_STRING
,
3922 .type
= QEMU_OPT_NUMBER
,
3925 .type
= QEMU_OPT_BOOL
,
3928 .type
= QEMU_OPT_BOOL
,
3931 .type
= QEMU_OPT_BOOL
,
3934 .type
= QEMU_OPT_BOOL
,
3937 .type
= QEMU_OPT_BOOL
,
3939 .name
= "reconnect",
3940 .type
= QEMU_OPT_NUMBER
,
3943 .type
= QEMU_OPT_BOOL
,
3946 .type
= QEMU_OPT_NUMBER
,
3949 .type
= QEMU_OPT_NUMBER
,
3952 .type
= QEMU_OPT_NUMBER
,
3955 .type
= QEMU_OPT_NUMBER
,
3958 .type
= QEMU_OPT_BOOL
,
3961 .type
= QEMU_OPT_BOOL
,
3964 .type
= QEMU_OPT_STRING
,
3967 .type
= QEMU_OPT_NUMBER
,
3970 .type
= QEMU_OPT_SIZE
,
3973 .type
= QEMU_OPT_STRING
,
3975 { /* end of list */ }
3981 static CharDriverState
*qmp_chardev_open_file(ChardevFile
*file
, Error
**errp
)
3986 error_setg(errp
, "input file not supported");
3990 out
= CreateFile(file
->out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3991 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3992 if (out
== INVALID_HANDLE_VALUE
) {
3993 error_setg(errp
, "open %s failed", file
->out
);
3996 return qemu_chr_open_win_file(out
);
3999 static CharDriverState
*qmp_chardev_open_serial(ChardevHostdev
*serial
,
4002 return qemu_chr_open_win_path(serial
->device
);
4005 static CharDriverState
*qmp_chardev_open_parallel(ChardevHostdev
*parallel
,
4008 error_setg(errp
, "character device backend type 'parallel' not supported");
4014 static int qmp_chardev_open_file_source(char *src
, int flags
,
4019 TFR(fd
= qemu_open(src
, flags
, 0666));
4021 error_setg_file_open(errp
, errno
, src
);
4026 static CharDriverState
*qmp_chardev_open_file(ChardevFile
*file
, Error
**errp
)
4028 int flags
, in
= -1, out
;
4030 flags
= O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
;
4031 out
= qmp_chardev_open_file_source(file
->out
, flags
, errp
);
4038 in
= qmp_chardev_open_file_source(file
->in
, flags
, errp
);
4045 return qemu_chr_open_fd(in
, out
);
4048 static CharDriverState
*qmp_chardev_open_serial(ChardevHostdev
*serial
,
4051 #ifdef HAVE_CHARDEV_TTY
4054 fd
= qmp_chardev_open_file_source(serial
->device
, O_RDWR
, errp
);
4058 qemu_set_nonblock(fd
);
4059 return qemu_chr_open_tty_fd(fd
);
4061 error_setg(errp
, "character device backend type 'serial' not supported");
4066 static CharDriverState
*qmp_chardev_open_parallel(ChardevHostdev
*parallel
,
4069 #ifdef HAVE_CHARDEV_PARPORT
4072 fd
= qmp_chardev_open_file_source(parallel
->device
, O_RDWR
, errp
);
4076 return qemu_chr_open_pp_fd(fd
);
4078 error_setg(errp
, "character device backend type 'parallel' not supported");
4085 static void socket_try_connect(CharDriverState
*chr
)
4089 if (!qemu_chr_open_socket_fd(chr
, &err
)) {
4090 check_report_connect_error(chr
, err
);
4094 static gboolean
socket_reconnect_timeout(gpointer opaque
)
4096 CharDriverState
*chr
= opaque
;
4097 TCPCharDriver
*s
= chr
->opaque
;
4099 s
->reconnect_timer
= 0;
4105 socket_try_connect(chr
);
4110 static CharDriverState
*qmp_chardev_open_socket(ChardevSocket
*sock
,
4113 CharDriverState
*chr
;
4115 SocketAddress
*addr
= sock
->addr
;
4116 bool do_nodelay
= sock
->has_nodelay
? sock
->nodelay
: false;
4117 bool is_listen
= sock
->has_server
? sock
->server
: true;
4118 bool is_telnet
= sock
->has_telnet
? sock
->telnet
: false;
4119 bool is_waitconnect
= sock
->has_wait
? sock
->wait
: false;
4120 int64_t reconnect
= sock
->has_reconnect
? sock
->reconnect
: 0;
4122 chr
= qemu_chr_alloc();
4123 s
= g_malloc0(sizeof(TCPCharDriver
));
4127 s
->is_unix
= addr
->kind
== SOCKET_ADDRESS_KIND_UNIX
;
4128 s
->is_listen
= is_listen
;
4129 s
->is_telnet
= is_telnet
;
4130 s
->do_nodelay
= do_nodelay
;
4131 qapi_copy_SocketAddress(&s
->addr
, sock
->addr
);
4134 chr
->chr_write
= tcp_chr_write
;
4135 chr
->chr_sync_read
= tcp_chr_sync_read
;
4136 chr
->chr_close
= tcp_chr_close
;
4137 chr
->get_msgfds
= tcp_get_msgfds
;
4138 chr
->set_msgfds
= tcp_set_msgfds
;
4139 chr
->chr_add_client
= tcp_chr_add_client
;
4140 chr
->chr_add_watch
= tcp_chr_add_watch
;
4141 chr
->chr_update_read_handler
= tcp_chr_update_read_handler
;
4142 /* be isn't opened until we get a connection */
4143 chr
->explicit_be_open
= true;
4145 chr
->filename
= g_malloc(CHR_MAX_FILENAME_SIZE
);
4146 SocketAddress_to_str(chr
->filename
, CHR_MAX_FILENAME_SIZE
, "disconnected:",
4147 addr
, is_listen
, is_telnet
);
4151 s
->do_telnetopt
= 1;
4153 } else if (reconnect
> 0) {
4154 s
->reconnect_time
= reconnect
;
4157 if (s
->reconnect_time
) {
4158 socket_try_connect(chr
);
4159 } else if (!qemu_chr_open_socket_fd(chr
, errp
)) {
4161 g_free(chr
->filename
);
4166 if (is_listen
&& is_waitconnect
) {
4167 fprintf(stderr
, "QEMU waiting for connection on: %s\n",
4169 tcp_chr_accept(s
->listen_chan
, G_IO_IN
, chr
);
4170 qemu_set_nonblock(s
->listen_fd
);
4176 static CharDriverState
*qmp_chardev_open_udp(ChardevUdp
*udp
,
4181 fd
= socket_dgram(udp
->remote
, udp
->local
, errp
);
4185 return qemu_chr_open_udp_fd(fd
);
4188 ChardevReturn
*qmp_chardev_add(const char *id
, ChardevBackend
*backend
,
4191 ChardevReturn
*ret
= g_new0(ChardevReturn
, 1);
4192 CharDriverState
*base
, *chr
= NULL
;
4194 chr
= qemu_chr_find(id
);
4196 error_setg(errp
, "Chardev '%s' already exists", id
);
4201 switch (backend
->kind
) {
4202 case CHARDEV_BACKEND_KIND_FILE
:
4203 chr
= qmp_chardev_open_file(backend
->file
, errp
);
4205 case CHARDEV_BACKEND_KIND_SERIAL
:
4206 chr
= qmp_chardev_open_serial(backend
->serial
, errp
);
4208 case CHARDEV_BACKEND_KIND_PARALLEL
:
4209 chr
= qmp_chardev_open_parallel(backend
->parallel
, errp
);
4211 case CHARDEV_BACKEND_KIND_PIPE
:
4212 chr
= qemu_chr_open_pipe(backend
->pipe
);
4214 case CHARDEV_BACKEND_KIND_SOCKET
:
4215 chr
= qmp_chardev_open_socket(backend
->socket
, errp
);
4217 case CHARDEV_BACKEND_KIND_UDP
:
4218 chr
= qmp_chardev_open_udp(backend
->udp
, errp
);
4220 #ifdef HAVE_CHARDEV_TTY
4221 case CHARDEV_BACKEND_KIND_PTY
:
4222 chr
= qemu_chr_open_pty(id
, ret
);
4225 case CHARDEV_BACKEND_KIND_NULL
:
4226 chr
= qemu_chr_open_null();
4228 case CHARDEV_BACKEND_KIND_MUX
:
4229 base
= qemu_chr_find(backend
->mux
->chardev
);
4231 error_setg(errp
, "mux: base chardev %s not found",
4232 backend
->mux
->chardev
);
4235 chr
= qemu_chr_open_mux(base
);
4237 case CHARDEV_BACKEND_KIND_MSMOUSE
:
4238 chr
= qemu_chr_open_msmouse();
4240 #ifdef CONFIG_BRLAPI
4241 case CHARDEV_BACKEND_KIND_BRAILLE
:
4242 chr
= chr_baum_init();
4245 case CHARDEV_BACKEND_KIND_TESTDEV
:
4246 chr
= chr_testdev_init();
4248 case CHARDEV_BACKEND_KIND_STDIO
:
4249 chr
= qemu_chr_open_stdio(backend
->stdio
);
4252 case CHARDEV_BACKEND_KIND_CONSOLE
:
4253 chr
= qemu_chr_open_win_con();
4257 case CHARDEV_BACKEND_KIND_SPICEVMC
:
4258 chr
= qemu_chr_open_spice_vmc(backend
->spicevmc
->type
);
4260 case CHARDEV_BACKEND_KIND_SPICEPORT
:
4261 chr
= qemu_chr_open_spice_port(backend
->spiceport
->fqdn
);
4264 case CHARDEV_BACKEND_KIND_VC
:
4265 chr
= vc_init(backend
->vc
);
4267 case CHARDEV_BACKEND_KIND_RINGBUF
:
4268 case CHARDEV_BACKEND_KIND_MEMORY
:
4269 chr
= qemu_chr_open_ringbuf(backend
->ringbuf
, errp
);
4272 error_setg(errp
, "unknown chardev backend (%d)", backend
->kind
);
4277 * Character backend open hasn't been fully converted to the Error
4278 * API. Some opens fail without setting an error. Set a generic
4280 * TODO full conversion to Error API
4282 if (chr
== NULL
&& errp
&& !*errp
) {
4283 error_setg(errp
, "Failed to create chardev");
4286 chr
->label
= g_strdup(id
);
4287 chr
->avail_connections
=
4288 (backend
->kind
== CHARDEV_BACKEND_KIND_MUX
) ? MAX_MUX
: 1;
4289 if (!chr
->filename
) {
4290 chr
->filename
= g_strdup(ChardevBackendKind_lookup
[backend
->kind
]);
4292 if (!chr
->explicit_be_open
) {
4293 qemu_chr_be_event(chr
, CHR_EVENT_OPENED
);
4295 QTAILQ_INSERT_TAIL(&chardevs
, chr
, next
);
4303 void qmp_chardev_remove(const char *id
, Error
**errp
)
4305 CharDriverState
*chr
;
4307 chr
= qemu_chr_find(id
);
4309 error_setg(errp
, "Chardev '%s' not found", id
);
4312 if (chr
->chr_can_read
|| chr
->chr_read
||
4313 chr
->chr_event
|| chr
->handler_opaque
) {
4314 error_setg(errp
, "Chardev '%s' is busy", id
);
4317 qemu_chr_delete(chr
);
4320 static void register_types(void)
4322 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL
, NULL
);
4323 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET
,
4324 qemu_chr_parse_socket
);
4325 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP
, qemu_chr_parse_udp
);
4326 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF
,
4327 qemu_chr_parse_ringbuf
);
4328 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE
,
4329 qemu_chr_parse_file_out
);
4330 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO
,
4331 qemu_chr_parse_stdio
);
4332 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL
,
4333 qemu_chr_parse_serial
);
4334 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL
,
4335 qemu_chr_parse_serial
);
4336 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL
,
4337 qemu_chr_parse_parallel
);
4338 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL
,
4339 qemu_chr_parse_parallel
);
4340 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY
, NULL
);
4341 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE
, NULL
);
4342 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE
,
4343 qemu_chr_parse_pipe
);
4344 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX
, qemu_chr_parse_mux
);
4345 /* Bug-compatibility: */
4346 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY
,
4347 qemu_chr_parse_ringbuf
);
4348 /* this must be done after machine init, since we register FEs with muxes
4349 * as part of realize functions like serial_isa_realizefn when -nographic
4352 qemu_add_machine_init_done_notifier(&muxes_realize_notify
);
4355 type_init(register_types
);