[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

[libvirt] [PATCH 03/15] Introduce a generic object for using network sockets



Introduces a simple wrapper around the raw POSIX sockets APIs
and name resolution APIs. Allows for easy creation of client
and server sockets with correct usage of name resolution APIs
for protocol agnostic socket setup.

It can listen for UNIX and TCP stream sockets.

It can connect to UNIX, TCP streams directly, or indirectly
to UNIX sockets via an SSH tunnel or external command

* src/Makefile.am: Add to libvirt-net-rpc.la
* src/rpc/virnetsocket.c, src/rpc/virnetsocket.h: Generic
  sockets APIs
---
 .x-sc_avoid_write      |    1 +
 po/POTFILES.in         |    1 +
 src/Makefile.am        |    3 +-
 src/rpc/virnetsocket.c |  723 ++++++++++++++++++++++++++++++++++++++++++++++++
 src/rpc/virnetsocket.h |  100 +++++++
 5 files changed, 827 insertions(+), 1 deletions(-)
 create mode 100644 src/rpc/virnetsocket.c
 create mode 100644 src/rpc/virnetsocket.h

diff --git a/.x-sc_avoid_write b/.x-sc_avoid_write
index f6fc1b2..3d43ddb 100644
--- a/.x-sc_avoid_write
+++ b/.x-sc_avoid_write
@@ -1,6 +1,7 @@
 ^src/libvirt\.c$
 ^src/fdstream\.c$
 ^src/qemu/qemu_monitor\.c$
+^src/rpc/virnetsocket.c$
 ^src/util/command\.c$
 ^src/util/util\.c$
 ^src/xen/xend_internal\.c$
diff --git a/po/POTFILES.in b/po/POTFILES.in
index c79234a..bc45b3d 100644
--- a/po/POTFILES.in
+++ b/po/POTFILES.in
@@ -59,6 +59,7 @@ src/qemu/qemu_monitor_text.c
 src/qemu/qemu_security_dac.c
 src/remote/remote_driver.c
 src/rpc/virnetmessage.c
+src/rpc/virnetsocket.c
 src/secret/secret_driver.c
 src/security/security_apparmor.c
 src/security/security_driver.c
diff --git a/src/Makefile.am b/src/Makefile.am
index daf7643..a19b304 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1122,7 +1122,8 @@ noinst_LTLIBRARIES += libvirt-net-rpc.la
 
 libvirt_net_rpc_la_SOURCES = \
 	rpc/virnetmessage.h rpc/virnetmessage.c \
-	rpc/virnetprotocol.h rpc/virnetprotocol.c
+	rpc/virnetprotocol.h rpc/virnetprotocol.c \
+	rpc/virnetsocket.h rpc/virnetsocket.c
 libvirt_net_rpc_la_CFLAGS = \
 			$(AM_CFLAGS)
 libvirt_net_rpc_la_LDFLAGS = \
diff --git a/src/rpc/virnetsocket.c b/src/rpc/virnetsocket.c
new file mode 100644
index 0000000..2bcb8fa
--- /dev/null
+++ b/src/rpc/virnetsocket.c
@@ -0,0 +1,723 @@
+/*
+ * virnetsocket.h: generic network socket handling
+ *
+ * Copyright (C) 2006-2010 Red Hat, Inc.
+ * Copyright (C) 2006 Daniel P. Berrange
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
+ *
+ * Author: Daniel P. Berrange <berrange redhat com>
+ */
+
+#include <config.h>
+
+#include <sys/stat.h>
+#include <unistd.h>
+#include <netinet/tcp.h>
+#include <sys/wait.h>
+
+#include "virnetsocket.h"
+#include "util.h"
+#include "memory.h"
+#include "virterror_internal.h"
+#include "logging.h"
+#include "files.h"
+#include "event.h"
+
+#define VIR_FROM_THIS VIR_FROM_RPC
+
+#define virNetError(code, ...)                                    \
+    virReportErrorHelper(NULL, VIR_FROM_RPC, code, __FILE__,      \
+                         __FUNCTION__, __LINE__, __VA_ARGS__)
+
+
+struct _virNetSocket {
+    int fd;
+    int watch;
+    pid_t pid;
+    int errfd;
+    bool client;
+    virNetSocketIOFunc func;
+    void *opaque;
+    virSocketAddr localAddr;
+    virSocketAddr remoteAddr;
+    char *localAddrStr;
+    char *remoteAddrStr;
+};
+
+
+static int virNetSocketForkDaemon(const char *binary)
+{
+    const char *const daemonargs[] = { binary, "--timeout=30", NULL };
+    pid_t pid;
+
+    if (virExecDaemonize(daemonargs, NULL, NULL,
+                         &pid, -1, NULL, NULL,
+                         VIR_EXEC_CLEAR_CAPS,
+                         NULL, NULL, NULL) < 0)
+        return -1;
+
+    return 0;
+}
+
+
+static virNetSocketPtr virNetSocketNew(virSocketAddrPtr localAddr,
+                                       virSocketAddrPtr remoteAddr,
+                                       int fd, int errfd, pid_t pid)
+{
+    virNetSocketPtr sock;
+    int no_slow_start = 1;
+
+    VIR_DEBUG("localAddr=%p remoteAddr=%p fd=%d errfd=%d pid=%d",
+              localAddr, remoteAddr,
+              fd, errfd, pid);
+
+    if (virSetCloseExec(fd) < 0 ||
+        virSetNonBlock(fd) < 0)
+        return NULL;
+
+    if (VIR_ALLOC(sock) < 0) {
+        virReportOOMError();
+        return NULL;
+    }
+
+    sock->localAddr = *localAddr;
+    if (remoteAddr)
+        sock->remoteAddr = *remoteAddr;
+    sock->fd = fd;
+    sock->errfd = errfd;
+    sock->pid = pid;
+
+    /* Disable nagle */
+    if (sock->localAddr.data.sa.sa_family != AF_UNIX)
+        setsockopt (fd, IPPROTO_TCP, TCP_NODELAY,
+                    (void *)&no_slow_start,
+                    sizeof(no_slow_start));
+
+
+    DEBUG("local family = %d remote family = %d",
+          localAddr->data.sa.sa_family,
+          remoteAddr ? remoteAddr->data.sa.sa_family : 0);
+    if (!(sock->localAddrStr = virSocketFormatAddrFull(localAddr, true, ";")))
+        goto error;
+
+    if (remoteAddr &&
+        !(sock->remoteAddrStr = virSocketFormatAddrFull(remoteAddr, true, ";")))
+        goto error;
+
+    sock->client = localAddr && !remoteAddr ? false : true;
+
+    VIR_DEBUG("sock=%p localAddrStr=%s remoteAddrStr=%s",
+              sock, NULLSTR(sock->localAddrStr), NULLSTR(sock->remoteAddrStr));
+
+    return sock;
+
+error:
+    virNetSocketFree(sock);
+    return NULL;
+}
+
+
+int virNetSocketNewListenTCP(const char *nodename,
+                             const char *service,
+                             virNetSocketPtr **retsocks,
+                             size_t *nretsocks)
+{
+    virNetSocketPtr *socks = NULL;
+    size_t nsocks = 0;
+    struct addrinfo *ai;
+    struct addrinfo hints;
+    int fd = -1;
+
+    *retsocks = NULL;
+    *nretsocks = 0;
+
+    memset (&hints, 0, sizeof hints);
+    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
+    hints.ai_socktype = SOCK_STREAM;
+
+    int e = getaddrinfo (nodename, service, &hints, &ai);
+    if (e != 0) {
+        virNetError(VIR_ERR_SYSTEM_ERROR,
+                    _("Unable to resolve address '%s' service '%s': %s"),
+                    nodename, service, gai_strerror (e));
+        goto error;
+    }
+
+    struct addrinfo *runp = ai;
+    while (runp) {
+        virSocketAddr addr;
+
+        memset(&addr, 0, sizeof(addr));
+
+        if ((fd = socket(runp->ai_family, runp->ai_socktype,
+                         runp->ai_protocol)) < 0) {
+            virReportSystemError(errno, "%s", _("Unable to create socket"));
+            goto error;
+        }
+
+        int opt = 1;
+        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt);
+
+#ifdef IPV6_V6ONLY
+        if (runp->ai_family == PF_INET6) {
+            int on = 1;
+            /*
+             * Normally on Linux an INET6 socket will bind to the INET4
+             * address too. If getaddrinfo returns results with INET4
+             * first though, this will result in INET6 binding failing.
+             * We can trivially cope with multiple server sockets, so
+             * we force it to only listen on IPv6
+             */
+            setsockopt(fd, IPPROTO_IPV6,IPV6_V6ONLY,
+                       (void*)&on, sizeof on);
+        }
+#endif
+
+        if (bind(fd, runp->ai_addr, runp->ai_addrlen) < 0) {
+            if (errno != EADDRINUSE) {
+                virReportSystemError(errno, "%s", _("Unable to bind to port"));
+                goto error;
+            }
+            VIR_FORCE_CLOSE(fd);
+            continue;
+        }
+
+        addr.len = sizeof(addr.data);
+        if (getsockname(fd, &addr.data.sa, &addr.len) < 0) {
+            virReportSystemError(errno, "%s", _("Unable to get local socket name"));
+            goto error;
+        }
+
+        VIR_DEBUG("%p f=%d f=%d", &addr, runp->ai_family, addr.data.sa.sa_family);
+
+        if (VIR_EXPAND_N(socks, nsocks, 1) < 0) {
+            virReportOOMError();
+            goto error;
+        }
+
+        if (!(socks[nsocks-1] = virNetSocketNew(&addr, NULL, fd, -1, 0)))
+            goto error;
+        runp = runp->ai_next;
+    }
+
+    freeaddrinfo (ai);
+
+    *retsocks = socks;
+    *nretsocks = nsocks;
+    return 0;
+
+error:
+    VIR_FORCE_CLOSE(fd);
+    return -1;
+}
+
+int virNetSocketNewListenUNIX(const char *path,
+                              mode_t mask,
+                              gid_t grp,
+                              virNetSocketPtr *retsock)
+{
+    virSocketAddr addr;
+    mode_t oldmask;
+    gid_t oldgrp;
+    int fd;
+
+    *retsock = NULL;
+
+    memset(&addr, 0, sizeof(addr));
+
+    addr.len = sizeof(addr.data.un);
+
+    if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
+        virReportSystemError(errno, "%s", _("Failed to create socket"));
+        goto error;
+    }
+
+    addr.data.un.sun_family = AF_UNIX;
+    if (virStrcpyStatic(addr.data.un.sun_path, path) == NULL) {
+        virReportSystemError(ENOMEM, _("Path %s too long for unix socket"), path);
+        goto error;
+    }
+    if (addr.data.un.sun_path[0] == '@')
+        addr.data.un.sun_path[0] = '\0';
+    else
+        unlink(addr.data.un.sun_path);
+
+    oldgrp = getgid();
+    oldmask = umask(~mask);
+    if (grp != 0 && setgid(grp) < 0) {
+        virReportSystemError(errno,
+                             _("Failed to set group ID to %d"), grp);
+        goto error;
+    }
+
+    if (bind(fd, &addr.data.sa, addr.len) < 0) {
+        virReportSystemError(errno,
+                             _("Failed to bind socket to '%s'"),
+                             path);
+        goto error;
+    }
+    umask(oldmask);
+    if (grp != 0 && setgid(oldgrp)) {
+        virReportSystemError(errno,
+                             _("Failed to restore group ID to %d"), oldgrp);
+        goto error;
+    }
+
+    if (!(*retsock = virNetSocketNew(&addr, NULL, fd, -1, 0)))
+        goto error;
+
+    return 0;
+
+error:
+    VIR_FORCE_CLOSE(fd);
+    return -1;
+}
+
+
+int virNetSocketNewConnectTCP(const char *nodename,
+                              const char *service,
+                              virNetSocketPtr *retsock)
+{
+    virNetSocketPtr *socks = NULL;
+    size_t nsocks = 0;
+    struct addrinfo *ai;
+    struct addrinfo hints;
+    int fd = -1;
+    virSocketAddr localAddr;
+    virSocketAddr remoteAddr;
+    struct addrinfo *runp;
+    int savedErrno = ENOENT;
+
+    *retsock = NULL;
+
+    memset(&localAddr, 0, sizeof(localAddr));
+    memset(&remoteAddr, 0, sizeof(remoteAddr));
+
+    memset (&hints, 0, sizeof hints);
+    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
+    hints.ai_socktype = SOCK_STREAM;
+
+    int e = getaddrinfo (nodename, service, &hints, &ai);
+    if (e != 0) {
+        virNetError(VIR_ERR_SYSTEM_ERROR,
+                    _("Unable to resolve address '%s' service '%s': %s"),
+                    nodename, service, gai_strerror (e));
+        goto error;
+    }
+
+    runp = ai;
+    while (runp) {
+        int opt = 1;
+
+        if ((fd = socket(runp->ai_family, runp->ai_socktype,
+                         runp->ai_protocol)) < 0) {
+            virReportSystemError(errno, "%s", _("Unable to create socket"));
+            goto error;
+        }
+
+        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt);
+
+        if (connect(fd, runp->ai_addr, runp->ai_addrlen) >= 0)
+            break;
+
+        savedErrno = errno;
+        VIR_FORCE_CLOSE(fd);
+        runp = runp->ai_next;
+    }
+
+    if (fd == -1) {
+        virReportSystemError(savedErrno,
+                             _("unable to connect to server at '%s:%s'"),
+                             nodename, service);
+        return -1;
+    }
+
+    freeaddrinfo (ai);
+
+    localAddr.len = sizeof(localAddr.data);
+    if (getsockname(fd, &localAddr.data.sa, &localAddr.len) < 0) {
+        virReportSystemError(errno, "%s", _("Unable to get local socket name"));
+        goto error;
+    }
+
+    remoteAddr.len = sizeof(remoteAddr.data);
+    if (getpeername(fd, &remoteAddr.data.sa, &remoteAddr.len) < 0) {
+        virReportSystemError(errno, "%s", _("Unable to get remote socket name"));
+        goto error;
+    }
+
+    if (VIR_EXPAND_N(socks, nsocks, 1) < 0) {
+        virReportOOMError();
+        goto error;
+    }
+
+    if (!(*retsock = virNetSocketNew(&localAddr, &remoteAddr, fd, -1, 0)))
+        goto error;
+
+    return 0;
+
+error:
+    VIR_FORCE_CLOSE(fd);
+    return -1;
+}
+
+
+int virNetSocketNewConnectUNIX(const char *path,
+                               bool spawnDaemon,
+                               const char *binary,
+                               virNetSocketPtr *retsock)
+{
+    virSocketAddr localAddr;
+    virSocketAddr remoteAddr;
+    int fd;
+    int retries = 0;
+
+    memset(&localAddr, 0, sizeof(localAddr));
+    memset(&remoteAddr, 0, sizeof(remoteAddr));
+
+    remoteAddr.len = sizeof(remoteAddr.data.un);
+
+    if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
+        virReportSystemError(errno, "%s", _("Failed to create socket"));
+        goto error;
+    }
+
+    remoteAddr.data.un.sun_family = AF_UNIX;
+    if (virStrcpyStatic(remoteAddr.data.un.sun_path, path) == NULL) {
+        virReportSystemError(ENOMEM, _("Path %s too long for unix socket"), path);
+        goto error;
+    }
+    if (remoteAddr.data.un.sun_path[0] == '@')
+        remoteAddr.data.un.sun_path[0] = '\0';
+
+retry:
+    if (connect(fd, &remoteAddr.data.sa, remoteAddr.len) < 0) {
+        if (errno == ECONNREFUSED && spawnDaemon && retries < 20) {
+            if (retries == 0 &&
+                virNetSocketForkDaemon(binary) < 0)
+                goto error;
+
+            retries++;
+            usleep(1000 * 100 * retries);
+            goto retry;
+        }
+
+        virReportSystemError(errno,
+                             _("Failed to connect socket to '%s'"),
+                             path);
+        goto error;
+    }
+
+    localAddr.len = sizeof(localAddr.data);
+    if (getsockname(fd, &localAddr.data.sa, &localAddr.len) < 0) {
+        virReportSystemError(errno, "%s", _("Unable to get local socket name"));
+        goto error;
+    }
+
+    if (!(*retsock = virNetSocketNew(&localAddr, &remoteAddr, fd, -1, 0)))
+        goto error;
+
+    return 0;
+
+error:
+    VIR_FORCE_CLOSE(fd);
+    return -1;
+}
+
+
+int virNetSocketNewConnectCommand(virCommandPtr cmd,
+                                  virNetSocketPtr *retsock)
+{
+    pid_t pid = 0;
+    int sv[2];
+    int errfd[2];
+
+    *retsock = NULL;
+
+    /* Fork off the external process.  Use socketpair to create a private
+     * (unnamed) Unix domain socket to the child process so we don't have
+     * to faff around with two file descriptors (a la 'pipe(2)').
+     */
+    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {
+        virReportSystemError(errno, "%s",
+                             _("unable to create socket pair"));
+        goto error;
+    }
+
+    if (pipe(errfd) < 0) {
+        virReportSystemError(errno, "%s",
+                             _("unable to create socket pair"));
+        goto error;
+    }
+
+    virCommandSetInputFD(cmd, sv[1]);
+    virCommandSetOutputFD(cmd, &sv[1]);
+    virCommandSetOutputFD(cmd, &errfd[1]);
+
+    if (virCommandRunAsync(cmd, &pid) < 0)
+        goto error;
+
+    /* Parent continues here. */
+    VIR_FORCE_CLOSE(sv[1]);
+    VIR_FORCE_CLOSE(errfd[1]);
+
+    if (!(*retsock = virNetSocketNew(NULL, NULL, sv[0], errfd[0], pid)))
+        goto error;
+
+    virCommandFree(cmd);
+
+    return 0;
+
+error:
+    VIR_FORCE_CLOSE(sv[0]);
+    VIR_FORCE_CLOSE(sv[1]);
+    VIR_FORCE_CLOSE(errfd[0]);
+    VIR_FORCE_CLOSE(errfd[1]);
+
+    if (pid > 0 &&
+        virCommandWait(cmd, NULL) < 0)
+        VIR_WARN("Unable to wait for command %d", pid);
+
+    virCommandFree(cmd);
+
+    return -1;
+}
+
+
+int virNetSocketNewConnectSSH(const char *nodename,
+                              const char *service,
+                              const char *binary,
+                              const char *username,
+                              bool noTTY,
+                              const char *netcat,
+                              const char *path,
+                              virNetSocketPtr *retsock)
+{
+    virCommandPtr cmd;
+    *retsock = NULL;
+
+    cmd = virCommandNew(binary);
+    virCommandAddEnvPassCommon(cmd);
+    virCommandClearCaps(cmd);
+
+    if (service)
+        virCommandAddArgList(cmd, "-p", service, NULL);
+    if (username)
+        virCommandAddArgList(cmd, "-l", username, NULL);
+    if (noTTY)
+        virCommandAddArgList(cmd, "-T", "-o", "BatchMode=yes",
+                             "-e", "none", NULL);
+    virCommandAddArgList(cmd, nodename,
+                         netcat ? netcat : "nc",
+                         "-U", path, NULL);
+
+    return virNetSocketNewConnectCommand(cmd, retsock);
+}
+
+
+int virNetSocketNewConnectExternal(const char **cmdargv,
+                                   virNetSocketPtr *retsock)
+{
+    virCommandPtr cmd;
+    int i;
+
+    *retsock = NULL;
+
+    cmd = virCommandNew(cmdargv[0]);
+    virCommandAddEnvPassCommon(cmd);
+    virCommandClearCaps(cmd);
+
+    for (i = 1 ; cmdargv[i] != NULL ; i++)
+        virCommandAddArg(cmd, cmdargv[i]);
+
+    return virNetSocketNewConnectCommand(cmd, retsock);
+}
+
+
+void virNetSocketFree(virNetSocketPtr sock)
+{
+    if (!sock)
+        return;
+
+    VIR_DEBUG("sock=%p fd=%d", sock, sock->fd);
+    if (sock->watch > 0) {
+        virEventRemoveHandle(sock->watch);
+        sock->watch = -1;
+    }
+
+    /* If a server socket, then unlink UNIX path */
+    if (!sock->client &&
+        sock->localAddr.data.sa.sa_family == AF_UNIX &&
+        sock->localAddr.data.un.sun_path[0] != '\0')
+        unlink(sock->localAddr.data.un.sun_path);
+
+    VIR_FORCE_CLOSE(sock->fd);
+    VIR_FORCE_CLOSE(sock->errfd);
+
+    if (sock->pid > 0) {
+        pid_t reap;
+        kill(sock->pid, SIGTERM);
+        do {
+retry:
+            reap = waitpid(sock->pid, NULL, 0);
+            if (reap == -1 && errno == EINTR)
+                goto retry;
+        } while (reap != -1 && reap != sock->pid);
+    }
+
+    VIR_FREE(sock->localAddrStr);
+    VIR_FREE(sock->remoteAddrStr);
+
+    VIR_FREE(sock);
+}
+
+
+int virNetSocketGetFD(virNetSocketPtr sock)
+{
+    return sock->fd;
+}
+
+
+bool virNetSocketIsLocal(virNetSocketPtr sock)
+{
+    if (sock->localAddr.data.sa.sa_family == AF_UNIX)
+        return true;
+    return false;
+}
+
+
+const char *virNetSocketLocalAddrString(virNetSocketPtr sock)
+{
+    return sock->localAddrStr;
+}
+
+const char *virNetSocketRemoteAddrString(virNetSocketPtr sock)
+{
+    return sock->remoteAddrStr;
+}
+
+ssize_t virNetSocketRead(virNetSocketPtr sock, char *buf, size_t len)
+{
+    return read(sock->fd, buf, len);
+}
+
+ssize_t virNetSocketWrite(virNetSocketPtr sock, const char *buf, size_t len)
+{
+    return write(sock->fd, buf, len);
+}
+
+
+int virNetSocketListen(virNetSocketPtr sock)
+{
+    if (listen(sock->fd, 30) < 0) {
+        virReportSystemError(errno, "%s", _("Unable to listen on socket"));
+        return -1;
+    }
+    return 0;
+}
+
+int virNetSocketAccept(virNetSocketPtr sock, virNetSocketPtr *clientsock)
+{
+    int fd;
+    virSocketAddr localAddr;
+    virSocketAddr remoteAddr;
+
+    *clientsock = NULL;
+
+    memset(&localAddr, 0, sizeof(localAddr));
+    memset(&remoteAddr, 0, sizeof(remoteAddr));
+
+    remoteAddr.len = sizeof(remoteAddr.data.stor);
+    if ((fd = accept(sock->fd, &remoteAddr.data.sa, &remoteAddr.len)) < 0) {
+        if (errno == ECONNABORTED ||
+            errno == EAGAIN)
+            return 0;
+
+        virReportSystemError(errno, "%s",
+                             _("Unable to accept client"));
+        return -1;
+    }
+
+    localAddr.len = sizeof(localAddr.data);
+    if (getsockname(fd, &localAddr.data.sa, &localAddr.len) < 0) {
+        virReportSystemError(errno, "%s", _("Unable to get local socket name"));
+        VIR_FORCE_CLOSE(fd);
+        return -1;
+    }
+
+    if (!(*clientsock = virNetSocketNew(&localAddr,
+                                        &remoteAddr,
+                                        fd, -1, 0)))
+        return -1;
+
+    return 0;
+}
+
+
+static void virNetSocketEventHandle(int fd ATTRIBUTE_UNUSED,
+                                    int watch ATTRIBUTE_UNUSED,
+                                    int events,
+                                    void *opaque)
+{
+    virNetSocketPtr sock = opaque;
+
+    sock->func(sock, events, sock->opaque);
+}
+
+int virNetSocketAddIOCallback(virNetSocketPtr sock,
+                              int events,
+                              virNetSocketIOFunc func,
+                              void *opaque)
+{
+    if (sock->watch > 0) {
+        VIR_DEBUG("Watch already registered on socket %p", sock);
+        return -1;
+    }
+
+    if ((sock->watch = virEventAddHandle(sock->fd,
+                                         events,
+                                         virNetSocketEventHandle,
+                                         sock,
+                                         NULL)) < 0) {
+        VIR_WARN("Failed to register watch on socket %p", sock);
+        return -1;
+    }
+    sock->func = func;
+    sock->opaque = opaque;
+
+    return 0;
+}
+
+void virNetSocketUpdateIOCallback(virNetSocketPtr sock,
+                                  int events)
+{
+    if (sock->watch <= 0) {
+        VIR_DEBUG("Watch not registered on socket %p", sock);
+        return;
+    }
+
+    virEventUpdateHandle(sock->watch, events);
+}
+
+void virNetSocketRemoveIOCallback(virNetSocketPtr sock)
+{
+    if (sock->watch <= 0) {
+        VIR_DEBUG("Watch not registered on socket %p", sock);
+        return;
+    }
+
+    virEventRemoveHandle(sock->watch);
+}
diff --git a/src/rpc/virnetsocket.h b/src/rpc/virnetsocket.h
new file mode 100644
index 0000000..4441848
--- /dev/null
+++ b/src/rpc/virnetsocket.h
@@ -0,0 +1,100 @@
+/*
+ * virnetsocket.h: generic network socket handling
+ *
+ * Copyright (C) 2006-2010 Red Hat, Inc.
+ * Copyright (C) 2006 Daniel P. Berrange
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
+ *
+ * Author: Daniel P. Berrange <berrange redhat com>
+ */
+
+#ifndef __VIR_NET_SOCKET_H__
+# define __VIR_NET_SOCKET_H__
+
+# include "network.h"
+# include "command.h"
+
+typedef struct _virNetSocket virNetSocket;
+typedef virNetSocket *virNetSocketPtr;
+
+
+typedef void (*virNetSocketIOFunc)(virNetSocketPtr sock,
+                                   int events,
+                                   void *opaque);
+
+
+int virNetSocketNewListenTCP(const char *nodename,
+                             const char *service,
+                             virNetSocketPtr **addrs,
+                             size_t *naddrs);
+
+int virNetSocketNewListenUNIX(const char *path,
+                              mode_t mask,
+                              gid_t grp,
+                              virNetSocketPtr *addr);
+
+int virNetSocketNewConnectTCP(const char *nodename,
+                              const char *service,
+                              virNetSocketPtr *addr);
+
+int virNetSocketNewConnectUNIX(const char *path,
+                               bool spawnDaemon,
+                               const char *binary,
+                               virNetSocketPtr *addr);
+
+int virNetSocketNewConnectCommand(virCommandPtr cmd,
+                                  virNetSocketPtr *retsock);
+
+int virNetSocketNewConnectSSH(const char *nodename,
+                              const char *service,
+                              const char *binary,
+                              const char *username,
+                              bool noTTY,
+                              const char *netcat,
+                              const char *path,
+                              virNetSocketPtr *addr);
+
+int virNetSocketNewConnectExternal(const char **cmdargv,
+                                   virNetSocketPtr *addr);
+
+int virNetSocketGetFD(virNetSocketPtr sock);
+bool virNetSocketIsLocal(virNetSocketPtr sock);
+
+ssize_t virNetSocketRead(virNetSocketPtr sock, char *buf, size_t len);
+ssize_t virNetSocketWrite(virNetSocketPtr sock, const char *buf, size_t len);
+
+void virNetSocketFree(virNetSocketPtr sock);
+
+const char *virNetSocketLocalAddrString(virNetSocketPtr sock);
+const char *virNetSocketRemoteAddrString(virNetSocketPtr sock);
+
+int virNetSocketListen(virNetSocketPtr sock);
+int virNetSocketAccept(virNetSocketPtr sock,
+                       virNetSocketPtr *clientsock);
+
+int virNetSocketAddIOCallback(virNetSocketPtr sock,
+                              int events,
+                              virNetSocketIOFunc func,
+                              void *opaque);
+
+void virNetSocketUpdateIOCallback(virNetSocketPtr sock,
+                                  int events);
+
+void virNetSocketRemoveIOCallback(virNetSocketPtr sock);
+
+
+
+#endif /* __VIR_NET_SOCKET_H__ */
-- 
1.7.2.3


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]