This converts the blockdev NBD server to use the QIOChannelSocket class for initial listener socket setup and accepting of client connections. Actual I/O is still being performed against the socket file descriptor using the POSIX socket APIs.
Signed-off-by: Daniel P. Berrange <berra...@redhat.com> --- blockdev-nbd.c | 53 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/blockdev-nbd.c b/blockdev-nbd.c index bcdd18b..71ee021 100644 --- a/blockdev-nbd.c +++ b/blockdev-nbd.c @@ -17,33 +17,49 @@ #include "qmp-commands.h" #include "trace.h" #include "block/nbd.h" -#include "qemu/sockets.h" +#include "io/channel-socket.h" -static int server_fd = -1; +static QIOChannelSocket *server_ioc; +static int server_watch = -1; -static void nbd_accept(void *opaque) +static gboolean nbd_accept(QIOChannel *ioc, GIOCondition condition, + gpointer opaque) { - struct sockaddr_in addr; - socklen_t addr_len = sizeof(addr); + QIOChannelSocket *cioc; + int fd; - int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len); - if (fd >= 0 && !nbd_client_new(NULL, fd, nbd_client_put)) { - shutdown(fd, 2); + cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc), + NULL); + if (!cioc) { + return TRUE; + } + + fd = dup(cioc->fd); + if (fd >= 0 && + !nbd_client_new(NULL, fd, nbd_client_put)) { close(fd); } + object_unref(OBJECT(cioc)); + return TRUE; } void qmp_nbd_server_start(SocketAddress *addr, Error **errp) { - if (server_fd != -1) { + if (server_ioc) { error_setg(errp, "NBD server already running"); return; } - server_fd = socket_listen(addr, errp); - if (server_fd != -1) { - qemu_set_fd_handler(server_fd, nbd_accept, NULL, NULL); + server_ioc = qio_channel_socket_new(); + if (qio_channel_socket_listen_sync(server_ioc, addr, errp) < 0) { + return; } + + server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc), + G_IO_IN, + nbd_accept, + NULL, + NULL); } /* @@ -78,7 +94,7 @@ void qmp_nbd_server_add(const char *device, bool has_writable, bool writable, NBDExport *exp; NBDCloseNotifier *n; - if (server_fd == -1) { + if (!server_ioc) { error_setg(errp, "NBD server not running"); return; } @@ -128,9 +144,12 @@ void qmp_nbd_server_stop(Error **errp) nbd_close_notifier(&cn->n, nbd_export_get_blockdev(cn->exp)); } - if (server_fd != -1) { - qemu_set_fd_handler(server_fd, NULL, NULL, NULL); - close(server_fd); - server_fd = -1; + if (server_watch != -1) { + g_source_remove(server_watch); + server_watch = -1; + } + if (server_ioc) { + object_unref(OBJECT(server_ioc)); + server_ioc = NULL; } } -- 2.5.0