xref: /openbmc/qemu/chardev/char.c (revision 33343bff)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/cutils.h"
27 #include "monitor/monitor.h"
28 #include "monitor/qmp-helpers.h"
29 #include "qemu/config-file.h"
30 #include "qemu/error-report.h"
31 #include "qemu/qemu-print.h"
32 #include "chardev/char.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-commands-char.h"
35 #include "qapi/qmp/qerror.h"
36 #include "sysemu/replay.h"
37 #include "qemu/help_option.h"
38 #include "qemu/module.h"
39 #include "qemu/option.h"
40 #include "qemu/id.h"
41 #include "qemu/coroutine.h"
42 #include "qemu/yank.h"
43 
44 #include "chardev-internal.h"
45 
46 /***********************************************************/
47 /* character device */
48 
49 Object *get_chardevs_root(void)
50 {
51     return container_get(object_get_root(), "/chardevs");
52 }
53 
54 static void chr_be_event(Chardev *s, QEMUChrEvent event)
55 {
56     CharBackend *be = s->be;
57 
58     if (!be || !be->chr_event) {
59         return;
60     }
61 
62     be->chr_event(be->opaque, event);
63 }
64 
65 void qemu_chr_be_event(Chardev *s, QEMUChrEvent event)
66 {
67     /* Keep track if the char device is open */
68     switch (event) {
69         case CHR_EVENT_OPENED:
70             s->be_open = 1;
71             break;
72         case CHR_EVENT_CLOSED:
73             s->be_open = 0;
74             break;
75     case CHR_EVENT_BREAK:
76     case CHR_EVENT_MUX_IN:
77     case CHR_EVENT_MUX_OUT:
78         /* Ignore */
79         break;
80     }
81 
82     CHARDEV_GET_CLASS(s)->chr_be_event(s, event);
83 }
84 
85 /* Not reporting errors from writing to logfile, as logs are
86  * defined to be "best effort" only */
87 static void qemu_chr_write_log(Chardev *s, const uint8_t *buf, size_t len)
88 {
89     size_t done = 0;
90     ssize_t ret;
91 
92     if (s->logfd < 0) {
93         return;
94     }
95 
96     while (done < len) {
97     retry:
98         ret = write(s->logfd, buf + done, len - done);
99         if (ret == -1 && errno == EAGAIN) {
100             g_usleep(100);
101             goto retry;
102         }
103 
104         if (ret <= 0) {
105             return;
106         }
107         done += ret;
108     }
109 }
110 
111 static int qemu_chr_write_buffer(Chardev *s,
112                                  const uint8_t *buf, int len,
113                                  int *offset, bool write_all)
114 {
115     ChardevClass *cc = CHARDEV_GET_CLASS(s);
116     int res = 0;
117     *offset = 0;
118 
119     qemu_mutex_lock(&s->chr_write_lock);
120     while (*offset < len) {
121     retry:
122         res = cc->chr_write(s, buf + *offset, len - *offset);
123         if (res < 0 && errno == EAGAIN && write_all) {
124             if (qemu_in_coroutine()) {
125                 qemu_co_sleep_ns(QEMU_CLOCK_REALTIME, 100000);
126             } else {
127                 g_usleep(100);
128             }
129             goto retry;
130         }
131 
132         if (res <= 0) {
133             break;
134         }
135 
136         *offset += res;
137         if (!write_all) {
138             break;
139         }
140     }
141     if (*offset > 0) {
142         /*
143          * If some data was written by backend, we should
144          * only log what was actually written. This method
145          * may be invoked again to write the remaining
146          * method, thus we'll log the remainder at that time.
147          */
148         qemu_chr_write_log(s, buf, *offset);
149     } else if (res < 0) {
150         /*
151          * If a fatal error was reported by the backend,
152          * assume this method won't be invoked again with
153          * this buffer, so log it all right away.
154          */
155         qemu_chr_write_log(s, buf, len);
156     }
157     qemu_mutex_unlock(&s->chr_write_lock);
158 
159     return res;
160 }
161 
162 int qemu_chr_write(Chardev *s, const uint8_t *buf, int len, bool write_all)
163 {
164     int offset = 0;
165     int res;
166 
167     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
168         replay_char_write_event_load(&res, &offset);
169         assert(offset <= len);
170         qemu_chr_write_buffer(s, buf, offset, &offset, true);
171         return res;
172     }
173 
174     if (replay_mode == REPLAY_MODE_RECORD) {
175         /*
176          * When recording we don't want temporary conditions to
177          * perturb the result. By ensuring we write everything we can
178          * while recording we avoid playback being out of sync if it
179          * doesn't encounter the same temporary conditions (usually
180          * triggered by external programs not reading the chardev fast
181          * enough and pipes filling up).
182          */
183         write_all = true;
184     }
185 
186     res = qemu_chr_write_buffer(s, buf, len, &offset, write_all);
187 
188     if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
189         replay_char_write_event_save(res, offset);
190     }
191 
192     if (res < 0) {
193         return res;
194     }
195     return offset;
196 }
197 
198 int qemu_chr_be_can_write(Chardev *s)
199 {
200     CharBackend *be = s->be;
201 
202     if (!be || !be->chr_can_read) {
203         return 0;
204     }
205 
206     return be->chr_can_read(be->opaque);
207 }
208 
209 void qemu_chr_be_write_impl(Chardev *s, const uint8_t *buf, int len)
210 {
211     CharBackend *be = s->be;
212 
213     if (be && be->chr_read) {
214         be->chr_read(be->opaque, buf, len);
215     }
216 }
217 
218 void qemu_chr_be_write(Chardev *s, const uint8_t *buf, int len)
219 {
220     if (qemu_chr_replay(s)) {
221         if (replay_mode == REPLAY_MODE_PLAY) {
222             return;
223         }
224         replay_chr_be_write(s, buf, len);
225     } else {
226         qemu_chr_be_write_impl(s, buf, len);
227     }
228 }
229 
230 void qemu_chr_be_update_read_handlers(Chardev *s,
231                                       GMainContext *context)
232 {
233     ChardevClass *cc = CHARDEV_GET_CLASS(s);
234 
235     assert(qemu_chr_has_feature(s, QEMU_CHAR_FEATURE_GCONTEXT)
236            || !context);
237     s->gcontext = context;
238     if (cc->chr_update_read_handler) {
239         cc->chr_update_read_handler(s);
240     }
241 }
242 
243 int qemu_chr_add_client(Chardev *s, int fd)
244 {
245     return CHARDEV_GET_CLASS(s)->chr_add_client ?
246         CHARDEV_GET_CLASS(s)->chr_add_client(s, fd) : -1;
247 }
248 
249 static void qemu_char_open(Chardev *chr, ChardevBackend *backend,
250                            bool *be_opened, Error **errp)
251 {
252     ChardevClass *cc = CHARDEV_GET_CLASS(chr);
253     /* Any ChardevCommon member would work */
254     ChardevCommon *common = backend ? backend->u.null.data : NULL;
255 
256     if (common && common->logfile) {
257         int flags = O_WRONLY;
258         if (common->has_logappend &&
259             common->logappend) {
260             flags |= O_APPEND;
261         } else {
262             flags |= O_TRUNC;
263         }
264         chr->logfd = qemu_create(common->logfile, flags, 0666, errp);
265         if (chr->logfd < 0) {
266             return;
267         }
268     }
269 
270     if (cc->open) {
271         cc->open(chr, backend, be_opened, errp);
272     }
273 }
274 
275 static void char_init(Object *obj)
276 {
277     Chardev *chr = CHARDEV(obj);
278 
279     chr->handover_yank_instance = false;
280     chr->logfd = -1;
281     qemu_mutex_init(&chr->chr_write_lock);
282 
283     /*
284      * Assume if chr_update_read_handler is implemented it will
285      * take the updated gcontext into account.
286      */
287     if (CHARDEV_GET_CLASS(chr)->chr_update_read_handler) {
288         qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT);
289     }
290 
291 }
292 
293 static int null_chr_write(Chardev *chr, const uint8_t *buf, int len)
294 {
295     return len;
296 }
297 
298 static void char_class_init(ObjectClass *oc, void *data)
299 {
300     ChardevClass *cc = CHARDEV_CLASS(oc);
301 
302     cc->chr_write = null_chr_write;
303     cc->chr_be_event = chr_be_event;
304 }
305 
306 static void char_finalize(Object *obj)
307 {
308     Chardev *chr = CHARDEV(obj);
309 
310     if (chr->be) {
311         chr->be->chr = NULL;
312     }
313     g_free(chr->filename);
314     g_free(chr->label);
315     if (chr->logfd != -1) {
316         close(chr->logfd);
317     }
318     qemu_mutex_destroy(&chr->chr_write_lock);
319 }
320 
321 static const TypeInfo char_type_info = {
322     .name = TYPE_CHARDEV,
323     .parent = TYPE_OBJECT,
324     .instance_size = sizeof(Chardev),
325     .instance_init = char_init,
326     .instance_finalize = char_finalize,
327     .abstract = true,
328     .class_size = sizeof(ChardevClass),
329     .class_init = char_class_init,
330 };
331 
332 static bool qemu_chr_is_busy(Chardev *s)
333 {
334     if (CHARDEV_IS_MUX(s)) {
335         MuxChardev *d = MUX_CHARDEV(s);
336         return d->mux_bitset != 0;
337     } else {
338         return s->be != NULL;
339     }
340 }
341 
342 int qemu_chr_wait_connected(Chardev *chr, Error **errp)
343 {
344     ChardevClass *cc = CHARDEV_GET_CLASS(chr);
345 
346     if (cc->chr_wait_connected) {
347         return cc->chr_wait_connected(chr, errp);
348     }
349 
350     return 0;
351 }
352 
353 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename,
354                                 bool permit_mux_mon)
355 {
356     char host[65], port[33], width[8], height[8];
357     int pos;
358     const char *p;
359     QemuOpts *opts;
360     Error *local_err = NULL;
361 
362     opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
363     if (local_err) {
364         error_report_err(local_err);
365         return NULL;
366     }
367 
368     if (strstart(filename, "mon:", &p)) {
369         if (!permit_mux_mon) {
370             error_report("mon: isn't supported in this context");
371             return NULL;
372         }
373         filename = p;
374         qemu_opt_set(opts, "mux", "on", &error_abort);
375         if (strcmp(filename, "stdio") == 0) {
376             /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
377              * but pass it to the guest.  Handle this only for compat syntax,
378              * for -chardev syntax we have special option for this.
379              * This is what -nographic did, redirecting+muxing serial+monitor
380              * to stdio causing Ctrl+C to be passed to guest. */
381             qemu_opt_set(opts, "signal", "off", &error_abort);
382         }
383     }
384 
385     if (strcmp(filename, "null")    == 0 ||
386         strcmp(filename, "pty")     == 0 ||
387         strcmp(filename, "msmouse") == 0 ||
388         strcmp(filename, "wctablet") == 0 ||
389         strcmp(filename, "braille") == 0 ||
390         strcmp(filename, "testdev") == 0 ||
391         strcmp(filename, "stdio")   == 0) {
392         qemu_opt_set(opts, "backend", filename, &error_abort);
393         return opts;
394     }
395     if (strstart(filename, "vc", &p)) {
396         qemu_opt_set(opts, "backend", "vc", &error_abort);
397         if (*p == ':') {
398             if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
399                 /* pixels */
400                 qemu_opt_set(opts, "width", width, &error_abort);
401                 qemu_opt_set(opts, "height", height, &error_abort);
402             } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
403                 /* chars */
404                 qemu_opt_set(opts, "cols", width, &error_abort);
405                 qemu_opt_set(opts, "rows", height, &error_abort);
406             } else {
407                 goto fail;
408             }
409         }
410         return opts;
411     }
412     if (strcmp(filename, "con:") == 0) {
413         qemu_opt_set(opts, "backend", "console", &error_abort);
414         return opts;
415     }
416     if (strstart(filename, "COM", NULL)) {
417         qemu_opt_set(opts, "backend", "serial", &error_abort);
418         qemu_opt_set(opts, "path", filename, &error_abort);
419         return opts;
420     }
421     if (strstart(filename, "file:", &p)) {
422         qemu_opt_set(opts, "backend", "file", &error_abort);
423         qemu_opt_set(opts, "path", p, &error_abort);
424         return opts;
425     }
426     if (strstart(filename, "pipe:", &p)) {
427         qemu_opt_set(opts, "backend", "pipe", &error_abort);
428         qemu_opt_set(opts, "path", p, &error_abort);
429         return opts;
430     }
431     if (strstart(filename, "pty:", &p)) {
432         qemu_opt_set(opts, "backend", "pty", &error_abort);
433         qemu_opt_set(opts, "path", p, &error_abort);
434         return opts;
435     }
436     if (strstart(filename, "tcp:", &p) ||
437         strstart(filename, "telnet:", &p) ||
438         strstart(filename, "tn3270:", &p) ||
439         strstart(filename, "websocket:", &p)) {
440         if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
441             host[0] = 0;
442             if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
443                 goto fail;
444         }
445         qemu_opt_set(opts, "backend", "socket", &error_abort);
446         qemu_opt_set(opts, "host", host, &error_abort);
447         qemu_opt_set(opts, "port", port, &error_abort);
448         if (p[pos] == ',') {
449             if (!qemu_opts_do_parse(opts, p + pos + 1, NULL, &local_err)) {
450                 error_report_err(local_err);
451                 goto fail;
452             }
453         }
454         if (strstart(filename, "telnet:", &p)) {
455             qemu_opt_set(opts, "telnet", "on", &error_abort);
456         } else if (strstart(filename, "tn3270:", &p)) {
457             qemu_opt_set(opts, "tn3270", "on", &error_abort);
458         } else if (strstart(filename, "websocket:", &p)) {
459             qemu_opt_set(opts, "websocket", "on", &error_abort);
460         }
461         return opts;
462     }
463     if (strstart(filename, "udp:", &p)) {
464         qemu_opt_set(opts, "backend", "udp", &error_abort);
465         if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
466             host[0] = 0;
467             if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
468                 goto fail;
469             }
470         }
471         qemu_opt_set(opts, "host", host, &error_abort);
472         qemu_opt_set(opts, "port", port, &error_abort);
473         if (p[pos] == '@') {
474             p += pos + 1;
475             if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
476                 host[0] = 0;
477                 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
478                     goto fail;
479                 }
480             }
481             qemu_opt_set(opts, "localaddr", host, &error_abort);
482             qemu_opt_set(opts, "localport", port, &error_abort);
483         }
484         return opts;
485     }
486     if (strstart(filename, "unix:", &p)) {
487         qemu_opt_set(opts, "backend", "socket", &error_abort);
488         if (!qemu_opts_do_parse(opts, p, "path", &local_err)) {
489             error_report_err(local_err);
490             goto fail;
491         }
492         return opts;
493     }
494     if (strstart(filename, "/dev/parport", NULL) ||
495         strstart(filename, "/dev/ppi", NULL)) {
496         qemu_opt_set(opts, "backend", "parallel", &error_abort);
497         qemu_opt_set(opts, "path", filename, &error_abort);
498         return opts;
499     }
500     if (strstart(filename, "/dev/", NULL)) {
501         qemu_opt_set(opts, "backend", "serial", &error_abort);
502         qemu_opt_set(opts, "path", filename, &error_abort);
503         return opts;
504     }
505 
506     error_report("'%s' is not a valid char driver", filename);
507 
508 fail:
509     qemu_opts_del(opts);
510     return NULL;
511 }
512 
513 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
514 {
515     const char *logfile = qemu_opt_get(opts, "logfile");
516 
517     backend->logfile = g_strdup(logfile);
518     backend->has_logappend = true;
519     backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
520 }
521 
522 static const ChardevClass *char_get_class(const char *driver, Error **errp)
523 {
524     ObjectClass *oc;
525     const ChardevClass *cc;
526     char *typename = g_strdup_printf("chardev-%s", driver);
527 
528     oc = module_object_class_by_name(typename);
529     g_free(typename);
530 
531     if (!object_class_dynamic_cast(oc, TYPE_CHARDEV)) {
532         error_setg(errp, "'%s' is not a valid char driver name", driver);
533         return NULL;
534     }
535 
536     if (object_class_is_abstract(oc)) {
537         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
538                    "a non-abstract device type");
539         return NULL;
540     }
541 
542     cc = CHARDEV_CLASS(oc);
543     if (cc->internal) {
544         error_setg(errp, "'%s' is not a valid char driver name", driver);
545         return NULL;
546     }
547 
548     return cc;
549 }
550 
551 typedef struct ChadevClassFE {
552     void (*fn)(const char *name, void *opaque);
553     void *opaque;
554 } ChadevClassFE;
555 
556 static void
557 chardev_class_foreach(ObjectClass *klass, void *opaque)
558 {
559     ChadevClassFE *fe = opaque;
560 
561     assert(g_str_has_prefix(object_class_get_name(klass), "chardev-"));
562     if (CHARDEV_CLASS(klass)->internal) {
563         return;
564     }
565 
566     fe->fn(object_class_get_name(klass) + 8, fe->opaque);
567 }
568 
569 static void
570 chardev_name_foreach(void (*fn)(const char *name, void *opaque),
571                      void *opaque)
572 {
573     ChadevClassFE fe = { .fn = fn, .opaque = opaque };
574 
575     object_class_foreach(chardev_class_foreach, TYPE_CHARDEV, false, &fe);
576 }
577 
578 static void
579 help_string_append(const char *name, void *opaque)
580 {
581     GString *str = opaque;
582 
583     g_string_append_printf(str, "\n  %s", name);
584 }
585 
586 ChardevBackend *qemu_chr_parse_opts(QemuOpts *opts, Error **errp)
587 {
588     Error *local_err = NULL;
589     const ChardevClass *cc;
590     ChardevBackend *backend = NULL;
591     const char *name = qemu_opt_get(opts, "backend");
592 
593     if (name == NULL) {
594         error_setg(errp, "chardev: \"%s\" missing backend",
595                    qemu_opts_id(opts));
596         return NULL;
597     }
598 
599     cc = char_get_class(name, errp);
600     if (cc == NULL) {
601         return NULL;
602     }
603 
604     backend = g_new0(ChardevBackend, 1);
605     backend->type = CHARDEV_BACKEND_KIND_NULL;
606 
607     if (cc->parse) {
608         cc->parse(opts, backend, &local_err);
609         if (local_err) {
610             error_propagate(errp, local_err);
611             qapi_free_ChardevBackend(backend);
612             return NULL;
613         }
614     } else {
615         ChardevCommon *ccom = g_new0(ChardevCommon, 1);
616         qemu_chr_parse_common(opts, ccom);
617         backend->u.null.data = ccom; /* Any ChardevCommon member would work */
618     }
619 
620     return backend;
621 }
622 
623 static void qemu_chardev_set_replay(Chardev *chr, Error **errp)
624 {
625     if (replay_mode != REPLAY_MODE_NONE) {
626         if (CHARDEV_GET_CLASS(chr)->chr_ioctl) {
627             error_setg(errp, "Replay: ioctl is not supported "
628                              "for serial devices yet");
629             return;
630         }
631         qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_REPLAY);
632         replay_register_char_driver(chr);
633     }
634 }
635 
636 static Chardev *__qemu_chr_new_from_opts(QemuOpts *opts, GMainContext *context,
637                                          bool replay, Error **errp)
638 {
639     const ChardevClass *cc;
640     Chardev *base = NULL, *chr = NULL;
641     ChardevBackend *backend = NULL;
642     const char *name = qemu_opt_get(opts, "backend");
643     const char *id = qemu_opts_id(opts);
644     char *bid = NULL;
645 
646     if (name && is_help_option(name)) {
647         GString *str = g_string_new("");
648 
649         chardev_name_foreach(help_string_append, str);
650 
651         qemu_printf("Available chardev backend types: %s\n", str->str);
652         g_string_free(str, true);
653         return NULL;
654     }
655 
656     if (id == NULL) {
657         error_setg(errp, "chardev: no id specified");
658         return NULL;
659     }
660 
661     backend = qemu_chr_parse_opts(opts, errp);
662     if (backend == NULL) {
663         return NULL;
664     }
665 
666     cc = char_get_class(name, errp);
667     if (cc == NULL) {
668         goto out;
669     }
670 
671     if (qemu_opt_get_bool(opts, "mux", 0)) {
672         bid = g_strdup_printf("%s-base", id);
673     }
674 
675     chr = qemu_chardev_new(bid ? bid : id,
676                            object_class_get_name(OBJECT_CLASS(cc)),
677                            backend, context, errp);
678     if (chr == NULL) {
679         goto out;
680     }
681 
682     base = chr;
683     if (bid) {
684         Chardev *mux;
685         qapi_free_ChardevBackend(backend);
686         backend = g_new0(ChardevBackend, 1);
687         backend->type = CHARDEV_BACKEND_KIND_MUX;
688         backend->u.mux.data = g_new0(ChardevMux, 1);
689         backend->u.mux.data->chardev = g_strdup(bid);
690         mux = qemu_chardev_new(id, TYPE_CHARDEV_MUX, backend, context, errp);
691         if (mux == NULL) {
692             object_unparent(OBJECT(chr));
693             chr = NULL;
694             goto out;
695         }
696         chr = mux;
697     }
698 
699 out:
700     qapi_free_ChardevBackend(backend);
701     g_free(bid);
702 
703     if (replay && base) {
704         /* RR should be set on the base device, not the mux */
705         qemu_chardev_set_replay(base, errp);
706     }
707 
708     return chr;
709 }
710 
711 Chardev *qemu_chr_new_from_opts(QemuOpts *opts, GMainContext *context,
712                                 Error **errp)
713 {
714     /* XXX: should this really not record/replay? */
715     return __qemu_chr_new_from_opts(opts, context, false, errp);
716 }
717 
718 static Chardev *__qemu_chr_new(const char *label, const char *filename,
719                                bool permit_mux_mon, GMainContext *context,
720                                bool replay)
721 {
722     const char *p;
723     Chardev *chr;
724     QemuOpts *opts;
725     Error *err = NULL;
726 
727     if (strstart(filename, "chardev:", &p)) {
728         chr = qemu_chr_find(p);
729         if (replay) {
730             qemu_chardev_set_replay(chr, &err);
731             if (err) {
732                 error_report_err(err);
733                 return NULL;
734             }
735         }
736         return chr;
737     }
738 
739     opts = qemu_chr_parse_compat(label, filename, permit_mux_mon);
740     if (!opts)
741         return NULL;
742 
743     chr = __qemu_chr_new_from_opts(opts, context, replay, &err);
744     if (!chr) {
745         error_report_err(err);
746         goto out;
747     }
748 
749     if (qemu_opt_get_bool(opts, "mux", 0)) {
750         assert(permit_mux_mon);
751         monitor_init_hmp(chr, true, &err);
752         if (err) {
753             error_report_err(err);
754             object_unparent(OBJECT(chr));
755             chr = NULL;
756             goto out;
757         }
758     }
759 
760 out:
761     qemu_opts_del(opts);
762     return chr;
763 }
764 
765 Chardev *qemu_chr_new_noreplay(const char *label, const char *filename,
766                                bool permit_mux_mon, GMainContext *context)
767 {
768     return __qemu_chr_new(label, filename, permit_mux_mon, context, false);
769 }
770 
771 static Chardev *qemu_chr_new_permit_mux_mon(const char *label,
772                                           const char *filename,
773                                           bool permit_mux_mon,
774                                           GMainContext *context)
775 {
776     return __qemu_chr_new(label, filename, permit_mux_mon, context, true);
777 }
778 
779 Chardev *qemu_chr_new(const char *label, const char *filename,
780                       GMainContext *context)
781 {
782     return qemu_chr_new_permit_mux_mon(label, filename, false, context);
783 }
784 
785 Chardev *qemu_chr_new_mux_mon(const char *label, const char *filename,
786                               GMainContext *context)
787 {
788     return qemu_chr_new_permit_mux_mon(label, filename, true, context);
789 }
790 
791 static int qmp_query_chardev_foreach(Object *obj, void *data)
792 {
793     Chardev *chr = CHARDEV(obj);
794     ChardevInfoList **list = data;
795     ChardevInfo *value = g_malloc0(sizeof(*value));
796 
797     value->label = g_strdup(chr->label);
798     value->filename = g_strdup(chr->filename);
799     value->frontend_open = chr->be && chr->be->fe_is_open;
800 
801     QAPI_LIST_PREPEND(*list, value);
802 
803     return 0;
804 }
805 
806 ChardevInfoList *qmp_query_chardev(Error **errp)
807 {
808     ChardevInfoList *chr_list = NULL;
809 
810     object_child_foreach(get_chardevs_root(),
811                          qmp_query_chardev_foreach, &chr_list);
812 
813     return chr_list;
814 }
815 
816 static void
817 qmp_prepend_backend(const char *name, void *opaque)
818 {
819     ChardevBackendInfoList **list = opaque;
820     ChardevBackendInfo *value;
821 
822     value = g_new0(ChardevBackendInfo, 1);
823     value->name = g_strdup(name);
824     QAPI_LIST_PREPEND(*list, value);
825 }
826 
827 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
828 {
829     ChardevBackendInfoList *backend_list = NULL;
830 
831     chardev_name_foreach(qmp_prepend_backend, &backend_list);
832 
833     return backend_list;
834 }
835 
836 Chardev *qemu_chr_find(const char *name)
837 {
838     Object *obj = object_resolve_path_component(get_chardevs_root(), name);
839 
840     return obj ? CHARDEV(obj) : NULL;
841 }
842 
843 QemuOptsList qemu_chardev_opts = {
844     .name = "chardev",
845     .implied_opt_name = "backend",
846     .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
847     .desc = {
848         {
849             .name = "backend",
850             .type = QEMU_OPT_STRING,
851         },{
852             .name = "path",
853             .type = QEMU_OPT_STRING,
854         },{
855             .name = "input-path",
856             .type = QEMU_OPT_STRING,
857         },{
858             .name = "host",
859             .type = QEMU_OPT_STRING,
860         },{
861             .name = "port",
862             .type = QEMU_OPT_STRING,
863         },{
864             .name = "fd",
865             .type = QEMU_OPT_STRING,
866         },{
867             .name = "localaddr",
868             .type = QEMU_OPT_STRING,
869         },{
870             .name = "localport",
871             .type = QEMU_OPT_STRING,
872         },{
873             .name = "to",
874             .type = QEMU_OPT_NUMBER,
875         },{
876             .name = "ipv4",
877             .type = QEMU_OPT_BOOL,
878         },{
879             .name = "ipv6",
880             .type = QEMU_OPT_BOOL,
881         },{
882             .name = "wait",
883             .type = QEMU_OPT_BOOL,
884         },{
885             .name = "server",
886             .type = QEMU_OPT_BOOL,
887         },{
888             .name = "delay",
889             .type = QEMU_OPT_BOOL,
890         },{
891             .name = "nodelay",
892             .type = QEMU_OPT_BOOL,
893         },{
894             .name = "reconnect",
895             .type = QEMU_OPT_NUMBER,
896         },{
897             .name = "reconnect-ms",
898             .type = QEMU_OPT_NUMBER,
899         },{
900             .name = "telnet",
901             .type = QEMU_OPT_BOOL,
902         },{
903             .name = "tn3270",
904             .type = QEMU_OPT_BOOL,
905         },{
906             .name = "tls-creds",
907             .type = QEMU_OPT_STRING,
908         },{
909             .name = "tls-authz",
910             .type = QEMU_OPT_STRING,
911         },{
912             .name = "websocket",
913             .type = QEMU_OPT_BOOL,
914         },{
915             .name = "width",
916             .type = QEMU_OPT_NUMBER,
917         },{
918             .name = "height",
919             .type = QEMU_OPT_NUMBER,
920         },{
921             .name = "cols",
922             .type = QEMU_OPT_NUMBER,
923         },{
924             .name = "rows",
925             .type = QEMU_OPT_NUMBER,
926         },{
927             .name = "mux",
928             .type = QEMU_OPT_BOOL,
929         },{
930             .name = "signal",
931             .type = QEMU_OPT_BOOL,
932         },{
933             .name = "name",
934             .type = QEMU_OPT_STRING,
935         },{
936             .name = "debug",
937             .type = QEMU_OPT_NUMBER,
938         },{
939             .name = "size",
940             .type = QEMU_OPT_SIZE,
941         },{
942             .name = "chardev",
943             .type = QEMU_OPT_STRING,
944         },{
945             .name = "append",
946             .type = QEMU_OPT_BOOL,
947         },{
948             .name = "logfile",
949             .type = QEMU_OPT_STRING,
950         },{
951             .name = "logappend",
952             .type = QEMU_OPT_BOOL,
953         },{
954             .name = "mouse",
955             .type = QEMU_OPT_BOOL,
956         },{
957             .name = "clipboard",
958             .type = QEMU_OPT_BOOL,
959 #ifdef CONFIG_LINUX
960         },{
961             .name = "tight",
962             .type = QEMU_OPT_BOOL,
963             .def_value_str = "on",
964         },{
965             .name = "abstract",
966             .type = QEMU_OPT_BOOL,
967 #endif
968         },
969         { /* end of list */ }
970     },
971 };
972 
973 bool qemu_chr_has_feature(Chardev *chr,
974                           ChardevFeature feature)
975 {
976     return test_bit(feature, chr->features);
977 }
978 
979 void qemu_chr_set_feature(Chardev *chr,
980                            ChardevFeature feature)
981 {
982     return set_bit(feature, chr->features);
983 }
984 
985 static Chardev *chardev_new(const char *id, const char *typename,
986                             ChardevBackend *backend,
987                             GMainContext *gcontext,
988                             bool handover_yank_instance,
989                             Error **errp)
990 {
991     Object *obj;
992     Chardev *chr = NULL;
993     Error *local_err = NULL;
994     bool be_opened = true;
995 
996     assert(g_str_has_prefix(typename, "chardev-"));
997     assert(id);
998 
999     obj = object_new(typename);
1000     chr = CHARDEV(obj);
1001     chr->handover_yank_instance = handover_yank_instance;
1002     chr->label = g_strdup(id);
1003     chr->gcontext = gcontext;
1004 
1005     qemu_char_open(chr, backend, &be_opened, &local_err);
1006     if (local_err) {
1007         error_propagate(errp, local_err);
1008         object_unref(obj);
1009         return NULL;
1010     }
1011 
1012     if (!chr->filename) {
1013         chr->filename = g_strdup(typename + 8);
1014     }
1015     if (be_opened) {
1016         qemu_chr_be_event(chr, CHR_EVENT_OPENED);
1017     }
1018 
1019     return chr;
1020 }
1021 
1022 Chardev *qemu_chardev_new(const char *id, const char *typename,
1023                           ChardevBackend *backend,
1024                           GMainContext *gcontext,
1025                           Error **errp)
1026 {
1027     Chardev *chr;
1028     g_autofree char *genid = NULL;
1029 
1030     if (!id) {
1031         genid = id_generate(ID_CHR);
1032         id = genid;
1033     }
1034 
1035     chr = chardev_new(id, typename, backend, gcontext, false, errp);
1036     if (!chr) {
1037         return NULL;
1038     }
1039 
1040     if (!object_property_try_add_child(get_chardevs_root(), id, OBJECT(chr),
1041                                        errp)) {
1042         object_unref(OBJECT(chr));
1043         return NULL;
1044     }
1045     object_unref(OBJECT(chr));
1046 
1047     return chr;
1048 }
1049 
1050 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
1051                                Error **errp)
1052 {
1053     ERRP_GUARD();
1054     const ChardevClass *cc;
1055     ChardevReturn *ret;
1056     g_autoptr(Chardev) chr = NULL;
1057 
1058     if (qemu_chr_find(id)) {
1059         error_setg(errp, "Chardev with id '%s' already exists", id);
1060         return NULL;
1061     }
1062 
1063     cc = char_get_class(ChardevBackendKind_str(backend->type), errp);
1064     if (!cc) {
1065         goto err;
1066     }
1067 
1068     chr = chardev_new(id, object_class_get_name(OBJECT_CLASS(cc)),
1069                       backend, NULL, false, errp);
1070     if (!chr) {
1071         goto err;
1072     }
1073 
1074     if (!object_property_try_add_child(get_chardevs_root(), id, OBJECT(chr),
1075                                        errp)) {
1076         goto err;
1077     }
1078 
1079     ret = g_new0(ChardevReturn, 1);
1080     if (CHARDEV_IS_PTY(chr)) {
1081         ret->pty = g_strdup(chr->filename + 4);
1082     }
1083 
1084     return ret;
1085 
1086 err:
1087     error_prepend(errp, "Failed to add chardev '%s': ", id);
1088     return NULL;
1089 }
1090 
1091 ChardevReturn *qmp_chardev_change(const char *id, ChardevBackend *backend,
1092                                   Error **errp)
1093 {
1094     CharBackend *be;
1095     const ChardevClass *cc, *cc_new;
1096     Chardev *chr, *chr_new;
1097     bool closed_sent = false;
1098     bool handover_yank_instance;
1099     ChardevReturn *ret;
1100 
1101     chr = qemu_chr_find(id);
1102     if (!chr) {
1103         error_setg(errp, "Chardev '%s' does not exist", id);
1104         return NULL;
1105     }
1106 
1107     if (CHARDEV_IS_MUX(chr)) {
1108         error_setg(errp, "Mux device hotswap not supported yet");
1109         return NULL;
1110     }
1111 
1112     if (qemu_chr_replay(chr)) {
1113         error_setg(errp,
1114             "Chardev '%s' cannot be changed in record/replay mode", id);
1115         return NULL;
1116     }
1117 
1118     be = chr->be;
1119     if (!be) {
1120         /* easy case */
1121         object_unparent(OBJECT(chr));
1122         return qmp_chardev_add(id, backend, errp);
1123     }
1124 
1125     if (!be->chr_be_change) {
1126         error_setg(errp, "Chardev user does not support chardev hotswap");
1127         return NULL;
1128     }
1129 
1130     cc = CHARDEV_GET_CLASS(chr);
1131     cc_new = char_get_class(ChardevBackendKind_str(backend->type), errp);
1132     if (!cc_new) {
1133         return NULL;
1134     }
1135 
1136     /*
1137      * The new chardev should not register a yank instance if the current
1138      * chardev has registered one already.
1139      */
1140     handover_yank_instance = cc->supports_yank && cc_new->supports_yank;
1141 
1142     chr_new = chardev_new(id, object_class_get_name(OBJECT_CLASS(cc_new)),
1143                           backend, chr->gcontext, handover_yank_instance, errp);
1144     if (!chr_new) {
1145         return NULL;
1146     }
1147 
1148     if (chr->be_open && !chr_new->be_open) {
1149         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1150         closed_sent = true;
1151     }
1152 
1153     chr->be = NULL;
1154     qemu_chr_fe_init(be, chr_new, &error_abort);
1155 
1156     if (be->chr_be_change(be->opaque) < 0) {
1157         error_setg(errp, "Chardev '%s' change failed", chr_new->label);
1158         chr_new->be = NULL;
1159         qemu_chr_fe_init(be, chr, &error_abort);
1160         if (closed_sent) {
1161             qemu_chr_be_event(chr, CHR_EVENT_OPENED);
1162         }
1163         object_unref(OBJECT(chr_new));
1164         return NULL;
1165     }
1166 
1167     /* change successful, clean up */
1168     chr_new->handover_yank_instance = false;
1169 
1170     /*
1171      * When the old chardev is freed, it should not unregister the yank
1172      * instance if the new chardev needs it.
1173      */
1174     chr->handover_yank_instance = handover_yank_instance;
1175 
1176     object_unparent(OBJECT(chr));
1177     object_property_add_child(get_chardevs_root(), chr_new->label,
1178                               OBJECT(chr_new));
1179     object_unref(OBJECT(chr_new));
1180 
1181     ret = g_new0(ChardevReturn, 1);
1182     if (CHARDEV_IS_PTY(chr_new)) {
1183         ret->pty = g_strdup(chr_new->filename + 4);
1184     }
1185 
1186     return ret;
1187 }
1188 
1189 void qmp_chardev_remove(const char *id, Error **errp)
1190 {
1191     Chardev *chr;
1192 
1193     chr = qemu_chr_find(id);
1194     if (chr == NULL) {
1195         error_setg(errp, "Chardev '%s' not found", id);
1196         return;
1197     }
1198     if (qemu_chr_is_busy(chr)) {
1199         error_setg(errp, "Chardev '%s' is busy", id);
1200         return;
1201     }
1202     if (qemu_chr_replay(chr)) {
1203         error_setg(errp,
1204             "Chardev '%s' cannot be unplugged in record/replay mode", id);
1205         return;
1206     }
1207     object_unparent(OBJECT(chr));
1208 }
1209 
1210 void qmp_chardev_send_break(const char *id, Error **errp)
1211 {
1212     Chardev *chr;
1213 
1214     chr = qemu_chr_find(id);
1215     if (chr == NULL) {
1216         error_setg(errp, "Chardev '%s' not found", id);
1217         return;
1218     }
1219     qemu_chr_be_event(chr, CHR_EVENT_BREAK);
1220 }
1221 
1222 bool qmp_add_client_char(int fd, bool has_skipauth, bool skipauth,
1223                          bool has_tls, bool tls, const char *protocol,
1224                          Error **errp)
1225 {
1226     Chardev *s = qemu_chr_find(protocol);
1227 
1228     if (!s) {
1229         error_setg(errp, "protocol '%s' is invalid", protocol);
1230         return false;
1231     }
1232     if (qemu_chr_add_client(s, fd) < 0) {
1233         error_setg(errp, "failed to add client");
1234         return false;
1235     }
1236     return true;
1237 }
1238 
1239 /*
1240  * Add a timeout callback for the chardev (in milliseconds), return
1241  * the GSource object created. Please use this to add timeout hook for
1242  * chardev instead of g_timeout_add() and g_timeout_add_seconds(), to
1243  * make sure the gcontext that the task bound to is correct.
1244  */
1245 GSource *qemu_chr_timeout_add_ms(Chardev *chr, guint ms,
1246                                  GSourceFunc func, void *private)
1247 {
1248     GSource *source = g_timeout_source_new(ms);
1249 
1250     assert(func);
1251     g_source_set_callback(source, func, private, NULL);
1252     g_source_attach(source, chr->gcontext);
1253 
1254     return source;
1255 }
1256 
1257 void qemu_chr_cleanup(void)
1258 {
1259     object_unparent(get_chardevs_root());
1260 }
1261 
1262 static void register_types(void)
1263 {
1264     type_register_static(&char_type_info);
1265 }
1266 
1267 type_init(register_types);
1268