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