char: move mux to its own file
[qemu/ar7.git] / chardev / char.c
blobc8d03776b180041c137790ceab4617ec0f726be8
1 /*
2 * QEMU System Emulator
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
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include "qemu-common.h"
26 #include "qemu/cutils.h"
27 #include "monitor/monitor.h"
28 #include "sysemu/sysemu.h"
29 #include "sysemu/block-backend.h"
30 #include "qemu/error-report.h"
31 #include "qemu/timer.h"
32 #include "sysemu/char.h"
33 #include "hw/usb.h"
34 #include "qmp-commands.h"
35 #include "qapi/clone-visitor.h"
36 #include "qapi-visit.h"
37 #include "qemu/base64.h"
38 #include "io/channel-socket.h"
39 #include "io/channel-file.h"
40 #include "io/channel-tls.h"
41 #include "sysemu/replay.h"
42 #include "qemu/help_option.h"
44 #include <zlib.h>
46 #ifndef _WIN32
47 #include <sys/times.h>
48 #include <sys/wait.h>
49 #include <termios.h>
50 #include <sys/ioctl.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <net/if.h>
55 #include <arpa/inet.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef CONFIG_BSD
59 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
60 #include <dev/ppbus/ppi.h>
61 #include <dev/ppbus/ppbconf.h>
62 #elif defined(__DragonFly__)
63 #include <dev/misc/ppi/ppi.h>
64 #include <bus/ppbus/ppbconf.h>
65 #endif
66 #else
67 #ifdef __linux__
68 #include <linux/ppdev.h>
69 #include <linux/parport.h>
70 #endif
71 #ifdef __sun__
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>
81 #endif
82 #endif
83 #endif
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #include "char-mux.h"
90 #define READ_BUF_LEN 4096
91 #define READ_RETRIES 10
92 #define TCP_MAX_FDS 16
94 /***********************************************************/
95 /* Socket address helpers */
97 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
98 bool is_listen, bool is_telnet)
100 switch (addr->type) {
101 case SOCKET_ADDRESS_KIND_INET:
102 return g_strdup_printf("%s%s:%s:%s%s", prefix,
103 is_telnet ? "telnet" : "tcp",
104 addr->u.inet.data->host,
105 addr->u.inet.data->port,
106 is_listen ? ",server" : "");
107 break;
108 case SOCKET_ADDRESS_KIND_UNIX:
109 return g_strdup_printf("%sunix:%s%s", prefix,
110 addr->u.q_unix.data->path,
111 is_listen ? ",server" : "");
112 break;
113 case SOCKET_ADDRESS_KIND_FD:
114 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
115 is_listen ? ",server" : "");
116 break;
117 default:
118 abort();
122 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
123 struct sockaddr_storage *ps, socklen_t ps_len,
124 bool is_listen, bool is_telnet)
126 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
127 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
128 const char *left = "", *right = "";
130 switch (ss->ss_family) {
131 #ifndef _WIN32
132 case AF_UNIX:
133 return g_strdup_printf("unix:%s%s",
134 ((struct sockaddr_un *)(ss))->sun_path,
135 is_listen ? ",server" : "");
136 #endif
137 case AF_INET6:
138 left = "[";
139 right = "]";
140 /* fall through */
141 case AF_INET:
142 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
143 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
144 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
145 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
146 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
147 is_telnet ? "telnet" : "tcp",
148 left, shost, right, sserv,
149 is_listen ? ",server" : "",
150 left, phost, right, pserv);
152 default:
153 return g_strdup_printf("unknown");
157 /***********************************************************/
158 /* character device */
160 static QTAILQ_HEAD(ChardevHead, Chardev) chardevs =
161 QTAILQ_HEAD_INITIALIZER(chardevs);
163 void qemu_chr_be_event(Chardev *s, int event)
165 CharBackend *be = s->be;
167 /* Keep track if the char device is open */
168 switch (event) {
169 case CHR_EVENT_OPENED:
170 s->be_open = 1;
171 break;
172 case CHR_EVENT_CLOSED:
173 s->be_open = 0;
174 break;
177 if (!be || !be->chr_event) {
178 return;
181 be->chr_event(be->opaque, event);
184 void qemu_chr_be_generic_open(Chardev *s)
186 qemu_chr_be_event(s, CHR_EVENT_OPENED);
190 /* Not reporting errors from writing to logfile, as logs are
191 * defined to be "best effort" only */
192 static void qemu_chr_fe_write_log(Chardev *s,
193 const uint8_t *buf, size_t len)
195 size_t done = 0;
196 ssize_t ret;
198 if (s->logfd < 0) {
199 return;
202 while (done < len) {
203 retry:
204 ret = write(s->logfd, buf + done, len - done);
205 if (ret == -1 && errno == EAGAIN) {
206 g_usleep(100);
207 goto retry;
210 if (ret <= 0) {
211 return;
213 done += ret;
217 static int qemu_chr_fe_write_buffer(Chardev *s,
218 const uint8_t *buf, int len, int *offset)
220 ChardevClass *cc = CHARDEV_GET_CLASS(s);
221 int res = 0;
222 *offset = 0;
224 qemu_mutex_lock(&s->chr_write_lock);
225 while (*offset < len) {
226 retry:
227 res = cc->chr_write(s, buf + *offset, len - *offset);
228 if (res < 0 && errno == EAGAIN) {
229 g_usleep(100);
230 goto retry;
233 if (res <= 0) {
234 break;
237 *offset += res;
239 if (*offset > 0) {
240 qemu_chr_fe_write_log(s, buf, *offset);
242 qemu_mutex_unlock(&s->chr_write_lock);
244 return res;
247 static bool qemu_chr_replay(Chardev *chr)
249 return qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_REPLAY);
252 int qemu_chr_fe_write(CharBackend *be, const uint8_t *buf, int len)
254 Chardev *s = be->chr;
255 ChardevClass *cc;
256 int ret;
258 if (!s) {
259 return 0;
262 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
263 int offset;
264 replay_char_write_event_load(&ret, &offset);
265 assert(offset <= len);
266 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
267 return ret;
270 cc = CHARDEV_GET_CLASS(s);
271 qemu_mutex_lock(&s->chr_write_lock);
272 ret = cc->chr_write(s, buf, len);
274 if (ret > 0) {
275 qemu_chr_fe_write_log(s, buf, ret);
278 qemu_mutex_unlock(&s->chr_write_lock);
280 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
281 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
284 return ret;
287 int qemu_chr_write_all(Chardev *s, const uint8_t *buf, int len)
289 int offset;
290 int res;
292 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
293 replay_char_write_event_load(&res, &offset);
294 assert(offset <= len);
295 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
296 return res;
299 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
301 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
302 replay_char_write_event_save(res, offset);
305 if (res < 0) {
306 return res;
308 return offset;
311 int qemu_chr_fe_write_all(CharBackend *be, const uint8_t *buf, int len)
313 Chardev *s = be->chr;
315 if (!s) {
316 return 0;
319 return qemu_chr_write_all(s, buf, len);
322 int qemu_chr_fe_read_all(CharBackend *be, uint8_t *buf, int len)
324 Chardev *s = be->chr;
325 int offset = 0, counter = 10;
326 int res;
328 if (!s || !CHARDEV_GET_CLASS(s)->chr_sync_read) {
329 return 0;
332 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
333 return replay_char_read_all_load(buf);
336 while (offset < len) {
337 retry:
338 res = CHARDEV_GET_CLASS(s)->chr_sync_read(s, buf + offset,
339 len - offset);
340 if (res == -1 && errno == EAGAIN) {
341 g_usleep(100);
342 goto retry;
345 if (res == 0) {
346 break;
349 if (res < 0) {
350 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
351 replay_char_read_all_save_error(res);
353 return res;
356 offset += res;
358 if (!counter--) {
359 break;
363 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
364 replay_char_read_all_save_buf(buf, offset);
366 return offset;
369 int qemu_chr_fe_ioctl(CharBackend *be, int cmd, void *arg)
371 Chardev *s = be->chr;
372 int res;
374 if (!s || !CHARDEV_GET_CLASS(s)->chr_ioctl || qemu_chr_replay(s)) {
375 res = -ENOTSUP;
376 } else {
377 res = CHARDEV_GET_CLASS(s)->chr_ioctl(s, cmd, arg);
380 return res;
383 int qemu_chr_be_can_write(Chardev *s)
385 CharBackend *be = s->be;
387 if (!be || !be->chr_can_read) {
388 return 0;
391 return be->chr_can_read(be->opaque);
394 void qemu_chr_be_write_impl(Chardev *s, uint8_t *buf, int len)
396 CharBackend *be = s->be;
398 if (be && be->chr_read) {
399 be->chr_read(be->opaque, buf, len);
403 void qemu_chr_be_write(Chardev *s, uint8_t *buf, int len)
405 if (qemu_chr_replay(s)) {
406 if (replay_mode == REPLAY_MODE_PLAY) {
407 return;
409 replay_chr_be_write(s, buf, len);
410 } else {
411 qemu_chr_be_write_impl(s, buf, len);
415 int qemu_chr_fe_get_msgfd(CharBackend *be)
417 Chardev *s = be->chr;
418 int fd;
419 int res = (qemu_chr_fe_get_msgfds(be, &fd, 1) == 1) ? fd : -1;
420 if (s && qemu_chr_replay(s)) {
421 error_report("Replay: get msgfd is not supported "
422 "for serial devices yet");
423 exit(1);
425 return res;
428 int qemu_chr_fe_get_msgfds(CharBackend *be, int *fds, int len)
430 Chardev *s = be->chr;
432 if (!s) {
433 return -1;
436 return CHARDEV_GET_CLASS(s)->get_msgfds ?
437 CHARDEV_GET_CLASS(s)->get_msgfds(s, fds, len) : -1;
440 int qemu_chr_fe_set_msgfds(CharBackend *be, int *fds, int num)
442 Chardev *s = be->chr;
444 if (!s) {
445 return -1;
448 return CHARDEV_GET_CLASS(s)->set_msgfds ?
449 CHARDEV_GET_CLASS(s)->set_msgfds(s, fds, num) : -1;
452 int qemu_chr_add_client(Chardev *s, int fd)
454 return CHARDEV_GET_CLASS(s)->chr_add_client ?
455 CHARDEV_GET_CLASS(s)->chr_add_client(s, fd) : -1;
458 void qemu_chr_fe_accept_input(CharBackend *be)
460 Chardev *s = be->chr;
462 if (!s) {
463 return;
466 if (CHARDEV_GET_CLASS(s)->chr_accept_input) {
467 CHARDEV_GET_CLASS(s)->chr_accept_input(s);
469 qemu_notify_event();
472 void qemu_chr_fe_printf(CharBackend *be, const char *fmt, ...)
474 char buf[READ_BUF_LEN];
475 va_list ap;
476 va_start(ap, fmt);
477 vsnprintf(buf, sizeof(buf), fmt, ap);
478 /* XXX this blocks entire thread. Rewrite to use
479 * qemu_chr_fe_write and background I/O callbacks */
480 qemu_chr_fe_write_all(be, (uint8_t *)buf, strlen(buf));
481 va_end(ap);
484 static void remove_fd_in_watch(Chardev *chr);
486 static void qemu_char_open(Chardev *chr, ChardevBackend *backend,
487 bool *be_opened, Error **errp)
489 ChardevClass *cc = CHARDEV_GET_CLASS(chr);
490 /* Any ChardevCommon member would work */
491 ChardevCommon *common = backend ? backend->u.null.data : NULL;
493 if (common && common->has_logfile) {
494 int flags = O_WRONLY | O_CREAT;
495 if (common->has_logappend &&
496 common->logappend) {
497 flags |= O_APPEND;
498 } else {
499 flags |= O_TRUNC;
501 chr->logfd = qemu_open(common->logfile, flags, 0666);
502 if (chr->logfd < 0) {
503 error_setg_errno(errp, errno,
504 "Unable to open logfile %s",
505 common->logfile);
506 return;
510 if (cc->open) {
511 cc->open(chr, backend, be_opened, errp);
515 static void char_init(Object *obj)
517 Chardev *chr = CHARDEV(obj);
519 chr->logfd = -1;
520 qemu_mutex_init(&chr->chr_write_lock);
523 static int null_chr_write(Chardev *chr, const uint8_t *buf, int len)
525 return len;
528 static void char_class_init(ObjectClass *oc, void *data)
530 ChardevClass *cc = CHARDEV_CLASS(oc);
532 cc->chr_write = null_chr_write;
535 static void char_finalize(Object *obj)
537 Chardev *chr = CHARDEV(obj);
539 if (chr->be) {
540 chr->be->chr = NULL;
542 g_free(chr->filename);
543 g_free(chr->label);
544 if (chr->logfd != -1) {
545 close(chr->logfd);
547 qemu_mutex_destroy(&chr->chr_write_lock);
550 static const TypeInfo char_type_info = {
551 .name = TYPE_CHARDEV,
552 .parent = TYPE_OBJECT,
553 .instance_size = sizeof(Chardev),
554 .instance_init = char_init,
555 .instance_finalize = char_finalize,
556 .abstract = true,
557 .class_size = sizeof(ChardevClass),
558 .class_init = char_class_init,
562 * Called after processing of default and command-line-specified
563 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
564 * to a mux chardev. This is done here to ensure that
565 * output/prompts/banners are only displayed for the FE that has
566 * focus when initial command-line processing/machine init is
567 * completed.
569 * After this point, any new FE attached to any new or existing
570 * mux will receive CHR_EVENT_OPENED notifications for the BE
571 * immediately.
573 static void muxes_realize_done(Notifier *notifier, void *unused)
575 Chardev *chr;
577 QTAILQ_FOREACH(chr, &chardevs, next) {
578 if (CHARDEV_IS_MUX(chr)) {
579 MuxChardev *d = MUX_CHARDEV(chr);
580 int i;
582 /* send OPENED to all already-attached FEs */
583 for (i = 0; i < d->mux_cnt; i++) {
584 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
586 /* mark mux as OPENED so any new FEs will immediately receive
587 * OPENED event
589 qemu_chr_be_generic_open(chr);
592 muxes_realized = true;
595 static Notifier muxes_realize_notify = {
596 .notify = muxes_realize_done,
599 Chardev *qemu_chr_fe_get_driver(CharBackend *be)
601 return be->chr;
604 bool qemu_chr_fe_init(CharBackend *b, Chardev *s, Error **errp)
606 int tag = 0;
608 if (CHARDEV_IS_MUX(s)) {
609 MuxChardev *d = MUX_CHARDEV(s);
611 if (d->mux_cnt >= MAX_MUX) {
612 goto unavailable;
615 d->backends[d->mux_cnt] = b;
616 tag = d->mux_cnt++;
617 } else if (s->be) {
618 goto unavailable;
619 } else {
620 s->be = b;
623 b->fe_open = false;
624 b->tag = tag;
625 b->chr = s;
626 return true;
628 unavailable:
629 error_setg(errp, QERR_DEVICE_IN_USE, s->label);
630 return false;
633 static bool qemu_chr_is_busy(Chardev *s)
635 if (CHARDEV_IS_MUX(s)) {
636 MuxChardev *d = MUX_CHARDEV(s);
637 return d->mux_cnt >= 0;
638 } else {
639 return s->be != NULL;
643 void qemu_chr_fe_deinit(CharBackend *b)
645 assert(b);
647 if (b->chr) {
648 qemu_chr_fe_set_handlers(b, NULL, NULL, NULL, NULL, NULL, true);
649 if (b->chr->be == b) {
650 b->chr->be = NULL;
652 if (CHARDEV_IS_MUX(b->chr)) {
653 MuxChardev *d = MUX_CHARDEV(b->chr);
654 d->backends[b->tag] = NULL;
656 b->chr = NULL;
660 void qemu_chr_fe_set_handlers(CharBackend *b,
661 IOCanReadHandler *fd_can_read,
662 IOReadHandler *fd_read,
663 IOEventHandler *fd_event,
664 void *opaque,
665 GMainContext *context,
666 bool set_open)
668 Chardev *s;
669 ChardevClass *cc;
670 int fe_open;
672 s = b->chr;
673 if (!s) {
674 return;
677 cc = CHARDEV_GET_CLASS(s);
678 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
679 fe_open = 0;
680 remove_fd_in_watch(s);
681 } else {
682 fe_open = 1;
684 b->chr_can_read = fd_can_read;
685 b->chr_read = fd_read;
686 b->chr_event = fd_event;
687 b->opaque = opaque;
688 if (cc->chr_update_read_handler) {
689 cc->chr_update_read_handler(s, context);
692 if (set_open) {
693 qemu_chr_fe_set_open(b, fe_open);
696 if (fe_open) {
697 qemu_chr_fe_take_focus(b);
698 /* We're connecting to an already opened device, so let's make sure we
699 also get the open event */
700 if (s->be_open) {
701 qemu_chr_be_generic_open(s);
705 if (CHARDEV_IS_MUX(s)) {
706 mux_chr_set_handlers(s, context);
710 void qemu_chr_fe_take_focus(CharBackend *b)
712 if (!b->chr) {
713 return;
716 if (CHARDEV_IS_MUX(b->chr)) {
717 mux_set_focus(b->chr, b->tag);
721 typedef struct IOWatchPoll
723 GSource parent;
725 QIOChannel *ioc;
726 GSource *src;
728 IOCanReadHandler *fd_can_read;
729 GSourceFunc fd_read;
730 void *opaque;
731 GMainContext *context;
732 } IOWatchPoll;
734 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
736 return container_of(source, IOWatchPoll, parent);
739 static gboolean io_watch_poll_prepare(GSource *source,
740 gint *timeout_)
742 IOWatchPoll *iwp = io_watch_poll_from_source(source);
743 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
744 bool was_active = iwp->src != NULL;
745 if (was_active == now_active) {
746 return FALSE;
749 if (now_active) {
750 iwp->src = qio_channel_create_watch(
751 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
752 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
753 g_source_attach(iwp->src, iwp->context);
754 } else {
755 g_source_destroy(iwp->src);
756 g_source_unref(iwp->src);
757 iwp->src = NULL;
759 return FALSE;
762 static gboolean io_watch_poll_check(GSource *source)
764 return FALSE;
767 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
768 gpointer user_data)
770 abort();
773 static void io_watch_poll_finalize(GSource *source)
775 /* Due to a glib bug, removing the last reference to a source
776 * inside a finalize callback causes recursive locking (and a
777 * deadlock). This is not a problem inside other callbacks,
778 * including dispatch callbacks, so we call io_remove_watch_poll
779 * to remove this source. At this point, iwp->src must
780 * be NULL, or we would leak it.
782 * This would be solved much more elegantly by child sources,
783 * but we support older glib versions that do not have them.
785 IOWatchPoll *iwp = io_watch_poll_from_source(source);
786 assert(iwp->src == NULL);
789 static GSourceFuncs io_watch_poll_funcs = {
790 .prepare = io_watch_poll_prepare,
791 .check = io_watch_poll_check,
792 .dispatch = io_watch_poll_dispatch,
793 .finalize = io_watch_poll_finalize,
796 /* Can only be used for read */
797 static guint io_add_watch_poll(Chardev *chr,
798 QIOChannel *ioc,
799 IOCanReadHandler *fd_can_read,
800 QIOChannelFunc fd_read,
801 gpointer user_data,
802 GMainContext *context)
804 IOWatchPoll *iwp;
805 int tag;
806 char *name;
808 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
809 sizeof(IOWatchPoll));
810 iwp->fd_can_read = fd_can_read;
811 iwp->opaque = user_data;
812 iwp->ioc = ioc;
813 iwp->fd_read = (GSourceFunc) fd_read;
814 iwp->src = NULL;
815 iwp->context = context;
817 name = g_strdup_printf("chardev-iowatch-%s", chr->label);
818 g_source_set_name((GSource *)iwp, name);
819 g_free(name);
821 tag = g_source_attach(&iwp->parent, context);
822 g_source_unref(&iwp->parent);
823 return tag;
826 static void io_remove_watch_poll(guint tag)
828 GSource *source;
829 IOWatchPoll *iwp;
831 g_return_if_fail (tag > 0);
833 source = g_main_context_find_source_by_id(NULL, tag);
834 g_return_if_fail (source != NULL);
836 iwp = io_watch_poll_from_source(source);
837 if (iwp->src) {
838 g_source_destroy(iwp->src);
839 g_source_unref(iwp->src);
840 iwp->src = NULL;
842 g_source_destroy(&iwp->parent);
845 static void remove_fd_in_watch(Chardev *chr)
847 if (chr->fd_in_tag) {
848 io_remove_watch_poll(chr->fd_in_tag);
849 chr->fd_in_tag = 0;
854 static int io_channel_send_full(QIOChannel *ioc,
855 const void *buf, size_t len,
856 int *fds, size_t nfds)
858 size_t offset = 0;
860 while (offset < len) {
861 ssize_t ret = 0;
862 struct iovec iov = { .iov_base = (char *)buf + offset,
863 .iov_len = len - offset };
865 ret = qio_channel_writev_full(
866 ioc, &iov, 1,
867 fds, nfds, NULL);
868 if (ret == QIO_CHANNEL_ERR_BLOCK) {
869 if (offset) {
870 return offset;
873 errno = EAGAIN;
874 return -1;
875 } else if (ret < 0) {
876 errno = EINVAL;
877 return -1;
880 offset += ret;
883 return offset;
887 #ifndef _WIN32
888 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
890 return io_channel_send_full(ioc, buf, len, NULL, 0);
893 typedef struct FDChardev {
894 Chardev parent;
895 Chardev *chr;
896 QIOChannel *ioc_in, *ioc_out;
897 int max_size;
898 } FDChardev;
900 #define TYPE_CHARDEV_FD "chardev-fd"
901 #define FD_CHARDEV(obj) OBJECT_CHECK(FDChardev, (obj), TYPE_CHARDEV_FD)
903 /* Called with chr_write_lock held. */
904 static int fd_chr_write(Chardev *chr, const uint8_t *buf, int len)
906 FDChardev *s = FD_CHARDEV(chr);
908 return io_channel_send(s->ioc_out, buf, len);
911 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
913 Chardev *chr = CHARDEV(opaque);
914 FDChardev *s = FD_CHARDEV(opaque);
915 int len;
916 uint8_t buf[READ_BUF_LEN];
917 ssize_t ret;
919 len = sizeof(buf);
920 if (len > s->max_size) {
921 len = s->max_size;
923 if (len == 0) {
924 return TRUE;
927 ret = qio_channel_read(
928 chan, (gchar *)buf, len, NULL);
929 if (ret == 0) {
930 remove_fd_in_watch(chr);
931 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
932 return FALSE;
934 if (ret > 0) {
935 qemu_chr_be_write(chr, buf, ret);
938 return TRUE;
941 static int fd_chr_read_poll(void *opaque)
943 Chardev *chr = CHARDEV(opaque);
944 FDChardev *s = FD_CHARDEV(opaque);
946 s->max_size = qemu_chr_be_can_write(chr);
947 return s->max_size;
950 static GSource *fd_chr_add_watch(Chardev *chr, GIOCondition cond)
952 FDChardev *s = FD_CHARDEV(chr);
953 return qio_channel_create_watch(s->ioc_out, cond);
956 static void fd_chr_update_read_handler(Chardev *chr,
957 GMainContext *context)
959 FDChardev *s = FD_CHARDEV(chr);
961 remove_fd_in_watch(chr);
962 if (s->ioc_in) {
963 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc_in,
964 fd_chr_read_poll,
965 fd_chr_read, chr,
966 context);
970 static void char_fd_finalize(Object *obj)
972 Chardev *chr = CHARDEV(obj);
973 FDChardev *s = FD_CHARDEV(obj);
975 remove_fd_in_watch(chr);
976 if (s->ioc_in) {
977 object_unref(OBJECT(s->ioc_in));
979 if (s->ioc_out) {
980 object_unref(OBJECT(s->ioc_out));
983 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
986 /* open a character device to a unix fd */
987 static void qemu_chr_open_fd(Chardev *chr,
988 int fd_in, int fd_out)
990 FDChardev *s = FD_CHARDEV(chr);
991 char *name;
993 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
994 name = g_strdup_printf("chardev-file-in-%s", chr->label);
995 qio_channel_set_name(QIO_CHANNEL(s->ioc_in), name);
996 g_free(name);
997 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
998 name = g_strdup_printf("chardev-file-out-%s", chr->label);
999 qio_channel_set_name(QIO_CHANNEL(s->ioc_out), name);
1000 g_free(name);
1001 qemu_set_nonblock(fd_out);
1002 s->chr = chr;
1005 static void char_fd_class_init(ObjectClass *oc, void *data)
1007 ChardevClass *cc = CHARDEV_CLASS(oc);
1009 cc->chr_add_watch = fd_chr_add_watch;
1010 cc->chr_write = fd_chr_write;
1011 cc->chr_update_read_handler = fd_chr_update_read_handler;
1014 static const TypeInfo char_fd_type_info = {
1015 .name = TYPE_CHARDEV_FD,
1016 .parent = TYPE_CHARDEV,
1017 .instance_size = sizeof(FDChardev),
1018 .instance_finalize = char_fd_finalize,
1019 .class_init = char_fd_class_init,
1020 .abstract = true,
1023 static void qemu_chr_open_pipe(Chardev *chr,
1024 ChardevBackend *backend,
1025 bool *be_opened,
1026 Error **errp)
1028 ChardevHostdev *opts = backend->u.pipe.data;
1029 int fd_in, fd_out;
1030 char *filename_in;
1031 char *filename_out;
1032 const char *filename = opts->device;
1034 filename_in = g_strdup_printf("%s.in", filename);
1035 filename_out = g_strdup_printf("%s.out", filename);
1036 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1037 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1038 g_free(filename_in);
1039 g_free(filename_out);
1040 if (fd_in < 0 || fd_out < 0) {
1041 if (fd_in >= 0)
1042 close(fd_in);
1043 if (fd_out >= 0)
1044 close(fd_out);
1045 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1046 if (fd_in < 0) {
1047 error_setg_file_open(errp, errno, filename);
1048 return;
1051 qemu_chr_open_fd(chr, fd_in, fd_out);
1054 /* init terminal so that we can grab keys */
1055 static struct termios oldtty;
1056 static int old_fd0_flags;
1057 static bool stdio_in_use;
1058 static bool stdio_allow_signal;
1059 static bool stdio_echo_state;
1061 static void qemu_chr_set_echo_stdio(Chardev *chr, bool echo);
1063 static void term_exit(void)
1065 tcsetattr (0, TCSANOW, &oldtty);
1066 fcntl(0, F_SETFL, old_fd0_flags);
1069 static void term_stdio_handler(int sig)
1071 /* restore echo after resume from suspend. */
1072 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1075 static void qemu_chr_set_echo_stdio(Chardev *chr, bool echo)
1077 struct termios tty;
1079 stdio_echo_state = echo;
1080 tty = oldtty;
1081 if (!echo) {
1082 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1083 |INLCR|IGNCR|ICRNL|IXON);
1084 tty.c_oflag |= OPOST;
1085 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1086 tty.c_cflag &= ~(CSIZE|PARENB);
1087 tty.c_cflag |= CS8;
1088 tty.c_cc[VMIN] = 1;
1089 tty.c_cc[VTIME] = 0;
1091 if (!stdio_allow_signal)
1092 tty.c_lflag &= ~ISIG;
1094 tcsetattr (0, TCSANOW, &tty);
1097 static void char_stdio_finalize(Object *obj)
1099 term_exit();
1102 static void qemu_chr_open_stdio(Chardev *chr,
1103 ChardevBackend *backend,
1104 bool *be_opened,
1105 Error **errp)
1107 ChardevStdio *opts = backend->u.stdio.data;
1108 struct sigaction act;
1110 if (is_daemonized()) {
1111 error_setg(errp, "cannot use stdio with -daemonize");
1112 return;
1115 if (stdio_in_use) {
1116 error_setg(errp, "cannot use stdio by multiple character devices");
1117 return;
1120 stdio_in_use = true;
1121 old_fd0_flags = fcntl(0, F_GETFL);
1122 tcgetattr(0, &oldtty);
1123 qemu_set_nonblock(0);
1124 atexit(term_exit);
1126 memset(&act, 0, sizeof(act));
1127 act.sa_handler = term_stdio_handler;
1128 sigaction(SIGCONT, &act, NULL);
1130 qemu_chr_open_fd(chr, 0, 1);
1132 if (opts->has_signal) {
1133 stdio_allow_signal = opts->signal;
1135 qemu_chr_set_echo_stdio(chr, false);
1138 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1139 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1140 || defined(__GLIBC__)
1142 #define HAVE_CHARDEV_SERIAL 1
1143 #define HAVE_CHARDEV_PTY 1
1145 typedef struct {
1146 Chardev parent;
1147 QIOChannel *ioc;
1148 int read_bytes;
1150 /* Protected by the Chardev chr_write_lock. */
1151 int connected;
1152 guint timer_tag;
1153 guint open_tag;
1154 } PtyChardev;
1156 #define PTY_CHARDEV(obj) OBJECT_CHECK(PtyChardev, (obj), TYPE_CHARDEV_PTY)
1158 static void pty_chr_update_read_handler_locked(Chardev *chr);
1159 static void pty_chr_state(Chardev *chr, int connected);
1161 static gboolean pty_chr_timer(gpointer opaque)
1163 struct Chardev *chr = CHARDEV(opaque);
1164 PtyChardev *s = PTY_CHARDEV(opaque);
1166 qemu_mutex_lock(&chr->chr_write_lock);
1167 s->timer_tag = 0;
1168 s->open_tag = 0;
1169 if (!s->connected) {
1170 /* Next poll ... */
1171 pty_chr_update_read_handler_locked(chr);
1173 qemu_mutex_unlock(&chr->chr_write_lock);
1174 return FALSE;
1177 /* Called with chr_write_lock held. */
1178 static void pty_chr_rearm_timer(Chardev *chr, int ms)
1180 PtyChardev *s = PTY_CHARDEV(chr);
1181 char *name;
1183 if (s->timer_tag) {
1184 g_source_remove(s->timer_tag);
1185 s->timer_tag = 0;
1188 if (ms == 1000) {
1189 name = g_strdup_printf("pty-timer-secs-%s", chr->label);
1190 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1191 } else {
1192 name = g_strdup_printf("pty-timer-ms-%s", chr->label);
1193 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1195 g_source_set_name_by_id(s->timer_tag, name);
1196 g_free(name);
1199 /* Called with chr_write_lock held. */
1200 static void pty_chr_update_read_handler_locked(Chardev *chr)
1202 PtyChardev *s = PTY_CHARDEV(chr);
1203 GPollFD pfd;
1204 int rc;
1205 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1207 pfd.fd = fioc->fd;
1208 pfd.events = G_IO_OUT;
1209 pfd.revents = 0;
1210 do {
1211 rc = g_poll(&pfd, 1, 0);
1212 } while (rc == -1 && errno == EINTR);
1213 assert(rc >= 0);
1215 if (pfd.revents & G_IO_HUP) {
1216 pty_chr_state(chr, 0);
1217 } else {
1218 pty_chr_state(chr, 1);
1222 static void pty_chr_update_read_handler(Chardev *chr,
1223 GMainContext *context)
1225 qemu_mutex_lock(&chr->chr_write_lock);
1226 pty_chr_update_read_handler_locked(chr);
1227 qemu_mutex_unlock(&chr->chr_write_lock);
1230 /* Called with chr_write_lock held. */
1231 static int char_pty_chr_write(Chardev *chr, const uint8_t *buf, int len)
1233 PtyChardev *s = PTY_CHARDEV(chr);
1235 if (!s->connected) {
1236 /* guest sends data, check for (re-)connect */
1237 pty_chr_update_read_handler_locked(chr);
1238 if (!s->connected) {
1239 return 0;
1242 return io_channel_send(s->ioc, buf, len);
1245 static GSource *pty_chr_add_watch(Chardev *chr, GIOCondition cond)
1247 PtyChardev *s = PTY_CHARDEV(chr);
1248 if (!s->connected) {
1249 return NULL;
1251 return qio_channel_create_watch(s->ioc, cond);
1254 static int pty_chr_read_poll(void *opaque)
1256 Chardev *chr = CHARDEV(opaque);
1257 PtyChardev *s = PTY_CHARDEV(opaque);
1259 s->read_bytes = qemu_chr_be_can_write(chr);
1260 return s->read_bytes;
1263 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1265 Chardev *chr = CHARDEV(opaque);
1266 PtyChardev *s = PTY_CHARDEV(opaque);
1267 gsize len;
1268 uint8_t buf[READ_BUF_LEN];
1269 ssize_t ret;
1271 len = sizeof(buf);
1272 if (len > s->read_bytes)
1273 len = s->read_bytes;
1274 if (len == 0) {
1275 return TRUE;
1277 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1278 if (ret <= 0) {
1279 pty_chr_state(chr, 0);
1280 return FALSE;
1281 } else {
1282 pty_chr_state(chr, 1);
1283 qemu_chr_be_write(chr, buf, ret);
1285 return TRUE;
1288 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1290 Chardev *chr = CHARDEV(opaque);
1291 PtyChardev *s = PTY_CHARDEV(opaque);
1293 s->open_tag = 0;
1294 qemu_chr_be_generic_open(chr);
1295 return FALSE;
1298 /* Called with chr_write_lock held. */
1299 static void pty_chr_state(Chardev *chr, int connected)
1301 PtyChardev *s = PTY_CHARDEV(chr);
1303 if (!connected) {
1304 if (s->open_tag) {
1305 g_source_remove(s->open_tag);
1306 s->open_tag = 0;
1308 remove_fd_in_watch(chr);
1309 s->connected = 0;
1310 /* (re-)connect poll interval for idle guests: once per second.
1311 * We check more frequently in case the guests sends data to
1312 * the virtual device linked to our pty. */
1313 pty_chr_rearm_timer(chr, 1000);
1314 } else {
1315 if (s->timer_tag) {
1316 g_source_remove(s->timer_tag);
1317 s->timer_tag = 0;
1319 if (!s->connected) {
1320 g_assert(s->open_tag == 0);
1321 s->connected = 1;
1322 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1324 if (!chr->fd_in_tag) {
1325 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
1326 pty_chr_read_poll,
1327 pty_chr_read,
1328 chr, NULL);
1333 static void char_pty_finalize(Object *obj)
1335 Chardev *chr = CHARDEV(obj);
1336 PtyChardev *s = PTY_CHARDEV(obj);
1338 qemu_mutex_lock(&chr->chr_write_lock);
1339 pty_chr_state(chr, 0);
1340 object_unref(OBJECT(s->ioc));
1341 if (s->timer_tag) {
1342 g_source_remove(s->timer_tag);
1343 s->timer_tag = 0;
1345 qemu_mutex_unlock(&chr->chr_write_lock);
1346 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1349 static void char_pty_open(Chardev *chr,
1350 ChardevBackend *backend,
1351 bool *be_opened,
1352 Error **errp)
1354 PtyChardev *s;
1355 int master_fd, slave_fd;
1356 char pty_name[PATH_MAX];
1357 char *name;
1359 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1360 if (master_fd < 0) {
1361 error_setg_errno(errp, errno, "Failed to create PTY");
1362 return;
1365 close(slave_fd);
1366 qemu_set_nonblock(master_fd);
1368 chr->filename = g_strdup_printf("pty:%s", pty_name);
1369 error_report("char device redirected to %s (label %s)",
1370 pty_name, chr->label);
1372 s = PTY_CHARDEV(chr);
1373 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1374 name = g_strdup_printf("chardev-pty-%s", chr->label);
1375 qio_channel_set_name(QIO_CHANNEL(s->ioc), name);
1376 g_free(name);
1377 s->timer_tag = 0;
1378 *be_opened = false;
1381 static void char_pty_class_init(ObjectClass *oc, void *data)
1383 ChardevClass *cc = CHARDEV_CLASS(oc);
1385 cc->open = char_pty_open;
1386 cc->chr_write = char_pty_chr_write;
1387 cc->chr_update_read_handler = pty_chr_update_read_handler;
1388 cc->chr_add_watch = pty_chr_add_watch;
1391 static const TypeInfo char_pty_type_info = {
1392 .name = TYPE_CHARDEV_PTY,
1393 .parent = TYPE_CHARDEV,
1394 .instance_size = sizeof(PtyChardev),
1395 .instance_finalize = char_pty_finalize,
1396 .class_init = char_pty_class_init,
1399 static void tty_serial_init(int fd, int speed,
1400 int parity, int data_bits, int stop_bits)
1402 struct termios tty;
1403 speed_t spd;
1405 #if 0
1406 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1407 speed, parity, data_bits, stop_bits);
1408 #endif
1409 tcgetattr (fd, &tty);
1411 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1412 speed = speed * 10 / 11;
1413 do {
1414 check_speed(50);
1415 check_speed(75);
1416 check_speed(110);
1417 check_speed(134);
1418 check_speed(150);
1419 check_speed(200);
1420 check_speed(300);
1421 check_speed(600);
1422 check_speed(1200);
1423 check_speed(1800);
1424 check_speed(2400);
1425 check_speed(4800);
1426 check_speed(9600);
1427 check_speed(19200);
1428 check_speed(38400);
1429 /* Non-Posix values follow. They may be unsupported on some systems. */
1430 check_speed(57600);
1431 check_speed(115200);
1432 #ifdef B230400
1433 check_speed(230400);
1434 #endif
1435 #ifdef B460800
1436 check_speed(460800);
1437 #endif
1438 #ifdef B500000
1439 check_speed(500000);
1440 #endif
1441 #ifdef B576000
1442 check_speed(576000);
1443 #endif
1444 #ifdef B921600
1445 check_speed(921600);
1446 #endif
1447 #ifdef B1000000
1448 check_speed(1000000);
1449 #endif
1450 #ifdef B1152000
1451 check_speed(1152000);
1452 #endif
1453 #ifdef B1500000
1454 check_speed(1500000);
1455 #endif
1456 #ifdef B2000000
1457 check_speed(2000000);
1458 #endif
1459 #ifdef B2500000
1460 check_speed(2500000);
1461 #endif
1462 #ifdef B3000000
1463 check_speed(3000000);
1464 #endif
1465 #ifdef B3500000
1466 check_speed(3500000);
1467 #endif
1468 #ifdef B4000000
1469 check_speed(4000000);
1470 #endif
1471 spd = B115200;
1472 } while (0);
1474 cfsetispeed(&tty, spd);
1475 cfsetospeed(&tty, spd);
1477 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1478 |INLCR|IGNCR|ICRNL|IXON);
1479 tty.c_oflag |= OPOST;
1480 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1481 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1482 switch(data_bits) {
1483 default:
1484 case 8:
1485 tty.c_cflag |= CS8;
1486 break;
1487 case 7:
1488 tty.c_cflag |= CS7;
1489 break;
1490 case 6:
1491 tty.c_cflag |= CS6;
1492 break;
1493 case 5:
1494 tty.c_cflag |= CS5;
1495 break;
1497 switch(parity) {
1498 default:
1499 case 'N':
1500 break;
1501 case 'E':
1502 tty.c_cflag |= PARENB;
1503 break;
1504 case 'O':
1505 tty.c_cflag |= PARENB | PARODD;
1506 break;
1508 if (stop_bits == 2)
1509 tty.c_cflag |= CSTOPB;
1511 tcsetattr (fd, TCSANOW, &tty);
1514 static int tty_serial_ioctl(Chardev *chr, int cmd, void *arg)
1516 FDChardev *s = FD_CHARDEV(chr);
1517 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1519 switch(cmd) {
1520 case CHR_IOCTL_SERIAL_SET_PARAMS:
1522 QEMUSerialSetParams *ssp = arg;
1523 tty_serial_init(fioc->fd,
1524 ssp->speed, ssp->parity,
1525 ssp->data_bits, ssp->stop_bits);
1527 break;
1528 case CHR_IOCTL_SERIAL_SET_BREAK:
1530 int enable = *(int *)arg;
1531 if (enable) {
1532 tcsendbreak(fioc->fd, 1);
1535 break;
1536 case CHR_IOCTL_SERIAL_GET_TIOCM:
1538 int sarg = 0;
1539 int *targ = (int *)arg;
1540 ioctl(fioc->fd, TIOCMGET, &sarg);
1541 *targ = 0;
1542 if (sarg & TIOCM_CTS)
1543 *targ |= CHR_TIOCM_CTS;
1544 if (sarg & TIOCM_CAR)
1545 *targ |= CHR_TIOCM_CAR;
1546 if (sarg & TIOCM_DSR)
1547 *targ |= CHR_TIOCM_DSR;
1548 if (sarg & TIOCM_RI)
1549 *targ |= CHR_TIOCM_RI;
1550 if (sarg & TIOCM_DTR)
1551 *targ |= CHR_TIOCM_DTR;
1552 if (sarg & TIOCM_RTS)
1553 *targ |= CHR_TIOCM_RTS;
1555 break;
1556 case CHR_IOCTL_SERIAL_SET_TIOCM:
1558 int sarg = *(int *)arg;
1559 int targ = 0;
1560 ioctl(fioc->fd, TIOCMGET, &targ);
1561 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1562 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1563 if (sarg & CHR_TIOCM_CTS)
1564 targ |= TIOCM_CTS;
1565 if (sarg & CHR_TIOCM_CAR)
1566 targ |= TIOCM_CAR;
1567 if (sarg & CHR_TIOCM_DSR)
1568 targ |= TIOCM_DSR;
1569 if (sarg & CHR_TIOCM_RI)
1570 targ |= TIOCM_RI;
1571 if (sarg & CHR_TIOCM_DTR)
1572 targ |= TIOCM_DTR;
1573 if (sarg & CHR_TIOCM_RTS)
1574 targ |= TIOCM_RTS;
1575 ioctl(fioc->fd, TIOCMSET, &targ);
1577 break;
1578 default:
1579 return -ENOTSUP;
1581 return 0;
1583 #endif /* __linux__ || __sun__ */
1585 #if defined(__linux__)
1587 #define HAVE_CHARDEV_PARPORT 1
1589 typedef struct {
1590 Chardev parent;
1591 int fd;
1592 int mode;
1593 } ParallelChardev;
1595 #define PARALLEL_CHARDEV(obj) \
1596 OBJECT_CHECK(ParallelChardev, (obj), TYPE_CHARDEV_PARALLEL)
1598 static int pp_hw_mode(ParallelChardev *s, uint16_t mode)
1600 if (s->mode != mode) {
1601 int m = mode;
1602 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1603 return 0;
1604 s->mode = mode;
1606 return 1;
1609 static int pp_ioctl(Chardev *chr, int cmd, void *arg)
1611 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
1612 int fd = drv->fd;
1613 uint8_t b;
1615 switch(cmd) {
1616 case CHR_IOCTL_PP_READ_DATA:
1617 if (ioctl(fd, PPRDATA, &b) < 0)
1618 return -ENOTSUP;
1619 *(uint8_t *)arg = b;
1620 break;
1621 case CHR_IOCTL_PP_WRITE_DATA:
1622 b = *(uint8_t *)arg;
1623 if (ioctl(fd, PPWDATA, &b) < 0)
1624 return -ENOTSUP;
1625 break;
1626 case CHR_IOCTL_PP_READ_CONTROL:
1627 if (ioctl(fd, PPRCONTROL, &b) < 0)
1628 return -ENOTSUP;
1629 /* Linux gives only the lowest bits, and no way to know data
1630 direction! For better compatibility set the fixed upper
1631 bits. */
1632 *(uint8_t *)arg = b | 0xc0;
1633 break;
1634 case CHR_IOCTL_PP_WRITE_CONTROL:
1635 b = *(uint8_t *)arg;
1636 if (ioctl(fd, PPWCONTROL, &b) < 0)
1637 return -ENOTSUP;
1638 break;
1639 case CHR_IOCTL_PP_READ_STATUS:
1640 if (ioctl(fd, PPRSTATUS, &b) < 0)
1641 return -ENOTSUP;
1642 *(uint8_t *)arg = b;
1643 break;
1644 case CHR_IOCTL_PP_DATA_DIR:
1645 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1646 return -ENOTSUP;
1647 break;
1648 case CHR_IOCTL_PP_EPP_READ_ADDR:
1649 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1650 struct ParallelIOArg *parg = arg;
1651 int n = read(fd, parg->buffer, parg->count);
1652 if (n != parg->count) {
1653 return -EIO;
1656 break;
1657 case CHR_IOCTL_PP_EPP_READ:
1658 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1659 struct ParallelIOArg *parg = arg;
1660 int n = read(fd, parg->buffer, parg->count);
1661 if (n != parg->count) {
1662 return -EIO;
1665 break;
1666 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1667 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1668 struct ParallelIOArg *parg = arg;
1669 int n = write(fd, parg->buffer, parg->count);
1670 if (n != parg->count) {
1671 return -EIO;
1674 break;
1675 case CHR_IOCTL_PP_EPP_WRITE:
1676 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1677 struct ParallelIOArg *parg = arg;
1678 int n = write(fd, parg->buffer, parg->count);
1679 if (n != parg->count) {
1680 return -EIO;
1683 break;
1684 default:
1685 return -ENOTSUP;
1687 return 0;
1690 static void qemu_chr_open_pp_fd(Chardev *chr,
1691 int fd,
1692 bool *be_opened,
1693 Error **errp)
1695 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
1697 if (ioctl(fd, PPCLAIM) < 0) {
1698 error_setg_errno(errp, errno, "not a parallel port");
1699 close(fd);
1700 return;
1703 drv->fd = fd;
1704 drv->mode = IEEE1284_MODE_COMPAT;
1706 #endif /* __linux__ */
1708 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1710 #define HAVE_CHARDEV_PARPORT 1
1712 typedef struct {
1713 Chardev parent;
1714 int fd;
1715 } ParallelChardev;
1717 #define PARALLEL_CHARDEV(obj) \
1718 OBJECT_CHECK(ParallelChardev, (obj), TYPE_CHARDEV_PARALLEL)
1720 static int pp_ioctl(Chardev *chr, int cmd, void *arg)
1722 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
1723 uint8_t b;
1725 switch (cmd) {
1726 case CHR_IOCTL_PP_READ_DATA:
1727 if (ioctl(drv->fd, PPIGDATA, &b) < 0) {
1728 return -ENOTSUP;
1730 *(uint8_t *)arg = b;
1731 break;
1732 case CHR_IOCTL_PP_WRITE_DATA:
1733 b = *(uint8_t *)arg;
1734 if (ioctl(drv->fd, PPISDATA, &b) < 0) {
1735 return -ENOTSUP;
1737 break;
1738 case CHR_IOCTL_PP_READ_CONTROL:
1739 if (ioctl(drv->fd, PPIGCTRL, &b) < 0) {
1740 return -ENOTSUP;
1742 *(uint8_t *)arg = b;
1743 break;
1744 case CHR_IOCTL_PP_WRITE_CONTROL:
1745 b = *(uint8_t *)arg;
1746 if (ioctl(drv->fd, PPISCTRL, &b) < 0) {
1747 return -ENOTSUP;
1749 break;
1750 case CHR_IOCTL_PP_READ_STATUS:
1751 if (ioctl(drv->fd, PPIGSTATUS, &b) < 0) {
1752 return -ENOTSUP;
1754 *(uint8_t *)arg = b;
1755 break;
1756 default:
1757 return -ENOTSUP;
1759 return 0;
1762 static void qemu_chr_open_pp_fd(Chardev *chr,
1763 int fd,
1764 bool *be_opened,
1765 Error **errp)
1767 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
1768 drv->fd = fd;
1769 *be_opened = false;
1771 #endif
1773 #else /* _WIN32 */
1775 #define HAVE_CHARDEV_SERIAL 1
1777 typedef struct {
1778 Chardev parent;
1779 int max_size;
1780 HANDLE hcom, hrecv, hsend;
1781 OVERLAPPED orecv;
1782 BOOL fpipe;
1783 DWORD len;
1785 /* Protected by the Chardev chr_write_lock. */
1786 OVERLAPPED osend;
1787 /* FIXME: file/console do not finalize */
1788 bool skip_free;
1789 } WinChardev;
1791 #define TYPE_CHARDEV_WIN "chardev-win"
1792 #define WIN_CHARDEV(obj) OBJECT_CHECK(WinChardev, (obj), TYPE_CHARDEV_WIN)
1794 typedef struct {
1795 Chardev parent;
1796 HANDLE hStdIn;
1797 HANDLE hInputReadyEvent;
1798 HANDLE hInputDoneEvent;
1799 HANDLE hInputThread;
1800 uint8_t win_stdio_buf;
1801 } WinStdioChardev;
1803 #define TYPE_CHARDEV_WIN_STDIO "chardev-win-stdio"
1804 #define WIN_STDIO_CHARDEV(obj) \
1805 OBJECT_CHECK(WinStdioChardev, (obj), TYPE_CHARDEV_WIN_STDIO)
1807 #define NSENDBUF 2048
1808 #define NRECVBUF 2048
1809 #define MAXCONNECT 1
1810 #define NTIMEOUT 5000
1812 static int win_chr_poll(void *opaque);
1813 static int win_chr_pipe_poll(void *opaque);
1815 static void char_win_finalize(Object *obj)
1817 Chardev *chr = CHARDEV(obj);
1818 WinChardev *s = WIN_CHARDEV(chr);
1820 if (s->skip_free) {
1821 return;
1824 if (s->hsend) {
1825 CloseHandle(s->hsend);
1827 if (s->hrecv) {
1828 CloseHandle(s->hrecv);
1830 if (s->hcom) {
1831 CloseHandle(s->hcom);
1833 if (s->fpipe)
1834 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1835 else
1836 qemu_del_polling_cb(win_chr_poll, chr);
1838 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1841 static int win_chr_init(Chardev *chr, const char *filename, Error **errp)
1843 WinChardev *s = WIN_CHARDEV(chr);
1844 COMMCONFIG comcfg;
1845 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1846 COMSTAT comstat;
1847 DWORD size;
1848 DWORD err;
1850 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1851 if (!s->hsend) {
1852 error_setg(errp, "Failed CreateEvent");
1853 goto fail;
1855 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1856 if (!s->hrecv) {
1857 error_setg(errp, "Failed CreateEvent");
1858 goto fail;
1861 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1862 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1863 if (s->hcom == INVALID_HANDLE_VALUE) {
1864 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1865 s->hcom = NULL;
1866 goto fail;
1869 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1870 error_setg(errp, "Failed SetupComm");
1871 goto fail;
1874 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1875 size = sizeof(COMMCONFIG);
1876 GetDefaultCommConfig(filename, &comcfg, &size);
1877 comcfg.dcb.DCBlength = sizeof(DCB);
1878 CommConfigDialog(filename, NULL, &comcfg);
1880 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1881 error_setg(errp, "Failed SetCommState");
1882 goto fail;
1885 if (!SetCommMask(s->hcom, EV_ERR)) {
1886 error_setg(errp, "Failed SetCommMask");
1887 goto fail;
1890 cto.ReadIntervalTimeout = MAXDWORD;
1891 if (!SetCommTimeouts(s->hcom, &cto)) {
1892 error_setg(errp, "Failed SetCommTimeouts");
1893 goto fail;
1896 if (!ClearCommError(s->hcom, &err, &comstat)) {
1897 error_setg(errp, "Failed ClearCommError");
1898 goto fail;
1900 qemu_add_polling_cb(win_chr_poll, chr);
1901 return 0;
1903 fail:
1904 return -1;
1907 /* Called with chr_write_lock held. */
1908 static int win_chr_write(Chardev *chr, const uint8_t *buf, int len1)
1910 WinChardev *s = WIN_CHARDEV(chr);
1911 DWORD len, ret, size, err;
1913 len = len1;
1914 ZeroMemory(&s->osend, sizeof(s->osend));
1915 s->osend.hEvent = s->hsend;
1916 while (len > 0) {
1917 if (s->hsend)
1918 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1919 else
1920 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1921 if (!ret) {
1922 err = GetLastError();
1923 if (err == ERROR_IO_PENDING) {
1924 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1925 if (ret) {
1926 buf += size;
1927 len -= size;
1928 } else {
1929 break;
1931 } else {
1932 break;
1934 } else {
1935 buf += size;
1936 len -= size;
1939 return len1 - len;
1942 static int win_chr_read_poll(Chardev *chr)
1944 WinChardev *s = WIN_CHARDEV(chr);
1946 s->max_size = qemu_chr_be_can_write(chr);
1947 return s->max_size;
1950 static void win_chr_readfile(Chardev *chr)
1952 WinChardev *s = WIN_CHARDEV(chr);
1954 int ret, err;
1955 uint8_t buf[READ_BUF_LEN];
1956 DWORD size;
1958 ZeroMemory(&s->orecv, sizeof(s->orecv));
1959 s->orecv.hEvent = s->hrecv;
1960 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1961 if (!ret) {
1962 err = GetLastError();
1963 if (err == ERROR_IO_PENDING) {
1964 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1968 if (size > 0) {
1969 qemu_chr_be_write(chr, buf, size);
1973 static void win_chr_read(Chardev *chr)
1975 WinChardev *s = WIN_CHARDEV(chr);
1977 if (s->len > s->max_size)
1978 s->len = s->max_size;
1979 if (s->len == 0)
1980 return;
1982 win_chr_readfile(chr);
1985 static int win_chr_poll(void *opaque)
1987 Chardev *chr = CHARDEV(opaque);
1988 WinChardev *s = WIN_CHARDEV(opaque);
1989 COMSTAT status;
1990 DWORD comerr;
1992 ClearCommError(s->hcom, &comerr, &status);
1993 if (status.cbInQue > 0) {
1994 s->len = status.cbInQue;
1995 win_chr_read_poll(chr);
1996 win_chr_read(chr);
1997 return 1;
1999 return 0;
2002 static int win_chr_pipe_poll(void *opaque)
2004 Chardev *chr = CHARDEV(opaque);
2005 WinChardev *s = WIN_CHARDEV(opaque);
2006 DWORD size;
2008 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2009 if (size > 0) {
2010 s->len = size;
2011 win_chr_read_poll(chr);
2012 win_chr_read(chr);
2013 return 1;
2015 return 0;
2018 static int win_chr_pipe_init(Chardev *chr, const char *filename,
2019 Error **errp)
2021 WinChardev *s = WIN_CHARDEV(chr);
2022 OVERLAPPED ov;
2023 int ret;
2024 DWORD size;
2025 char *openname;
2027 s->fpipe = TRUE;
2029 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2030 if (!s->hsend) {
2031 error_setg(errp, "Failed CreateEvent");
2032 goto fail;
2034 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2035 if (!s->hrecv) {
2036 error_setg(errp, "Failed CreateEvent");
2037 goto fail;
2040 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2041 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2042 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2043 PIPE_WAIT,
2044 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2045 g_free(openname);
2046 if (s->hcom == INVALID_HANDLE_VALUE) {
2047 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2048 s->hcom = NULL;
2049 goto fail;
2052 ZeroMemory(&ov, sizeof(ov));
2053 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2054 ret = ConnectNamedPipe(s->hcom, &ov);
2055 if (ret) {
2056 error_setg(errp, "Failed ConnectNamedPipe");
2057 goto fail;
2060 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2061 if (!ret) {
2062 error_setg(errp, "Failed GetOverlappedResult");
2063 if (ov.hEvent) {
2064 CloseHandle(ov.hEvent);
2065 ov.hEvent = NULL;
2067 goto fail;
2070 if (ov.hEvent) {
2071 CloseHandle(ov.hEvent);
2072 ov.hEvent = NULL;
2074 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2075 return 0;
2077 fail:
2078 return -1;
2082 static void qemu_chr_open_pipe(Chardev *chr,
2083 ChardevBackend *backend,
2084 bool *be_opened,
2085 Error **errp)
2087 ChardevHostdev *opts = backend->u.pipe.data;
2088 const char *filename = opts->device;
2090 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2091 return;
2095 static void qemu_chr_open_win_file(Chardev *chr, HANDLE fd_out)
2097 WinChardev *s = WIN_CHARDEV(chr);
2099 s->skip_free = true;
2100 s->hcom = fd_out;
2103 static void char_win_class_init(ObjectClass *oc, void *data)
2105 ChardevClass *cc = CHARDEV_CLASS(oc);
2107 cc->chr_write = win_chr_write;
2110 static const TypeInfo char_win_type_info = {
2111 .name = TYPE_CHARDEV_WIN,
2112 .parent = TYPE_CHARDEV,
2113 .instance_size = sizeof(WinChardev),
2114 .instance_finalize = char_win_finalize,
2115 .class_init = char_win_class_init,
2116 .abstract = true,
2119 static void qemu_chr_open_win_con(Chardev *chr,
2120 ChardevBackend *backend,
2121 bool *be_opened,
2122 Error **errp)
2124 qemu_chr_open_win_file(chr, GetStdHandle(STD_OUTPUT_HANDLE));
2127 static void char_console_class_init(ObjectClass *oc, void *data)
2129 ChardevClass *cc = CHARDEV_CLASS(oc);
2131 cc->open = qemu_chr_open_win_con;
2134 static const TypeInfo char_console_type_info = {
2135 .name = TYPE_CHARDEV_CONSOLE,
2136 .parent = TYPE_CHARDEV_WIN,
2137 .class_init = char_console_class_init,
2140 static int win_stdio_write(Chardev *chr, const uint8_t *buf, int len)
2142 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2143 DWORD dwSize;
2144 int len1;
2146 len1 = len;
2148 while (len1 > 0) {
2149 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2150 break;
2152 buf += dwSize;
2153 len1 -= dwSize;
2156 return len - len1;
2159 static void win_stdio_wait_func(void *opaque)
2161 Chardev *chr = CHARDEV(opaque);
2162 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(opaque);
2163 INPUT_RECORD buf[4];
2164 int ret;
2165 DWORD dwSize;
2166 int i;
2168 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2170 if (!ret) {
2171 /* Avoid error storm */
2172 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2173 return;
2176 for (i = 0; i < dwSize; i++) {
2177 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2179 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2180 int j;
2181 if (kev->uChar.AsciiChar != 0) {
2182 for (j = 0; j < kev->wRepeatCount; j++) {
2183 if (qemu_chr_be_can_write(chr)) {
2184 uint8_t c = kev->uChar.AsciiChar;
2185 qemu_chr_be_write(chr, &c, 1);
2193 static DWORD WINAPI win_stdio_thread(LPVOID param)
2195 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(param);
2196 int ret;
2197 DWORD dwSize;
2199 while (1) {
2201 /* Wait for one byte */
2202 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2204 /* Exit in case of error, continue if nothing read */
2205 if (!ret) {
2206 break;
2208 if (!dwSize) {
2209 continue;
2212 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2213 if (stdio->win_stdio_buf == '\r') {
2214 continue;
2217 /* Signal the main thread and wait until the byte was eaten */
2218 if (!SetEvent(stdio->hInputReadyEvent)) {
2219 break;
2221 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2222 != WAIT_OBJECT_0) {
2223 break;
2227 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2228 return 0;
2231 static void win_stdio_thread_wait_func(void *opaque)
2233 Chardev *chr = CHARDEV(opaque);
2234 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(opaque);
2236 if (qemu_chr_be_can_write(chr)) {
2237 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2240 SetEvent(stdio->hInputDoneEvent);
2243 static void qemu_chr_set_echo_win_stdio(Chardev *chr, bool echo)
2245 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(chr);
2246 DWORD dwMode = 0;
2248 GetConsoleMode(stdio->hStdIn, &dwMode);
2250 if (echo) {
2251 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2252 } else {
2253 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2257 static void char_win_stdio_finalize(Object *obj)
2259 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(obj);
2261 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2262 CloseHandle(stdio->hInputReadyEvent);
2264 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2265 CloseHandle(stdio->hInputDoneEvent);
2267 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2268 TerminateThread(stdio->hInputThread, 0);
2272 static const TypeInfo char_win_stdio_type_info = {
2273 .name = TYPE_CHARDEV_WIN_STDIO,
2274 .parent = TYPE_CHARDEV,
2275 .instance_size = sizeof(WinStdioChardev),
2276 .instance_finalize = char_win_stdio_finalize,
2277 .abstract = true,
2280 static void qemu_chr_open_stdio(Chardev *chr,
2281 ChardevBackend *backend,
2282 bool *be_opened,
2283 Error **errp)
2285 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(chr);
2286 DWORD dwMode;
2287 int is_console = 0;
2289 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2290 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2291 error_setg(errp, "cannot open stdio: invalid handle");
2292 return;
2295 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2297 if (is_console) {
2298 if (qemu_add_wait_object(stdio->hStdIn,
2299 win_stdio_wait_func, chr)) {
2300 error_setg(errp, "qemu_add_wait_object: failed");
2301 goto err1;
2303 } else {
2304 DWORD dwId;
2306 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2307 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2308 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2309 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2310 error_setg(errp, "cannot create event");
2311 goto err2;
2313 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2314 win_stdio_thread_wait_func, chr)) {
2315 error_setg(errp, "qemu_add_wait_object: failed");
2316 goto err2;
2318 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2319 chr, 0, &dwId);
2321 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2322 error_setg(errp, "cannot create stdio thread");
2323 goto err3;
2327 dwMode |= ENABLE_LINE_INPUT;
2329 if (is_console) {
2330 /* set the terminal in raw mode */
2331 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2332 dwMode |= ENABLE_PROCESSED_INPUT;
2335 SetConsoleMode(stdio->hStdIn, dwMode);
2337 qemu_chr_set_echo_win_stdio(chr, false);
2339 return;
2341 err3:
2342 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2343 err2:
2344 CloseHandle(stdio->hInputReadyEvent);
2345 CloseHandle(stdio->hInputDoneEvent);
2346 err1:
2347 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2349 #endif /* !_WIN32 */
2351 /***********************************************************/
2352 /* UDP Net console */
2354 typedef struct {
2355 Chardev parent;
2356 QIOChannel *ioc;
2357 uint8_t buf[READ_BUF_LEN];
2358 int bufcnt;
2359 int bufptr;
2360 int max_size;
2361 } UdpChardev;
2363 #define UDP_CHARDEV(obj) OBJECT_CHECK(UdpChardev, (obj), TYPE_CHARDEV_UDP)
2365 /* Called with chr_write_lock held. */
2366 static int udp_chr_write(Chardev *chr, const uint8_t *buf, int len)
2368 UdpChardev *s = UDP_CHARDEV(chr);
2370 return qio_channel_write(
2371 s->ioc, (const char *)buf, len, NULL);
2374 static int udp_chr_read_poll(void *opaque)
2376 Chardev *chr = CHARDEV(opaque);
2377 UdpChardev *s = UDP_CHARDEV(opaque);
2379 s->max_size = qemu_chr_be_can_write(chr);
2381 /* If there were any stray characters in the queue process them
2382 * first
2384 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2385 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2386 s->bufptr++;
2387 s->max_size = qemu_chr_be_can_write(chr);
2389 return s->max_size;
2392 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2394 Chardev *chr = CHARDEV(opaque);
2395 UdpChardev *s = UDP_CHARDEV(opaque);
2396 ssize_t ret;
2398 if (s->max_size == 0) {
2399 return TRUE;
2401 ret = qio_channel_read(
2402 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2403 if (ret <= 0) {
2404 remove_fd_in_watch(chr);
2405 return FALSE;
2407 s->bufcnt = ret;
2409 s->bufptr = 0;
2410 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2411 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2412 s->bufptr++;
2413 s->max_size = qemu_chr_be_can_write(chr);
2416 return TRUE;
2419 static void udp_chr_update_read_handler(Chardev *chr,
2420 GMainContext *context)
2422 UdpChardev *s = UDP_CHARDEV(chr);
2424 remove_fd_in_watch(chr);
2425 if (s->ioc) {
2426 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
2427 udp_chr_read_poll,
2428 udp_chr_read, chr,
2429 context);
2433 static void char_udp_finalize(Object *obj)
2435 Chardev *chr = CHARDEV(obj);
2436 UdpChardev *s = UDP_CHARDEV(obj);
2438 remove_fd_in_watch(chr);
2439 if (s->ioc) {
2440 object_unref(OBJECT(s->ioc));
2442 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2445 /***********************************************************/
2446 /* TCP Net console */
2448 typedef struct {
2449 Chardev parent;
2450 QIOChannel *ioc; /* Client I/O channel */
2451 QIOChannelSocket *sioc; /* Client master channel */
2452 QIOChannelSocket *listen_ioc;
2453 guint listen_tag;
2454 QCryptoTLSCreds *tls_creds;
2455 int connected;
2456 int max_size;
2457 int do_telnetopt;
2458 int do_nodelay;
2459 int is_unix;
2460 int *read_msgfds;
2461 size_t read_msgfds_num;
2462 int *write_msgfds;
2463 size_t write_msgfds_num;
2465 SocketAddress *addr;
2466 bool is_listen;
2467 bool is_telnet;
2469 guint reconnect_timer;
2470 int64_t reconnect_time;
2471 bool connect_err_reported;
2472 } SocketChardev;
2474 #define SOCKET_CHARDEV(obj) \
2475 OBJECT_CHECK(SocketChardev, (obj), TYPE_CHARDEV_SOCKET)
2477 static gboolean socket_reconnect_timeout(gpointer opaque);
2479 static void qemu_chr_socket_restart_timer(Chardev *chr)
2481 SocketChardev *s = SOCKET_CHARDEV(chr);
2482 char *name;
2484 assert(s->connected == 0);
2485 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2486 socket_reconnect_timeout, chr);
2487 name = g_strdup_printf("chardev-socket-reconnect-%s", chr->label);
2488 g_source_set_name_by_id(s->reconnect_timer, name);
2489 g_free(name);
2492 static void check_report_connect_error(Chardev *chr,
2493 Error *err)
2495 SocketChardev *s = SOCKET_CHARDEV(chr);
2497 if (!s->connect_err_reported) {
2498 error_report("Unable to connect character device %s: %s",
2499 chr->label, error_get_pretty(err));
2500 s->connect_err_reported = true;
2502 qemu_chr_socket_restart_timer(chr);
2505 static gboolean tcp_chr_accept(QIOChannel *chan,
2506 GIOCondition cond,
2507 void *opaque);
2509 /* Called with chr_write_lock held. */
2510 static int tcp_chr_write(Chardev *chr, const uint8_t *buf, int len)
2512 SocketChardev *s = SOCKET_CHARDEV(chr);
2514 if (s->connected) {
2515 int ret = io_channel_send_full(s->ioc, buf, len,
2516 s->write_msgfds,
2517 s->write_msgfds_num);
2519 /* free the written msgfds, no matter what */
2520 if (s->write_msgfds_num) {
2521 g_free(s->write_msgfds);
2522 s->write_msgfds = 0;
2523 s->write_msgfds_num = 0;
2526 return ret;
2527 } else {
2528 /* XXX: indicate an error ? */
2529 return len;
2533 static int tcp_chr_read_poll(void *opaque)
2535 Chardev *chr = CHARDEV(opaque);
2536 SocketChardev *s = SOCKET_CHARDEV(opaque);
2537 if (!s->connected)
2538 return 0;
2539 s->max_size = qemu_chr_be_can_write(chr);
2540 return s->max_size;
2543 #define IAC 255
2544 #define IAC_BREAK 243
2545 static void tcp_chr_process_IAC_bytes(Chardev *chr,
2546 SocketChardev *s,
2547 uint8_t *buf, int *size)
2549 /* Handle any telnet client's basic IAC options to satisfy char by
2550 * char mode with no echo. All IAC options will be removed from
2551 * the buf and the do_telnetopt variable will be used to track the
2552 * state of the width of the IAC information.
2554 * IAC commands come in sets of 3 bytes with the exception of the
2555 * "IAC BREAK" command and the double IAC.
2558 int i;
2559 int j = 0;
2561 for (i = 0; i < *size; i++) {
2562 if (s->do_telnetopt > 1) {
2563 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2564 /* Double IAC means send an IAC */
2565 if (j != i)
2566 buf[j] = buf[i];
2567 j++;
2568 s->do_telnetopt = 1;
2569 } else {
2570 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2571 /* Handle IAC break commands by sending a serial break */
2572 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2573 s->do_telnetopt++;
2575 s->do_telnetopt++;
2577 if (s->do_telnetopt >= 4) {
2578 s->do_telnetopt = 1;
2580 } else {
2581 if ((unsigned char)buf[i] == IAC) {
2582 s->do_telnetopt = 2;
2583 } else {
2584 if (j != i)
2585 buf[j] = buf[i];
2586 j++;
2590 *size = j;
2593 static int tcp_get_msgfds(Chardev *chr, int *fds, int num)
2595 SocketChardev *s = SOCKET_CHARDEV(chr);
2597 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2599 assert(num <= TCP_MAX_FDS);
2601 if (to_copy) {
2602 int i;
2604 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2606 /* Close unused fds */
2607 for (i = to_copy; i < s->read_msgfds_num; i++) {
2608 close(s->read_msgfds[i]);
2611 g_free(s->read_msgfds);
2612 s->read_msgfds = 0;
2613 s->read_msgfds_num = 0;
2616 return to_copy;
2619 static int tcp_set_msgfds(Chardev *chr, int *fds, int num)
2621 SocketChardev *s = SOCKET_CHARDEV(chr);
2623 /* clear old pending fd array */
2624 g_free(s->write_msgfds);
2625 s->write_msgfds = NULL;
2626 s->write_msgfds_num = 0;
2628 if (!s->connected ||
2629 !qio_channel_has_feature(s->ioc,
2630 QIO_CHANNEL_FEATURE_FD_PASS)) {
2631 return -1;
2634 if (num) {
2635 s->write_msgfds = g_new(int, num);
2636 memcpy(s->write_msgfds, fds, num * sizeof(int));
2639 s->write_msgfds_num = num;
2641 return 0;
2644 static ssize_t tcp_chr_recv(Chardev *chr, char *buf, size_t len)
2646 SocketChardev *s = SOCKET_CHARDEV(chr);
2647 struct iovec iov = { .iov_base = buf, .iov_len = len };
2648 int ret;
2649 size_t i;
2650 int *msgfds = NULL;
2651 size_t msgfds_num = 0;
2653 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2654 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2655 &msgfds, &msgfds_num,
2656 NULL);
2657 } else {
2658 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2659 NULL, NULL,
2660 NULL);
2663 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2664 errno = EAGAIN;
2665 ret = -1;
2666 } else if (ret == -1) {
2667 errno = EIO;
2670 if (msgfds_num) {
2671 /* close and clean read_msgfds */
2672 for (i = 0; i < s->read_msgfds_num; i++) {
2673 close(s->read_msgfds[i]);
2676 if (s->read_msgfds_num) {
2677 g_free(s->read_msgfds);
2680 s->read_msgfds = msgfds;
2681 s->read_msgfds_num = msgfds_num;
2684 for (i = 0; i < s->read_msgfds_num; i++) {
2685 int fd = s->read_msgfds[i];
2686 if (fd < 0) {
2687 continue;
2690 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2691 qemu_set_block(fd);
2693 #ifndef MSG_CMSG_CLOEXEC
2694 qemu_set_cloexec(fd);
2695 #endif
2698 return ret;
2701 static GSource *tcp_chr_add_watch(Chardev *chr, GIOCondition cond)
2703 SocketChardev *s = SOCKET_CHARDEV(chr);
2704 return qio_channel_create_watch(s->ioc, cond);
2707 static void tcp_chr_free_connection(Chardev *chr)
2709 SocketChardev *s = SOCKET_CHARDEV(chr);
2710 int i;
2712 if (!s->connected) {
2713 return;
2716 if (s->read_msgfds_num) {
2717 for (i = 0; i < s->read_msgfds_num; i++) {
2718 close(s->read_msgfds[i]);
2720 g_free(s->read_msgfds);
2721 s->read_msgfds = NULL;
2722 s->read_msgfds_num = 0;
2725 tcp_set_msgfds(chr, NULL, 0);
2726 remove_fd_in_watch(chr);
2727 object_unref(OBJECT(s->sioc));
2728 s->sioc = NULL;
2729 object_unref(OBJECT(s->ioc));
2730 s->ioc = NULL;
2731 g_free(chr->filename);
2732 chr->filename = NULL;
2733 s->connected = 0;
2736 static void tcp_chr_disconnect(Chardev *chr)
2738 SocketChardev *s = SOCKET_CHARDEV(chr);
2740 if (!s->connected) {
2741 return;
2744 tcp_chr_free_connection(chr);
2746 if (s->listen_ioc) {
2747 s->listen_tag = qio_channel_add_watch(
2748 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2750 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2751 s->is_listen, s->is_telnet);
2752 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2753 if (s->reconnect_time) {
2754 qemu_chr_socket_restart_timer(chr);
2758 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2760 Chardev *chr = CHARDEV(opaque);
2761 SocketChardev *s = SOCKET_CHARDEV(opaque);
2762 uint8_t buf[READ_BUF_LEN];
2763 int len, size;
2765 if (!s->connected || s->max_size <= 0) {
2766 return TRUE;
2768 len = sizeof(buf);
2769 if (len > s->max_size)
2770 len = s->max_size;
2771 size = tcp_chr_recv(chr, (void *)buf, len);
2772 if (size == 0 || size == -1) {
2773 /* connection closed */
2774 tcp_chr_disconnect(chr);
2775 } else if (size > 0) {
2776 if (s->do_telnetopt)
2777 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2778 if (size > 0)
2779 qemu_chr_be_write(chr, buf, size);
2782 return TRUE;
2785 static int tcp_chr_sync_read(Chardev *chr, const uint8_t *buf, int len)
2787 SocketChardev *s = SOCKET_CHARDEV(chr);
2788 int size;
2790 if (!s->connected) {
2791 return 0;
2794 size = tcp_chr_recv(chr, (void *) buf, len);
2795 if (size == 0) {
2796 /* connection closed */
2797 tcp_chr_disconnect(chr);
2800 return size;
2803 static void tcp_chr_connect(void *opaque)
2805 Chardev *chr = CHARDEV(opaque);
2806 SocketChardev *s = SOCKET_CHARDEV(opaque);
2808 g_free(chr->filename);
2809 chr->filename = sockaddr_to_str(
2810 &s->sioc->localAddr, s->sioc->localAddrLen,
2811 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2812 s->is_listen, s->is_telnet);
2814 s->connected = 1;
2815 if (s->ioc) {
2816 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
2817 tcp_chr_read_poll,
2818 tcp_chr_read,
2819 chr, NULL);
2821 qemu_chr_be_generic_open(chr);
2824 static void tcp_chr_update_read_handler(Chardev *chr,
2825 GMainContext *context)
2827 SocketChardev *s = SOCKET_CHARDEV(chr);
2829 if (!s->connected) {
2830 return;
2833 remove_fd_in_watch(chr);
2834 if (s->ioc) {
2835 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
2836 tcp_chr_read_poll,
2837 tcp_chr_read, chr,
2838 context);
2842 typedef struct {
2843 Chardev *chr;
2844 char buf[12];
2845 size_t buflen;
2846 } TCPChardevTelnetInit;
2848 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
2849 GIOCondition cond G_GNUC_UNUSED,
2850 gpointer user_data)
2852 TCPChardevTelnetInit *init = user_data;
2853 ssize_t ret;
2855 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
2856 if (ret < 0) {
2857 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2858 ret = 0;
2859 } else {
2860 tcp_chr_disconnect(init->chr);
2861 return FALSE;
2864 init->buflen -= ret;
2866 if (init->buflen == 0) {
2867 tcp_chr_connect(init->chr);
2868 return FALSE;
2871 memmove(init->buf, init->buf + ret, init->buflen);
2873 return TRUE;
2876 static void tcp_chr_telnet_init(Chardev *chr)
2878 SocketChardev *s = SOCKET_CHARDEV(chr);
2879 TCPChardevTelnetInit *init = g_new0(TCPChardevTelnetInit, 1);
2880 size_t n = 0;
2882 init->chr = chr;
2883 init->buflen = 12;
2885 #define IACSET(x, a, b, c) \
2886 do { \
2887 x[n++] = a; \
2888 x[n++] = b; \
2889 x[n++] = c; \
2890 } while (0)
2892 /* Prep the telnet negotion to put telnet in binary,
2893 * no echo, single char mode */
2894 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2895 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2896 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2897 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2899 #undef IACSET
2901 qio_channel_add_watch(
2902 s->ioc, G_IO_OUT,
2903 tcp_chr_telnet_init_io,
2904 init, NULL);
2908 static void tcp_chr_tls_handshake(QIOTask *task,
2909 gpointer user_data)
2911 Chardev *chr = user_data;
2912 SocketChardev *s = user_data;
2914 if (qio_task_propagate_error(task, NULL)) {
2915 tcp_chr_disconnect(chr);
2916 } else {
2917 if (s->do_telnetopt) {
2918 tcp_chr_telnet_init(chr);
2919 } else {
2920 tcp_chr_connect(chr);
2926 static void tcp_chr_tls_init(Chardev *chr)
2928 SocketChardev *s = SOCKET_CHARDEV(chr);
2929 QIOChannelTLS *tioc;
2930 Error *err = NULL;
2931 gchar *name;
2933 if (s->is_listen) {
2934 tioc = qio_channel_tls_new_server(
2935 s->ioc, s->tls_creds,
2936 NULL, /* XXX Use an ACL */
2937 &err);
2938 } else {
2939 tioc = qio_channel_tls_new_client(
2940 s->ioc, s->tls_creds,
2941 s->addr->u.inet.data->host,
2942 &err);
2944 if (tioc == NULL) {
2945 error_free(err);
2946 tcp_chr_disconnect(chr);
2947 return;
2949 name = g_strdup_printf("chardev-tls-%s-%s",
2950 s->is_listen ? "server" : "client",
2951 chr->label);
2952 qio_channel_set_name(QIO_CHANNEL(tioc), name);
2953 g_free(name);
2954 object_unref(OBJECT(s->ioc));
2955 s->ioc = QIO_CHANNEL(tioc);
2957 qio_channel_tls_handshake(tioc,
2958 tcp_chr_tls_handshake,
2959 chr,
2960 NULL);
2964 static void tcp_chr_set_client_ioc_name(Chardev *chr,
2965 QIOChannelSocket *sioc)
2967 SocketChardev *s = SOCKET_CHARDEV(chr);
2968 char *name;
2969 name = g_strdup_printf("chardev-tcp-%s-%s",
2970 s->is_listen ? "server" : "client",
2971 chr->label);
2972 qio_channel_set_name(QIO_CHANNEL(sioc), name);
2973 g_free(name);
2977 static int tcp_chr_new_client(Chardev *chr, QIOChannelSocket *sioc)
2979 SocketChardev *s = SOCKET_CHARDEV(chr);
2981 if (s->ioc != NULL) {
2982 return -1;
2985 s->ioc = QIO_CHANNEL(sioc);
2986 object_ref(OBJECT(sioc));
2987 s->sioc = sioc;
2988 object_ref(OBJECT(sioc));
2990 qio_channel_set_blocking(s->ioc, false, NULL);
2992 if (s->do_nodelay) {
2993 qio_channel_set_delay(s->ioc, false);
2995 if (s->listen_tag) {
2996 g_source_remove(s->listen_tag);
2997 s->listen_tag = 0;
3000 if (s->tls_creds) {
3001 tcp_chr_tls_init(chr);
3002 } else {
3003 if (s->do_telnetopt) {
3004 tcp_chr_telnet_init(chr);
3005 } else {
3006 tcp_chr_connect(chr);
3010 return 0;
3014 static int tcp_chr_add_client(Chardev *chr, int fd)
3016 int ret;
3017 QIOChannelSocket *sioc;
3019 sioc = qio_channel_socket_new_fd(fd, NULL);
3020 if (!sioc) {
3021 return -1;
3023 tcp_chr_set_client_ioc_name(chr, sioc);
3024 ret = tcp_chr_new_client(chr, sioc);
3025 object_unref(OBJECT(sioc));
3026 return ret;
3029 static gboolean tcp_chr_accept(QIOChannel *channel,
3030 GIOCondition cond,
3031 void *opaque)
3033 Chardev *chr = CHARDEV(opaque);
3034 QIOChannelSocket *sioc;
3036 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3037 NULL);
3038 if (!sioc) {
3039 return TRUE;
3042 tcp_chr_new_client(chr, sioc);
3044 object_unref(OBJECT(sioc));
3046 return TRUE;
3049 static int tcp_chr_wait_connected(Chardev *chr, Error **errp)
3051 SocketChardev *s = SOCKET_CHARDEV(chr);
3052 QIOChannelSocket *sioc;
3054 /* It can't wait on s->connected, since it is set asynchronously
3055 * in TLS and telnet cases, only wait for an accepted socket */
3056 while (!s->ioc) {
3057 if (s->is_listen) {
3058 error_report("QEMU waiting for connection on: %s",
3059 chr->filename);
3060 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3061 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3062 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3063 } else {
3064 sioc = qio_channel_socket_new();
3065 tcp_chr_set_client_ioc_name(chr, sioc);
3066 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3067 object_unref(OBJECT(sioc));
3068 return -1;
3070 tcp_chr_new_client(chr, sioc);
3071 object_unref(OBJECT(sioc));
3075 return 0;
3078 static int qemu_chr_wait_connected(Chardev *chr, Error **errp)
3080 ChardevClass *cc = CHARDEV_GET_CLASS(chr);
3082 if (cc->chr_wait_connected) {
3083 return cc->chr_wait_connected(chr, errp);
3086 return 0;
3089 int qemu_chr_fe_wait_connected(CharBackend *be, Error **errp)
3091 if (!be->chr) {
3092 error_setg(errp, "missing associated backend");
3093 return -1;
3096 return qemu_chr_wait_connected(be->chr, errp);
3099 static void char_socket_finalize(Object *obj)
3101 Chardev *chr = CHARDEV(obj);
3102 SocketChardev *s = SOCKET_CHARDEV(obj);
3104 tcp_chr_free_connection(chr);
3106 if (s->reconnect_timer) {
3107 g_source_remove(s->reconnect_timer);
3108 s->reconnect_timer = 0;
3110 qapi_free_SocketAddress(s->addr);
3111 if (s->listen_tag) {
3112 g_source_remove(s->listen_tag);
3113 s->listen_tag = 0;
3115 if (s->listen_ioc) {
3116 object_unref(OBJECT(s->listen_ioc));
3118 if (s->tls_creds) {
3119 object_unref(OBJECT(s->tls_creds));
3122 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3126 static void qemu_chr_socket_connected(QIOTask *task, void *opaque)
3128 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(qio_task_get_source(task));
3129 Chardev *chr = CHARDEV(opaque);
3130 SocketChardev *s = SOCKET_CHARDEV(chr);
3131 Error *err = NULL;
3133 if (qio_task_propagate_error(task, &err)) {
3134 check_report_connect_error(chr, err);
3135 error_free(err);
3136 goto cleanup;
3139 s->connect_err_reported = false;
3140 tcp_chr_new_client(chr, sioc);
3142 cleanup:
3143 object_unref(OBJECT(sioc));
3147 /*********************************************************/
3148 /* Ring buffer chardev */
3150 typedef struct {
3151 Chardev parent;
3152 size_t size;
3153 size_t prod;
3154 size_t cons;
3155 uint8_t *cbuf;
3156 } RingBufChardev;
3158 #define RINGBUF_CHARDEV(obj) \
3159 OBJECT_CHECK(RingBufChardev, (obj), TYPE_CHARDEV_RINGBUF)
3161 static size_t ringbuf_count(const Chardev *chr)
3163 const RingBufChardev *d = RINGBUF_CHARDEV(chr);
3165 return d->prod - d->cons;
3168 /* Called with chr_write_lock held. */
3169 static int ringbuf_chr_write(Chardev *chr, const uint8_t *buf, int len)
3171 RingBufChardev *d = RINGBUF_CHARDEV(chr);
3172 int i;
3174 if (!buf || (len < 0)) {
3175 return -1;
3178 for (i = 0; i < len; i++ ) {
3179 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3180 if (d->prod - d->cons > d->size) {
3181 d->cons = d->prod - d->size;
3185 return len;
3188 static int ringbuf_chr_read(Chardev *chr, uint8_t *buf, int len)
3190 RingBufChardev *d = RINGBUF_CHARDEV(chr);
3191 int i;
3193 qemu_mutex_lock(&chr->chr_write_lock);
3194 for (i = 0; i < len && d->cons != d->prod; i++) {
3195 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3197 qemu_mutex_unlock(&chr->chr_write_lock);
3199 return i;
3202 static void char_ringbuf_finalize(Object *obj)
3204 RingBufChardev *d = RINGBUF_CHARDEV(obj);
3206 g_free(d->cbuf);
3209 static void qemu_chr_open_ringbuf(Chardev *chr,
3210 ChardevBackend *backend,
3211 bool *be_opened,
3212 Error **errp)
3214 ChardevRingbuf *opts = backend->u.ringbuf.data;
3215 RingBufChardev *d = RINGBUF_CHARDEV(chr);
3217 d->size = opts->has_size ? opts->size : 65536;
3219 /* The size must be power of 2 */
3220 if (d->size & (d->size - 1)) {
3221 error_setg(errp, "size of ringbuf chardev must be power of two");
3222 return;
3225 d->prod = 0;
3226 d->cons = 0;
3227 d->cbuf = g_malloc0(d->size);
3230 void qmp_ringbuf_write(const char *device, const char *data,
3231 bool has_format, enum DataFormat format,
3232 Error **errp)
3234 Chardev *chr;
3235 const uint8_t *write_data;
3236 int ret;
3237 gsize write_count;
3239 chr = qemu_chr_find(device);
3240 if (!chr) {
3241 error_setg(errp, "Device '%s' not found", device);
3242 return;
3245 if (!CHARDEV_IS_RINGBUF(chr)) {
3246 error_setg(errp,"%s is not a ringbuf device", device);
3247 return;
3250 if (has_format && (format == DATA_FORMAT_BASE64)) {
3251 write_data = qbase64_decode(data, -1,
3252 &write_count,
3253 errp);
3254 if (!write_data) {
3255 return;
3257 } else {
3258 write_data = (uint8_t *)data;
3259 write_count = strlen(data);
3262 ret = ringbuf_chr_write(chr, write_data, write_count);
3264 if (write_data != (uint8_t *)data) {
3265 g_free((void *)write_data);
3268 if (ret < 0) {
3269 error_setg(errp, "Failed to write to device %s", device);
3270 return;
3274 char *qmp_ringbuf_read(const char *device, int64_t size,
3275 bool has_format, enum DataFormat format,
3276 Error **errp)
3278 Chardev *chr;
3279 uint8_t *read_data;
3280 size_t count;
3281 char *data;
3283 chr = qemu_chr_find(device);
3284 if (!chr) {
3285 error_setg(errp, "Device '%s' not found", device);
3286 return NULL;
3289 if (!CHARDEV_IS_RINGBUF(chr)) {
3290 error_setg(errp,"%s is not a ringbuf device", device);
3291 return NULL;
3294 if (size <= 0) {
3295 error_setg(errp, "size must be greater than zero");
3296 return NULL;
3299 count = ringbuf_count(chr);
3300 size = size > count ? count : size;
3301 read_data = g_malloc(size + 1);
3303 ringbuf_chr_read(chr, read_data, size);
3305 if (has_format && (format == DATA_FORMAT_BASE64)) {
3306 data = g_base64_encode(read_data, size);
3307 g_free(read_data);
3308 } else {
3310 * FIXME should read only complete, valid UTF-8 characters up
3311 * to @size bytes. Invalid sequences should be replaced by a
3312 * suitable replacement character. Except when (and only
3313 * when) ring buffer lost characters since last read, initial
3314 * continuation characters should be dropped.
3316 read_data[size] = 0;
3317 data = (char *)read_data;
3320 return data;
3323 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3325 char host[65], port[33], width[8], height[8];
3326 int pos;
3327 const char *p;
3328 QemuOpts *opts;
3329 Error *local_err = NULL;
3331 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3332 if (local_err) {
3333 error_report_err(local_err);
3334 return NULL;
3337 if (strstart(filename, "mon:", &p)) {
3338 filename = p;
3339 qemu_opt_set(opts, "mux", "on", &error_abort);
3340 if (strcmp(filename, "stdio") == 0) {
3341 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3342 * but pass it to the guest. Handle this only for compat syntax,
3343 * for -chardev syntax we have special option for this.
3344 * This is what -nographic did, redirecting+muxing serial+monitor
3345 * to stdio causing Ctrl+C to be passed to guest. */
3346 qemu_opt_set(opts, "signal", "off", &error_abort);
3350 if (strcmp(filename, "null") == 0 ||
3351 strcmp(filename, "pty") == 0 ||
3352 strcmp(filename, "msmouse") == 0 ||
3353 strcmp(filename, "braille") == 0 ||
3354 strcmp(filename, "testdev") == 0 ||
3355 strcmp(filename, "stdio") == 0) {
3356 qemu_opt_set(opts, "backend", filename, &error_abort);
3357 return opts;
3359 if (strstart(filename, "vc", &p)) {
3360 qemu_opt_set(opts, "backend", "vc", &error_abort);
3361 if (*p == ':') {
3362 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3363 /* pixels */
3364 qemu_opt_set(opts, "width", width, &error_abort);
3365 qemu_opt_set(opts, "height", height, &error_abort);
3366 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3367 /* chars */
3368 qemu_opt_set(opts, "cols", width, &error_abort);
3369 qemu_opt_set(opts, "rows", height, &error_abort);
3370 } else {
3371 goto fail;
3374 return opts;
3376 if (strcmp(filename, "con:") == 0) {
3377 qemu_opt_set(opts, "backend", "console", &error_abort);
3378 return opts;
3380 if (strstart(filename, "COM", NULL)) {
3381 qemu_opt_set(opts, "backend", "serial", &error_abort);
3382 qemu_opt_set(opts, "path", filename, &error_abort);
3383 return opts;
3385 if (strstart(filename, "file:", &p)) {
3386 qemu_opt_set(opts, "backend", "file", &error_abort);
3387 qemu_opt_set(opts, "path", p, &error_abort);
3388 return opts;
3390 if (strstart(filename, "pipe:", &p)) {
3391 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3392 qemu_opt_set(opts, "path", p, &error_abort);
3393 return opts;
3395 if (strstart(filename, "tcp:", &p) ||
3396 strstart(filename, "telnet:", &p)) {
3397 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3398 host[0] = 0;
3399 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3400 goto fail;
3402 qemu_opt_set(opts, "backend", "socket", &error_abort);
3403 qemu_opt_set(opts, "host", host, &error_abort);
3404 qemu_opt_set(opts, "port", port, &error_abort);
3405 if (p[pos] == ',') {
3406 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3407 if (local_err) {
3408 error_report_err(local_err);
3409 goto fail;
3412 if (strstart(filename, "telnet:", &p))
3413 qemu_opt_set(opts, "telnet", "on", &error_abort);
3414 return opts;
3416 if (strstart(filename, "udp:", &p)) {
3417 qemu_opt_set(opts, "backend", "udp", &error_abort);
3418 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3419 host[0] = 0;
3420 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3421 goto fail;
3424 qemu_opt_set(opts, "host", host, &error_abort);
3425 qemu_opt_set(opts, "port", port, &error_abort);
3426 if (p[pos] == '@') {
3427 p += pos + 1;
3428 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3429 host[0] = 0;
3430 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3431 goto fail;
3434 qemu_opt_set(opts, "localaddr", host, &error_abort);
3435 qemu_opt_set(opts, "localport", port, &error_abort);
3437 return opts;
3439 if (strstart(filename, "unix:", &p)) {
3440 qemu_opt_set(opts, "backend", "socket", &error_abort);
3441 qemu_opts_do_parse(opts, p, "path", &local_err);
3442 if (local_err) {
3443 error_report_err(local_err);
3444 goto fail;
3446 return opts;
3448 if (strstart(filename, "/dev/parport", NULL) ||
3449 strstart(filename, "/dev/ppi", NULL)) {
3450 qemu_opt_set(opts, "backend", "parport", &error_abort);
3451 qemu_opt_set(opts, "path", filename, &error_abort);
3452 return opts;
3454 if (strstart(filename, "/dev/", NULL)) {
3455 qemu_opt_set(opts, "backend", "tty", &error_abort);
3456 qemu_opt_set(opts, "path", filename, &error_abort);
3457 return opts;
3460 fail:
3461 qemu_opts_del(opts);
3462 return NULL;
3465 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3467 const char *logfile = qemu_opt_get(opts, "logfile");
3469 backend->has_logfile = logfile != NULL;
3470 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3472 backend->has_logappend = true;
3473 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3477 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3478 Error **errp)
3480 const char *path = qemu_opt_get(opts, "path");
3481 ChardevFile *file;
3483 backend->type = CHARDEV_BACKEND_KIND_FILE;
3484 if (path == NULL) {
3485 error_setg(errp, "chardev: file: no filename given");
3486 return;
3488 file = backend->u.file.data = g_new0(ChardevFile, 1);
3489 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3490 file->out = g_strdup(path);
3492 file->has_append = true;
3493 file->append = qemu_opt_get_bool(opts, "append", false);
3496 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3497 Error **errp)
3499 ChardevStdio *stdio;
3501 backend->type = CHARDEV_BACKEND_KIND_STDIO;
3502 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3503 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3504 stdio->has_signal = true;
3505 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3508 static void char_stdio_class_init(ObjectClass *oc, void *data)
3510 ChardevClass *cc = CHARDEV_CLASS(oc);
3512 cc->parse = qemu_chr_parse_stdio;
3513 cc->open = qemu_chr_open_stdio;
3514 #ifdef _WIN32
3515 cc->chr_write = win_stdio_write;
3516 cc->chr_set_echo = qemu_chr_set_echo_win_stdio;
3517 #else
3518 cc->chr_set_echo = qemu_chr_set_echo_stdio;
3519 #endif
3522 static const TypeInfo char_stdio_type_info = {
3523 .name = TYPE_CHARDEV_STDIO,
3524 #ifdef _WIN32
3525 .parent = TYPE_CHARDEV_WIN_STDIO,
3526 #else
3527 .parent = TYPE_CHARDEV_FD,
3528 .instance_finalize = char_stdio_finalize,
3529 #endif
3530 .class_init = char_stdio_class_init,
3533 #ifdef HAVE_CHARDEV_SERIAL
3534 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3535 Error **errp)
3537 const char *device = qemu_opt_get(opts, "path");
3538 ChardevHostdev *serial;
3540 backend->type = CHARDEV_BACKEND_KIND_SERIAL;
3541 if (device == NULL) {
3542 error_setg(errp, "chardev: serial/tty: no device path given");
3543 return;
3545 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3546 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3547 serial->device = g_strdup(device);
3549 #endif
3551 #ifdef HAVE_CHARDEV_PARPORT
3552 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3553 Error **errp)
3555 const char *device = qemu_opt_get(opts, "path");
3556 ChardevHostdev *parallel;
3558 backend->type = CHARDEV_BACKEND_KIND_PARALLEL;
3559 if (device == NULL) {
3560 error_setg(errp, "chardev: parallel: no device path given");
3561 return;
3563 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3564 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3565 parallel->device = g_strdup(device);
3567 #endif
3569 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3570 Error **errp)
3572 const char *device = qemu_opt_get(opts, "path");
3573 ChardevHostdev *dev;
3575 backend->type = CHARDEV_BACKEND_KIND_PIPE;
3576 if (device == NULL) {
3577 error_setg(errp, "chardev: pipe: no device path given");
3578 return;
3580 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3581 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3582 dev->device = g_strdup(device);
3585 static void char_pipe_class_init(ObjectClass *oc, void *data)
3587 ChardevClass *cc = CHARDEV_CLASS(oc);
3589 cc->parse = qemu_chr_parse_pipe;
3590 cc->open = qemu_chr_open_pipe;
3593 static const TypeInfo char_pipe_type_info = {
3594 .name = TYPE_CHARDEV_PIPE,
3595 #ifdef _WIN32
3596 .parent = TYPE_CHARDEV_WIN,
3597 #else
3598 .parent = TYPE_CHARDEV_FD,
3599 #endif
3600 .class_init = char_pipe_class_init,
3603 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3604 Error **errp)
3606 int val;
3607 ChardevRingbuf *ringbuf;
3609 backend->type = CHARDEV_BACKEND_KIND_RINGBUF;
3610 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3611 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3613 val = qemu_opt_get_size(opts, "size", 0);
3614 if (val != 0) {
3615 ringbuf->has_size = true;
3616 ringbuf->size = val;
3620 static void char_ringbuf_class_init(ObjectClass *oc, void *data)
3622 ChardevClass *cc = CHARDEV_CLASS(oc);
3624 cc->parse = qemu_chr_parse_ringbuf;
3625 cc->open = qemu_chr_open_ringbuf;
3626 cc->chr_write = ringbuf_chr_write;
3629 static const TypeInfo char_ringbuf_type_info = {
3630 .name = TYPE_CHARDEV_RINGBUF,
3631 .parent = TYPE_CHARDEV,
3632 .class_init = char_ringbuf_class_init,
3633 .instance_size = sizeof(RingBufChardev),
3634 .instance_finalize = char_ringbuf_finalize,
3637 /* Bug-compatibility: */
3638 static const TypeInfo char_memory_type_info = {
3639 .name = TYPE_CHARDEV_MEMORY,
3640 .parent = TYPE_CHARDEV_RINGBUF,
3643 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3644 Error **errp)
3646 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3647 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3648 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3649 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3650 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3651 const char *path = qemu_opt_get(opts, "path");
3652 const char *host = qemu_opt_get(opts, "host");
3653 const char *port = qemu_opt_get(opts, "port");
3654 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3655 SocketAddress *addr;
3656 ChardevSocket *sock;
3658 backend->type = CHARDEV_BACKEND_KIND_SOCKET;
3659 if (!path) {
3660 if (!host) {
3661 error_setg(errp, "chardev: socket: no host given");
3662 return;
3664 if (!port) {
3665 error_setg(errp, "chardev: socket: no port given");
3666 return;
3668 } else {
3669 if (tls_creds) {
3670 error_setg(errp, "TLS can only be used over TCP socket");
3671 return;
3675 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3676 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3678 sock->has_nodelay = true;
3679 sock->nodelay = do_nodelay;
3680 sock->has_server = true;
3681 sock->server = is_listen;
3682 sock->has_telnet = true;
3683 sock->telnet = is_telnet;
3684 sock->has_wait = true;
3685 sock->wait = is_waitconnect;
3686 sock->has_reconnect = true;
3687 sock->reconnect = reconnect;
3688 sock->tls_creds = g_strdup(tls_creds);
3690 addr = g_new0(SocketAddress, 1);
3691 if (path) {
3692 UnixSocketAddress *q_unix;
3693 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3694 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3695 q_unix->path = g_strdup(path);
3696 } else {
3697 addr->type = SOCKET_ADDRESS_KIND_INET;
3698 addr->u.inet.data = g_new(InetSocketAddress, 1);
3699 *addr->u.inet.data = (InetSocketAddress) {
3700 .host = g_strdup(host),
3701 .port = g_strdup(port),
3702 .has_to = qemu_opt_get(opts, "to"),
3703 .to = qemu_opt_get_number(opts, "to", 0),
3704 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3705 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3706 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3707 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3710 sock->addr = addr;
3713 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3714 Error **errp)
3716 const char *host = qemu_opt_get(opts, "host");
3717 const char *port = qemu_opt_get(opts, "port");
3718 const char *localaddr = qemu_opt_get(opts, "localaddr");
3719 const char *localport = qemu_opt_get(opts, "localport");
3720 bool has_local = false;
3721 SocketAddress *addr;
3722 ChardevUdp *udp;
3724 backend->type = CHARDEV_BACKEND_KIND_UDP;
3725 if (host == NULL || strlen(host) == 0) {
3726 host = "localhost";
3728 if (port == NULL || strlen(port) == 0) {
3729 error_setg(errp, "chardev: udp: remote port not specified");
3730 return;
3732 if (localport == NULL || strlen(localport) == 0) {
3733 localport = "0";
3734 } else {
3735 has_local = true;
3737 if (localaddr == NULL || strlen(localaddr) == 0) {
3738 localaddr = "";
3739 } else {
3740 has_local = true;
3743 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3744 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3746 addr = g_new0(SocketAddress, 1);
3747 addr->type = SOCKET_ADDRESS_KIND_INET;
3748 addr->u.inet.data = g_new(InetSocketAddress, 1);
3749 *addr->u.inet.data = (InetSocketAddress) {
3750 .host = g_strdup(host),
3751 .port = g_strdup(port),
3752 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3753 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3754 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3755 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3757 udp->remote = addr;
3759 if (has_local) {
3760 udp->has_local = true;
3761 addr = g_new0(SocketAddress, 1);
3762 addr->type = SOCKET_ADDRESS_KIND_INET;
3763 addr->u.inet.data = g_new(InetSocketAddress, 1);
3764 *addr->u.inet.data = (InetSocketAddress) {
3765 .host = g_strdup(localaddr),
3766 .port = g_strdup(localport),
3768 udp->local = addr;
3772 static const ChardevClass *char_get_class(const char *driver, Error **errp)
3774 ObjectClass *oc;
3775 const ChardevClass *cc;
3776 char *typename = g_strdup_printf("chardev-%s", driver);
3778 oc = object_class_by_name(typename);
3779 g_free(typename);
3781 if (!object_class_dynamic_cast(oc, TYPE_CHARDEV)) {
3782 error_setg(errp, "'%s' is not a valid char driver name", driver);
3783 return NULL;
3786 if (object_class_is_abstract(oc)) {
3787 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
3788 "abstract device type");
3789 return NULL;
3792 cc = CHARDEV_CLASS(oc);
3793 if (cc->internal) {
3794 error_setg(errp, "'%s' is not a valid char driver name", driver);
3795 return NULL;
3798 return cc;
3801 static Chardev *qemu_chardev_add(const char *id, const char *typename,
3802 ChardevBackend *backend, Error **errp)
3804 Chardev *chr;
3806 chr = qemu_chr_find(id);
3807 if (chr) {
3808 error_setg(errp, "Chardev '%s' already exists", id);
3809 return NULL;
3812 chr = qemu_chardev_new(id, typename, backend, errp);
3813 if (!chr) {
3814 return NULL;
3817 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3818 return chr;
3821 static const struct ChardevAlias {
3822 const char *typename;
3823 const char *alias;
3824 } chardev_alias_table[] = {
3825 #ifdef HAVE_CHARDEV_PARPORT
3826 { "parallel", "parport" },
3827 #endif
3828 #ifdef HAVE_CHARDEV_SERIAL
3829 { "serial", "tty" },
3830 #endif
3833 typedef struct ChadevClassFE {
3834 void (*fn)(const char *name, void *opaque);
3835 void *opaque;
3836 } ChadevClassFE;
3838 static void
3839 chardev_class_foreach(ObjectClass *klass, void *opaque)
3841 ChadevClassFE *fe = opaque;
3843 assert(g_str_has_prefix(object_class_get_name(klass), "chardev-"));
3844 if (CHARDEV_CLASS(klass)->internal) {
3845 return;
3848 fe->fn(object_class_get_name(klass) + 8, fe->opaque);
3851 static void
3852 chardev_name_foreach(void (*fn)(const char *name, void *opaque), void *opaque)
3854 ChadevClassFE fe = { .fn = fn, .opaque = opaque };
3855 int i;
3857 object_class_foreach(chardev_class_foreach, TYPE_CHARDEV, false, &fe);
3859 for (i = 0; i < ARRAY_SIZE(chardev_alias_table); i++) {
3860 fn(chardev_alias_table[i].alias, opaque);
3864 static void
3865 help_string_append(const char *name, void *opaque)
3867 GString *str = opaque;
3869 g_string_append_printf(str, "\n%s", name);
3872 Chardev *qemu_chr_new_from_opts(QemuOpts *opts,
3873 Error **errp)
3875 Error *local_err = NULL;
3876 const ChardevClass *cc;
3877 Chardev *chr;
3878 int i;
3879 ChardevBackend *backend = NULL;
3880 const char *name = qemu_opt_get(opts, "backend");
3881 const char *id = qemu_opts_id(opts);
3882 char *bid = NULL;
3884 if (name == NULL) {
3885 error_setg(errp, "chardev: \"%s\" missing backend",
3886 qemu_opts_id(opts));
3887 return NULL;
3890 if (is_help_option(name)) {
3891 GString *str = g_string_new("");
3893 chardev_name_foreach(help_string_append, str);
3895 error_report("Available chardev backend types: %s", str->str);
3896 g_string_free(str, true);
3897 exit(0);
3900 if (id == NULL) {
3901 error_setg(errp, "chardev: no id specified");
3902 return NULL;
3905 for (i = 0; i < ARRAY_SIZE(chardev_alias_table); i++) {
3906 if (g_strcmp0(chardev_alias_table[i].alias, name) == 0) {
3907 name = chardev_alias_table[i].typename;
3908 break;
3912 cc = char_get_class(name, errp);
3913 if (cc == NULL) {
3914 return NULL;
3917 backend = g_new0(ChardevBackend, 1);
3918 backend->type = CHARDEV_BACKEND_KIND_NULL;
3920 if (qemu_opt_get_bool(opts, "mux", 0)) {
3921 bid = g_strdup_printf("%s-base", id);
3924 chr = NULL;
3925 if (cc->parse) {
3926 cc->parse(opts, backend, &local_err);
3927 if (local_err) {
3928 error_propagate(errp, local_err);
3929 goto out;
3931 } else {
3932 ChardevCommon *ccom = g_new0(ChardevCommon, 1);
3933 qemu_chr_parse_common(opts, ccom);
3934 backend->u.null.data = ccom; /* Any ChardevCommon member would work */
3937 chr = qemu_chardev_add(bid ? bid : id,
3938 object_class_get_name(OBJECT_CLASS(cc)),
3939 backend, errp);
3940 if (chr == NULL) {
3941 goto out;
3944 if (bid) {
3945 Chardev *mux;
3946 qapi_free_ChardevBackend(backend);
3947 backend = g_new0(ChardevBackend, 1);
3948 backend->type = CHARDEV_BACKEND_KIND_MUX;
3949 backend->u.mux.data = g_new0(ChardevMux, 1);
3950 backend->u.mux.data->chardev = g_strdup(bid);
3951 mux = qemu_chardev_add(id, TYPE_CHARDEV_MUX, backend, errp);
3952 if (mux == NULL) {
3953 qemu_chr_delete(chr);
3954 chr = NULL;
3955 goto out;
3957 chr = mux;
3960 out:
3961 qapi_free_ChardevBackend(backend);
3962 g_free(bid);
3963 return chr;
3966 Chardev *qemu_chr_new_noreplay(const char *label, const char *filename)
3968 const char *p;
3969 Chardev *chr;
3970 QemuOpts *opts;
3971 Error *err = NULL;
3973 if (strstart(filename, "chardev:", &p)) {
3974 return qemu_chr_find(p);
3977 opts = qemu_chr_parse_compat(label, filename);
3978 if (!opts)
3979 return NULL;
3981 chr = qemu_chr_new_from_opts(opts, &err);
3982 if (err) {
3983 error_report_err(err);
3985 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3986 monitor_init(chr, MONITOR_USE_READLINE);
3988 qemu_opts_del(opts);
3989 return chr;
3992 Chardev *qemu_chr_new(const char *label, const char *filename)
3994 Chardev *chr;
3995 chr = qemu_chr_new_noreplay(label, filename);
3996 if (chr) {
3997 if (replay_mode != REPLAY_MODE_NONE) {
3998 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_REPLAY);
4000 if (qemu_chr_replay(chr) && CHARDEV_GET_CLASS(chr)->chr_ioctl) {
4001 error_report("Replay: ioctl is not supported "
4002 "for serial devices yet");
4004 replay_register_char_driver(chr);
4006 return chr;
4009 void qemu_chr_fe_set_echo(CharBackend *be, bool echo)
4011 Chardev *chr = be->chr;
4013 if (chr && CHARDEV_GET_CLASS(chr)->chr_set_echo) {
4014 CHARDEV_GET_CLASS(chr)->chr_set_echo(chr, echo);
4018 void qemu_chr_fe_set_open(CharBackend *be, int fe_open)
4020 Chardev *chr = be->chr;
4022 if (!chr) {
4023 return;
4026 if (be->fe_open == fe_open) {
4027 return;
4029 be->fe_open = fe_open;
4030 if (CHARDEV_GET_CLASS(chr)->chr_set_fe_open) {
4031 CHARDEV_GET_CLASS(chr)->chr_set_fe_open(chr, fe_open);
4035 guint qemu_chr_fe_add_watch(CharBackend *be, GIOCondition cond,
4036 GIOFunc func, void *user_data)
4038 Chardev *s = be->chr;
4039 GSource *src;
4040 guint tag;
4042 if (!s || CHARDEV_GET_CLASS(s)->chr_add_watch == NULL) {
4043 return 0;
4046 src = CHARDEV_GET_CLASS(s)->chr_add_watch(s, cond);
4047 if (!src) {
4048 return 0;
4051 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4052 tag = g_source_attach(src, NULL);
4053 g_source_unref(src);
4055 return tag;
4058 void qemu_chr_fe_disconnect(CharBackend *be)
4060 Chardev *chr = be->chr;
4062 if (chr && CHARDEV_GET_CLASS(chr)->chr_disconnect) {
4063 CHARDEV_GET_CLASS(chr)->chr_disconnect(chr);
4067 void qemu_chr_delete(Chardev *chr)
4069 QTAILQ_REMOVE(&chardevs, chr, next);
4070 object_unref(OBJECT(chr));
4073 ChardevInfoList *qmp_query_chardev(Error **errp)
4075 ChardevInfoList *chr_list = NULL;
4076 Chardev *chr;
4078 QTAILQ_FOREACH(chr, &chardevs, next) {
4079 ChardevInfoList *info = g_malloc0(sizeof(*info));
4080 info->value = g_malloc0(sizeof(*info->value));
4081 info->value->label = g_strdup(chr->label);
4082 info->value->filename = g_strdup(chr->filename);
4083 info->value->frontend_open = chr->be && chr->be->fe_open;
4085 info->next = chr_list;
4086 chr_list = info;
4089 return chr_list;
4092 static void
4093 qmp_prepend_backend(const char *name, void *opaque)
4095 ChardevBackendInfoList **list = opaque;
4096 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4098 info->value = g_malloc0(sizeof(*info->value));
4099 info->value->name = g_strdup(name);
4100 info->next = *list;
4101 *list = info;
4104 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4106 ChardevBackendInfoList *backend_list = NULL;
4108 chardev_name_foreach(qmp_prepend_backend, &backend_list);
4110 return backend_list;
4113 Chardev *qemu_chr_find(const char *name)
4115 Chardev *chr;
4117 QTAILQ_FOREACH(chr, &chardevs, next) {
4118 if (strcmp(chr->label, name) != 0)
4119 continue;
4120 return chr;
4122 return NULL;
4125 QemuOptsList qemu_chardev_opts = {
4126 .name = "chardev",
4127 .implied_opt_name = "backend",
4128 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4129 .desc = {
4131 .name = "backend",
4132 .type = QEMU_OPT_STRING,
4134 .name = "path",
4135 .type = QEMU_OPT_STRING,
4137 .name = "host",
4138 .type = QEMU_OPT_STRING,
4140 .name = "port",
4141 .type = QEMU_OPT_STRING,
4143 .name = "localaddr",
4144 .type = QEMU_OPT_STRING,
4146 .name = "localport",
4147 .type = QEMU_OPT_STRING,
4149 .name = "to",
4150 .type = QEMU_OPT_NUMBER,
4152 .name = "ipv4",
4153 .type = QEMU_OPT_BOOL,
4155 .name = "ipv6",
4156 .type = QEMU_OPT_BOOL,
4158 .name = "wait",
4159 .type = QEMU_OPT_BOOL,
4161 .name = "server",
4162 .type = QEMU_OPT_BOOL,
4164 .name = "delay",
4165 .type = QEMU_OPT_BOOL,
4167 .name = "reconnect",
4168 .type = QEMU_OPT_NUMBER,
4170 .name = "telnet",
4171 .type = QEMU_OPT_BOOL,
4173 .name = "tls-creds",
4174 .type = QEMU_OPT_STRING,
4176 .name = "width",
4177 .type = QEMU_OPT_NUMBER,
4179 .name = "height",
4180 .type = QEMU_OPT_NUMBER,
4182 .name = "cols",
4183 .type = QEMU_OPT_NUMBER,
4185 .name = "rows",
4186 .type = QEMU_OPT_NUMBER,
4188 .name = "mux",
4189 .type = QEMU_OPT_BOOL,
4191 .name = "signal",
4192 .type = QEMU_OPT_BOOL,
4194 .name = "name",
4195 .type = QEMU_OPT_STRING,
4197 .name = "debug",
4198 .type = QEMU_OPT_NUMBER,
4200 .name = "size",
4201 .type = QEMU_OPT_SIZE,
4203 .name = "chardev",
4204 .type = QEMU_OPT_STRING,
4206 .name = "append",
4207 .type = QEMU_OPT_BOOL,
4209 .name = "logfile",
4210 .type = QEMU_OPT_STRING,
4212 .name = "logappend",
4213 .type = QEMU_OPT_BOOL,
4215 { /* end of list */ }
4219 #ifdef _WIN32
4221 static void qmp_chardev_open_file(Chardev *chr,
4222 ChardevBackend *backend,
4223 bool *be_opened,
4224 Error **errp)
4226 ChardevFile *file = backend->u.file.data;
4227 HANDLE out;
4228 DWORD accessmode;
4229 DWORD flags;
4231 if (file->has_in) {
4232 error_setg(errp, "input file not supported");
4233 return;
4236 if (file->has_append && file->append) {
4237 /* Append to file if it already exists. */
4238 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4239 flags = OPEN_ALWAYS;
4240 } else {
4241 /* Truncate file if it already exists. */
4242 accessmode = GENERIC_WRITE;
4243 flags = CREATE_ALWAYS;
4246 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4247 FILE_ATTRIBUTE_NORMAL, NULL);
4248 if (out == INVALID_HANDLE_VALUE) {
4249 error_setg(errp, "open %s failed", file->out);
4250 return;
4253 qemu_chr_open_win_file(chr, out);
4256 static void qmp_chardev_open_serial(Chardev *chr,
4257 ChardevBackend *backend,
4258 bool *be_opened,
4259 Error **errp)
4261 ChardevHostdev *serial = backend->u.serial.data;
4263 win_chr_init(chr, serial->device, errp);
4266 #else /* WIN32 */
4268 static int qmp_chardev_open_file_source(char *src, int flags,
4269 Error **errp)
4271 int fd = -1;
4273 TFR(fd = qemu_open(src, flags, 0666));
4274 if (fd == -1) {
4275 error_setg_file_open(errp, errno, src);
4277 return fd;
4280 static void qmp_chardev_open_file(Chardev *chr,
4281 ChardevBackend *backend,
4282 bool *be_opened,
4283 Error **errp)
4285 ChardevFile *file = backend->u.file.data;
4286 int flags, in = -1, out;
4288 flags = O_WRONLY | O_CREAT | O_BINARY;
4289 if (file->has_append && file->append) {
4290 flags |= O_APPEND;
4291 } else {
4292 flags |= O_TRUNC;
4295 out = qmp_chardev_open_file_source(file->out, flags, errp);
4296 if (out < 0) {
4297 return;
4300 if (file->has_in) {
4301 flags = O_RDONLY;
4302 in = qmp_chardev_open_file_source(file->in, flags, errp);
4303 if (in < 0) {
4304 qemu_close(out);
4305 return;
4309 qemu_chr_open_fd(chr, in, out);
4312 #ifdef HAVE_CHARDEV_SERIAL
4313 static void qmp_chardev_open_serial(Chardev *chr,
4314 ChardevBackend *backend,
4315 bool *be_opened,
4316 Error **errp)
4318 ChardevHostdev *serial = backend->u.serial.data;
4319 int fd;
4321 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4322 if (fd < 0) {
4323 return;
4325 qemu_set_nonblock(fd);
4326 tty_serial_init(fd, 115200, 'N', 8, 1);
4328 qemu_chr_open_fd(chr, fd, fd);
4330 #endif
4332 #ifdef HAVE_CHARDEV_PARPORT
4333 static void qmp_chardev_open_parallel(Chardev *chr,
4334 ChardevBackend *backend,
4335 bool *be_opened,
4336 Error **errp)
4338 ChardevHostdev *parallel = backend->u.parallel.data;
4339 int fd;
4341 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4342 if (fd < 0) {
4343 return;
4345 qemu_chr_open_pp_fd(chr, fd, be_opened, errp);
4348 static void char_parallel_class_init(ObjectClass *oc, void *data)
4350 ChardevClass *cc = CHARDEV_CLASS(oc);
4352 cc->parse = qemu_chr_parse_parallel;
4353 cc->open = qmp_chardev_open_parallel;
4354 #if defined(__linux__)
4355 cc->chr_ioctl = pp_ioctl;
4356 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
4357 cc->chr_ioctl = pp_ioctl;
4358 #endif
4361 static void char_parallel_finalize(Object *obj)
4363 #if defined(__linux__)
4364 Chardev *chr = CHARDEV(obj);
4365 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
4366 int fd = drv->fd;
4368 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
4369 ioctl(fd, PPRELEASE);
4370 close(fd);
4371 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
4372 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
4373 /* FIXME: close fd? */
4374 #endif
4377 static const TypeInfo char_parallel_type_info = {
4378 .name = TYPE_CHARDEV_PARALLEL,
4379 .parent = TYPE_CHARDEV,
4380 .instance_size = sizeof(ParallelChardev),
4381 .instance_finalize = char_parallel_finalize,
4382 .class_init = char_parallel_class_init,
4384 #endif
4386 #endif /* WIN32 */
4388 static void char_file_class_init(ObjectClass *oc, void *data)
4390 ChardevClass *cc = CHARDEV_CLASS(oc);
4392 cc->parse = qemu_chr_parse_file_out;
4393 cc->open = qmp_chardev_open_file;
4396 static const TypeInfo char_file_type_info = {
4397 .name = TYPE_CHARDEV_FILE,
4398 #ifdef _WIN32
4399 .parent = TYPE_CHARDEV_WIN,
4400 #else
4401 .parent = TYPE_CHARDEV_FD,
4402 #endif
4403 .class_init = char_file_class_init,
4406 #ifdef HAVE_CHARDEV_SERIAL
4408 static void char_serial_class_init(ObjectClass *oc, void *data)
4410 ChardevClass *cc = CHARDEV_CLASS(oc);
4412 cc->parse = qemu_chr_parse_serial;
4413 cc->open = qmp_chardev_open_serial;
4414 #ifndef _WIN32
4415 cc->chr_ioctl = tty_serial_ioctl;
4416 #endif
4419 static const TypeInfo char_serial_type_info = {
4420 .name = TYPE_CHARDEV_SERIAL,
4421 #ifdef _WIN32
4422 .parent = TYPE_CHARDEV_WIN,
4423 #else
4424 .parent = TYPE_CHARDEV_FD,
4425 #endif
4426 .class_init = char_serial_class_init,
4428 #endif
4430 static gboolean socket_reconnect_timeout(gpointer opaque)
4432 Chardev *chr = CHARDEV(opaque);
4433 SocketChardev *s = SOCKET_CHARDEV(opaque);
4434 QIOChannelSocket *sioc;
4436 s->reconnect_timer = 0;
4438 if (chr->be_open) {
4439 return false;
4442 sioc = qio_channel_socket_new();
4443 tcp_chr_set_client_ioc_name(chr, sioc);
4444 qio_channel_socket_connect_async(sioc, s->addr,
4445 qemu_chr_socket_connected,
4446 chr, NULL);
4448 return false;
4451 static void qmp_chardev_open_socket(Chardev *chr,
4452 ChardevBackend *backend,
4453 bool *be_opened,
4454 Error **errp)
4456 SocketChardev *s = SOCKET_CHARDEV(chr);
4457 ChardevSocket *sock = backend->u.socket.data;
4458 SocketAddress *addr = sock->addr;
4459 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4460 bool is_listen = sock->has_server ? sock->server : true;
4461 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4462 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4463 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4464 QIOChannelSocket *sioc = NULL;
4466 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4467 s->is_listen = is_listen;
4468 s->is_telnet = is_telnet;
4469 s->do_nodelay = do_nodelay;
4470 if (sock->tls_creds) {
4471 Object *creds;
4472 creds = object_resolve_path_component(
4473 object_get_objects_root(), sock->tls_creds);
4474 if (!creds) {
4475 error_setg(errp, "No TLS credentials with id '%s'",
4476 sock->tls_creds);
4477 goto error;
4479 s->tls_creds = (QCryptoTLSCreds *)
4480 object_dynamic_cast(creds,
4481 TYPE_QCRYPTO_TLS_CREDS);
4482 if (!s->tls_creds) {
4483 error_setg(errp, "Object with id '%s' is not TLS credentials",
4484 sock->tls_creds);
4485 goto error;
4487 object_ref(OBJECT(s->tls_creds));
4488 if (is_listen) {
4489 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4490 error_setg(errp, "%s",
4491 "Expected TLS credentials for server endpoint");
4492 goto error;
4494 } else {
4495 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4496 error_setg(errp, "%s",
4497 "Expected TLS credentials for client endpoint");
4498 goto error;
4503 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4505 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);
4506 if (s->is_unix) {
4507 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);
4510 /* be isn't opened until we get a connection */
4511 *be_opened = false;
4513 chr->filename = SocketAddress_to_str("disconnected:",
4514 addr, is_listen, is_telnet);
4516 if (is_listen) {
4517 if (is_telnet) {
4518 s->do_telnetopt = 1;
4520 } else if (reconnect > 0) {
4521 s->reconnect_time = reconnect;
4524 if (s->reconnect_time) {
4525 sioc = qio_channel_socket_new();
4526 tcp_chr_set_client_ioc_name(chr, sioc);
4527 qio_channel_socket_connect_async(sioc, s->addr,
4528 qemu_chr_socket_connected,
4529 chr, NULL);
4530 } else {
4531 if (s->is_listen) {
4532 char *name;
4533 sioc = qio_channel_socket_new();
4535 name = g_strdup_printf("chardev-tcp-listener-%s", chr->label);
4536 qio_channel_set_name(QIO_CHANNEL(sioc), name);
4537 g_free(name);
4539 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4540 goto error;
4542 s->listen_ioc = sioc;
4543 if (is_waitconnect &&
4544 qemu_chr_wait_connected(chr, errp) < 0) {
4545 return;
4547 if (!s->ioc) {
4548 s->listen_tag = qio_channel_add_watch(
4549 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4550 tcp_chr_accept, chr, NULL);
4552 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4553 goto error;
4557 return;
4559 error:
4560 if (sioc) {
4561 object_unref(OBJECT(sioc));
4565 static void char_socket_class_init(ObjectClass *oc, void *data)
4567 ChardevClass *cc = CHARDEV_CLASS(oc);
4569 cc->parse = qemu_chr_parse_socket;
4570 cc->open = qmp_chardev_open_socket;
4571 cc->chr_wait_connected = tcp_chr_wait_connected;
4572 cc->chr_write = tcp_chr_write;
4573 cc->chr_sync_read = tcp_chr_sync_read;
4574 cc->chr_disconnect = tcp_chr_disconnect;
4575 cc->get_msgfds = tcp_get_msgfds;
4576 cc->set_msgfds = tcp_set_msgfds;
4577 cc->chr_add_client = tcp_chr_add_client;
4578 cc->chr_add_watch = tcp_chr_add_watch;
4579 cc->chr_update_read_handler = tcp_chr_update_read_handler;
4582 static const TypeInfo char_socket_type_info = {
4583 .name = TYPE_CHARDEV_SOCKET,
4584 .parent = TYPE_CHARDEV,
4585 .instance_size = sizeof(SocketChardev),
4586 .instance_finalize = char_socket_finalize,
4587 .class_init = char_socket_class_init,
4590 static void qmp_chardev_open_udp(Chardev *chr,
4591 ChardevBackend *backend,
4592 bool *be_opened,
4593 Error **errp)
4595 ChardevUdp *udp = backend->u.udp.data;
4596 QIOChannelSocket *sioc = qio_channel_socket_new();
4597 char *name;
4598 UdpChardev *s = UDP_CHARDEV(chr);
4600 if (qio_channel_socket_dgram_sync(sioc,
4601 udp->local, udp->remote,
4602 errp) < 0) {
4603 object_unref(OBJECT(sioc));
4604 return;
4607 name = g_strdup_printf("chardev-udp-%s", chr->label);
4608 qio_channel_set_name(QIO_CHANNEL(sioc), name);
4609 g_free(name);
4611 s->ioc = QIO_CHANNEL(sioc);
4612 /* be isn't opened until we get a connection */
4613 *be_opened = false;
4616 static void char_udp_class_init(ObjectClass *oc, void *data)
4618 ChardevClass *cc = CHARDEV_CLASS(oc);
4620 cc->parse = qemu_chr_parse_udp;
4621 cc->open = qmp_chardev_open_udp;
4622 cc->chr_write = udp_chr_write;
4623 cc->chr_update_read_handler = udp_chr_update_read_handler;
4626 static const TypeInfo char_udp_type_info = {
4627 .name = TYPE_CHARDEV_UDP,
4628 .parent = TYPE_CHARDEV,
4629 .instance_size = sizeof(UdpChardev),
4630 .instance_finalize = char_udp_finalize,
4631 .class_init = char_udp_class_init,
4634 bool qemu_chr_has_feature(Chardev *chr,
4635 ChardevFeature feature)
4637 return test_bit(feature, chr->features);
4640 void qemu_chr_set_feature(Chardev *chr,
4641 ChardevFeature feature)
4643 return set_bit(feature, chr->features);
4646 Chardev *qemu_chardev_new(const char *id, const char *typename,
4647 ChardevBackend *backend, Error **errp)
4649 Chardev *chr = NULL;
4650 Error *local_err = NULL;
4651 bool be_opened = true;
4653 assert(g_str_has_prefix(typename, "chardev-"));
4655 chr = CHARDEV(object_new(typename));
4656 chr->label = g_strdup(id);
4658 qemu_char_open(chr, backend, &be_opened, &local_err);
4659 if (local_err) {
4660 error_propagate(errp, local_err);
4661 object_unref(OBJECT(chr));
4662 return NULL;
4665 if (!chr->filename) {
4666 chr->filename = g_strdup(typename + 8);
4668 if (be_opened) {
4669 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4672 return chr;
4675 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4676 Error **errp)
4678 const ChardevClass *cc;
4679 ChardevReturn *ret;
4680 Chardev *chr;
4682 cc = char_get_class(ChardevBackendKind_lookup[backend->type], errp);
4683 if (!cc) {
4684 return NULL;
4687 chr = qemu_chardev_add(id, object_class_get_name(OBJECT_CLASS(cc)),
4688 backend, errp);
4689 if (!chr) {
4690 return NULL;
4693 ret = g_new0(ChardevReturn, 1);
4694 if (CHARDEV_IS_PTY(chr)) {
4695 ret->pty = g_strdup(chr->filename + 4);
4696 ret->has_pty = true;
4699 return ret;
4702 void qmp_chardev_remove(const char *id, Error **errp)
4704 Chardev *chr;
4706 chr = qemu_chr_find(id);
4707 if (chr == NULL) {
4708 error_setg(errp, "Chardev '%s' not found", id);
4709 return;
4711 if (qemu_chr_is_busy(chr)) {
4712 error_setg(errp, "Chardev '%s' is busy", id);
4713 return;
4715 if (qemu_chr_replay(chr)) {
4716 error_setg(errp,
4717 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4718 return;
4720 qemu_chr_delete(chr);
4723 void qemu_chr_cleanup(void)
4725 Chardev *chr, *tmp;
4727 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4728 qemu_chr_delete(chr);
4732 static void register_types(void)
4734 type_register_static(&char_type_info);
4735 #ifndef _WIN32
4736 type_register_static(&char_fd_type_info);
4737 #else
4738 type_register_static(&char_win_type_info);
4739 type_register_static(&char_win_stdio_type_info);
4740 #endif
4741 type_register_static(&char_socket_type_info);
4742 type_register_static(&char_udp_type_info);
4743 type_register_static(&char_ringbuf_type_info);
4744 type_register_static(&char_file_type_info);
4745 type_register_static(&char_stdio_type_info);
4746 #ifdef HAVE_CHARDEV_SERIAL
4747 type_register_static(&char_serial_type_info);
4748 #endif
4749 #ifdef HAVE_CHARDEV_PARPORT
4750 type_register_static(&char_parallel_type_info);
4751 #endif
4752 #ifdef HAVE_CHARDEV_PTY
4753 type_register_static(&char_pty_type_info);
4754 #endif
4755 #ifdef _WIN32
4756 type_register_static(&char_console_type_info);
4757 #endif
4758 type_register_static(&char_pipe_type_info);
4759 type_register_static(&char_memory_type_info);
4761 /* this must be done after machine init, since we register FEs with muxes
4762 * as part of realize functions like serial_isa_realizefn when -nographic
4763 * is specified
4765 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4768 type_init(register_types);