Skip to contentSkip to conversation

Add reconnect capability for client sockets

PATCH Superseded [email protected] 3 participants 20 messages Sep 21, 2014 – Sep 22, 2014

v1 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#1 lore raw

PATCH 1/6 qemu-char: Make the filename size for a chardev a #define

In reply to [email protected]

From: Corey Minyard <[email protected]>

---
 qemu-char.c | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)
qemu-char.c +9 -7
index 2a3cb9f..39fb9e4 100644
@@ -84,6 +84,7 @@
 
 #define READ_BUF_LEN 4096
 #define READ_RETRIES 10
+#define CHR_MAX_FILENAME_SIZE 256
 
 /***********************************************************/
 /* character device */
@@ -989,7 +990,8 @@ static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
 {
     int fd_in, fd_out;
-    char filename_in[256], filename_out[256];
+    char filename_in[CHR_MAX_FILENAME_SIZE];
+    char filename_out[CHR_MAX_FILENAME_SIZE];
     const char *filename = opts->device;
 
     if (filename == NULL) {
@@ -997,8 +999,8 @@ static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
         return NULL;
     }
 
-    snprintf(filename_in, 256, "%s.in", filename);
-    snprintf(filename_out, 256, "%s.out", filename);
+    snprintf(filename_in, CHR_MAX_FILENAME_SIZE, "%s.in", filename);
+    snprintf(filename_out, CHR_MAX_FILENAME_SIZE, "%s.out", filename);
     TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
     TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
     if (fd_in < 0 || fd_out < 0) {
@@ -1968,7 +1970,7 @@ static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
     OVERLAPPED ov;
     int ret;
     DWORD size;
-    char openname[256];
+    char openname[CHR_MAX_FILENAME_SIZE];
 
     s->fpipe = TRUE;
 
@@ -2910,12 +2912,12 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
     s->write_msgfds = 0;
     s->write_msgfds_num = 0;
 
-    chr->filename = g_malloc(256);
+    chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
     switch (ss.ss_family) {
 #ifndef _WIN32
     case AF_UNIX:
         s->is_unix = 1;
-        snprintf(chr->filename, 256, "unix:%s%s",
+        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
                  ((struct sockaddr_un *)(&ss))->sun_path,
                  is_listen ? ",server" : "");
         break;
@@ -2928,7 +2930,7 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
         s->do_nodelay = do_nodelay;
         getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
                     serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
-        snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
+        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
                  is_telnet ? "telnet" : "tcp",
                  left, host, right, serv,
                  is_listen ? ",server" : "");
Signature · 1 line
1.8.3.1
#3 lore raw

PATCH 2/6 qemu-char: Rework qemu_chr_open_socket() for reconnect

In reply to [email protected]

From: Corey Minyard <[email protected]>

Move all socket configuration to qmp_chardev_open_socket(). qemu_chr_open_socket_fd() just opens the socket. This is getting ready for the reconnect code, which will call open_sock_fd() on a reconnect attempt.

---
 qemu-char.c | 123 ++++++++++++++++++++++++++++++++++++------------------------
 1 file changed, 73 insertions(+), 50 deletions(-)
qemu-char.c +73 -50
index 39fb9e4..23ec641 100644
@@ -2883,13 +2883,11 @@ static void tcp_chr_close(CharDriverState *chr)
     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
 }
 
-static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
-                                                bool is_listen, bool is_telnet,
-                                                bool is_waitconnect,
-                                                Error **errp)
+static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
+                                              bool is_listen, bool is_telnet,
+                                              Error **errp)
 {
-    CharDriverState *chr = NULL;
-    TCPCharDriver *s = NULL;
+    TCPCharDriver *s = chr->opaque;
     char host[NI_MAXHOST], serv[NI_MAXSERV];
     const char *left = "", *right = "";
     struct sockaddr_storage ss;
@@ -2897,26 +2895,14 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
 
     memset(&ss, 0, ss_len);
     if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
+        closesocket(fd);
         error_setg_errno(errp, errno, "getsockname");
-        return NULL;
+        return false;
     }
 
-    chr = qemu_chr_alloc();
-    s = g_malloc0(sizeof(TCPCharDriver));
-
-    s->connected = 0;
-    s->fd = -1;
-    s->listen_fd = -1;
-    s->read_msgfds = 0;
-    s->read_msgfds_num = 0;
-    s->write_msgfds = 0;
-    s->write_msgfds_num = 0;
-
-    chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
     switch (ss.ss_family) {
 #ifndef _WIN32
     case AF_UNIX:
-        s->is_unix = 1;
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
                  ((struct sockaddr_un *)(&ss))->sun_path,
                  is_listen ? ",server" : "");
@@ -2927,7 +2913,6 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
         right = "]";
         /* fall through */
     case AF_INET:
-        s->do_nodelay = do_nodelay;
         getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
                     serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
@@ -2937,25 +2922,11 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
         break;
     }
 
-    chr->opaque = s;
-    chr->chr_write = tcp_chr_write;
-    chr->chr_sync_read = tcp_chr_sync_read;
-    chr->chr_close = tcp_chr_close;
-    chr->get_msgfds = tcp_get_msgfds;
-    chr->set_msgfds = tcp_set_msgfds;
-    chr->chr_add_client = tcp_chr_add_client;
-    chr->chr_add_watch = tcp_chr_add_watch;
-    chr->chr_update_read_handler = tcp_chr_update_read_handler;
-    /* be isn't opened until we get a connection */
-    chr->explicit_be_open = true;
-
     if (is_listen) {
         s->listen_fd = fd;
         s->listen_chan = io_channel_from_socket(s->listen_fd);
-        s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
-        if (is_telnet) {
-            s->do_telnetopt = 1;
-        }
+        s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
+                                       tcp_chr_accept, chr);
     } else {
         s->connected = 1;
         s->fd = fd;
@@ -2964,15 +2935,28 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
         tcp_chr_connect(chr);
     }
 
-    if (is_listen && is_waitconnect) {
-        fprintf(stderr, "QEMU waiting for connection on: %s\n",
-                chr->filename);
-        tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
-        qemu_set_nonblock(s->listen_fd);
-    }
     return chr;
 }
 
+static bool qemu_chr_open_socket_fd(CharDriverState *chr, SocketAddress *addr,
+                                    bool is_listen, bool is_telnet,
+                                    Error **errp)
+{
+    int fd;
+
+    if (is_listen) {
+        fd = socket_listen(addr, errp);
+    } else  {
+        fd = socket_connect(addr, errp, NULL, NULL);
+    }
+    if (fd < 0) {
+        return false;
+    }
+
+    return qemu_chr_finish_socket_connection(chr, fd, is_listen, is_telnet,
+                                             errp);
+}
+
 /*********************************************************/
 /* Ring buffer chardev */
 
@@ -3961,23 +3945,62 @@ static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
                                                 Error **errp)
 {
+    CharDriverState *chr;
+    TCPCharDriver *s;
     SocketAddress *addr = sock->addr;
     bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;
     bool is_listen      = sock->has_server  ? sock->server  : true;
     bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;
     bool is_waitconnect = sock->has_wait    ? sock->wait    : false;
-    int fd;
+
+    chr = qemu_chr_alloc();
+    s = g_malloc0(sizeof(TCPCharDriver));
+
+    s->connected = 0;
+    s->fd = -1;
+    s->listen_fd = -1;
+    s->read_msgfds = 0;
+    s->read_msgfds_num = 0;
+    s->write_msgfds = 0;
+    s->write_msgfds_num = 0;
+    s->is_unix = addr->kind == SOCKET_ADDRESS_KIND_UNIX;
+    s->do_nodelay = do_nodelay;
+
+    chr->opaque = s;
+    chr->chr_write = tcp_chr_write;
+    chr->chr_sync_read = tcp_chr_sync_read;
+    chr->chr_close = tcp_chr_close;
+    chr->get_msgfds = tcp_get_msgfds;
+    chr->set_msgfds = tcp_set_msgfds;
+    chr->chr_add_client = tcp_chr_add_client;
+    chr->chr_add_watch = tcp_chr_add_watch;
+    chr->chr_update_read_handler = tcp_chr_update_read_handler;
+    /* be isn't opened until we get a connection */
+    chr->explicit_be_open = true;
+
+    chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
 
     if (is_listen) {
-        fd = socket_listen(addr, errp);
-    } else {
-        fd = socket_connect(addr, errp, NULL, NULL);
+        if (is_telnet) {
+            s->do_telnetopt = 1;
+        }
     }
-    if (fd < 0) {
+
+    if (!qemu_chr_open_socket_fd(chr, addr, is_listen, is_telnet, errp)) {
+        g_free(s);
+        g_free(chr->filename);
+        g_free(chr);
         return NULL;
     }
-    return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
-                                   is_telnet, is_waitconnect, errp);
+
+    if (is_listen && is_waitconnect) {
+        fprintf(stderr, "QEMU waiting for connection on: %s\n",
+                chr->filename);
+        tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
+        qemu_set_nonblock(s->listen_fd);
+    }
+
+    return chr;
 }
 
 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
Signature · 1 line
1.8.3.1
#13 lore raw

PATCH 5/6 qemu-char: Add reconnecting to client sockets

In reply to [email protected]

From: Corey Minyard <[email protected]>

Adds a "reconnect" option to socket backends that gives a reconnect timeout. This only applies to client sockets. If the other end of a socket closes the connection, qemu will attempt to reconnect after the given number of seconds.

---
 qapi-schema.json | 14 +++++----
 qemu-char.c      | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++----
 qemu-options.hx  | 20 ++++++++-----
 3 files changed, 106 insertions(+), 17 deletions(-)
qapi-schema.json +9 -5
index 689b548..79f7a07 100644
@@ -2648,14 +2648,18 @@
 # @nodelay: #optional set TCP_NODELAY socket option (default: false)
 # @telnet: #optional enable telnet protocol on server
 #          sockets (default: false)
+# @reconnect: #optional If not a server socket, if the socket disconnect
+#          then reconnect after the given number of seconds.  Setting
+#          to zero disables this function. (default: 0). Since: 2.2.
 #
 # Since: 1.4
 ##
-{ 'type': 'ChardevSocket', 'data': { 'addr'     : 'SocketAddress',
-                                     '*server'  : 'bool',
-                                     '*wait'    : 'bool',
-                                     '*nodelay' : 'bool',
-                                     '*telnet'  : 'bool' } }
+{ 'type': 'ChardevSocket', 'data': { 'addr'       : 'SocketAddress',
+                                     '*server'    : 'bool',
+                                     '*wait'      : 'bool',
+                                     '*nodelay'   : 'bool',
+                                     '*telnet'    : 'bool',
+                                     '*reconnect' : 'int' } }
 
 ##
 # @ChardevUdp:
qemu-char.c +84 -5

166 lines not on this page · raw message

qemu-options.hx +13 -7
index 365b56c..0cb856f 100644
@@ -1930,9 +1930,9 @@ ETEXI
 
 DEF("chardev", HAS_ARG, QEMU_OPTION_chardev,
     "-chardev null,id=id[,mux=on|off]\n"
-    "-chardev socket,id=id[,host=host],port=port[,to=to][,ipv4][,ipv6][,nodelay]\n"
-    "         [,server][,nowait][,telnet][,mux=on|off] (tcp)\n"
-    "-chardev socket,id=id,path=path[,server][,nowait][,telnet],[mux=on|off] (unix)\n"
+    "-chardev socket,id=id[,host=host],port=port[,to=to][,ipv4][,ipv6][,nodelay][,reconnect=reconnect_time]\n"
+    "         [,server][,nowait][,telnet][,reconnect=reconnect_time][,mux=on|off] (tcp)\n"
+    "-chardev socket,id=id,path=path[,server][,nowait][,telnet][,reconnect=reconnect_time][,mux=on|off] (unix)\n"
     "-chardev udp,id=id[,host=host],port=port[,localaddr=localaddr]\n"
     "         [,localport=localport][,ipv4][,ipv6][,mux=on|off]\n"
     "-chardev msmouse,id=id[,mux=on|off]\n"
@@ -2004,7 +2004,7 @@ Options to each backend are described below.
 A void device. This device will not emit any data, and will drop any data it
 receives. The null backend does not take any options.
 
-@item -chardev socket ,id=@var{id} [@var{TCP options} or @var{unix options}] [,server] [,nowait] [,telnet]
+@item -chardev socket ,id=@var{id} [@var{TCP options} or @var{unix options}] [,server] [,nowait] [,telnet] [,reconnect=reconnect_time]
 
 Create a two-way stream socket, which can be either a TCP or a unix socket. A
 unix socket will be created if @option{path} is specified. Behaviour is
@@ -2018,6 +2018,10 @@ connect to a listening socket.
 @option{telnet} specifies that traffic on the socket should interpret telnet
 escape sequences.
 
+@option{reconnect} sets the timeout for reconnecting on non-server sockets when
+the remote end goes away.  qemu will delay this many seconds and then attempt
+to reconnect.  Zero disables reconnecting, and is the default.
+
 TCP and unix socket options are given below:
 
 @table @option
@@ -2687,14 +2691,16 @@ telnet on port 5555 to access the QEMU port.
 localhost 5555
 @end table
 
-@item tcp:[@var{host}]:@var{port}[,@var{server}][,nowait][,nodelay]
+@item tcp:[@var{host}]:@var{port}[,@var{server}][,nowait][,nodelay][,reconnect=reconnect_time]
 The TCP Net Console has two modes of operation.  It can send the serial
 I/O to a location or wait for a connection from a location.  By default
 the TCP Net Console is sent to @var{host} at the @var{port}.  If you use
 the @var{server} option QEMU will wait for a client socket application
 to connect to the port before continuing, unless the @code{nowait}
 option was specified.  The @code{nodelay} option disables the Nagle buffering
-algorithm.  If @var{host} is omitted, 0.0.0.0 is assumed. Only
+algorithm.  The @code{reconnect} option only applies if @var{noserver} is
+set, if the connection goes down it will attempt to reconnect at the
+given interval.  If @var{host} is omitted, 0.0.0.0 is assumed. Only
 one TCP connection at a time is accepted. You can use @code{telnet} to
 connect to the corresponding character device.
 @table @code
@@ -2715,7 +2721,7 @@ MAGIC_SYSRQ sequence if you use a telnet that supports sending the break
 sequence.  Typically in unix telnet you do it with Control-] and then
 type "send break" followed by pressing the enter key.
 
-@item unix:@var{path}[,server][,nowait]
+@item unix:@var{path}[,server][,nowait][,reconnect=reconnect_time]
 A unix domain socket is used instead of a tcp socket.  The option works the
 same as if you had specified @code{-serial tcp} except the unix domain socket
 @var{path} is used for connections.
Signature · 1 line
1.8.3.1
#18 lore raw

PATCH 6/6 qemu-char: Print the remote and local addresses for a socket

In reply to [email protected]

From: Corey Minyard <[email protected]>

It seems that it might be a good idea to know what is at the remote end of a socket for tracking down issues. So add that to the socket filename.

---
 qemu-char.c | 27 ++++++++++++++++++---------
 1 file changed, 18 insertions(+), 9 deletions(-)
qemu-char.c +18 -9
index eefebd4..13ef14f 100644
@@ -142,9 +142,11 @@ static int SocketAddress_to_str(char *dest, int max_len,
 
 static int sockaddr_to_str(char *dest, int max_len,
                            struct sockaddr_storage *ss, socklen_t ss_len,
+                           struct sockaddr_storage *ps, socklen_t ps_len,
                            bool is_listen, bool is_telnet)
 {
-    char host[NI_MAXHOST], serv[NI_MAXSERV];
+    char shost[NI_MAXHOST], sserv[NI_MAXSERV];
+    char phost[NI_MAXHOST], pserv[NI_MAXSERV];
     const char *left = "", *right = "";
 
     switch (ss->ss_family) {
@@ -159,12 +161,15 @@ static int sockaddr_to_str(char *dest, int max_len,
         right = "]";
         /* fall through */
     case AF_INET:
-        getnameinfo((struct sockaddr *) ss, ss_len, host, sizeof(host),
-                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
-        return snprintf(dest, max_len, "%s:%s%s%s:%s%s",
+        getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
+                    sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
+        getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
+                    pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
+        return snprintf(dest, max_len, "%s:%s%s%s:%s%s <-> %s%s%s:%s",
                         is_telnet ? "telnet" : "tcp",
-                        left, host, right, serv,
-                        is_listen ? ",server" : "");
+                        left, shost, right, sserv,
+                        is_listen ? ",server" : "",
+                        left, phost, right, pserv);
 
     default:
         return snprintf(dest, max_len, "unknown");
@@ -2861,15 +2866,19 @@ static void tcp_chr_connect(void *opaque)
 {
     CharDriverState *chr = opaque;
     TCPCharDriver *s = chr->opaque;
-    struct sockaddr_storage ss;
-    socklen_t ss_len = sizeof(ss);
+    struct sockaddr_storage ss, ps;
+    socklen_t ss_len = sizeof(ss), ps_len = sizeof(ps);
 
     memset(&ss, 0, ss_len);
     if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
                  "Error in getsockname: %s\n", strerror(errno));
+    } else if (getpeername(s->fd, (struct sockaddr *) &ps, &ps_len) != 0) {
+        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
+                 "Error in getpeername: %s\n", strerror(errno));
     } else {
-        sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, &ss, ss_len,
+        sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
+                        &ss, ss_len, &ps, ps_len,
                         s->is_listen, s->is_telnet);
     }
 
Signature · 1 line
1.8.3.1
#5 lore raw

PATCH 3/6 qemu-char: Move some items into TCPCharDriver

In reply to [email protected]

From: Corey Minyard <[email protected]>

This keeps them from having to be passed around and makes them available for later functions, like printing and reconnecting.

---
 qemu-char.c | 65 ++++++++++++++++++++++++++++++++++++++++++++++++-------------
 1 file changed, 51 insertions(+), 14 deletions(-)
qemu-char.c +51 -14
index 23ec641..e59321d 100644
@@ -28,6 +28,9 @@
 #include "sysemu/char.h"
 #include "hw/usb.h"
 #include "qmp-commands.h"
+#include "qapi/qmp-input-visitor.h"
+#include "qapi/qmp-output-visitor.h"
+#include "qapi-visit.h"
 
 #include <unistd.h>
 #include <fcntl.h>
@@ -87,6 +90,34 @@
 #define CHR_MAX_FILENAME_SIZE 256
 
 /***********************************************************/
+/* Socket address helpers */
+static void qapi_copy_SocketAddress(SocketAddress **p_dest,
+				    SocketAddress *src)
+{
+    QmpOutputVisitor *qov;
+    QmpInputVisitor *qiv;
+    Visitor *ov, *iv;
+    QObject *obj;
+
+    *p_dest = NULL;
+
+    qov = qmp_output_visitor_new();
+    ov = qmp_output_get_visitor(qov);
+    visit_type_SocketAddress(ov, &src, NULL, &error_abort);
+    obj = qmp_output_get_qobject(qov);
+    qmp_output_visitor_cleanup(qov);
+    if (!obj) {
+        return;
+    }
+
+    qiv = qmp_input_visitor_new(obj);
+    iv = qmp_input_get_visitor(qiv);
+    visit_type_SocketAddress(iv, p_dest, NULL, &error_abort);
+    qmp_input_visitor_cleanup(qiv);
+    qobject_decref(obj);
+}
+
+/***********************************************************/
 /* character device */
 
 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
@@ -2404,6 +2435,10 @@ typedef struct {
     int read_msgfds_num;
     int *write_msgfds;
     int write_msgfds_num;
+
+    SocketAddress *addr;
+    bool is_listen;
+    bool is_telnet;
 } TCPCharDriver;
 
 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
@@ -2853,6 +2888,8 @@ static void tcp_chr_close(CharDriverState *chr)
 {
     TCPCharDriver *s = chr->opaque;
     int i;
+
+    qapi_free_SocketAddress(s->addr);
     if (s->fd >= 0) {
         remove_fd_in_watch(chr);
         if (s->chan) {
@@ -2884,7 +2921,6 @@ static void tcp_chr_close(CharDriverState *chr)
 }
 
 static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
-                                              bool is_listen, bool is_telnet,
                                               Error **errp)
 {
     TCPCharDriver *s = chr->opaque;
@@ -2905,7 +2941,7 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
     case AF_UNIX:
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
                  ((struct sockaddr_un *)(&ss))->sun_path,
-                 is_listen ? ",server" : "");
+                 s->is_listen ? ",server" : "");
         break;
 #endif
     case AF_INET6:
@@ -2916,13 +2952,13 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
         getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
                     serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
-                 is_telnet ? "telnet" : "tcp",
+                 s->is_telnet ? "telnet" : "tcp",
                  left, host, right, serv,
-                 is_listen ? ",server" : "");
+                 s->is_listen ? ",server" : "");
         break;
     }
 
-    if (is_listen) {
+    if (s->is_listen) {
         s->listen_fd = fd;
         s->listen_chan = io_channel_from_socket(s->listen_fd);
         s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
@@ -2938,23 +2974,21 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
     return chr;
 }
 
-static bool qemu_chr_open_socket_fd(CharDriverState *chr, SocketAddress *addr,
-                                    bool is_listen, bool is_telnet,
-                                    Error **errp)
+static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
 {
+    TCPCharDriver *s = chr->opaque;
     int fd;
 
-    if (is_listen) {
-        fd = socket_listen(addr, errp);
+    if (s->is_listen) {
+        fd = socket_listen(s->addr, errp);
     } else  {
-        fd = socket_connect(addr, errp, NULL, NULL);
+        fd = socket_connect(s->addr, errp, NULL, NULL);
     }
     if (fd < 0) {
         return false;
     }
 
-    return qemu_chr_finish_socket_connection(chr, fd, is_listen, is_telnet,
-                                             errp);
+    return qemu_chr_finish_socket_connection(chr, fd, errp);
 }
 
 /*********************************************************/
@@ -3964,7 +3998,10 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
     s->write_msgfds = 0;
     s->write_msgfds_num = 0;
     s->is_unix = addr->kind == SOCKET_ADDRESS_KIND_UNIX;
+    s->is_listen = is_listen;
+    s->is_telnet = is_telnet;
     s->do_nodelay = do_nodelay;
+    qapi_copy_SocketAddress(&s->addr, sock->addr);
 
     chr->opaque = s;
     chr->chr_write = tcp_chr_write;
@@ -3986,7 +4023,7 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
         }
     }
 
-    if (!qemu_chr_open_socket_fd(chr, addr, is_listen, is_telnet, errp)) {
+    if (!qemu_chr_open_socket_fd(chr, errp)) {
         g_free(s);
         g_free(chr->filename);
         g_free(chr);
Signature · 1 line
1.8.3.1
#7 lore raw

PATCH 4/6 qemu-char: set socket filename to disconnected when not connected

In reply to [email protected]

From: Corey Minyard <[email protected]>

This way we can tell if the socket is connected or not. It also splits the string conversions out into separate functions to make this more convenient.

---
 qemu-char.c | 102 ++++++++++++++++++++++++++++++++++++++++--------------------
 1 file changed, 69 insertions(+), 33 deletions(-)
qemu-char.c +69 -33
index e59321d..8418e33 100644
@@ -117,6 +117,60 @@ static void qapi_copy_SocketAddress(SocketAddress **p_dest,
     qobject_decref(obj);
 }
 
+static int SocketAddress_to_str(char *dest, int max_len,
+                                const char *prefix, SocketAddress *addr,
+                                bool is_listen, bool is_telnet)
+{
+    switch (addr->kind) {
+    case SOCKET_ADDRESS_KIND_INET:
+        return snprintf(dest, max_len, "%s%s:%s:%s%s", prefix,
+                        is_telnet ? "telnet" : "tcp", addr->inet->host,
+                        addr->inet->port, is_listen ? ",server" : "");
+        break;
+    case SOCKET_ADDRESS_KIND_UNIX:
+        return snprintf(dest, max_len, "%sunix:%s%s", prefix,
+                        addr->q_unix->path, is_listen ? ",server" : "");
+        break;
+    case SOCKET_ADDRESS_KIND_FD:
+        return snprintf(dest, max_len, "%sfd:%s%s", prefix, addr->fd->str,
+                        is_listen ? ",server" : "");
+        break;
+    default:
+        abort();
+    }
+}
+
+static int sockaddr_to_str(char *dest, int max_len,
+                           struct sockaddr_storage *ss, socklen_t ss_len,
+                           bool is_listen, bool is_telnet)
+{
+    char host[NI_MAXHOST], serv[NI_MAXSERV];
+    const char *left = "", *right = "";
+
+    switch (ss->ss_family) {
+#ifndef _WIN32
+    case AF_UNIX:
+        return snprintf(dest, max_len, "unix:%s%s",
+                        ((struct sockaddr_un *)(ss))->sun_path,
+                        is_listen ? ",server" : "");
+#endif
+    case AF_INET6:
+        left  = "[";
+        right = "]";
+        /* fall through */
+    case AF_INET:
+        getnameinfo((struct sockaddr *) ss, ss_len, host, sizeof(host),
+                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
+        return snprintf(dest, max_len, "%s:%s%s%s:%s%s",
+                        is_telnet ? "telnet" : "tcp",
+                        left, host, right, serv,
+                        is_listen ? ",server" : "");
+
+    default:
+        return snprintf(dest, max_len, "unknown");
+    }
+}
+
 /***********************************************************/
 /* character device */
 
@@ -2719,6 +2773,8 @@ static void tcp_chr_disconnect(CharDriverState *chr)
     s->chan = NULL;
     closesocket(s->fd);
     s->fd = -1;
+    SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
+                         "disconnected:", s->addr, s->is_listen, s->is_telnet);
     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
 }
 
@@ -2790,6 +2846,17 @@ static void tcp_chr_connect(void *opaque)
 {
     CharDriverState *chr = opaque;
     TCPCharDriver *s = chr->opaque;
+    struct sockaddr_storage ss;
+    socklen_t ss_len = sizeof(ss);
+
+    memset(&ss, 0, ss_len);
+    if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
+        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
+                 "Error in getsockname: %s\n", strerror(errno));
+    } else {
+        sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, &ss, ss_len,
+                        s->is_listen, s->is_telnet);
+    }
 
     s->connected = 1;
     if (s->chan) {
@@ -2924,39 +2991,6 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
                                               Error **errp)
 {
     TCPCharDriver *s = chr->opaque;
-    char host[NI_MAXHOST], serv[NI_MAXSERV];
-    const char *left = "", *right = "";
-    struct sockaddr_storage ss;
-    socklen_t ss_len = sizeof(ss);
-
-    memset(&ss, 0, ss_len);
-    if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
-        closesocket(fd);
-        error_setg_errno(errp, errno, "getsockname");
-        return false;
-    }
-
-    switch (ss.ss_family) {
-#ifndef _WIN32
-    case AF_UNIX:
-        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
-                 ((struct sockaddr_un *)(&ss))->sun_path,
-                 s->is_listen ? ",server" : "");
-        break;
-#endif
-    case AF_INET6:
-        left  = "[";
-        right = "]";
-        /* fall through */
-    case AF_INET:
-        getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
-                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
-        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
-                 s->is_telnet ? "telnet" : "tcp",
-                 left, host, right, serv,
-                 s->is_listen ? ",server" : "");
-        break;
-    }
 
     if (s->is_listen) {
         s->listen_fd = fd;
@@ -4016,6 +4050,8 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
     chr->explicit_be_open = true;
 
     chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
+    SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, "disconnected:",
+                         addr, is_listen, is_telnet);
 
     if (is_listen) {
         if (is_telnet) {
Signature · 1 line
1.8.3.1
#0 lore raw

cover Add reconnect capability for client sockets

I believe this fixes all the issues identified by the reviewers, and also avoids leaking a few data items.

I also added some fixes for things that seemed sub-optimal. The biggest was that there was no way to tell from the monitor whether a socket was connected or not. Patch 4 sets the filename to "disconnected:<addr>" when the socket disconnects, were <addr> is the address supplied by the user.

Changing "256' to a #define also seemed like a good idea.

It also seems like a good idea to me to print out the peer address of a socket. That's the last patch, so it can be easily dropped if this is not wanted.

Thanks all,

-corey

Reviewed-by on v1 3/6
#6 lore raw

Re: [Qemu-devel] [PATCH 3/6] qemu-char: Move some items into TCPCharDriver

In reply to [email protected]

Il 22/09/2014 01:04, [email protected] ha scritto:

Quoted 156 lines

From: Corey Minyard <[email protected]>

This keeps them from having to be passed around and makes them available for later functions, like printing and reconnecting.

---
 qemu-char.c | 65 ++++++++++++++++++++++++++++++++++++++++++++++++-------------
 1 file changed, 51 insertions(+), 14 deletions(-)
qemu-char.c +50 -13
index 23ec641..e59321d 100644
@@ -28,6 +28,9 @@
 #include "sysemu/char.h"
 #include "hw/usb.h"
 #include "qmp-commands.h"
+#include "qapi/qmp-input-visitor.h"
+#include "qapi/qmp-output-visitor.h"
+#include "qapi-visit.h"
 
 #include <unistd.h>
 #include <fcntl.h>
@@ -87,6 +90,34 @@
 #define CHR_MAX_FILENAME_SIZE 256
 
 /***********************************************************/
+/* Socket address helpers */
+static void qapi_copy_SocketAddress(SocketAddress **p_dest,
+				    SocketAddress *src)
+{
+    QmpOutputVisitor *qov;
+    QmpInputVisitor *qiv;
+    Visitor *ov, *iv;
+    QObject *obj;
+
+    *p_dest = NULL;
+
+    qov = qmp_output_visitor_new();
+    ov = qmp_output_get_visitor(qov);
+    visit_type_SocketAddress(ov, &src, NULL, &error_abort);
+    obj = qmp_output_get_qobject(qov);
+    qmp_output_visitor_cleanup(qov);
+    if (!obj) {
+        return;
+    }
+
+    qiv = qmp_input_visitor_new(obj);
+    iv = qmp_input_get_visitor(qiv);
+    visit_type_SocketAddress(iv, p_dest, NULL, &error_abort);
+    qmp_input_visitor_cleanup(qiv);
+    qobject_decref(obj);
+}
+
+/***********************************************************/
 /* character device */
 
 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
@@ -2404,6 +2435,10 @@ typedef struct {
     int read_msgfds_num;
     int *write_msgfds;
     int write_msgfds_num;
+
+    SocketAddress *addr;
+    bool is_listen;
+    bool is_telnet;
 } TCPCharDriver;
 
 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
@@ -2853,6 +2888,8 @@ static void tcp_chr_close(CharDriverState *chr)
 {
     TCPCharDriver *s = chr->opaque;
     int i;
+
+    qapi_free_SocketAddress(s->addr);
     if (s->fd >= 0) {
         remove_fd_in_watch(chr);
         if (s->chan) {
@@ -2884,7 +2921,6 @@ static void tcp_chr_close(CharDriverState *chr)
 }
 
 static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
-                                              bool is_listen, bool is_telnet,
                                               Error **errp)
 {
     TCPCharDriver *s = chr->opaque;
@@ -2905,7 +2941,7 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
     case AF_UNIX:
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
                  ((struct sockaddr_un *)(&ss))->sun_path,
-                 is_listen ? ",server" : "");
+                 s->is_listen ? ",server" : "");
         break;
 #endif
     case AF_INET6:
@@ -2916,13 +2952,13 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
         getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
                     serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
-                 is_telnet ? "telnet" : "tcp",
+                 s->is_telnet ? "telnet" : "tcp",
                  left, host, right, serv,
-                 is_listen ? ",server" : "");
+                 s->is_listen ? ",server" : "");
         break;
     }
 
-    if (is_listen) {
+    if (s->is_listen) {
         s->listen_fd = fd;
         s->listen_chan = io_channel_from_socket(s->listen_fd);
         s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
@@ -2938,23 +2974,21 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
     return chr;
 }
 
-static bool qemu_chr_open_socket_fd(CharDriverState *chr, SocketAddress *addr,
-                                    bool is_listen, bool is_telnet,
-                                    Error **errp)
+static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
 {
+    TCPCharDriver *s = chr->opaque;
     int fd;
 
-    if (is_listen) {
-        fd = socket_listen(addr, errp);
+    if (s->is_listen) {
+        fd = socket_listen(s->addr, errp);
     } else  {
-        fd = socket_connect(addr, errp, NULL, NULL);
+        fd = socket_connect(s->addr, errp, NULL, NULL);
     }
     if (fd < 0) {
         return false;
     }
 
-    return qemu_chr_finish_socket_connection(chr, fd, is_listen, is_telnet,
-                                             errp);
+    return qemu_chr_finish_socket_connection(chr, fd, errp);
 }
 
 /*********************************************************/
@@ -3964,7 +3998,10 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
     s->write_msgfds = 0;
     s->write_msgfds_num = 0;
     s->is_unix = addr->kind == SOCKET_ADDRESS_KIND_UNIX;
+    s->is_listen = is_listen;
+    s->is_telnet = is_telnet;
     s->do_nodelay = do_nodelay;
+    qapi_copy_SocketAddress(&s->addr, sock->addr);
 
     chr->opaque = s;
     chr->chr_write = tcp_chr_write;

qemu-char.c static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock, · line 4029

Quoted 8 lines
qemu-char.c +1 -1
@@ -3986,7 +4023,7 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
         }
     }
 
-    if (!qemu_chr_open_socket_fd(chr, addr, is_listen, is_telnet, errp)) {
+    if (!qemu_chr_open_socket_fd(chr, errp)) {
         g_free(s);
         g_free(chr->filename);
         g_free(chr);
Reviewed-by on v1 1/6
#2 lore raw

Re: [Qemu-devel] [PATCH 1/6] qemu-char: Make the filename size for a chardev a #define

In reply to [email protected]

Il 22/09/2014 01:04, [email protected] ha scritto:

Quoted 66 lines

From: Corey Minyard <[email protected]>

---
 qemu-char.c | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)
qemu-char.c +8 -6
index 2a3cb9f..39fb9e4 100644
@@ -84,6 +84,7 @@
 
 #define READ_BUF_LEN 4096
 #define READ_RETRIES 10
+#define CHR_MAX_FILENAME_SIZE 256
 
 /***********************************************************/
 /* character device */
@@ -989,7 +990,8 @@ static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
 {
     int fd_in, fd_out;
-    char filename_in[256], filename_out[256];
+    char filename_in[CHR_MAX_FILENAME_SIZE];
+    char filename_out[CHR_MAX_FILENAME_SIZE];
     const char *filename = opts->device;
 
     if (filename == NULL) {
@@ -997,8 +999,8 @@ static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
         return NULL;
     }
 
-    snprintf(filename_in, 256, "%s.in", filename);
-    snprintf(filename_out, 256, "%s.out", filename);
+    snprintf(filename_in, CHR_MAX_FILENAME_SIZE, "%s.in", filename);
+    snprintf(filename_out, CHR_MAX_FILENAME_SIZE, "%s.out", filename);
     TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
     TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
     if (fd_in < 0 || fd_out < 0) {
@@ -1968,7 +1970,7 @@ static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
     OVERLAPPED ov;
     int ret;
     DWORD size;
-    char openname[256];
+    char openname[CHR_MAX_FILENAME_SIZE];
 
     s->fpipe = TRUE;
 
@@ -2910,12 +2912,12 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
     s->write_msgfds = 0;
     s->write_msgfds_num = 0;
 
-    chr->filename = g_malloc(256);
+    chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
     switch (ss.ss_family) {
 #ifndef _WIN32
     case AF_UNIX:
         s->is_unix = 1;
-        snprintf(chr->filename, 256, "unix:%s%s",
+        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
                  ((struct sockaddr_un *)(&ss))->sun_path,
                  is_listen ? ",server" : "");
         break;

qemu-char.c static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay, · line 2936

Quoted 8 lines
qemu-char.c +1 -1
@@ -2928,7 +2930,7 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
         s->do_nodelay = do_nodelay;
         getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
                     serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
-        snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
+        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
                  is_telnet ? "telnet" : "tcp",
                  left, host, right, serv,
                  is_listen ? ",server" : "");
#14 lore raw

Re: [Qemu-devel] [PATCH 5/6] qemu-char: Add reconnecting to client sockets

In reply to [email protected]

Il 22/09/2014 01:04, [email protected] ha scritto:

Quoted 8 lines

From: Corey Minyard <[email protected]>

Adds a "reconnect" option to socket backends that gives a reconnect timeout. This only applies to client sockets. If the other end of a socket closes the connection, qemu will attempt to reconnect after the given number of seconds.

Comments inline.

Quoted 70 lines
---
 qapi-schema.json | 14 +++++----
 qemu-char.c      | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++----
 qemu-options.hx  | 20 ++++++++-----
 3 files changed, 106 insertions(+), 17 deletions(-)
qapi-schema.json +9 -5
index 689b548..79f7a07 100644
@@ -2648,14 +2648,18 @@
 # @nodelay: #optional set TCP_NODELAY socket option (default: false)
 # @telnet: #optional enable telnet protocol on server
 #          sockets (default: false)
+# @reconnect: #optional If not a server socket, if the socket disconnect
+#          then reconnect after the given number of seconds.  Setting
+#          to zero disables this function. (default: 0). Since: 2.2.
 #
 # Since: 1.4
 ##
-{ 'type': 'ChardevSocket', 'data': { 'addr'     : 'SocketAddress',
-                                     '*server'  : 'bool',
-                                     '*wait'    : 'bool',
-                                     '*nodelay' : 'bool',
-                                     '*telnet'  : 'bool' } }
+{ 'type': 'ChardevSocket', 'data': { 'addr'       : 'SocketAddress',
+                                     '*server'    : 'bool',
+                                     '*wait'      : 'bool',
+                                     '*nodelay'   : 'bool',
+                                     '*telnet'    : 'bool',
+                                     '*reconnect' : 'int' } }
 
 ##
 # @ChardevUdp:
qemu-char.c +15 -0
index 8418e33..eefebd4 100644
@@ -2493,8 +2493,20 @@ typedef struct {
     SocketAddress *addr;
     bool is_listen;
     bool is_telnet;
+
+    guint reconnect_timer;
+    int64_t reconnect_time;
 } TCPCharDriver;
 
+static gboolean socket_reconnect_timeout(gpointer opaque);
+
+static void qemu_chr_socket_restart_timer(CharDriverState *chr)
+{
+    TCPCharDriver *s = chr->opaque;
+    s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
+                                               socket_reconnect_timeout, chr);
+}
+
 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
 
 #ifndef _WIN32
@@ -2776,6 +2788,9 @@ static void tcp_chr_disconnect(CharDriverState *chr)
     SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
                          "disconnected:", s->addr, s->is_listen, s->is_telnet);
     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
+    if (s->reconnect_time) {
+        qemu_chr_socket_restart_timer(chr);
+    }
 }
 
 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)

qemu-char.c static void tcp_chr_close(CharDriverState *chr) · line 2975

Quoted 5 lines
qemu-char.c +2 -0
@@ -2956,6 +2971,9 @@ static void tcp_chr_close(CharDriverState *chr)
     TCPCharDriver *s = chr->opaque;
     int i;
 
+    if (s->reconnect_timer) {
+        g_source_remove(s->reconnect_timer);

Please add "s->reconnect_timer = 0;" here for easier debugging.

Quoted 35 lines
qemu-char.c +23 -1
+    }
     qapi_free_SocketAddress(s->addr);
     if (s->fd >= 0) {
         remove_fd_in_watch(chr);
@@ -3005,7 +3023,28 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
         tcp_chr_connect(chr);
     }
 
-    return chr;
+    return true;
+}
+
+static void qemu_chr_socket_connected(int fd, void *opaque)
+{
+    CharDriverState *chr = opaque;
+    TCPCharDriver *s = chr->opaque;
+    Error *err = NULL;
+
+    if (fd >= 0) {
+        if (qemu_chr_finish_socket_connection(chr, fd, &err)) {
+            return;
+        }
+        if (err) {
+            error_report("%s", error_get_pretty(err));
+            error_free(err);
+        }
+        closesocket(fd);
+    }
+
+    s->connected = 0;
+    qemu_chr_socket_restart_timer(chr);
 }
 
 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)

qemu-char.c static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp) · line 3058

Quoted 7 lines
qemu-char.c +4 -0
@@ -3013,6 +3052,11 @@ static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
     TCPCharDriver *s = chr->opaque;
     int fd;
 
+    if (s->reconnect_time) {
+        fd = socket_connect(s->addr, errp, qemu_chr_socket_connected, chr);
+        return (fd >= 0);
+    }

The placement of this condition looks weird...

You're missing a check somewhere that reconnect is not specified together with listen. Please add it, and move the condition in the "else" side of the "if" just below.

Quoted 20 lines
qemu-char.c +2 -0
     if (s->is_listen) {
         fd = socket_listen(s->addr, errp);
     } else  {
@@ -3442,6 +3486,7 @@ static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
     bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
     bool is_telnet      = qemu_opt_get_bool(opts, "telnet", false);
     bool do_nodelay     = !qemu_opt_get_bool(opts, "delay", true);
+    int64_t reconnect   = qemu_opt_get_number(opts, "reconnect", 0);
     const char *path = qemu_opt_get(opts, "path");
     const char *host = qemu_opt_get(opts, "host");
     const char *port = qemu_opt_get(opts, "port");
@@ -4020,6 +4090,7 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
     bool is_listen      = sock->has_server  ? sock->server  : true;
     bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;
     bool is_waitconnect = sock->has_wait    ? sock->wait    : false;
+    int64_t reconnect   = sock->has_reconnect ? sock->reconnect : 0;
 
     chr = qemu_chr_alloc();
     s = g_malloc0(sizeof(TCPCharDriver));

qemu-char.c static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock, · line 4111

Quoted 5 lines
qemu-char.c +2 -0
@@ -4036,6 +4107,8 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
     s->is_telnet = is_telnet;
     s->do_nodelay = do_nodelay;
     qapi_copy_SocketAddress(&s->addr, sock->addr);
+    s->reconnect_timer = 0;
+    s->reconnect_time = 0;

Not needed after g_malloc0.

Quoted 32 lines
qemu-char.c +10 -4
     chr->opaque = s;
     chr->chr_write = tcp_chr_write;
@@ -4057,13 +4130,19 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
         if (is_telnet) {
             s->do_telnetopt = 1;
         }
+    } else if (reconnect > 0) {
+        s->reconnect_time = reconnect;
     }
 
     if (!qemu_chr_open_socket_fd(chr, errp)) {
-        g_free(s);
-        g_free(chr->filename);
-        g_free(chr);
-        return NULL;
+        if (s->reconnect_time) {
+            qemu_chr_socket_restart_timer(chr);
+        } else {
+            g_free(s);
+            g_free(chr->filename);
+            g_free(chr);
+            return NULL;
+        }
     }
 
     if (is_listen && is_waitconnect) {
qemu-options.hx +0 -0
index 365b56c..0cb856f 100644

qemu-options.hx ETEXI · line 1933

Quoted 7 lines
qemu-options.hx +1 -3
@@ -1930,9 +1930,9 @@ ETEXI
 
 DEF("chardev", HAS_ARG, QEMU_OPTION_chardev,
     "-chardev null,id=id[,mux=on|off]\n"
-    "-chardev socket,id=id[,host=host],port=port[,to=to][,ipv4][,ipv6][,nodelay]\n"
-    "         [,server][,nowait][,telnet][,mux=on|off] (tcp)\n"
-    "-chardev socket,id=id,path=path[,server][,nowait][,telnet],[mux=on|off] (unix)\n"
+    "-chardev socket,id=id[,host=host],port=port[,to=to][,ipv4][,ipv6][,nodelay][,reconnect=reconnect_time]\n"

s/reconnect_time/seconds/

qemu-options.hx ETEXI · line 1935

Quoted 2 lines
qemu-options.hx +2 -0
+    "         [,server][,nowait][,telnet][,reconnect=reconnect_time][,mux=on|off] (tcp)\n"
+    "-chardev socket,id=id,path=path[,server][,nowait][,telnet][,reconnect=reconnect_time][,mux=on|off] (unix)\n"

s/reconnect_time/seconds/

qemu-options.hx Options to each backend are described below. · line 2007

Quoted 9 lines
qemu-options.hx +1 -1
     "-chardev udp,id=id[,host=host],port=port[,localaddr=localaddr]\n"
     "         [,localport=localport][,ipv4][,ipv6][,mux=on|off]\n"
     "-chardev msmouse,id=id[,mux=on|off]\n"
@@ -2004,7 +2004,7 @@ Options to each backend are described below.
 A void device. This device will not emit any data, and will drop any data it
 receives. The null backend does not take any options.
 
-@item -chardev socket ,id=@var{id} [@var{TCP options} or @var{unix options}] [,server] [,nowait] [,telnet]
+@item -chardev socket ,id=@var{id} [@var{TCP options} or @var{unix options}] [,server] [,nowait] [,telnet] [,reconnect=reconnect_time]

s/reconnect_time/@var{seconds}/

Quoted 14 lines
qemu-options.hx +4 -0
 Create a two-way stream socket, which can be either a TCP or a unix socket. A
 unix socket will be created if @option{path} is specified. Behaviour is
@@ -2018,6 +2018,10 @@ connect to a listening socket.
 @option{telnet} specifies that traffic on the socket should interpret telnet
 escape sequences.
 
+@option{reconnect} sets the timeout for reconnecting on non-server sockets when
+the remote end goes away.  qemu will delay this many seconds and then attempt
+to reconnect.  Zero disables reconnecting, and is the default.
+
 TCP and unix socket options are given below:
 
 @table @option

qemu-options.hx telnet on port 5555 to access the QEMU port. · line 2694

Quoted 5 lines
qemu-options.hx +1 -1
@@ -2687,14 +2691,16 @@ telnet on port 5555 to access the QEMU port.
 localhost 5555
 @end table
 
-@item tcp:[@var{host}]:@var{port}[,@var{server}][,nowait][,nodelay]
+@item tcp:[@var{host}]:@var{port}[,@var{server}][,nowait][,nodelay][,reconnect=reconnect_time]

s/reconnect_time/@var{seconds}/

Quoted 14 lines
qemu-options.hx +3 -1
 The TCP Net Console has two modes of operation.  It can send the serial
 I/O to a location or wait for a connection from a location.  By default
 the TCP Net Console is sent to @var{host} at the @var{port}.  If you use
 the @var{server} option QEMU will wait for a client socket application
 to connect to the port before continuing, unless the @code{nowait}
 option was specified.  The @code{nodelay} option disables the Nagle buffering
-algorithm.  If @var{host} is omitted, 0.0.0.0 is assumed. Only
+algorithm.  The @code{reconnect} option only applies if @var{noserver} is
+set, if the connection goes down it will attempt to reconnect at the
+given interval.  If @var{host} is omitted, 0.0.0.0 is assumed. Only
 one TCP connection at a time is accepted. You can use @code{telnet} to
 connect to the corresponding character device.
 @table @code

qemu-options.hx MAGIC_SYSRQ sequence if you use a telnet that supports sending the break · line 2724

Quoted 5 lines
qemu-options.hx +1 -1
@@ -2715,7 +2721,7 @@ MAGIC_SYSRQ sequence if you use a telnet that supports sending the break
 sequence.  Typically in unix telnet you do it with Control-] and then
 type "send break" followed by pressing the enter key.
 
-@item unix:@var{path}[,server][,nowait]
+@item unix:@var{path}[,server][,nowait][,reconnect=reconnect_time]

s/reconnect_time/@var{seconds}/

Paolo

Quoted 4 lines
qemu-options.hx +0 -0
 A unix domain socket is used instead of a tcp socket.  The option works the
 same as if you had specified @code{-serial tcp} except the unix domain socket
 @var{path} is used for connections.
Reviewed-by on v1 6/6
#19 lore raw

Re: [Qemu-devel] [PATCH 6/6] qemu-char: Print the remote and local addresses for a socket

In reply to [email protected]

Il 22/09/2014 01:04, [email protected] ha scritto:

Quoted 63 lines

From: Corey Minyard <[email protected]>

It seems that it might be a good idea to know what is at the remote end of a socket for tracking down issues. So add that to the socket filename.

---
 qemu-char.c | 27 ++++++++++++++++++---------
 1 file changed, 18 insertions(+), 9 deletions(-)
qemu-char.c +13 -8
index eefebd4..13ef14f 100644
@@ -142,9 +142,11 @@ static int SocketAddress_to_str(char *dest, int max_len,
 
 static int sockaddr_to_str(char *dest, int max_len,
                            struct sockaddr_storage *ss, socklen_t ss_len,
+                           struct sockaddr_storage *ps, socklen_t ps_len,
                            bool is_listen, bool is_telnet)
 {
-    char host[NI_MAXHOST], serv[NI_MAXSERV];
+    char shost[NI_MAXHOST], sserv[NI_MAXSERV];
+    char phost[NI_MAXHOST], pserv[NI_MAXSERV];
     const char *left = "", *right = "";
 
     switch (ss->ss_family) {
@@ -159,12 +161,15 @@ static int sockaddr_to_str(char *dest, int max_len,
         right = "]";
         /* fall through */
     case AF_INET:
-        getnameinfo((struct sockaddr *) ss, ss_len, host, sizeof(host),
-                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
-        return snprintf(dest, max_len, "%s:%s%s%s:%s%s",
+        getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
+                    sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
+        getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
+                    pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
+        return snprintf(dest, max_len, "%s:%s%s%s:%s%s <-> %s%s%s:%s",
                         is_telnet ? "telnet" : "tcp",
-                        left, host, right, serv,
-                        is_listen ? ",server" : "");
+                        left, shost, right, sserv,
+                        is_listen ? ",server" : "",
+                        left, phost, right, pserv);
 
     default:
         return snprintf(dest, max_len, "unknown");
@@ -2861,15 +2866,19 @@ static void tcp_chr_connect(void *opaque)
 {
     CharDriverState *chr = opaque;
     TCPCharDriver *s = chr->opaque;
-    struct sockaddr_storage ss;
-    socklen_t ss_len = sizeof(ss);
+    struct sockaddr_storage ss, ps;
+    socklen_t ss_len = sizeof(ss), ps_len = sizeof(ps);
 
     memset(&ss, 0, ss_len);
     if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
                  "Error in getsockname: %s\n", strerror(errno));

qemu-char.c static void tcp_chr_connect(void *opaque) · line 2884

Quoted 10 lines
qemu-char.c +5 -1
+    } else if (getpeername(s->fd, (struct sockaddr *) &ps, &ps_len) != 0) {
+        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
+                 "Error in getpeername: %s\n", strerror(errno));
     } else {
-        sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, &ss, ss_len,
+        sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
+                        &ss, ss_len, &ps, ps_len,
                         s->is_listen, s->is_telnet);
     }
 
#8 lore raw

Re: [Qemu-devel] [PATCH 4/6] qemu-char: set socket filename to disconnected when not connected

In reply to [email protected]

Il 22/09/2014 01:04, [email protected] ha scritto:

Quoted 90 lines

From: Corey Minyard <[email protected]>

This way we can tell if the socket is connected or not. It also splits the string conversions out into separate functions to make this more convenient.

---
 qemu-char.c | 102 ++++++++++++++++++++++++++++++++++++++++--------------------
 1 file changed, 69 insertions(+), 33 deletions(-)
qemu-char.c +57 -0
index e59321d..8418e33 100644
@@ -117,6 +117,60 @@ static void qapi_copy_SocketAddress(SocketAddress **p_dest,
     qobject_decref(obj);
 }
 
+static int SocketAddress_to_str(char *dest, int max_len,
+                                const char *prefix, SocketAddress *addr,
+                                bool is_listen, bool is_telnet)
+{
+    switch (addr->kind) {
+    case SOCKET_ADDRESS_KIND_INET:
+        return snprintf(dest, max_len, "%s%s:%s:%s%s", prefix,
+                        is_telnet ? "telnet" : "tcp", addr->inet->host,
+                        addr->inet->port, is_listen ? ",server" : "");
+        break;
+    case SOCKET_ADDRESS_KIND_UNIX:
+        return snprintf(dest, max_len, "%sunix:%s%s", prefix,
+                        addr->q_unix->path, is_listen ? ",server" : "");
+        break;
+    case SOCKET_ADDRESS_KIND_FD:
+        return snprintf(dest, max_len, "%sfd:%s%s", prefix, addr->fd->str,
+                        is_listen ? ",server" : "");
+        break;
+    default:
+        abort();
+    }
+}
+
+static int sockaddr_to_str(char *dest, int max_len,
+                           struct sockaddr_storage *ss, socklen_t ss_len,
+                           bool is_listen, bool is_telnet)
+{
+    char host[NI_MAXHOST], serv[NI_MAXSERV];
+    const char *left = "", *right = "";
+
+    switch (ss->ss_family) {
+#ifndef _WIN32
+    case AF_UNIX:
+        return snprintf(dest, max_len, "unix:%s%s",
+                        ((struct sockaddr_un *)(ss))->sun_path,
+                        is_listen ? ",server" : "");
+#endif
+    case AF_INET6:
+        left  = "[";
+        right = "]";
+        /* fall through */
+    case AF_INET:
+        getnameinfo((struct sockaddr *) ss, ss_len, host, sizeof(host),
+                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
+        return snprintf(dest, max_len, "%s:%s%s%s:%s%s",
+                        is_telnet ? "telnet" : "tcp",
+                        left, host, right, serv,
+                        is_listen ? ",server" : "");
+
+    default:
+        return snprintf(dest, max_len, "unknown");
+    }
+}
+
 /***********************************************************/
 /* character device */
 
@@ -2719,6 +2773,8 @@ static void tcp_chr_disconnect(CharDriverState *chr)
     s->chan = NULL;
     closesocket(s->fd);
     s->fd = -1;
+    SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
+                         "disconnected:", s->addr, s->is_listen, s->is_telnet);
     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
 }
 
@@ -2790,6 +2846,17 @@ static void tcp_chr_connect(void *opaque)
 {
     CharDriverState *chr = opaque;
     TCPCharDriver *s = chr->opaque;
+    struct sockaddr_storage ss;

qemu-char.c static void tcp_chr_connect(void *opaque) · line 2859

Quoted 10 lines
qemu-char.c +10 -0
+    socklen_t ss_len = sizeof(ss);
+
+    memset(&ss, 0, ss_len);
+    if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
+        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
+                 "Error in getsockname: %s\n", strerror(errno));
+    } else {
+        sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, &ss, ss_len,
+                        s->is_listen, s->is_telnet);
+    }

Why move this from qemu_chr_finish_socket_connection to tcp_chr_connect?
Perhaps move this part of the patch earlier, either just before or just
after patch 2?

Except for this question, the patch looks good. Thanks,

Paolo

Quoted 52 lines
qemu-char.c +2 -33
     s->connected = 1;
     if (s->chan) {
@@ -2924,39 +2991,6 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
                                               Error **errp)
 {
     TCPCharDriver *s = chr->opaque;
-    char host[NI_MAXHOST], serv[NI_MAXSERV];
-    const char *left = "", *right = "";
-    struct sockaddr_storage ss;
-    socklen_t ss_len = sizeof(ss);
-
-    memset(&ss, 0, ss_len);
-    if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
-        closesocket(fd);
-        error_setg_errno(errp, errno, "getsockname");
-        return false;
-    }
-
-    switch (ss.ss_family) {
-#ifndef _WIN32
-    case AF_UNIX:
-        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
-                 ((struct sockaddr_un *)(&ss))->sun_path,
-                 s->is_listen ? ",server" : "");
-        break;
-#endif
-    case AF_INET6:
-        left  = "[";
-        right = "]";
-        /* fall through */
-    case AF_INET:
-        getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
-                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
-        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
-                 s->is_telnet ? "telnet" : "tcp",
-                 left, host, right, serv,
-                 s->is_listen ? ",server" : "");
-        break;
-    }
 
     if (s->is_listen) {
         s->listen_fd = fd;
@@ -4016,6 +4050,8 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
     chr->explicit_be_open = true;
 
     chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
+    SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, "disconnected:",
+                         addr, is_listen, is_telnet);
 
     if (is_listen) {
         if (is_telnet) {
Reviewed-by on v1 2/6
#4 lore raw

Re: [Qemu-devel] [PATCH 2/6] qemu-char: Rework qemu_chr_open_socket() for reconnect

In reply to [email protected]

Il 22/09/2014 01:04, [email protected] ha scritto:

Quoted 149 lines

From: Corey Minyard <[email protected]>

Move all socket configuration to qmp_chardev_open_socket(). qemu_chr_open_socket_fd() just opens the socket. This is getting ready for the reconnect code, which will call open_sock_fd() on a reconnect attempt.

---
 qemu-char.c | 123 ++++++++++++++++++++++++++++++++++++------------------------
 1 file changed, 73 insertions(+), 50 deletions(-)
qemu-char.c +32 -44
index 39fb9e4..23ec641 100644
@@ -2883,13 +2883,11 @@ static void tcp_chr_close(CharDriverState *chr)
     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
 }
 
-static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
-                                                bool is_listen, bool is_telnet,
-                                                bool is_waitconnect,
-                                                Error **errp)
+static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
+                                              bool is_listen, bool is_telnet,
+                                              Error **errp)
 {
-    CharDriverState *chr = NULL;
-    TCPCharDriver *s = NULL;
+    TCPCharDriver *s = chr->opaque;
     char host[NI_MAXHOST], serv[NI_MAXSERV];
     const char *left = "", *right = "";
     struct sockaddr_storage ss;
@@ -2897,26 +2895,14 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
 
     memset(&ss, 0, ss_len);
     if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
+        closesocket(fd);
         error_setg_errno(errp, errno, "getsockname");
-        return NULL;
+        return false;
     }
 
-    chr = qemu_chr_alloc();
-    s = g_malloc0(sizeof(TCPCharDriver));
-
-    s->connected = 0;
-    s->fd = -1;
-    s->listen_fd = -1;
-    s->read_msgfds = 0;
-    s->read_msgfds_num = 0;
-    s->write_msgfds = 0;
-    s->write_msgfds_num = 0;
-
-    chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
     switch (ss.ss_family) {
 #ifndef _WIN32
     case AF_UNIX:
-        s->is_unix = 1;
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
                  ((struct sockaddr_un *)(&ss))->sun_path,
                  is_listen ? ",server" : "");
@@ -2927,7 +2913,6 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
         right = "]";
         /* fall through */
     case AF_INET:
-        s->do_nodelay = do_nodelay;
         getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
                     serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
         snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
@@ -2937,25 +2922,11 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
         break;
     }
 
-    chr->opaque = s;
-    chr->chr_write = tcp_chr_write;
-    chr->chr_sync_read = tcp_chr_sync_read;
-    chr->chr_close = tcp_chr_close;
-    chr->get_msgfds = tcp_get_msgfds;
-    chr->set_msgfds = tcp_set_msgfds;
-    chr->chr_add_client = tcp_chr_add_client;
-    chr->chr_add_watch = tcp_chr_add_watch;
-    chr->chr_update_read_handler = tcp_chr_update_read_handler;
-    /* be isn't opened until we get a connection */
-    chr->explicit_be_open = true;
-
     if (is_listen) {
         s->listen_fd = fd;
         s->listen_chan = io_channel_from_socket(s->listen_fd);
-        s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
-        if (is_telnet) {
-            s->do_telnetopt = 1;
-        }
+        s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
+                                       tcp_chr_accept, chr);
     } else {
         s->connected = 1;
         s->fd = fd;
@@ -2964,15 +2935,28 @@ static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
         tcp_chr_connect(chr);
     }
 
-    if (is_listen && is_waitconnect) {
-        fprintf(stderr, "QEMU waiting for connection on: %s\n",
-                chr->filename);
-        tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
-        qemu_set_nonblock(s->listen_fd);
-    }
     return chr;
 }
 
+static bool qemu_chr_open_socket_fd(CharDriverState *chr, SocketAddress *addr,
+                                    bool is_listen, bool is_telnet,
+                                    Error **errp)
+{
+    int fd;
+
+    if (is_listen) {
+        fd = socket_listen(addr, errp);
+    } else  {
+        fd = socket_connect(addr, errp, NULL, NULL);
+    }
+    if (fd < 0) {
+        return false;
+    }
+
+    return qemu_chr_finish_socket_connection(chr, fd, is_listen, is_telnet,
+                                             errp);
+}
+
 /*********************************************************/
 /* Ring buffer chardev */
 
@@ -3961,23 +3945,62 @@ static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
                                                 Error **errp)
 {
+    CharDriverState *chr;
+    TCPCharDriver *s;
     SocketAddress *addr = sock->addr;
     bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;
     bool is_listen      = sock->has_server  ? sock->server  : true;
     bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;
     bool is_waitconnect = sock->has_wait    ? sock->wait    : false;
-    int fd;
+
+    chr = qemu_chr_alloc();
+    s = g_malloc0(sizeof(TCPCharDriver));

qemu-char.c static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel, · line 3967

Quoted 10 lines
qemu-char.c +10 -0
+
+    s->connected = 0;
+    s->fd = -1;
+    s->listen_fd = -1;
+    s->read_msgfds = 0;
+    s->read_msgfds_num = 0;
+    s->write_msgfds = 0;
+    s->write_msgfds_num = 0;
+    s->is_unix = addr->kind == SOCKET_ADDRESS_KIND_UNIX;
+    s->do_nodelay = do_nodelay;

Initialization to zero not needed after g_malloc0.

With this change,

Quoted 46 lines
qemu-char.c +31 -6
+
+    chr->opaque = s;
+    chr->chr_write = tcp_chr_write;
+    chr->chr_sync_read = tcp_chr_sync_read;
+    chr->chr_close = tcp_chr_close;
+    chr->get_msgfds = tcp_get_msgfds;
+    chr->set_msgfds = tcp_set_msgfds;
+    chr->chr_add_client = tcp_chr_add_client;
+    chr->chr_add_watch = tcp_chr_add_watch;
+    chr->chr_update_read_handler = tcp_chr_update_read_handler;
+    /* be isn't opened until we get a connection */
+    chr->explicit_be_open = true;
+
+    chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
 
     if (is_listen) {
-        fd = socket_listen(addr, errp);
-    } else {
-        fd = socket_connect(addr, errp, NULL, NULL);
+        if (is_telnet) {
+            s->do_telnetopt = 1;
+        }
     }
-    if (fd < 0) {
+
+    if (!qemu_chr_open_socket_fd(chr, addr, is_listen, is_telnet, errp)) {
+        g_free(s);
+        g_free(chr->filename);
+        g_free(chr);
         return NULL;
     }
-    return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
-                                   is_telnet, is_waitconnect, errp);
+
+    if (is_listen && is_waitconnect) {
+        fprintf(stderr, "QEMU waiting for connection on: %s\n",
+                chr->filename);
+        tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
+        qemu_set_nonblock(s->listen_fd);
+    }
+
+    return chr;
 }
 
 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
#9 lore raw

Re: [Qemu-devel] [PATCH 4/6] qemu-char: set socket filename to disconnected when not connected

In reply to Paolo Bonzini
Quoted 96 lines · Paolo Bonzini

Il 22/09/2014 01:04, [email protected] ha scritto:

Quoted 95 lines

From: Corey Minyard <[email protected]>

This way we can tell if the socket is connected or not. It also splits the string conversions out into separate functions to make this more convenient.

---
 qemu-char.c | 102 ++++++++++++++++++++++++++++++++++++++++--------------------
 1 file changed, 69 insertions(+), 33 deletions(-)
qemu-char.c +62 -0
index e59321d..8418e33 100644
@@ -117,6 +117,60 @@ static void qapi_copy_SocketAddress(SocketAddress **p_dest,
     qobject_decref(obj);
 }
 
+static int SocketAddress_to_str(char *dest, int max_len,
+                                const char *prefix, SocketAddress *addr,
+                                bool is_listen, bool is_telnet)
+{
+    switch (addr->kind) {
+    case SOCKET_ADDRESS_KIND_INET:
+        return snprintf(dest, max_len, "%s%s:%s:%s%s", prefix,
+                        is_telnet ? "telnet" : "tcp", addr->inet->host,
+                        addr->inet->port, is_listen ? ",server" : "");
+        break;
+    case SOCKET_ADDRESS_KIND_UNIX:
+        return snprintf(dest, max_len, "%sunix:%s%s", prefix,
+                        addr->q_unix->path, is_listen ? ",server" : "");
+        break;
+    case SOCKET_ADDRESS_KIND_FD:
+        return snprintf(dest, max_len, "%sfd:%s%s", prefix, addr->fd->str,
+                        is_listen ? ",server" : "");
+        break;
+    default:
+        abort();
+    }
+}
+
+static int sockaddr_to_str(char *dest, int max_len,
+                           struct sockaddr_storage *ss, socklen_t ss_len,
+                           bool is_listen, bool is_telnet)
+{
+    char host[NI_MAXHOST], serv[NI_MAXSERV];
+    const char *left = "", *right = "";
+
+    switch (ss->ss_family) {
+#ifndef _WIN32
+    case AF_UNIX:
+        return snprintf(dest, max_len, "unix:%s%s",
+                        ((struct sockaddr_un *)(ss))->sun_path,
+                        is_listen ? ",server" : "");
+#endif
+    case AF_INET6:
+        left  = "[";
+        right = "]";
+        /* fall through */
+    case AF_INET:
+        getnameinfo((struct sockaddr *) ss, ss_len, host, sizeof(host),
+                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
+        return snprintf(dest, max_len, "%s:%s%s%s:%s%s",
+                        is_telnet ? "telnet" : "tcp",
+                        left, host, right, serv,
+                        is_listen ? ",server" : "");
+
+    default:
+        return snprintf(dest, max_len, "unknown");
+    }
+}
+
 /***********************************************************/
 /* character device */
 
@@ -2719,6 +2773,8 @@ static void tcp_chr_disconnect(CharDriverState *chr)
     s->chan = NULL;
     closesocket(s->fd);
     s->fd = -1;
+    SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
+                         "disconnected:", s->addr, s->is_listen, s->is_telnet);
     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
 }
 
@@ -2790,6 +2846,17 @@ static void tcp_chr_connect(void *opaque)
 {
     CharDriverState *chr = opaque;
     TCPCharDriver *s = chr->opaque;
+    struct sockaddr_storage ss;
+    socklen_t ss_len = sizeof(ss);
+
+    memset(&ss, 0, ss_len);
+    if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
+        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
Quoted 8 lines

qemu-char.c static void tcp_chr_connect(void *opaque) · line 2859

Quoted 5 lines
qemu-char.c +5 -0
+                 "Error in getsockname: %s\n", strerror(errno));
+    } else {
+        sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, &ss, ss_len,
+                        s->is_listen, s->is_telnet);
+    }

Why move this from qemu_chr_finish_socket_connection to tcp_chr_connect?
Perhaps move this part of the patch earlier, either just before or just
after patch 2?

I had to make this change, otherwise a server socket would never show that it reconnected. I originally hadn't moved it.

Thanks,

-corey

Quoted 57 lines

Except for this question, the patch looks good. Thanks,

Paolo

Quoted 52 lines
qemu-char.c +2 -33
     s->connected = 1;
     if (s->chan) {
@@ -2924,39 +2991,6 @@ static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
                                               Error **errp)
 {
     TCPCharDriver *s = chr->opaque;
-    char host[NI_MAXHOST], serv[NI_MAXSERV];
-    const char *left = "", *right = "";
-    struct sockaddr_storage ss;
-    socklen_t ss_len = sizeof(ss);
-
-    memset(&ss, 0, ss_len);
-    if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
-        closesocket(fd);
-        error_setg_errno(errp, errno, "getsockname");
-        return false;
-    }
-
-    switch (ss.ss_family) {
-#ifndef _WIN32
-    case AF_UNIX:
-        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
-                 ((struct sockaddr_un *)(&ss))->sun_path,
-                 s->is_listen ? ",server" : "");
-        break;
-#endif
-    case AF_INET6:
-        left  = "[";
-        right = "]";
-        /* fall through */
-    case AF_INET:
-        getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
-                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
-        snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
-                 s->is_telnet ? "telnet" : "tcp",
-                 left, host, right, serv,
-                 s->is_listen ? ",server" : "");
-        break;
-    }
 
     if (s->is_listen) {
         s->listen_fd = fd;
@@ -4016,6 +4050,8 @@ static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
     chr->explicit_be_open = true;
 
     chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
+    SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, "disconnected:",
+                         addr, is_listen, is_telnet);
 
     if (is_listen) {
         if (is_telnet) {
#10 lore raw

Re: [Qemu-devel] [PATCH 4/6] qemu-char: set socket filename to disconnected when not connected

Il 22/09/2014 15:15, Corey Minyard ha scritto:

Quoted 5 lines
Quoted 3 lines
Quoted 3 lines

Why move this from qemu_chr_finish_socket_connection to tcp_chr_connect?
Perhaps move this part of the patch earlier, either just before or just
after patch 2?

I had to make this change, otherwise a server socket would never show that it reconnected. I originally hadn't moved it.

Reconnected or connected? How does reconnection work with server sockets? I guess you can then move it to patch 2.

Paolo

#11 lore raw

Re: [Qemu-devel] [PATCH 4/6] qemu-char: set socket filename to disconnected when not connected

Quoted 8 lines · Paolo Bonzini

Il 22/09/2014 15:15, Corey Minyard ha scritto:

Quoted 5 lines
Quoted 3 lines
Quoted 3 lines

Why move this from qemu_chr_finish_socket_connection to tcp_chr_connect?
Perhaps move this part of the patch earlier, either just before or just
after patch 2?

I had to make this change, otherwise a server socket would never show that it reconnected. I originally hadn't moved it.

Reconnected or connected? How does reconnection work with server sockets? I guess you can then move it to patch 2.

When a server socket disconnects, it runs through the disconnect code so it shows "disconnected". It does not call qemu_chr_finish_socket_connection when
it reconnects, though, so it would never show the new connection.

I can move it to patch 2, but it seems more logical to me here, since it doesn't really
matter until this patch.

Thanks,

-corey

Reviewed-by
#12 lore raw

Re: [Qemu-devel] [PATCH 4/6] qemu-char: set socket filename to disconnected when not connected

Il 22/09/2014 15:30, Corey Minyard ha scritto:

Quoted 8 lines
Quoted 4 lines
Quoted 4 lines
Quoted 2 lines
Quoted 2 lines

I had to make this change, otherwise a server socket would never show that it reconnected. I originally hadn't moved it.

Reconnected or connected? How does reconnection work with server sockets? I guess you can then move it to patch 2.

When a server socket disconnects, it runs through the disconnect code so it shows "disconnected". It does not call qemu_chr_finish_socket_connection when
it reconnects, though, so it would never show the new connection.

Ah, I see now what you mean. Of course for a server socket it's reconnection from a different client; it's not related to the new functionality.

Quoted 3 lines

I can move it to patch 2, but it seems more logical to me here, since it doesn't really
matter until this patch.

Yes, that's fine.

#15 lore raw

Re: [Qemu-devel] [PATCH 5/6] qemu-char: Add reconnecting to client sockets

In reply to [email protected]
Quoted 19 lines · On 09/21/2014 05:04 PM, [email protected] wrote:

From: Corey Minyard <[email protected]>

Adds a "reconnect" option to socket backends that gives a reconnect timeout. This only applies to client sockets. If the other end of a socket closes the connection, qemu will attempt to reconnect after the given number of seconds.

---
 qapi-schema.json | 14 +++++----
 qemu-char.c      | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++----
 qemu-options.hx  | 20 ++++++++-----
 3 files changed, 106 insertions(+), 17 deletions(-)
qapi-schema.json +0 -0
index 689b548..79f7a07 100644

qapi-schema.json line 2651

Quoted 4 lines
qapi-schema.json +1 -0
@@ -2648,14 +2648,18 @@
 # @nodelay: #optional set TCP_NODELAY socket option (default: false)
 # @telnet: #optional enable telnet protocol on server
 #          sockets (default: false)
+# @reconnect: #optional If not a server socket, if the socket disconnect

Awkward. How about:

For a client socket, if a disconnect is detected,

qapi-schema.json line 2653

Quoted 2 lines
qapi-schema.json +2 -0
+#          then reconnect after the given number of seconds.  Setting
+#          to zero disables this function. (default: 0). Since: 2.2.

I think this is usually written "(Since 2.2)" rather than "Since: 2.2" when it occurs in the middle of a single option.

Quoted 4 lines
qapi-schema.json +0 -1
 #
 # Since: 1.4
 ##
-{ 'type': 'ChardevSocket', 'data': { 'addr'     : 'SocketAddress',

qapi-schema.json line 2662

Quoted 10 lines
qapi-schema.json +6 -4
-                                     '*server'  : 'bool',
-                                     '*wait'    : 'bool',
-                                     '*nodelay' : 'bool',
-                                     '*telnet'  : 'bool' } }
+{ 'type': 'ChardevSocket', 'data': { 'addr'       : 'SocketAddress',
+                                     '*server'    : 'bool',
+                                     '*wait'      : 'bool',
+                                     '*nodelay'   : 'bool',
+                                     '*telnet'    : 'bool',
+                                     '*reconnect' : 'int' } }

Hmm, thinking aloud here. What happens if 'reconnect' is provided with a 'server':true socket? The documentation only specifies 'server':false behavior. Should it be an error (incompatible options), or just be silently ignored?

Going further, would it be possible to treat 'ChardevSocket' as a flat union, where 'server' is the enum key that determines what other fields are valid? Granted, for this to work, we'd need to teach the qapi generator to allow a discriminator of type bool (since we can enumerate all of its values). looking something like:

{ 'type': 'ChardevSocketBase',
'data': { 'addr': 'SocketAddress', '*nodelay': 'bool' } }
{ 'type': 'ChardevSocketServer',
'data': { '*wait': 'bool', '*telnet': 'bool' } }
{ 'type': 'ChardevSocketClient',
'data': { '*reconnect': 'int' } }
{ 'union': 'ChardevSocket', 'base': 'ChardevSocketBase',
'discriminator': 'bool',
'data': { true : 'ChardevSocketServer',

            false: 'ChardevSocketClient' } }

but I don't know if it is worth the complexity for the added type safety.

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#16 lore raw

Re: [Qemu-devel] [PATCH 5/6] qemu-char: Add reconnecting to client sockets

Quoted 26 lines · Eric Blake
Quoted 19 lines · On 09/21/2014 05:04 PM, [email protected] wrote:

From: Corey Minyard <[email protected]>

Adds a "reconnect" option to socket backends that gives a reconnect timeout. This only applies to client sockets. If the other end of a socket closes the connection, qemu will attempt to reconnect after the given number of seconds.

---
 qapi-schema.json | 14 +++++----
 qemu-char.c      | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++----
 qemu-options.hx  | 20 ++++++++-----
 3 files changed, 106 insertions(+), 17 deletions(-)
qapi-schema.json +0 -0
index 689b548..79f7a07 100644

qapi-schema.json line 2651

Quoted 4 lines
qapi-schema.json +1 -0
@@ -2648,14 +2648,18 @@
 # @nodelay: #optional set TCP_NODELAY socket option (default: false)
 # @telnet: #optional enable telnet protocol on server
 #          sockets (default: false)
+# @reconnect: #optional If not a server socket, if the socket disconnect

Awkward. How about:

Quoted 1 line

For a client socket, if a disconnect is detected,

Point taken...

Quoted 4 lines

qapi-schema.json line 2653

Quoted 2 lines
qapi-schema.json +2 -0
+#          then reconnect after the given number of seconds.  Setting
+#          to zero disables this function. (default: 0). Since: 2.2.

I think this is usually written "(Since 2.2)" rather than "Since: 2.2" when it occurs in the middle of a single option.

Ok, I'll fix this.

Quoted 11 lines
Quoted 11 lines
qapi-schema.json +2 -5
 #
 # Since: 1.4
 ##
-{ 'type': 'ChardevSocket', 'data': { 'addr'     : 'SocketAddress',
-                                     '*server'  : 'bool',
-                                     '*wait'    : 'bool',
-                                     '*nodelay' : 'bool',
-                                     '*telnet'  : 'bool' } }
+{ 'type': 'ChardevSocket', 'data': { 'addr'       : 'SocketAddress',
+                                     '*server'    : 'bool',
Quoted 8 lines

qapi-schema.json line 2662

Quoted 4 lines
qapi-schema.json +4 -0
+                                     '*wait'      : 'bool',
+                                     '*nodelay'   : 'bool',
+                                     '*telnet'    : 'bool',
+                                     '*reconnect' : 'int' } }

Hmm, thinking aloud here. What happens if 'reconnect' is provided with a 'server':true socket? The documentation only specifies 'server':false behavior. Should it be an error (incompatible options), or just be silently ignored?

I was going on the behavior of "telnet" and "wait", which are silently ignored for client sockets. reconnect is silently ignored for server sockets.

Quoted 15 lines

Going further, would it be possible to treat 'ChardevSocket' as a flat union, where 'server' is the enum key that determines what other fields are valid? Granted, for this to work, we'd need to teach the qapi generator to allow a discriminator of type bool (since we can enumerate all of its values). looking something like:

{ 'type': 'ChardevSocketBase',
'data': { 'addr': 'SocketAddress', '*nodelay': 'bool' } }
{ 'type': 'ChardevSocketServer',
'data': { '*wait': 'bool', '*telnet': 'bool' } }
{ 'type': 'ChardevSocketClient',
'data': { '*reconnect': 'int' } }
{ 'union': 'ChardevSocket', 'base': 'ChardevSocketBase',
'discriminator': 'bool',
'data': { true : 'ChardevSocketServer',

Quoted 4 lines
            false: 'ChardevSocketClient' } }

but I don't know if it is worth the complexity for the added type safety.

Doesn't seem terrible, but I'm not sure.

-corey

#17 lore raw

Re: [Qemu-devel] [PATCH 5/6] qemu-char: Add reconnecting to client sockets

Quoted 8 lines · Corey Minyard
Quoted 4 lines

Hmm, thinking aloud here. What happens if 'reconnect' is provided with a 'server':true socket? The documentation only specifies 'server':false behavior. Should it be an error (incompatible options), or just be silently ignored?

I was going on the behavior of "telnet" and "wait", which are silently ignored for client sockets. reconnect is silently ignored for server sockets.

I can live with that.

Quoted 7 lines
Quoted 7 lines

Going further, would it be possible to treat 'ChardevSocket' as a flat union, where 'server' is the enum key that determines what other fields are valid? Granted, for this to work, we'd need to teach the qapi generator to allow a discriminator of type bool (since we can enumerate all of its values). looking something like:

Quoted 10 lines
Quoted 10 lines

{ 'type': 'ChardevSocketBase',
'data': { 'addr': 'SocketAddress', '*nodelay': 'bool' } }
{ 'type': 'ChardevSocketServer',
'data': { '*wait': 'bool', '*telnet': 'bool' } }
{ 'type': 'ChardevSocketClient',
'data': { '*reconnect': 'int' } }
{ 'union': 'ChardevSocket', 'base': 'ChardevSocketBase',
'discriminator': 'bool',
'data': { true : 'ChardevSocketServer',

            false: 'ChardevSocketClient' } }

Of course, this is invalid JSON. In a JSON dictionary, the left side of any 'key':'value' pair must be a string, only the right side can be an arbitrary JSON type. So we'd have to spell out the stringized version 'true' and 'false' as the enum keys, which is all the more special casing to be added to the qapi generator. Lots of work for not too much benefit.

Quoted 5 lines
Quoted 3 lines

but I don't know if it is worth the complexity for the added type safety.

Doesn't seem terrible, but I'm not sure.

You're welcome to try it if you're interested, but in just typing this email, I can already see it's not a beginner's project, so I'm not going to insist.

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org