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