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