xref: /openbmc/qemu/chardev/char-socket.c (revision 354908ce)
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 "chardev/char.h"
27 #include "io/channel-socket.h"
28 #include "io/channel-tls.h"
29 #include "io/channel-websock.h"
30 #include "io/net-listener.h"
31 #include "qemu/error-report.h"
32 #include "qemu/module.h"
33 #include "qemu/option.h"
34 #include "qapi/error.h"
35 #include "qapi/clone-visitor.h"
36 #include "qapi/qapi-visit-sockets.h"
37 
38 #include "chardev/char-io.h"
39 
40 /***********************************************************/
41 /* TCP Net console */
42 
43 #define TCP_MAX_FDS 16
44 
45 typedef struct {
46     char buf[21];
47     size_t buflen;
48 } TCPChardevTelnetInit;
49 
50 typedef enum {
51     TCP_CHARDEV_STATE_DISCONNECTED,
52     TCP_CHARDEV_STATE_CONNECTING,
53     TCP_CHARDEV_STATE_CONNECTED,
54 } TCPChardevState;
55 
56 typedef struct {
57     Chardev parent;
58     QIOChannel *ioc; /* Client I/O channel */
59     QIOChannelSocket *sioc; /* Client master channel */
60     QIONetListener *listener;
61     GSource *hup_source;
62     QCryptoTLSCreds *tls_creds;
63     char *tls_authz;
64     TCPChardevState state;
65     int max_size;
66     int do_telnetopt;
67     int do_nodelay;
68     int *read_msgfds;
69     size_t read_msgfds_num;
70     int *write_msgfds;
71     size_t write_msgfds_num;
72 
73     SocketAddress *addr;
74     bool is_listen;
75     bool is_telnet;
76     bool is_tn3270;
77     GSource *telnet_source;
78     TCPChardevTelnetInit *telnet_init;
79 
80     bool is_websock;
81 
82     GSource *reconnect_timer;
83     int64_t reconnect_time;
84     bool connect_err_reported;
85 
86     QIOTask *connect_task;
87 } SocketChardev;
88 
89 #define SOCKET_CHARDEV(obj)                                     \
90     OBJECT_CHECK(SocketChardev, (obj), TYPE_CHARDEV_SOCKET)
91 
92 static gboolean socket_reconnect_timeout(gpointer opaque);
93 static void tcp_chr_telnet_init(Chardev *chr);
94 
95 static void tcp_chr_change_state(SocketChardev *s, TCPChardevState state)
96 {
97     switch (state) {
98     case TCP_CHARDEV_STATE_DISCONNECTED:
99         break;
100     case TCP_CHARDEV_STATE_CONNECTING:
101         assert(s->state == TCP_CHARDEV_STATE_DISCONNECTED);
102         break;
103     case TCP_CHARDEV_STATE_CONNECTED:
104         assert(s->state == TCP_CHARDEV_STATE_CONNECTING);
105         break;
106     }
107     s->state = state;
108 }
109 
110 static void tcp_chr_reconn_timer_cancel(SocketChardev *s)
111 {
112     if (s->reconnect_timer) {
113         g_source_destroy(s->reconnect_timer);
114         g_source_unref(s->reconnect_timer);
115         s->reconnect_timer = NULL;
116     }
117 }
118 
119 static void qemu_chr_socket_restart_timer(Chardev *chr)
120 {
121     SocketChardev *s = SOCKET_CHARDEV(chr);
122     char *name;
123 
124     assert(s->state == TCP_CHARDEV_STATE_DISCONNECTED);
125     assert(!s->reconnect_timer);
126     name = g_strdup_printf("chardev-socket-reconnect-%s", chr->label);
127     s->reconnect_timer = qemu_chr_timeout_add_ms(chr,
128                                                  s->reconnect_time * 1000,
129                                                  socket_reconnect_timeout,
130                                                  chr);
131     g_source_set_name(s->reconnect_timer, name);
132     g_free(name);
133 }
134 
135 static void check_report_connect_error(Chardev *chr,
136                                        Error *err)
137 {
138     SocketChardev *s = SOCKET_CHARDEV(chr);
139 
140     if (!s->connect_err_reported) {
141         error_reportf_err(err,
142                           "Unable to connect character device %s: ",
143                           chr->label);
144         s->connect_err_reported = true;
145     }
146     qemu_chr_socket_restart_timer(chr);
147 }
148 
149 static void tcp_chr_accept(QIONetListener *listener,
150                            QIOChannelSocket *cioc,
151                            void *opaque);
152 
153 static int tcp_chr_read_poll(void *opaque);
154 static void tcp_chr_disconnect_locked(Chardev *chr);
155 
156 /* Called with chr_write_lock held.  */
157 static int tcp_chr_write(Chardev *chr, const uint8_t *buf, int len)
158 {
159     SocketChardev *s = SOCKET_CHARDEV(chr);
160 
161     if (s->state == TCP_CHARDEV_STATE_CONNECTED) {
162         int ret =  io_channel_send_full(s->ioc, buf, len,
163                                         s->write_msgfds,
164                                         s->write_msgfds_num);
165 
166         /* free the written msgfds in any cases
167          * other than ret < 0 && errno == EAGAIN
168          */
169         if (!(ret < 0 && EAGAIN == errno)
170             && s->write_msgfds_num) {
171             g_free(s->write_msgfds);
172             s->write_msgfds = 0;
173             s->write_msgfds_num = 0;
174         }
175 
176         if (ret < 0 && errno != EAGAIN) {
177             if (tcp_chr_read_poll(chr) <= 0) {
178                 /* Perform disconnect and return error. */
179                 tcp_chr_disconnect_locked(chr);
180             } /* else let the read handler finish it properly */
181         }
182 
183         return ret;
184     } else {
185         /* Indicate an error. */
186         errno = EIO;
187         return -1;
188     }
189 }
190 
191 static int tcp_chr_read_poll(void *opaque)
192 {
193     Chardev *chr = CHARDEV(opaque);
194     SocketChardev *s = SOCKET_CHARDEV(opaque);
195     if (s->state != TCP_CHARDEV_STATE_CONNECTED) {
196         return 0;
197     }
198     s->max_size = qemu_chr_be_can_write(chr);
199     return s->max_size;
200 }
201 
202 static void tcp_chr_process_IAC_bytes(Chardev *chr,
203                                       SocketChardev *s,
204                                       uint8_t *buf, int *size)
205 {
206     /* Handle any telnet or tn3270 client's basic IAC options.
207      * For telnet options, it satisfies char by char mode with no echo.
208      * For tn3270 options, it satisfies binary mode with EOR.
209      * All IAC options will be removed from the buf and the do_opt
210      * pointer will be used to track the state of the width of the
211      * IAC information.
212      *
213      * RFC854: "All TELNET commands consist of at least a two byte sequence.
214      * The commands dealing with option negotiation are three byte sequences,
215      * the third byte being the code for the option referenced."
216      * "IAC BREAK", "IAC IP", "IAC NOP" and the double IAC are two bytes.
217      * "IAC SB", "IAC SE" and "IAC EOR" are saved to split up data boundary
218      * for tn3270.
219      * NOP, Break and Interrupt Process(IP) might be encountered during a TN3270
220      * session, and NOP and IP need to be done later.
221      */
222 
223     int i;
224     int j = 0;
225 
226     for (i = 0; i < *size; i++) {
227         if (s->do_telnetopt > 1) {
228             if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
229                 /* Double IAC means send an IAC */
230                 if (j != i) {
231                     buf[j] = buf[i];
232                 }
233                 j++;
234                 s->do_telnetopt = 1;
235             } else {
236                 if ((unsigned char)buf[i] == IAC_BREAK
237                     && s->do_telnetopt == 2) {
238                     /* Handle IAC break commands by sending a serial break */
239                     qemu_chr_be_event(chr, CHR_EVENT_BREAK);
240                     s->do_telnetopt++;
241                 } else if (s->is_tn3270 && ((unsigned char)buf[i] == IAC_EOR
242                            || (unsigned char)buf[i] == IAC_SB
243                            || (unsigned char)buf[i] == IAC_SE)
244                            && s->do_telnetopt == 2) {
245                     buf[j++] = IAC;
246                     buf[j++] = buf[i];
247                     s->do_telnetopt++;
248                 } else if (s->is_tn3270 && ((unsigned char)buf[i] == IAC_IP
249                            || (unsigned char)buf[i] == IAC_NOP)
250                            && s->do_telnetopt == 2) {
251                     /* TODO: IP and NOP need to be implemented later. */
252                     s->do_telnetopt++;
253                 }
254                 s->do_telnetopt++;
255             }
256             if (s->do_telnetopt >= 4) {
257                 s->do_telnetopt = 1;
258             }
259         } else {
260             if ((unsigned char)buf[i] == IAC) {
261                 s->do_telnetopt = 2;
262             } else {
263                 if (j != i) {
264                     buf[j] = buf[i];
265                 }
266                 j++;
267             }
268         }
269     }
270     *size = j;
271 }
272 
273 static int tcp_get_msgfds(Chardev *chr, int *fds, int num)
274 {
275     SocketChardev *s = SOCKET_CHARDEV(chr);
276 
277     int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
278 
279     assert(num <= TCP_MAX_FDS);
280 
281     if (to_copy) {
282         int i;
283 
284         memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
285 
286         /* Close unused fds */
287         for (i = to_copy; i < s->read_msgfds_num; i++) {
288             close(s->read_msgfds[i]);
289         }
290 
291         g_free(s->read_msgfds);
292         s->read_msgfds = 0;
293         s->read_msgfds_num = 0;
294     }
295 
296     return to_copy;
297 }
298 
299 static int tcp_set_msgfds(Chardev *chr, int *fds, int num)
300 {
301     SocketChardev *s = SOCKET_CHARDEV(chr);
302 
303     /* clear old pending fd array */
304     g_free(s->write_msgfds);
305     s->write_msgfds = NULL;
306     s->write_msgfds_num = 0;
307 
308     if ((s->state != TCP_CHARDEV_STATE_CONNECTED) ||
309         !qio_channel_has_feature(s->ioc,
310                                  QIO_CHANNEL_FEATURE_FD_PASS)) {
311         return -1;
312     }
313 
314     if (num) {
315         s->write_msgfds = g_new(int, num);
316         memcpy(s->write_msgfds, fds, num * sizeof(int));
317     }
318 
319     s->write_msgfds_num = num;
320 
321     return 0;
322 }
323 
324 static ssize_t tcp_chr_recv(Chardev *chr, char *buf, size_t len)
325 {
326     SocketChardev *s = SOCKET_CHARDEV(chr);
327     struct iovec iov = { .iov_base = buf, .iov_len = len };
328     int ret;
329     size_t i;
330     int *msgfds = NULL;
331     size_t msgfds_num = 0;
332 
333     if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
334         ret = qio_channel_readv_full(s->ioc, &iov, 1,
335                                      &msgfds, &msgfds_num,
336                                      NULL);
337     } else {
338         ret = qio_channel_readv_full(s->ioc, &iov, 1,
339                                      NULL, NULL,
340                                      NULL);
341     }
342 
343     if (ret == QIO_CHANNEL_ERR_BLOCK) {
344         errno = EAGAIN;
345         ret = -1;
346     } else if (ret == -1) {
347         errno = EIO;
348     }
349 
350     if (msgfds_num) {
351         /* close and clean read_msgfds */
352         for (i = 0; i < s->read_msgfds_num; i++) {
353             close(s->read_msgfds[i]);
354         }
355 
356         if (s->read_msgfds_num) {
357             g_free(s->read_msgfds);
358         }
359 
360         s->read_msgfds = msgfds;
361         s->read_msgfds_num = msgfds_num;
362     }
363 
364     for (i = 0; i < s->read_msgfds_num; i++) {
365         int fd = s->read_msgfds[i];
366         if (fd < 0) {
367             continue;
368         }
369 
370         /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
371         qemu_set_block(fd);
372 
373 #ifndef MSG_CMSG_CLOEXEC
374         qemu_set_cloexec(fd);
375 #endif
376     }
377 
378     return ret;
379 }
380 
381 static GSource *tcp_chr_add_watch(Chardev *chr, GIOCondition cond)
382 {
383     SocketChardev *s = SOCKET_CHARDEV(chr);
384     return qio_channel_create_watch(s->ioc, cond);
385 }
386 
387 static void remove_hup_source(SocketChardev *s)
388 {
389     if (s->hup_source != NULL) {
390         g_source_destroy(s->hup_source);
391         g_source_unref(s->hup_source);
392         s->hup_source = NULL;
393     }
394 }
395 
396 static void tcp_chr_free_connection(Chardev *chr)
397 {
398     SocketChardev *s = SOCKET_CHARDEV(chr);
399     int i;
400 
401     if (s->read_msgfds_num) {
402         for (i = 0; i < s->read_msgfds_num; i++) {
403             close(s->read_msgfds[i]);
404         }
405         g_free(s->read_msgfds);
406         s->read_msgfds = NULL;
407         s->read_msgfds_num = 0;
408     }
409 
410     remove_hup_source(s);
411 
412     tcp_set_msgfds(chr, NULL, 0);
413     remove_fd_in_watch(chr);
414     object_unref(OBJECT(s->sioc));
415     s->sioc = NULL;
416     object_unref(OBJECT(s->ioc));
417     s->ioc = NULL;
418     g_free(chr->filename);
419     chr->filename = NULL;
420     tcp_chr_change_state(s, TCP_CHARDEV_STATE_DISCONNECTED);
421 }
422 
423 static const char *qemu_chr_socket_protocol(SocketChardev *s)
424 {
425     if (s->is_telnet) {
426         return "telnet";
427     }
428     return s->is_websock ? "websocket" : "tcp";
429 }
430 
431 static char *qemu_chr_socket_address(SocketChardev *s, const char *prefix)
432 {
433     switch (s->addr->type) {
434     case SOCKET_ADDRESS_TYPE_INET:
435         return g_strdup_printf("%s%s:%s:%s%s", prefix,
436                                qemu_chr_socket_protocol(s),
437                                s->addr->u.inet.host,
438                                s->addr->u.inet.port,
439                                s->is_listen ? ",server" : "");
440         break;
441     case SOCKET_ADDRESS_TYPE_UNIX:
442         return g_strdup_printf("%sunix:%s%s", prefix,
443                                s->addr->u.q_unix.path,
444                                s->is_listen ? ",server" : "");
445         break;
446     case SOCKET_ADDRESS_TYPE_FD:
447         return g_strdup_printf("%sfd:%s%s", prefix, s->addr->u.fd.str,
448                                s->is_listen ? ",server" : "");
449         break;
450     case SOCKET_ADDRESS_TYPE_VSOCK:
451         return g_strdup_printf("%svsock:%s:%s", prefix,
452                                s->addr->u.vsock.cid,
453                                s->addr->u.vsock.port);
454     default:
455         abort();
456     }
457 }
458 
459 static void update_disconnected_filename(SocketChardev *s)
460 {
461     Chardev *chr = CHARDEV(s);
462 
463     g_free(chr->filename);
464     if (s->addr) {
465         chr->filename = qemu_chr_socket_address(s, "disconnected:");
466     } else {
467         chr->filename = g_strdup("disconnected:socket");
468     }
469 }
470 
471 /* NB may be called even if tcp_chr_connect has not been
472  * reached, due to TLS or telnet initialization failure,
473  * so can *not* assume s->state == TCP_CHARDEV_STATE_CONNECTED
474  * This must be called with chr->chr_write_lock held.
475  */
476 static void tcp_chr_disconnect_locked(Chardev *chr)
477 {
478     SocketChardev *s = SOCKET_CHARDEV(chr);
479     bool emit_close = s->state == TCP_CHARDEV_STATE_CONNECTED;
480 
481     tcp_chr_free_connection(chr);
482 
483     if (s->listener) {
484         qio_net_listener_set_client_func_full(s->listener, tcp_chr_accept,
485                                               chr, NULL, chr->gcontext);
486     }
487     update_disconnected_filename(s);
488     if (emit_close) {
489         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
490     }
491     if (s->reconnect_time) {
492         qemu_chr_socket_restart_timer(chr);
493     }
494 }
495 
496 static void tcp_chr_disconnect(Chardev *chr)
497 {
498     qemu_mutex_lock(&chr->chr_write_lock);
499     tcp_chr_disconnect_locked(chr);
500     qemu_mutex_unlock(&chr->chr_write_lock);
501 }
502 
503 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
504 {
505     Chardev *chr = CHARDEV(opaque);
506     SocketChardev *s = SOCKET_CHARDEV(opaque);
507     uint8_t buf[CHR_READ_BUF_LEN];
508     int len, size;
509 
510     if ((s->state != TCP_CHARDEV_STATE_CONNECTED) ||
511         s->max_size <= 0) {
512         return TRUE;
513     }
514     len = sizeof(buf);
515     if (len > s->max_size) {
516         len = s->max_size;
517     }
518     size = tcp_chr_recv(chr, (void *)buf, len);
519     if (size == 0 || (size == -1 && errno != EAGAIN)) {
520         /* connection closed */
521         tcp_chr_disconnect(chr);
522     } else if (size > 0) {
523         if (s->do_telnetopt) {
524             tcp_chr_process_IAC_bytes(chr, s, buf, &size);
525         }
526         if (size > 0) {
527             qemu_chr_be_write(chr, buf, size);
528         }
529     }
530 
531     return TRUE;
532 }
533 
534 static gboolean tcp_chr_hup(QIOChannel *channel,
535                                GIOCondition cond,
536                                void *opaque)
537 {
538     Chardev *chr = CHARDEV(opaque);
539     tcp_chr_disconnect(chr);
540     return G_SOURCE_REMOVE;
541 }
542 
543 static int tcp_chr_sync_read(Chardev *chr, const uint8_t *buf, int len)
544 {
545     SocketChardev *s = SOCKET_CHARDEV(chr);
546     int size;
547 
548     if (s->state != TCP_CHARDEV_STATE_CONNECTED) {
549         return 0;
550     }
551 
552     qio_channel_set_blocking(s->ioc, true, NULL);
553     size = tcp_chr_recv(chr, (void *) buf, len);
554     if (s->state != TCP_CHARDEV_STATE_DISCONNECTED) {
555         qio_channel_set_blocking(s->ioc, false, NULL);
556     }
557     if (size == 0) {
558         /* connection closed */
559         tcp_chr_disconnect(chr);
560     }
561 
562     return size;
563 }
564 
565 static char *qemu_chr_compute_filename(SocketChardev *s)
566 {
567     struct sockaddr_storage *ss = &s->sioc->localAddr;
568     struct sockaddr_storage *ps = &s->sioc->remoteAddr;
569     socklen_t ss_len = s->sioc->localAddrLen;
570     socklen_t ps_len = s->sioc->remoteAddrLen;
571     char shost[NI_MAXHOST], sserv[NI_MAXSERV];
572     char phost[NI_MAXHOST], pserv[NI_MAXSERV];
573     const char *left = "", *right = "";
574 
575     switch (ss->ss_family) {
576 #ifndef _WIN32
577     case AF_UNIX:
578         return g_strdup_printf("unix:%s%s",
579                                ((struct sockaddr_un *)(ss))->sun_path,
580                                s->is_listen ? ",server" : "");
581 #endif
582     case AF_INET6:
583         left  = "[";
584         right = "]";
585         /* fall through */
586     case AF_INET:
587         getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
588                     sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
589         getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
590                     pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
591         return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
592                                qemu_chr_socket_protocol(s),
593                                left, shost, right, sserv,
594                                s->is_listen ? ",server" : "",
595                                left, phost, right, pserv);
596 
597     default:
598         return g_strdup_printf("unknown");
599     }
600 }
601 
602 static void update_ioc_handlers(SocketChardev *s)
603 {
604     Chardev *chr = CHARDEV(s);
605 
606     if (s->state != TCP_CHARDEV_STATE_CONNECTED) {
607         return;
608     }
609 
610     remove_fd_in_watch(chr);
611     chr->gsource = io_add_watch_poll(chr, s->ioc,
612                                      tcp_chr_read_poll,
613                                      tcp_chr_read, chr,
614                                      chr->gcontext);
615 
616     remove_hup_source(s);
617     s->hup_source = qio_channel_create_watch(s->ioc, G_IO_HUP);
618     g_source_set_callback(s->hup_source, (GSourceFunc)tcp_chr_hup,
619                           chr, NULL);
620     g_source_attach(s->hup_source, chr->gcontext);
621 }
622 
623 static void tcp_chr_connect(void *opaque)
624 {
625     Chardev *chr = CHARDEV(opaque);
626     SocketChardev *s = SOCKET_CHARDEV(opaque);
627 
628     g_free(chr->filename);
629     chr->filename = qemu_chr_compute_filename(s);
630 
631     tcp_chr_change_state(s, TCP_CHARDEV_STATE_CONNECTED);
632     update_ioc_handlers(s);
633     qemu_chr_be_event(chr, CHR_EVENT_OPENED);
634 }
635 
636 static void tcp_chr_telnet_destroy(SocketChardev *s)
637 {
638     if (s->telnet_source) {
639         g_source_destroy(s->telnet_source);
640         g_source_unref(s->telnet_source);
641         s->telnet_source = NULL;
642     }
643 }
644 
645 static void tcp_chr_update_read_handler(Chardev *chr)
646 {
647     SocketChardev *s = SOCKET_CHARDEV(chr);
648 
649     if (s->listener && s->state == TCP_CHARDEV_STATE_DISCONNECTED) {
650         /*
651          * It's possible that chardev context is changed in
652          * qemu_chr_be_update_read_handlers().  Reset it for QIO net
653          * listener if there is.
654          */
655         qio_net_listener_set_client_func_full(s->listener, tcp_chr_accept,
656                                               chr, NULL, chr->gcontext);
657     }
658 
659     if (s->telnet_source) {
660         tcp_chr_telnet_init(CHARDEV(s));
661     }
662 
663     update_ioc_handlers(s);
664 }
665 
666 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
667                                        GIOCondition cond G_GNUC_UNUSED,
668                                        gpointer user_data)
669 {
670     SocketChardev *s = user_data;
671     Chardev *chr = CHARDEV(s);
672     TCPChardevTelnetInit *init = s->telnet_init;
673     ssize_t ret;
674 
675     assert(init);
676 
677     ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
678     if (ret < 0) {
679         if (ret == QIO_CHANNEL_ERR_BLOCK) {
680             ret = 0;
681         } else {
682             tcp_chr_disconnect(chr);
683             goto end;
684         }
685     }
686     init->buflen -= ret;
687 
688     if (init->buflen == 0) {
689         tcp_chr_connect(chr);
690         goto end;
691     }
692 
693     memmove(init->buf, init->buf + ret, init->buflen);
694 
695     return G_SOURCE_CONTINUE;
696 
697 end:
698     g_free(s->telnet_init);
699     s->telnet_init = NULL;
700     g_source_unref(s->telnet_source);
701     s->telnet_source = NULL;
702     return G_SOURCE_REMOVE;
703 }
704 
705 static void tcp_chr_telnet_init(Chardev *chr)
706 {
707     SocketChardev *s = SOCKET_CHARDEV(chr);
708     TCPChardevTelnetInit *init;
709     size_t n = 0;
710 
711     /* Destroy existing task */
712     tcp_chr_telnet_destroy(s);
713 
714     if (s->telnet_init) {
715         /* We are possibly during a handshake already */
716         goto cont;
717     }
718 
719     s->telnet_init = g_new0(TCPChardevTelnetInit, 1);
720     init = s->telnet_init;
721 
722 #define IACSET(x, a, b, c)                      \
723     do {                                        \
724         x[n++] = a;                             \
725         x[n++] = b;                             \
726         x[n++] = c;                             \
727     } while (0)
728 
729     if (!s->is_tn3270) {
730         init->buflen = 12;
731         /* Prep the telnet negotion to put telnet in binary,
732          * no echo, single char mode */
733         IACSET(init->buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
734         IACSET(init->buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
735         IACSET(init->buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
736         IACSET(init->buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
737     } else {
738         init->buflen = 21;
739         /* Prep the TN3270 negotion based on RFC1576 */
740         IACSET(init->buf, 0xff, 0xfd, 0x19);  /* IAC DO EOR */
741         IACSET(init->buf, 0xff, 0xfb, 0x19);  /* IAC WILL EOR */
742         IACSET(init->buf, 0xff, 0xfd, 0x00);  /* IAC DO BINARY */
743         IACSET(init->buf, 0xff, 0xfb, 0x00);  /* IAC WILL BINARY */
744         IACSET(init->buf, 0xff, 0xfd, 0x18);  /* IAC DO TERMINAL TYPE */
745         IACSET(init->buf, 0xff, 0xfa, 0x18);  /* IAC SB TERMINAL TYPE */
746         IACSET(init->buf, 0x01, 0xff, 0xf0);  /* SEND IAC SE */
747     }
748 
749 #undef IACSET
750 
751 cont:
752     s->telnet_source = qio_channel_add_watch_source(s->ioc, G_IO_OUT,
753                                                     tcp_chr_telnet_init_io,
754                                                     s, NULL,
755                                                     chr->gcontext);
756 }
757 
758 
759 static void tcp_chr_websock_handshake(QIOTask *task, gpointer user_data)
760 {
761     Chardev *chr = user_data;
762     SocketChardev *s = user_data;
763 
764     if (qio_task_propagate_error(task, NULL)) {
765         tcp_chr_disconnect(chr);
766     } else {
767         if (s->do_telnetopt) {
768             tcp_chr_telnet_init(chr);
769         } else {
770             tcp_chr_connect(chr);
771         }
772     }
773 }
774 
775 
776 static void tcp_chr_websock_init(Chardev *chr)
777 {
778     SocketChardev *s = SOCKET_CHARDEV(chr);
779     QIOChannelWebsock *wioc = NULL;
780     gchar *name;
781 
782     wioc = qio_channel_websock_new_server(s->ioc);
783 
784     name = g_strdup_printf("chardev-websocket-server-%s", chr->label);
785     qio_channel_set_name(QIO_CHANNEL(wioc), name);
786     g_free(name);
787     object_unref(OBJECT(s->ioc));
788     s->ioc = QIO_CHANNEL(wioc);
789 
790     qio_channel_websock_handshake(wioc, tcp_chr_websock_handshake, chr, NULL);
791 }
792 
793 
794 static void tcp_chr_tls_handshake(QIOTask *task,
795                                   gpointer user_data)
796 {
797     Chardev *chr = user_data;
798     SocketChardev *s = user_data;
799 
800     if (qio_task_propagate_error(task, NULL)) {
801         tcp_chr_disconnect(chr);
802     } else {
803         if (s->is_websock) {
804             tcp_chr_websock_init(chr);
805         } else if (s->do_telnetopt) {
806             tcp_chr_telnet_init(chr);
807         } else {
808             tcp_chr_connect(chr);
809         }
810     }
811 }
812 
813 
814 static void tcp_chr_tls_init(Chardev *chr)
815 {
816     SocketChardev *s = SOCKET_CHARDEV(chr);
817     QIOChannelTLS *tioc;
818     Error *err = NULL;
819     gchar *name;
820 
821     if (s->is_listen) {
822         tioc = qio_channel_tls_new_server(
823             s->ioc, s->tls_creds,
824             s->tls_authz,
825             &err);
826     } else {
827         tioc = qio_channel_tls_new_client(
828             s->ioc, s->tls_creds,
829             s->addr->u.inet.host,
830             &err);
831     }
832     if (tioc == NULL) {
833         error_free(err);
834         tcp_chr_disconnect(chr);
835         return;
836     }
837     name = g_strdup_printf("chardev-tls-%s-%s",
838                            s->is_listen ? "server" : "client",
839                            chr->label);
840     qio_channel_set_name(QIO_CHANNEL(tioc), name);
841     g_free(name);
842     object_unref(OBJECT(s->ioc));
843     s->ioc = QIO_CHANNEL(tioc);
844 
845     qio_channel_tls_handshake(tioc,
846                               tcp_chr_tls_handshake,
847                               chr,
848                               NULL,
849                               chr->gcontext);
850 }
851 
852 
853 static void tcp_chr_set_client_ioc_name(Chardev *chr,
854                                         QIOChannelSocket *sioc)
855 {
856     SocketChardev *s = SOCKET_CHARDEV(chr);
857     char *name;
858     name = g_strdup_printf("chardev-tcp-%s-%s",
859                            s->is_listen ? "server" : "client",
860                            chr->label);
861     qio_channel_set_name(QIO_CHANNEL(sioc), name);
862     g_free(name);
863 
864 }
865 
866 static int tcp_chr_new_client(Chardev *chr, QIOChannelSocket *sioc)
867 {
868     SocketChardev *s = SOCKET_CHARDEV(chr);
869 
870     if (s->state != TCP_CHARDEV_STATE_CONNECTING) {
871         return -1;
872     }
873 
874     s->ioc = QIO_CHANNEL(sioc);
875     object_ref(OBJECT(sioc));
876     s->sioc = sioc;
877     object_ref(OBJECT(sioc));
878 
879     qio_channel_set_blocking(s->ioc, false, NULL);
880 
881     if (s->do_nodelay) {
882         qio_channel_set_delay(s->ioc, false);
883     }
884     if (s->listener) {
885         qio_net_listener_set_client_func_full(s->listener, NULL, NULL,
886                                               NULL, chr->gcontext);
887     }
888 
889     if (s->tls_creds) {
890         tcp_chr_tls_init(chr);
891     } else if (s->is_websock) {
892         tcp_chr_websock_init(chr);
893     } else if (s->do_telnetopt) {
894         tcp_chr_telnet_init(chr);
895     } else {
896         tcp_chr_connect(chr);
897     }
898 
899     return 0;
900 }
901 
902 
903 static int tcp_chr_add_client(Chardev *chr, int fd)
904 {
905     int ret;
906     QIOChannelSocket *sioc;
907     SocketChardev *s = SOCKET_CHARDEV(chr);
908 
909     if (s->state != TCP_CHARDEV_STATE_DISCONNECTED) {
910         return -1;
911     }
912 
913     sioc = qio_channel_socket_new_fd(fd, NULL);
914     if (!sioc) {
915         return -1;
916     }
917     tcp_chr_change_state(s, TCP_CHARDEV_STATE_CONNECTING);
918     tcp_chr_set_client_ioc_name(chr, sioc);
919     ret = tcp_chr_new_client(chr, sioc);
920     object_unref(OBJECT(sioc));
921     return ret;
922 }
923 
924 static void tcp_chr_accept(QIONetListener *listener,
925                            QIOChannelSocket *cioc,
926                            void *opaque)
927 {
928     Chardev *chr = CHARDEV(opaque);
929     SocketChardev *s = SOCKET_CHARDEV(chr);
930 
931     tcp_chr_change_state(s, TCP_CHARDEV_STATE_CONNECTING);
932     tcp_chr_set_client_ioc_name(chr, cioc);
933     tcp_chr_new_client(chr, cioc);
934 }
935 
936 
937 static int tcp_chr_connect_client_sync(Chardev *chr, Error **errp)
938 {
939     SocketChardev *s = SOCKET_CHARDEV(chr);
940     QIOChannelSocket *sioc = qio_channel_socket_new();
941     tcp_chr_change_state(s, TCP_CHARDEV_STATE_CONNECTING);
942     tcp_chr_set_client_ioc_name(chr, sioc);
943     if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
944         tcp_chr_change_state(s, TCP_CHARDEV_STATE_DISCONNECTED);
945         object_unref(OBJECT(sioc));
946         return -1;
947     }
948     tcp_chr_new_client(chr, sioc);
949     object_unref(OBJECT(sioc));
950     return 0;
951 }
952 
953 
954 static void tcp_chr_accept_server_sync(Chardev *chr)
955 {
956     SocketChardev *s = SOCKET_CHARDEV(chr);
957     QIOChannelSocket *sioc;
958     info_report("QEMU waiting for connection on: %s",
959                 chr->filename);
960     tcp_chr_change_state(s, TCP_CHARDEV_STATE_CONNECTING);
961     sioc = qio_net_listener_wait_client(s->listener);
962     tcp_chr_set_client_ioc_name(chr, sioc);
963     tcp_chr_new_client(chr, sioc);
964     object_unref(OBJECT(sioc));
965 }
966 
967 
968 static int tcp_chr_wait_connected(Chardev *chr, Error **errp)
969 {
970     SocketChardev *s = SOCKET_CHARDEV(chr);
971     const char *opts[] = { "telnet", "tn3270", "websock", "tls-creds" };
972     bool optset[] = { s->is_telnet, s->is_tn3270, s->is_websock, s->tls_creds };
973     size_t i;
974 
975     QEMU_BUILD_BUG_ON(G_N_ELEMENTS(opts) != G_N_ELEMENTS(optset));
976     for (i = 0; i < G_N_ELEMENTS(opts); i++) {
977         if (optset[i]) {
978             error_setg(errp,
979                        "'%s' option is incompatible with waiting for "
980                        "connection completion", opts[i]);
981             return -1;
982         }
983     }
984 
985     tcp_chr_reconn_timer_cancel(s);
986 
987     /*
988      * We expect states to be as follows:
989      *
990      *  - server
991      *    - wait   -> CONNECTED
992      *    - nowait -> DISCONNECTED
993      *  - client
994      *    - reconnect == 0 -> CONNECTED
995      *    - reconnect != 0 -> CONNECTING
996      *
997      */
998     if (s->state == TCP_CHARDEV_STATE_CONNECTING) {
999         if (!s->connect_task) {
1000             error_setg(errp,
1001                        "Unexpected 'connecting' state without connect task "
1002                        "while waiting for connection completion");
1003             return -1;
1004         }
1005         /*
1006          * tcp_chr_wait_connected should only ever be run from the
1007          * main loop thread associated with chr->gcontext, otherwise
1008          * qio_task_wait_thread has a dangerous race condition with
1009          * free'ing of the s->connect_task object.
1010          *
1011          * Acquiring the main context doesn't 100% prove we're in
1012          * the main loop thread, but it does at least guarantee
1013          * that the main loop won't be executed by another thread
1014          * avoiding the race condition with the task idle callback.
1015          */
1016         g_main_context_acquire(chr->gcontext);
1017         qio_task_wait_thread(s->connect_task);
1018         g_main_context_release(chr->gcontext);
1019 
1020         /*
1021          * The completion callback (qemu_chr_socket_connected) for
1022          * s->connect_task should have set this to NULL by the time
1023          * qio_task_wait_thread has returned.
1024          */
1025         assert(!s->connect_task);
1026 
1027         /*
1028          * NB we are *not* guaranteed to have "s->state == ..CONNECTED"
1029          * at this point as this first connect may be failed, so
1030          * allow the next loop to run regardless.
1031          */
1032     }
1033 
1034     while (s->state != TCP_CHARDEV_STATE_CONNECTED) {
1035         if (s->is_listen) {
1036             tcp_chr_accept_server_sync(chr);
1037         } else {
1038             Error *err = NULL;
1039             if (tcp_chr_connect_client_sync(chr, &err) < 0) {
1040                 if (s->reconnect_time) {
1041                     error_free(err);
1042                     g_usleep(s->reconnect_time * 1000ULL * 1000ULL);
1043                 } else {
1044                     error_propagate(errp, err);
1045                     return -1;
1046                 }
1047             }
1048         }
1049     }
1050 
1051     return 0;
1052 }
1053 
1054 static void char_socket_finalize(Object *obj)
1055 {
1056     Chardev *chr = CHARDEV(obj);
1057     SocketChardev *s = SOCKET_CHARDEV(obj);
1058 
1059     tcp_chr_free_connection(chr);
1060     tcp_chr_reconn_timer_cancel(s);
1061     qapi_free_SocketAddress(s->addr);
1062     tcp_chr_telnet_destroy(s);
1063     g_free(s->telnet_init);
1064     if (s->listener) {
1065         qio_net_listener_set_client_func_full(s->listener, NULL, NULL,
1066                                               NULL, chr->gcontext);
1067         object_unref(OBJECT(s->listener));
1068     }
1069     if (s->tls_creds) {
1070         object_unref(OBJECT(s->tls_creds));
1071     }
1072     g_free(s->tls_authz);
1073 
1074     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1075 }
1076 
1077 static void qemu_chr_socket_connected(QIOTask *task, void *opaque)
1078 {
1079     QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(qio_task_get_source(task));
1080     Chardev *chr = CHARDEV(opaque);
1081     SocketChardev *s = SOCKET_CHARDEV(chr);
1082     Error *err = NULL;
1083 
1084     s->connect_task = NULL;
1085 
1086     if (qio_task_propagate_error(task, &err)) {
1087         tcp_chr_change_state(s, TCP_CHARDEV_STATE_DISCONNECTED);
1088         check_report_connect_error(chr, err);
1089         error_free(err);
1090         goto cleanup;
1091     }
1092 
1093     s->connect_err_reported = false;
1094     tcp_chr_new_client(chr, sioc);
1095 
1096 cleanup:
1097     object_unref(OBJECT(sioc));
1098 }
1099 
1100 
1101 static void tcp_chr_connect_client_task(QIOTask *task,
1102                                         gpointer opaque)
1103 {
1104     QIOChannelSocket *ioc = QIO_CHANNEL_SOCKET(qio_task_get_source(task));
1105     SocketAddress *addr = opaque;
1106     Error *err = NULL;
1107 
1108     qio_channel_socket_connect_sync(ioc, addr, &err);
1109 
1110     qio_task_set_error(task, err);
1111 }
1112 
1113 
1114 static void tcp_chr_connect_client_async(Chardev *chr)
1115 {
1116     SocketChardev *s = SOCKET_CHARDEV(chr);
1117     QIOChannelSocket *sioc;
1118 
1119     tcp_chr_change_state(s, TCP_CHARDEV_STATE_CONNECTING);
1120     sioc = qio_channel_socket_new();
1121     tcp_chr_set_client_ioc_name(chr, sioc);
1122     /*
1123      * Normally code would use the qio_channel_socket_connect_async
1124      * method which uses a QIOTask + qio_task_set_error internally
1125      * to avoid blocking. The tcp_chr_wait_connected method, however,
1126      * needs a way to synchronize with completion of the background
1127      * connect task which can't be done with the QIOChannelSocket
1128      * async APIs. Thus we must use QIOTask directly to implement
1129      * the non-blocking concept locally.
1130      */
1131     s->connect_task = qio_task_new(OBJECT(sioc),
1132                                    qemu_chr_socket_connected,
1133                                    chr, NULL);
1134     qio_task_run_in_thread(s->connect_task,
1135                            tcp_chr_connect_client_task,
1136                            s->addr,
1137                            NULL,
1138                            chr->gcontext);
1139 }
1140 
1141 static gboolean socket_reconnect_timeout(gpointer opaque)
1142 {
1143     Chardev *chr = CHARDEV(opaque);
1144     SocketChardev *s = SOCKET_CHARDEV(opaque);
1145 
1146     qemu_mutex_lock(&chr->chr_write_lock);
1147     g_source_unref(s->reconnect_timer);
1148     s->reconnect_timer = NULL;
1149     qemu_mutex_unlock(&chr->chr_write_lock);
1150 
1151     if (chr->be_open) {
1152         return false;
1153     }
1154 
1155     tcp_chr_connect_client_async(chr);
1156 
1157     return false;
1158 }
1159 
1160 
1161 static int qmp_chardev_open_socket_server(Chardev *chr,
1162                                           bool is_telnet,
1163                                           bool is_waitconnect,
1164                                           Error **errp)
1165 {
1166     SocketChardev *s = SOCKET_CHARDEV(chr);
1167     char *name;
1168     if (is_telnet) {
1169         s->do_telnetopt = 1;
1170     }
1171     s->listener = qio_net_listener_new();
1172 
1173     name = g_strdup_printf("chardev-tcp-listener-%s", chr->label);
1174     qio_net_listener_set_name(s->listener, name);
1175     g_free(name);
1176 
1177     if (qio_net_listener_open_sync(s->listener, s->addr, 1, errp) < 0) {
1178         object_unref(OBJECT(s->listener));
1179         s->listener = NULL;
1180         return -1;
1181     }
1182 
1183     qapi_free_SocketAddress(s->addr);
1184     s->addr = socket_local_address(s->listener->sioc[0]->fd, errp);
1185     update_disconnected_filename(s);
1186 
1187     if (is_waitconnect) {
1188         tcp_chr_accept_server_sync(chr);
1189     } else {
1190         qio_net_listener_set_client_func_full(s->listener,
1191                                               tcp_chr_accept,
1192                                               chr, NULL,
1193                                               chr->gcontext);
1194     }
1195 
1196     return 0;
1197 }
1198 
1199 
1200 static int qmp_chardev_open_socket_client(Chardev *chr,
1201                                           int64_t reconnect,
1202                                           Error **errp)
1203 {
1204     SocketChardev *s = SOCKET_CHARDEV(chr);
1205 
1206     if (reconnect > 0) {
1207         s->reconnect_time = reconnect;
1208         tcp_chr_connect_client_async(chr);
1209         return 0;
1210     } else {
1211         return tcp_chr_connect_client_sync(chr, errp);
1212     }
1213 }
1214 
1215 
1216 static bool qmp_chardev_validate_socket(ChardevSocket *sock,
1217                                         SocketAddress *addr,
1218                                         Error **errp)
1219 {
1220     /* Validate any options which have a dependency on address type */
1221     switch (addr->type) {
1222     case SOCKET_ADDRESS_TYPE_FD:
1223         if (sock->has_reconnect) {
1224             error_setg(errp,
1225                        "'reconnect' option is incompatible with "
1226                        "'fd' address type");
1227             return false;
1228         }
1229         if (sock->has_tls_creds &&
1230             !(sock->has_server && sock->server)) {
1231             error_setg(errp,
1232                        "'tls_creds' option is incompatible with "
1233                        "'fd' address type as client");
1234             return false;
1235         }
1236         break;
1237 
1238     case SOCKET_ADDRESS_TYPE_UNIX:
1239         if (sock->has_tls_creds) {
1240             error_setg(errp,
1241                        "'tls_creds' option is incompatible with "
1242                        "'unix' address type");
1243             return false;
1244         }
1245         break;
1246 
1247     case SOCKET_ADDRESS_TYPE_INET:
1248         break;
1249 
1250     case SOCKET_ADDRESS_TYPE_VSOCK:
1251         if (sock->has_tls_creds) {
1252             error_setg(errp,
1253                        "'tls_creds' option is incompatible with "
1254                        "'vsock' address type");
1255             return false;
1256         }
1257 
1258     default:
1259         break;
1260     }
1261 
1262     if (sock->has_tls_authz && !sock->has_tls_creds) {
1263         error_setg(errp, "'tls_authz' option requires 'tls_creds' option");
1264         return false;
1265     }
1266 
1267     /* Validate any options which have a dependancy on client vs server */
1268     if (!sock->has_server || sock->server) {
1269         if (sock->has_reconnect) {
1270             error_setg(errp,
1271                        "'reconnect' option is incompatible with "
1272                        "socket in server listen mode");
1273             return false;
1274         }
1275     } else {
1276         if (sock->has_websocket && sock->websocket) {
1277             error_setg(errp, "%s", "Websocket client is not implemented");
1278             return false;
1279         }
1280         if (sock->has_wait) {
1281             warn_report("'wait' option is deprecated with "
1282                         "socket in client connect mode");
1283             if (sock->wait) {
1284                 error_setg(errp, "%s",
1285                            "'wait' option is incompatible with "
1286                            "socket in client connect mode");
1287                 return false;
1288             }
1289         }
1290     }
1291 
1292     return true;
1293 }
1294 
1295 
1296 static void qmp_chardev_open_socket(Chardev *chr,
1297                                     ChardevBackend *backend,
1298                                     bool *be_opened,
1299                                     Error **errp)
1300 {
1301     SocketChardev *s = SOCKET_CHARDEV(chr);
1302     ChardevSocket *sock = backend->u.socket.data;
1303     bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;
1304     bool is_listen      = sock->has_server  ? sock->server  : true;
1305     bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;
1306     bool is_tn3270      = sock->has_tn3270  ? sock->tn3270  : false;
1307     bool is_waitconnect = sock->has_wait    ? sock->wait    : false;
1308     bool is_websock     = sock->has_websocket ? sock->websocket : false;
1309     int64_t reconnect   = sock->has_reconnect ? sock->reconnect : 0;
1310     SocketAddress *addr;
1311 
1312     s->is_listen = is_listen;
1313     s->is_telnet = is_telnet;
1314     s->is_tn3270 = is_tn3270;
1315     s->is_websock = is_websock;
1316     s->do_nodelay = do_nodelay;
1317     if (sock->tls_creds) {
1318         Object *creds;
1319         creds = object_resolve_path_component(
1320             object_get_objects_root(), sock->tls_creds);
1321         if (!creds) {
1322             error_setg(errp, "No TLS credentials with id '%s'",
1323                        sock->tls_creds);
1324             return;
1325         }
1326         s->tls_creds = (QCryptoTLSCreds *)
1327             object_dynamic_cast(creds,
1328                                 TYPE_QCRYPTO_TLS_CREDS);
1329         if (!s->tls_creds) {
1330             error_setg(errp, "Object with id '%s' is not TLS credentials",
1331                        sock->tls_creds);
1332             return;
1333         }
1334         object_ref(OBJECT(s->tls_creds));
1335         if (is_listen) {
1336             if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
1337                 error_setg(errp, "%s",
1338                            "Expected TLS credentials for server endpoint");
1339                 return;
1340             }
1341         } else {
1342             if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
1343                 error_setg(errp, "%s",
1344                            "Expected TLS credentials for client endpoint");
1345                 return;
1346             }
1347         }
1348     }
1349     s->tls_authz = g_strdup(sock->tls_authz);
1350 
1351     s->addr = addr = socket_address_flatten(sock->addr);
1352 
1353     if (!qmp_chardev_validate_socket(sock, addr, errp)) {
1354         return;
1355     }
1356 
1357     qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);
1358     /* TODO SOCKET_ADDRESS_FD where fd has AF_UNIX */
1359     if (addr->type == SOCKET_ADDRESS_TYPE_UNIX) {
1360         qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);
1361     }
1362 
1363     /* be isn't opened until we get a connection */
1364     *be_opened = false;
1365 
1366     update_disconnected_filename(s);
1367 
1368     if (s->is_listen) {
1369         if (qmp_chardev_open_socket_server(chr, is_telnet || is_tn3270,
1370                                            is_waitconnect, errp) < 0) {
1371             return;
1372         }
1373     } else {
1374         if (qmp_chardev_open_socket_client(chr, reconnect, errp) < 0) {
1375             return;
1376         }
1377     }
1378 }
1379 
1380 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
1381                                   Error **errp)
1382 {
1383     const char *path = qemu_opt_get(opts, "path");
1384     const char *host = qemu_opt_get(opts, "host");
1385     const char *port = qemu_opt_get(opts, "port");
1386     const char *fd = qemu_opt_get(opts, "fd");
1387     bool tight = qemu_opt_get_bool(opts, "tight", true);
1388     bool abstract = qemu_opt_get_bool(opts, "abstract", false);
1389     SocketAddressLegacy *addr;
1390     ChardevSocket *sock;
1391 
1392     if ((!!path + !!fd + !!host) != 1) {
1393         error_setg(errp,
1394                    "Exactly one of 'path', 'fd' or 'host' required");
1395         return;
1396     }
1397 
1398     if (host && !port) {
1399         error_setg(errp, "chardev: socket: no port given");
1400         return;
1401     }
1402 
1403     backend->type = CHARDEV_BACKEND_KIND_SOCKET;
1404     sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
1405     qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
1406 
1407     sock->has_nodelay = qemu_opt_get(opts, "delay");
1408     sock->nodelay = !qemu_opt_get_bool(opts, "delay", true);
1409     /*
1410      * We have different default to QMP for 'server', hence
1411      * we can't just check for existence of 'server'
1412      */
1413     sock->has_server = true;
1414     sock->server = qemu_opt_get_bool(opts, "server", false);
1415     sock->has_telnet = qemu_opt_get(opts, "telnet");
1416     sock->telnet = qemu_opt_get_bool(opts, "telnet", false);
1417     sock->has_tn3270 = qemu_opt_get(opts, "tn3270");
1418     sock->tn3270 = qemu_opt_get_bool(opts, "tn3270", false);
1419     sock->has_websocket = qemu_opt_get(opts, "websocket");
1420     sock->websocket = qemu_opt_get_bool(opts, "websocket", false);
1421     /*
1422      * We have different default to QMP for 'wait' when 'server'
1423      * is set, hence we can't just check for existence of 'wait'
1424      */
1425     sock->has_wait = qemu_opt_find(opts, "wait") || sock->server;
1426     sock->wait = qemu_opt_get_bool(opts, "wait", true);
1427     sock->has_reconnect = qemu_opt_find(opts, "reconnect");
1428     sock->reconnect = qemu_opt_get_number(opts, "reconnect", 0);
1429     sock->has_tls_creds = qemu_opt_get(opts, "tls-creds");
1430     sock->tls_creds = g_strdup(qemu_opt_get(opts, "tls-creds"));
1431     sock->has_tls_authz = qemu_opt_get(opts, "tls-authz");
1432     sock->tls_authz = g_strdup(qemu_opt_get(opts, "tls-authz"));
1433 
1434     addr = g_new0(SocketAddressLegacy, 1);
1435     if (path) {
1436         UnixSocketAddress *q_unix;
1437         addr->type = SOCKET_ADDRESS_LEGACY_KIND_UNIX;
1438         q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
1439         q_unix->path = g_strdup(path);
1440         q_unix->tight = tight;
1441         q_unix->abstract = abstract;
1442     } else if (host) {
1443         addr->type = SOCKET_ADDRESS_LEGACY_KIND_INET;
1444         addr->u.inet.data = g_new(InetSocketAddress, 1);
1445         *addr->u.inet.data = (InetSocketAddress) {
1446             .host = g_strdup(host),
1447             .port = g_strdup(port),
1448             .has_to = qemu_opt_get(opts, "to"),
1449             .to = qemu_opt_get_number(opts, "to", 0),
1450             .has_ipv4 = qemu_opt_get(opts, "ipv4"),
1451             .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
1452             .has_ipv6 = qemu_opt_get(opts, "ipv6"),
1453             .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
1454         };
1455     } else if (fd) {
1456         addr->type = SOCKET_ADDRESS_LEGACY_KIND_FD;
1457         addr->u.fd.data = g_new(String, 1);
1458         addr->u.fd.data->str = g_strdup(fd);
1459     } else {
1460         g_assert_not_reached();
1461     }
1462     sock->addr = addr;
1463 }
1464 
1465 static void
1466 char_socket_get_addr(Object *obj, Visitor *v, const char *name,
1467                      void *opaque, Error **errp)
1468 {
1469     SocketChardev *s = SOCKET_CHARDEV(obj);
1470 
1471     visit_type_SocketAddress(v, name, &s->addr, errp);
1472 }
1473 
1474 static bool
1475 char_socket_get_connected(Object *obj, Error **errp)
1476 {
1477     SocketChardev *s = SOCKET_CHARDEV(obj);
1478 
1479     return s->state == TCP_CHARDEV_STATE_CONNECTED;
1480 }
1481 
1482 static void char_socket_class_init(ObjectClass *oc, void *data)
1483 {
1484     ChardevClass *cc = CHARDEV_CLASS(oc);
1485 
1486     cc->parse = qemu_chr_parse_socket;
1487     cc->open = qmp_chardev_open_socket;
1488     cc->chr_wait_connected = tcp_chr_wait_connected;
1489     cc->chr_write = tcp_chr_write;
1490     cc->chr_sync_read = tcp_chr_sync_read;
1491     cc->chr_disconnect = tcp_chr_disconnect;
1492     cc->get_msgfds = tcp_get_msgfds;
1493     cc->set_msgfds = tcp_set_msgfds;
1494     cc->chr_add_client = tcp_chr_add_client;
1495     cc->chr_add_watch = tcp_chr_add_watch;
1496     cc->chr_update_read_handler = tcp_chr_update_read_handler;
1497 
1498     object_class_property_add(oc, "addr", "SocketAddress",
1499                               char_socket_get_addr, NULL,
1500                               NULL, NULL);
1501 
1502     object_class_property_add_bool(oc, "connected", char_socket_get_connected,
1503                                    NULL);
1504 }
1505 
1506 static const TypeInfo char_socket_type_info = {
1507     .name = TYPE_CHARDEV_SOCKET,
1508     .parent = TYPE_CHARDEV,
1509     .instance_size = sizeof(SocketChardev),
1510     .instance_finalize = char_socket_finalize,
1511     .class_init = char_socket_class_init,
1512 };
1513 
1514 static void register_types(void)
1515 {
1516     type_register_static(&char_socket_type_info);
1517 }
1518 
1519 type_init(register_types);
1520