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