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