xref: /openbmc/qemu/chardev/char.c (revision ab0c7fb2)
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_cnt >= 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, "tcp:", &p) ||
432         strstart(filename, "telnet:", &p) ||
433         strstart(filename, "tn3270:", &p) ||
434         strstart(filename, "websocket:", &p)) {
435         if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
436             host[0] = 0;
437             if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
438                 goto fail;
439         }
440         qemu_opt_set(opts, "backend", "socket", &error_abort);
441         qemu_opt_set(opts, "host", host, &error_abort);
442         qemu_opt_set(opts, "port", port, &error_abort);
443         if (p[pos] == ',') {
444             if (!qemu_opts_do_parse(opts, p + pos + 1, NULL, &local_err)) {
445                 error_report_err(local_err);
446                 goto fail;
447             }
448         }
449         if (strstart(filename, "telnet:", &p)) {
450             qemu_opt_set(opts, "telnet", "on", &error_abort);
451         } else if (strstart(filename, "tn3270:", &p)) {
452             qemu_opt_set(opts, "tn3270", "on", &error_abort);
453         } else if (strstart(filename, "websocket:", &p)) {
454             qemu_opt_set(opts, "websocket", "on", &error_abort);
455         }
456         return opts;
457     }
458     if (strstart(filename, "udp:", &p)) {
459         qemu_opt_set(opts, "backend", "udp", &error_abort);
460         if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
461             host[0] = 0;
462             if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
463                 goto fail;
464             }
465         }
466         qemu_opt_set(opts, "host", host, &error_abort);
467         qemu_opt_set(opts, "port", port, &error_abort);
468         if (p[pos] == '@') {
469             p += pos + 1;
470             if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
471                 host[0] = 0;
472                 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
473                     goto fail;
474                 }
475             }
476             qemu_opt_set(opts, "localaddr", host, &error_abort);
477             qemu_opt_set(opts, "localport", port, &error_abort);
478         }
479         return opts;
480     }
481     if (strstart(filename, "unix:", &p)) {
482         qemu_opt_set(opts, "backend", "socket", &error_abort);
483         if (!qemu_opts_do_parse(opts, p, "path", &local_err)) {
484             error_report_err(local_err);
485             goto fail;
486         }
487         return opts;
488     }
489     if (strstart(filename, "/dev/parport", NULL) ||
490         strstart(filename, "/dev/ppi", NULL)) {
491         qemu_opt_set(opts, "backend", "parallel", &error_abort);
492         qemu_opt_set(opts, "path", filename, &error_abort);
493         return opts;
494     }
495     if (strstart(filename, "/dev/", NULL)) {
496         qemu_opt_set(opts, "backend", "serial", &error_abort);
497         qemu_opt_set(opts, "path", filename, &error_abort);
498         return opts;
499     }
500 
501     error_report("'%s' is not a valid char driver", filename);
502 
503 fail:
504     qemu_opts_del(opts);
505     return NULL;
506 }
507 
508 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
509 {
510     const char *logfile = qemu_opt_get(opts, "logfile");
511 
512     backend->logfile = g_strdup(logfile);
513     backend->has_logappend = true;
514     backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
515 }
516 
517 static const ChardevClass *char_get_class(const char *driver, Error **errp)
518 {
519     ObjectClass *oc;
520     const ChardevClass *cc;
521     char *typename = g_strdup_printf("chardev-%s", driver);
522 
523     oc = module_object_class_by_name(typename);
524     g_free(typename);
525 
526     if (!object_class_dynamic_cast(oc, TYPE_CHARDEV)) {
527         error_setg(errp, "'%s' is not a valid char driver name", driver);
528         return NULL;
529     }
530 
531     if (object_class_is_abstract(oc)) {
532         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
533                    "a non-abstract device type");
534         return NULL;
535     }
536 
537     cc = CHARDEV_CLASS(oc);
538     if (cc->internal) {
539         error_setg(errp, "'%s' is not a valid char driver name", driver);
540         return NULL;
541     }
542 
543     return cc;
544 }
545 
546 typedef struct ChadevClassFE {
547     void (*fn)(const char *name, void *opaque);
548     void *opaque;
549 } ChadevClassFE;
550 
551 static void
552 chardev_class_foreach(ObjectClass *klass, void *opaque)
553 {
554     ChadevClassFE *fe = opaque;
555 
556     assert(g_str_has_prefix(object_class_get_name(klass), "chardev-"));
557     if (CHARDEV_CLASS(klass)->internal) {
558         return;
559     }
560 
561     fe->fn(object_class_get_name(klass) + 8, fe->opaque);
562 }
563 
564 static void
565 chardev_name_foreach(void (*fn)(const char *name, void *opaque),
566                      void *opaque)
567 {
568     ChadevClassFE fe = { .fn = fn, .opaque = opaque };
569 
570     object_class_foreach(chardev_class_foreach, TYPE_CHARDEV, false, &fe);
571 }
572 
573 static void
574 help_string_append(const char *name, void *opaque)
575 {
576     GString *str = opaque;
577 
578     g_string_append_printf(str, "\n  %s", name);
579 }
580 
581 ChardevBackend *qemu_chr_parse_opts(QemuOpts *opts, Error **errp)
582 {
583     Error *local_err = NULL;
584     const ChardevClass *cc;
585     ChardevBackend *backend = NULL;
586     const char *name = qemu_opt_get(opts, "backend");
587 
588     if (name == NULL) {
589         error_setg(errp, "chardev: \"%s\" missing backend",
590                    qemu_opts_id(opts));
591         return NULL;
592     }
593 
594     cc = char_get_class(name, errp);
595     if (cc == NULL) {
596         return NULL;
597     }
598 
599     backend = g_new0(ChardevBackend, 1);
600     backend->type = CHARDEV_BACKEND_KIND_NULL;
601 
602     if (cc->parse) {
603         cc->parse(opts, backend, &local_err);
604         if (local_err) {
605             error_propagate(errp, local_err);
606             qapi_free_ChardevBackend(backend);
607             return NULL;
608         }
609     } else {
610         ChardevCommon *ccom = g_new0(ChardevCommon, 1);
611         qemu_chr_parse_common(opts, ccom);
612         backend->u.null.data = ccom; /* Any ChardevCommon member would work */
613     }
614 
615     return backend;
616 }
617 
618 Chardev *qemu_chr_new_from_opts(QemuOpts *opts, GMainContext *context,
619                                 Error **errp)
620 {
621     const ChardevClass *cc;
622     Chardev *chr = NULL;
623     ChardevBackend *backend = NULL;
624     const char *name = qemu_opt_get(opts, "backend");
625     const char *id = qemu_opts_id(opts);
626     char *bid = NULL;
627 
628     if (name && is_help_option(name)) {
629         GString *str = g_string_new("");
630 
631         chardev_name_foreach(help_string_append, str);
632 
633         qemu_printf("Available chardev backend types: %s\n", str->str);
634         g_string_free(str, true);
635         return NULL;
636     }
637 
638     if (id == NULL) {
639         error_setg(errp, "chardev: no id specified");
640         return NULL;
641     }
642 
643     backend = qemu_chr_parse_opts(opts, errp);
644     if (backend == NULL) {
645         return NULL;
646     }
647 
648     cc = char_get_class(name, errp);
649     if (cc == NULL) {
650         goto out;
651     }
652 
653     if (qemu_opt_get_bool(opts, "mux", 0)) {
654         bid = g_strdup_printf("%s-base", id);
655     }
656 
657     chr = qemu_chardev_new(bid ? bid : id,
658                            object_class_get_name(OBJECT_CLASS(cc)),
659                            backend, context, errp);
660 
661     if (chr == NULL) {
662         goto out;
663     }
664 
665     if (bid) {
666         Chardev *mux;
667         qapi_free_ChardevBackend(backend);
668         backend = g_new0(ChardevBackend, 1);
669         backend->type = CHARDEV_BACKEND_KIND_MUX;
670         backend->u.mux.data = g_new0(ChardevMux, 1);
671         backend->u.mux.data->chardev = g_strdup(bid);
672         mux = qemu_chardev_new(id, TYPE_CHARDEV_MUX, backend, context, errp);
673         if (mux == NULL) {
674             object_unparent(OBJECT(chr));
675             chr = NULL;
676             goto out;
677         }
678         chr = mux;
679     }
680 
681 out:
682     qapi_free_ChardevBackend(backend);
683     g_free(bid);
684     return chr;
685 }
686 
687 Chardev *qemu_chr_new_noreplay(const char *label, const char *filename,
688                                bool permit_mux_mon, GMainContext *context)
689 {
690     const char *p;
691     Chardev *chr;
692     QemuOpts *opts;
693     Error *err = NULL;
694 
695     if (strstart(filename, "chardev:", &p)) {
696         return qemu_chr_find(p);
697     }
698 
699     opts = qemu_chr_parse_compat(label, filename, permit_mux_mon);
700     if (!opts)
701         return NULL;
702 
703     chr = qemu_chr_new_from_opts(opts, context, &err);
704     if (!chr) {
705         error_report_err(err);
706         goto out;
707     }
708 
709     if (qemu_opt_get_bool(opts, "mux", 0)) {
710         assert(permit_mux_mon);
711         monitor_init_hmp(chr, true, &err);
712         if (err) {
713             error_report_err(err);
714             object_unparent(OBJECT(chr));
715             chr = NULL;
716             goto out;
717         }
718     }
719 
720 out:
721     qemu_opts_del(opts);
722     return chr;
723 }
724 
725 static Chardev *qemu_chr_new_permit_mux_mon(const char *label,
726                                           const char *filename,
727                                           bool permit_mux_mon,
728                                           GMainContext *context)
729 {
730     Chardev *chr;
731     chr = qemu_chr_new_noreplay(label, filename, permit_mux_mon, context);
732     if (chr) {
733         if (replay_mode != REPLAY_MODE_NONE) {
734             qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_REPLAY);
735         }
736         if (qemu_chr_replay(chr) && CHARDEV_GET_CLASS(chr)->chr_ioctl) {
737             error_report("Replay: ioctl is not supported "
738                          "for serial devices yet");
739         }
740         replay_register_char_driver(chr);
741     }
742     return chr;
743 }
744 
745 Chardev *qemu_chr_new(const char *label, const char *filename,
746                       GMainContext *context)
747 {
748     return qemu_chr_new_permit_mux_mon(label, filename, false, context);
749 }
750 
751 Chardev *qemu_chr_new_mux_mon(const char *label, const char *filename,
752                               GMainContext *context)
753 {
754     return qemu_chr_new_permit_mux_mon(label, filename, true, context);
755 }
756 
757 static int qmp_query_chardev_foreach(Object *obj, void *data)
758 {
759     Chardev *chr = CHARDEV(obj);
760     ChardevInfoList **list = data;
761     ChardevInfo *value = g_malloc0(sizeof(*value));
762 
763     value->label = g_strdup(chr->label);
764     value->filename = g_strdup(chr->filename);
765     value->frontend_open = chr->be && chr->be->fe_is_open;
766 
767     QAPI_LIST_PREPEND(*list, value);
768 
769     return 0;
770 }
771 
772 ChardevInfoList *qmp_query_chardev(Error **errp)
773 {
774     ChardevInfoList *chr_list = NULL;
775 
776     object_child_foreach(get_chardevs_root(),
777                          qmp_query_chardev_foreach, &chr_list);
778 
779     return chr_list;
780 }
781 
782 static void
783 qmp_prepend_backend(const char *name, void *opaque)
784 {
785     ChardevBackendInfoList **list = opaque;
786     ChardevBackendInfo *value;
787 
788     value = g_new0(ChardevBackendInfo, 1);
789     value->name = g_strdup(name);
790     QAPI_LIST_PREPEND(*list, value);
791 }
792 
793 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
794 {
795     ChardevBackendInfoList *backend_list = NULL;
796 
797     chardev_name_foreach(qmp_prepend_backend, &backend_list);
798 
799     return backend_list;
800 }
801 
802 Chardev *qemu_chr_find(const char *name)
803 {
804     Object *obj = object_resolve_path_component(get_chardevs_root(), name);
805 
806     return obj ? CHARDEV(obj) : NULL;
807 }
808 
809 QemuOptsList qemu_chardev_opts = {
810     .name = "chardev",
811     .implied_opt_name = "backend",
812     .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
813     .desc = {
814         {
815             .name = "backend",
816             .type = QEMU_OPT_STRING,
817         },{
818             .name = "path",
819             .type = QEMU_OPT_STRING,
820         },{
821             .name = "input-path",
822             .type = QEMU_OPT_STRING,
823         },{
824             .name = "host",
825             .type = QEMU_OPT_STRING,
826         },{
827             .name = "port",
828             .type = QEMU_OPT_STRING,
829         },{
830             .name = "fd",
831             .type = QEMU_OPT_STRING,
832         },{
833             .name = "localaddr",
834             .type = QEMU_OPT_STRING,
835         },{
836             .name = "localport",
837             .type = QEMU_OPT_STRING,
838         },{
839             .name = "to",
840             .type = QEMU_OPT_NUMBER,
841         },{
842             .name = "ipv4",
843             .type = QEMU_OPT_BOOL,
844         },{
845             .name = "ipv6",
846             .type = QEMU_OPT_BOOL,
847         },{
848             .name = "wait",
849             .type = QEMU_OPT_BOOL,
850         },{
851             .name = "server",
852             .type = QEMU_OPT_BOOL,
853         },{
854             .name = "delay",
855             .type = QEMU_OPT_BOOL,
856         },{
857             .name = "nodelay",
858             .type = QEMU_OPT_BOOL,
859         },{
860             .name = "reconnect",
861             .type = QEMU_OPT_NUMBER,
862         },{
863             .name = "telnet",
864             .type = QEMU_OPT_BOOL,
865         },{
866             .name = "tn3270",
867             .type = QEMU_OPT_BOOL,
868         },{
869             .name = "tls-creds",
870             .type = QEMU_OPT_STRING,
871         },{
872             .name = "tls-authz",
873             .type = QEMU_OPT_STRING,
874         },{
875             .name = "websocket",
876             .type = QEMU_OPT_BOOL,
877         },{
878             .name = "width",
879             .type = QEMU_OPT_NUMBER,
880         },{
881             .name = "height",
882             .type = QEMU_OPT_NUMBER,
883         },{
884             .name = "cols",
885             .type = QEMU_OPT_NUMBER,
886         },{
887             .name = "rows",
888             .type = QEMU_OPT_NUMBER,
889         },{
890             .name = "mux",
891             .type = QEMU_OPT_BOOL,
892         },{
893             .name = "signal",
894             .type = QEMU_OPT_BOOL,
895         },{
896             .name = "name",
897             .type = QEMU_OPT_STRING,
898         },{
899             .name = "debug",
900             .type = QEMU_OPT_NUMBER,
901         },{
902             .name = "size",
903             .type = QEMU_OPT_SIZE,
904         },{
905             .name = "chardev",
906             .type = QEMU_OPT_STRING,
907         },{
908             .name = "append",
909             .type = QEMU_OPT_BOOL,
910         },{
911             .name = "logfile",
912             .type = QEMU_OPT_STRING,
913         },{
914             .name = "logappend",
915             .type = QEMU_OPT_BOOL,
916         },{
917             .name = "mouse",
918             .type = QEMU_OPT_BOOL,
919         },{
920             .name = "clipboard",
921             .type = QEMU_OPT_BOOL,
922 #ifdef CONFIG_LINUX
923         },{
924             .name = "tight",
925             .type = QEMU_OPT_BOOL,
926             .def_value_str = "on",
927         },{
928             .name = "abstract",
929             .type = QEMU_OPT_BOOL,
930 #endif
931         },
932         { /* end of list */ }
933     },
934 };
935 
936 bool qemu_chr_has_feature(Chardev *chr,
937                           ChardevFeature feature)
938 {
939     return test_bit(feature, chr->features);
940 }
941 
942 void qemu_chr_set_feature(Chardev *chr,
943                            ChardevFeature feature)
944 {
945     return set_bit(feature, chr->features);
946 }
947 
948 static Chardev *chardev_new(const char *id, const char *typename,
949                             ChardevBackend *backend,
950                             GMainContext *gcontext,
951                             bool handover_yank_instance,
952                             Error **errp)
953 {
954     Object *obj;
955     Chardev *chr = NULL;
956     Error *local_err = NULL;
957     bool be_opened = true;
958 
959     assert(g_str_has_prefix(typename, "chardev-"));
960     assert(id);
961 
962     obj = object_new(typename);
963     chr = CHARDEV(obj);
964     chr->handover_yank_instance = handover_yank_instance;
965     chr->label = g_strdup(id);
966     chr->gcontext = gcontext;
967 
968     qemu_char_open(chr, backend, &be_opened, &local_err);
969     if (local_err) {
970         error_propagate(errp, local_err);
971         object_unref(obj);
972         return NULL;
973     }
974 
975     if (!chr->filename) {
976         chr->filename = g_strdup(typename + 8);
977     }
978     if (be_opened) {
979         qemu_chr_be_event(chr, CHR_EVENT_OPENED);
980     }
981 
982     return chr;
983 }
984 
985 Chardev *qemu_chardev_new(const char *id, const char *typename,
986                           ChardevBackend *backend,
987                           GMainContext *gcontext,
988                           Error **errp)
989 {
990     Chardev *chr;
991     g_autofree char *genid = NULL;
992 
993     if (!id) {
994         genid = id_generate(ID_CHR);
995         id = genid;
996     }
997 
998     chr = chardev_new(id, typename, backend, gcontext, false, errp);
999     if (!chr) {
1000         return NULL;
1001     }
1002 
1003     if (!object_property_try_add_child(get_chardevs_root(), id, OBJECT(chr),
1004                                        errp)) {
1005         object_unref(OBJECT(chr));
1006         return NULL;
1007     }
1008     object_unref(OBJECT(chr));
1009 
1010     return chr;
1011 }
1012 
1013 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
1014                                Error **errp)
1015 {
1016     ERRP_GUARD();
1017     const ChardevClass *cc;
1018     ChardevReturn *ret;
1019     g_autoptr(Chardev) chr = NULL;
1020 
1021     if (qemu_chr_find(id)) {
1022         error_setg(errp, "Chardev with id '%s' already exists", id);
1023         return NULL;
1024     }
1025 
1026     cc = char_get_class(ChardevBackendKind_str(backend->type), errp);
1027     if (!cc) {
1028         goto err;
1029     }
1030 
1031     chr = chardev_new(id, object_class_get_name(OBJECT_CLASS(cc)),
1032                       backend, NULL, false, errp);
1033     if (!chr) {
1034         goto err;
1035     }
1036 
1037     if (!object_property_try_add_child(get_chardevs_root(), id, OBJECT(chr),
1038                                        errp)) {
1039         goto err;
1040     }
1041 
1042     ret = g_new0(ChardevReturn, 1);
1043     if (CHARDEV_IS_PTY(chr)) {
1044         ret->pty = g_strdup(chr->filename + 4);
1045     }
1046 
1047     return ret;
1048 
1049 err:
1050     error_prepend(errp, "Failed to add chardev '%s': ", id);
1051     return NULL;
1052 }
1053 
1054 ChardevReturn *qmp_chardev_change(const char *id, ChardevBackend *backend,
1055                                   Error **errp)
1056 {
1057     CharBackend *be;
1058     const ChardevClass *cc, *cc_new;
1059     Chardev *chr, *chr_new;
1060     bool closed_sent = false;
1061     bool handover_yank_instance;
1062     ChardevReturn *ret;
1063 
1064     chr = qemu_chr_find(id);
1065     if (!chr) {
1066         error_setg(errp, "Chardev '%s' does not exist", id);
1067         return NULL;
1068     }
1069 
1070     if (CHARDEV_IS_MUX(chr)) {
1071         error_setg(errp, "Mux device hotswap not supported yet");
1072         return NULL;
1073     }
1074 
1075     if (qemu_chr_replay(chr)) {
1076         error_setg(errp,
1077             "Chardev '%s' cannot be changed in record/replay mode", id);
1078         return NULL;
1079     }
1080 
1081     be = chr->be;
1082     if (!be) {
1083         /* easy case */
1084         object_unparent(OBJECT(chr));
1085         return qmp_chardev_add(id, backend, errp);
1086     }
1087 
1088     if (!be->chr_be_change) {
1089         error_setg(errp, "Chardev user does not support chardev hotswap");
1090         return NULL;
1091     }
1092 
1093     cc = CHARDEV_GET_CLASS(chr);
1094     cc_new = char_get_class(ChardevBackendKind_str(backend->type), errp);
1095     if (!cc_new) {
1096         return NULL;
1097     }
1098 
1099     /*
1100      * The new chardev should not register a yank instance if the current
1101      * chardev has registered one already.
1102      */
1103     handover_yank_instance = cc->supports_yank && cc_new->supports_yank;
1104 
1105     chr_new = chardev_new(id, object_class_get_name(OBJECT_CLASS(cc_new)),
1106                           backend, chr->gcontext, handover_yank_instance, errp);
1107     if (!chr_new) {
1108         return NULL;
1109     }
1110 
1111     if (chr->be_open && !chr_new->be_open) {
1112         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1113         closed_sent = true;
1114     }
1115 
1116     chr->be = NULL;
1117     qemu_chr_fe_init(be, chr_new, &error_abort);
1118 
1119     if (be->chr_be_change(be->opaque) < 0) {
1120         error_setg(errp, "Chardev '%s' change failed", chr_new->label);
1121         chr_new->be = NULL;
1122         qemu_chr_fe_init(be, chr, &error_abort);
1123         if (closed_sent) {
1124             qemu_chr_be_event(chr, CHR_EVENT_OPENED);
1125         }
1126         object_unref(OBJECT(chr_new));
1127         return NULL;
1128     }
1129 
1130     /* change successful, clean up */
1131     chr_new->handover_yank_instance = false;
1132 
1133     /*
1134      * When the old chardev is freed, it should not unregister the yank
1135      * instance if the new chardev needs it.
1136      */
1137     chr->handover_yank_instance = handover_yank_instance;
1138 
1139     object_unparent(OBJECT(chr));
1140     object_property_add_child(get_chardevs_root(), chr_new->label,
1141                               OBJECT(chr_new));
1142     object_unref(OBJECT(chr_new));
1143 
1144     ret = g_new0(ChardevReturn, 1);
1145     if (CHARDEV_IS_PTY(chr_new)) {
1146         ret->pty = g_strdup(chr_new->filename + 4);
1147     }
1148 
1149     return ret;
1150 }
1151 
1152 void qmp_chardev_remove(const char *id, Error **errp)
1153 {
1154     Chardev *chr;
1155 
1156     chr = qemu_chr_find(id);
1157     if (chr == NULL) {
1158         error_setg(errp, "Chardev '%s' not found", id);
1159         return;
1160     }
1161     if (qemu_chr_is_busy(chr)) {
1162         error_setg(errp, "Chardev '%s' is busy", id);
1163         return;
1164     }
1165     if (qemu_chr_replay(chr)) {
1166         error_setg(errp,
1167             "Chardev '%s' cannot be unplugged in record/replay mode", id);
1168         return;
1169     }
1170     object_unparent(OBJECT(chr));
1171 }
1172 
1173 void qmp_chardev_send_break(const char *id, Error **errp)
1174 {
1175     Chardev *chr;
1176 
1177     chr = qemu_chr_find(id);
1178     if (chr == NULL) {
1179         error_setg(errp, "Chardev '%s' not found", id);
1180         return;
1181     }
1182     qemu_chr_be_event(chr, CHR_EVENT_BREAK);
1183 }
1184 
1185 bool qmp_add_client_char(int fd, bool has_skipauth, bool skipauth,
1186                          bool has_tls, bool tls, const char *protocol,
1187                          Error **errp)
1188 {
1189     Chardev *s = qemu_chr_find(protocol);
1190 
1191     if (!s) {
1192         error_setg(errp, "protocol '%s' is invalid", protocol);
1193         return false;
1194     }
1195     if (qemu_chr_add_client(s, fd) < 0) {
1196         error_setg(errp, "failed to add client");
1197         return false;
1198     }
1199     return true;
1200 }
1201 
1202 /*
1203  * Add a timeout callback for the chardev (in milliseconds), return
1204  * the GSource object created. Please use this to add timeout hook for
1205  * chardev instead of g_timeout_add() and g_timeout_add_seconds(), to
1206  * make sure the gcontext that the task bound to is correct.
1207  */
1208 GSource *qemu_chr_timeout_add_ms(Chardev *chr, guint ms,
1209                                  GSourceFunc func, void *private)
1210 {
1211     GSource *source = g_timeout_source_new(ms);
1212 
1213     assert(func);
1214     g_source_set_callback(source, func, private, NULL);
1215     g_source_attach(source, chr->gcontext);
1216 
1217     return source;
1218 }
1219 
1220 void qemu_chr_cleanup(void)
1221 {
1222     object_unparent(get_chardevs_root());
1223 }
1224 
1225 static void register_types(void)
1226 {
1227     type_register_static(&char_type_info);
1228 }
1229 
1230 type_init(register_types);
1231