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