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