[Telepathy-commits] [telepathy-gabble/master] Add gibbers async resolver abstraction
Sjoerd Simons
sjoerd.simons at collabora.co.uk
Thu Feb 19 02:52:32 PST 2009
---
configure.ac | 27 +-
lib/gibber/Makefile.am | 6 +
lib/gibber/asyncns.c | 1498 ++++++++++++++++++++++++++++++++++
lib/gibber/asyncns.h | 163 ++++
lib/gibber/gibber-resolver-asyncns.c | 415 ++++++++++
lib/gibber/gibber-resolver-asyncns.h | 59 ++
lib/gibber/gibber-resolver.c | 899 ++++++++++++++++++++
lib/gibber/gibber-resolver.h | 176 ++++
8 files changed, 3242 insertions(+), 1 deletions(-)
create mode 100644 lib/gibber/asyncns.c
create mode 100644 lib/gibber/asyncns.h
create mode 100644 lib/gibber/gibber-resolver-asyncns.c
create mode 100644 lib/gibber/gibber-resolver-asyncns.h
create mode 100644 lib/gibber/gibber-resolver.c
create mode 100644 lib/gibber/gibber-resolver.h
diff --git a/configure.ac b/configure.ac
index f93ae8e..e694b36 100644
--- a/configure.ac
+++ b/configure.ac
@@ -33,6 +33,8 @@ AC_PROG_CC_STDC
AC_PROG_INSTALL
AC_PROG_LIBTOOL
+AC_USE_SYSTEM_EXTENSIONS
+
COMPILER_OPTIMISATIONS
COMPILER_COVERAGE
@@ -129,6 +131,29 @@ PKG_CHECK_MODULES(TP_GLIB, [telepathy-glib >= 0.7.24])
AC_SUBST(TP_GLIB_CFLAGS)
AC_SUBST(TP_GLIB_LIBS)
+
+# Needed for hostname resolver
+AC_CHECK_FUNC(res_query, ,
+ [AC_CHECK_LIB(resolv, res_query, [ RESOLV_LIBS="-lresolv" ],
+ [ save_libs="$LIBS"
+ LIBS="-lresolv $LIBS"
+ AC_MSG_CHECKING([for res_query in -lresolv (alternate version)])
+ AC_LINK_IFELSE(
+ [AC_LANG_PROGRAM([[#include <resolv.h>]], [[res_query(0,0,0,0,0)]])],
+ [ AC_MSG_RESULT(yes)
+ LIBS="$save_libs"
+ RESOLV_LIBS="-lresolv"
+ ],
+ [ AC_MSG_RESULT(no)
+ LIBS="$save_libs"
+ AC_CHECK_LIB(bind, res_query,
+ [ RESOLV_LIBS="-lbind" ],
+ [ AC_MSG_ERROR(res_query not found) ] ) ] ) ] )
+ ]
+)
+
+AC_SUBST(RESOLV_LIBS)
+
dnl Check for code generation tools
XSLTPROC=
AC_CHECK_PROGS([XSLTPROC], [xsltproc])
@@ -166,7 +191,7 @@ AC_SUBST(LOUDMOUTH_CFLAGS)
AC_SUBST(LOUDMOUTH_LIBS)
dnl Check for functions
-AC_CHECK_FUNCS(getifaddrs)
+AC_CHECK_FUNCS(getifaddrs memset select strndup setresuid setreuid strerror)
AC_OUTPUT( Makefile \
docs/Makefile \
diff --git a/lib/gibber/Makefile.am b/lib/gibber/Makefile.am
index 4854dbf..eb8a801 100644
--- a/lib/gibber/Makefile.am
+++ b/lib/gibber/Makefile.am
@@ -20,6 +20,12 @@ HANDWRITTEN_SOURCES = \
gibber-linklocal-transport.h \
gibber-listener.c \
gibber-listener.h \
+ gibber-resolver.c \
+ gibber-resolver.h \
+ gibber-linklocal-transport.c \
+ gibber-linklocal-transport.h \
+ asyncns.c \
+ asyncns.h \
gibber-util.h \
gibber-util.c
diff --git a/lib/gibber/asyncns.c b/lib/gibber/asyncns.c
new file mode 100644
index 0000000..4088ce7
--- /dev/null
+++ b/lib/gibber/asyncns.c
@@ -0,0 +1,1498 @@
+/***
+ This file is part of libasyncns.
+
+ Copyright 2005-2008 Lennart Poettering
+
+ libasyncns 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.
+
+ libasyncns 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 libasyncns. If not, see
+ <http://www.gnu.org/licenses/>.
+***/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/* #undef HAVE_PTHREAD */
+
+#include <assert.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <unistd.h>
+#include <sys/select.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <sys/wait.h>
+#include <sys/types.h>
+#include <pwd.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <resolv.h>
+#include <dirent.h>
+
+#if HAVE_ARPA_NAMESER_COMPAT_H
+#include <arpa/nameser_compat.h>
+#endif
+
+#ifdef HAVE_SYS_PRCTL_H
+#include <sys/prctl.h>
+#endif
+
+#if HAVE_PTHREAD
+#include <pthread.h>
+#endif
+
+#include "asyncns.h"
+
+#ifndef MSG_NOSIGNAL
+#define MSG_NOSIGNAL 0
+#endif
+
+#define MAX_WORKERS 16
+#define MAX_QUERIES 256
+#define BUFSIZE (10240)
+
+typedef enum {
+ REQUEST_ADDRINFO,
+ RESPONSE_ADDRINFO,
+ REQUEST_NAMEINFO,
+ RESPONSE_NAMEINFO,
+ REQUEST_RES_QUERY,
+ REQUEST_RES_SEARCH,
+ RESPONSE_RES,
+ REQUEST_TERMINATE,
+ RESPONSE_DIED
+} query_type_t;
+
+enum {
+ REQUEST_RECV_FD = 0,
+ REQUEST_SEND_FD = 1,
+ RESPONSE_RECV_FD = 2,
+ RESPONSE_SEND_FD = 3,
+ MESSAGE_FD_MAX = 4
+};
+
+struct asyncns {
+ int fds[4];
+
+#ifndef HAVE_PTHREAD
+ pid_t workers[MAX_WORKERS];
+#else
+ pthread_t workers[MAX_WORKERS];
+#endif
+ unsigned valid_workers;
+
+ unsigned current_id, current_index;
+ asyncns_query_t* queries[MAX_QUERIES];
+
+ asyncns_query_t *done_head, *done_tail;
+
+ int n_queries;
+ int dead;
+};
+
+struct asyncns_query {
+ asyncns_t *asyncns;
+ int done;
+ unsigned id;
+ query_type_t type;
+ asyncns_query_t *done_next, *done_prev;
+ int ret;
+ int _errno;
+ int _h_errno;
+ struct addrinfo *addrinfo;
+ char *serv, *host;
+ void *userdata;
+};
+
+typedef struct rheader {
+ query_type_t type;
+ unsigned id;
+ size_t length;
+} rheader_t;
+
+typedef struct addrinfo_request {
+ struct rheader header;
+ int hints_is_null;
+ int ai_flags;
+ int ai_family;
+ int ai_socktype;
+ int ai_protocol;
+ size_t node_len, service_len;
+} addrinfo_request_t;
+
+typedef struct addrinfo_response {
+ struct rheader header;
+ int ret;
+ int _errno;
+ int _h_errno;
+ /* followed by addrinfo_serialization[] */
+} addrinfo_response_t;
+
+typedef struct addrinfo_serialization {
+ int ai_flags;
+ int ai_family;
+ int ai_socktype;
+ int ai_protocol;
+ size_t ai_addrlen;
+ size_t canonname_len;
+ /* Followed by ai_addr amd ai_canonname with variable lengths */
+} addrinfo_serialization_t;
+
+typedef struct nameinfo_request {
+ struct rheader header;
+ int flags;
+ socklen_t sockaddr_len;
+ int gethost, getserv;
+} nameinfo_request_t;
+
+typedef struct nameinfo_response {
+ struct rheader header;
+ size_t hostlen, servlen;
+ int ret;
+ int _errno;
+ int _h_errno;
+} nameinfo_response_t;
+
+typedef struct res_query_request {
+ struct rheader header;
+ int class;
+ int type;
+ size_t dname_len;
+} res_request_t;
+
+typedef struct res_query_response {
+ struct rheader header;
+ int ret;
+ int _errno;
+ int _h_errno;
+} res_response_t;
+
+#ifndef HAVE_STRNDUP
+
+static char *strndup(const char *s, size_t l) {
+ size_t a;
+ char *n;
+
+ a = strlen(s);
+ if (a > l)
+ a = l;
+
+ if (!(n = malloc(a+1)))
+ return NULL;
+
+ memcpy(n, s, a);
+ n[a] = 0;
+
+ return n;
+}
+
+#endif
+
+#ifndef HAVE_PTHREAD
+
+static int close_allv(const int except_fds[]) {
+ struct rlimit rl;
+ int fd;
+
+#ifdef __linux__
+
+ DIR *d;
+
+ assert(except_fds);
+
+ if ((d = opendir("/proc/self/fd"))) {
+
+ struct dirent *de;
+
+ while ((de = readdir(d))) {
+ int found;
+ long l;
+ char *e = NULL;
+ int i;
+
+ if (de->d_name[0] == '.')
+ continue;
+
+ errno = 0;
+ l = strtol(de->d_name, &e, 10);
+ if (errno != 0 || !e || *e) {
+ closedir(d);
+ errno = EINVAL;
+ return -1;
+ }
+
+ fd = (int) l;
+
+ if ((long) fd != l) {
+ closedir(d);
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (fd < 3)
+ continue;
+
+ if (fd == dirfd(d))
+ continue;
+
+ found = 0;
+ for (i = 0; except_fds[i] >= 0; i++)
+ if (except_fds[i] == fd) {
+ found = 1;
+ break;
+ }
+
+ if (found)
+ continue;
+
+ if (close(fd) < 0) {
+ int saved_errno;
+
+ saved_errno = errno;
+ closedir(d);
+ errno = saved_errno;
+
+ return -1;
+ }
+ }
+
+ closedir(d);
+ return 0;
+ }
+
+#endif
+
+ if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
+ return -1;
+
+ for (fd = 0; fd < (int) rl.rlim_max; fd++) {
+ int i;
+
+ if (fd <= 3)
+ continue;
+
+ for (i = 0; except_fds[i] >= 0; i++)
+ if (except_fds[i] == fd)
+ continue;
+
+ if (close(fd) < 0 && errno != EBADF)
+ return -1;
+ }
+
+ return 0;
+}
+
+static int reset_sigsv(const int except[]) {
+ int sig;
+ assert(except);
+
+ for (sig = 1; sig < NSIG; sig++) {
+ int reset = 1;
+
+ switch (sig) {
+ case SIGKILL:
+ case SIGSTOP:
+ reset = 0;
+ break;
+
+ default: {
+ int i;
+
+ for (i = 0; except[i] > 0; i++) {
+ if (sig == except[i]) {
+ reset = 0;
+ break;
+ }
+ }
+ }
+ }
+
+ if (reset) {
+ struct sigaction sa;
+
+ memset(&sa, 0, sizeof(sa));
+ sa.sa_handler = SIG_DFL;
+
+ /* On Linux the first two RT signals are reserved by
+ * glibc, and sigaction() will return EINVAL for them. */
+ if ((sigaction(sig, &sa, NULL) < 0))
+ if (errno != EINVAL)
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int ignore_sigsv(const int ignore[]) {
+ int i;
+ assert(ignore);
+
+ for (i = 0; ignore[i] > 0; i++) {
+ struct sigaction sa;
+
+ memset(&sa, 0, sizeof(sa));
+ sa.sa_handler = SIG_IGN;
+
+ if ((sigaction(ignore[i], &sa, NULL) < 0))
+ return -1;
+ }
+
+ return 0;
+}
+
+#endif
+
+static int fd_nonblock(int fd) {
+ int i;
+ assert(fd >= 0);
+
+ if ((i = fcntl(fd, F_GETFL, 0)) < 0)
+ return -1;
+
+ if (i & O_NONBLOCK)
+ return 0;
+
+ return fcntl(fd, F_SETFL, i | O_NONBLOCK);
+}
+
+static int fd_cloexec(int fd) {
+ int v;
+ assert(fd >= 0);
+
+ if ((v = fcntl(fd, F_GETFD, 0)) < 0)
+ return -1;
+
+ if (v & FD_CLOEXEC)
+ return 0;
+
+ return fcntl(fd, F_SETFD, v | FD_CLOEXEC);
+}
+
+static int send_died(int out_fd) {
+ rheader_t rh;
+ assert(out_fd > 0);
+
+ memset(&rh, 0, sizeof(rh));
+ rh.type = RESPONSE_DIED;
+ rh.id = 0;
+ rh.length = sizeof(rh);
+
+ return send(out_fd, &rh, rh.length, MSG_NOSIGNAL);
+}
+
+static void *serialize_addrinfo(void *p, const struct addrinfo *ai, size_t *length, size_t maxlength) {
+ addrinfo_serialization_t s;
+ size_t cnl, l;
+ assert(p);
+ assert(ai);
+ assert(length);
+ assert(*length <= maxlength);
+
+ cnl = (ai->ai_canonname ? strlen(ai->ai_canonname)+1 : 0);
+ l = sizeof(addrinfo_serialization_t) + ai->ai_addrlen + cnl;
+
+ if (*length + l > maxlength)
+ return NULL;
+
+ s.ai_flags = ai->ai_flags;
+ s.ai_family = ai->ai_family;
+ s.ai_socktype = ai->ai_socktype;
+ s.ai_protocol = ai->ai_protocol;
+ s.ai_addrlen = ai->ai_addrlen;
+ s.canonname_len = cnl;
+
+ memcpy((uint8_t*) p, &s, sizeof(addrinfo_serialization_t));
+ memcpy((uint8_t*) p + sizeof(addrinfo_serialization_t), ai->ai_addr, ai->ai_addrlen);
+
+ if (ai->ai_canonname)
+ strcpy((char*) p + sizeof(addrinfo_serialization_t) + ai->ai_addrlen, ai->ai_canonname);
+
+ *length += l;
+ return (uint8_t*) p + l;
+}
+
+static int send_addrinfo_reply(int out_fd, unsigned id, int ret, struct addrinfo *ai, int _errno, int _h_errno) {
+ addrinfo_response_t data[BUFSIZE/sizeof(addrinfo_response_t) + 1];
+ addrinfo_response_t *resp = data;
+ assert(out_fd >= 0);
+
+ memset(data, 0, sizeof(data));
+ resp->header.type = RESPONSE_ADDRINFO;
+ resp->header.id = id;
+ resp->header.length = sizeof(addrinfo_response_t);
+ resp->ret = ret;
+ resp->_errno = _errno;
+ resp->_h_errno = _h_errno;
+
+ if (ret == 0 && ai) {
+ void *p = data + 1;
+ struct addrinfo *k;
+
+ for (k = ai; k; k = k->ai_next) {
+
+ if (!(p = serialize_addrinfo(p, k, &resp->header.length, (char*) data + BUFSIZE - (char*) p))) {
+ resp->ret = EAI_MEMORY;
+ break;
+ }
+ }
+ }
+
+ if (ai)
+ freeaddrinfo(ai);
+
+ return send(out_fd, resp, resp->header.length, MSG_NOSIGNAL);
+}
+
+static int send_nameinfo_reply(int out_fd, unsigned id, int ret, const char *host, const char *serv, int _errno, int _h_errno) {
+ nameinfo_response_t data[BUFSIZE/sizeof(nameinfo_response_t) + 1];
+ size_t hl, sl;
+ nameinfo_response_t *resp = data;
+
+ assert(out_fd >= 0);
+
+ sl = serv ? strlen(serv)+1 : 0;
+ hl = host ? strlen(host)+1 : 0;
+
+ memset(data, 0, sizeof(data));
+ resp->header.type = RESPONSE_NAMEINFO;
+ resp->header.id = id;
+ resp->header.length = sizeof(nameinfo_response_t) + hl + sl;
+ resp->ret = ret;
+ resp->_errno = _errno;
+ resp->_h_errno = _h_errno;
+ resp->hostlen = hl;
+ resp->servlen = sl;
+
+ assert(sizeof(data) >= resp->header.length);
+
+ if (host)
+ memcpy((uint8_t *)data + sizeof(nameinfo_response_t), host, hl);
+
+ if (serv)
+ memcpy((uint8_t *)data + sizeof(nameinfo_response_t) + hl, serv, sl);
+
+ return send(out_fd, resp, resp->header.length, MSG_NOSIGNAL);
+}
+
+static int send_res_reply(int out_fd, unsigned id, const unsigned char *answer, int ret, int _errno, int _h_errno) {
+ res_response_t data[BUFSIZE/sizeof(res_response_t) + 1];
+ res_response_t *resp = data;
+
+ assert(out_fd >= 0);
+
+ memset(data, 0, sizeof(data));
+ resp->header.type = RESPONSE_RES;
+ resp->header.id = id;
+ resp->header.length = sizeof(res_response_t) + (ret < 0 ? 0 : ret);
+ resp->ret = ret;
+ resp->_errno = _errno;
+ resp->_h_errno = _h_errno;
+
+ assert(sizeof(data) >= resp->header.length);
+
+ if (ret > 0)
+ memcpy((uint8_t *)data + sizeof(res_response_t), answer, ret);
+
+ return send(out_fd, resp, resp->header.length, MSG_NOSIGNAL);
+}
+
+static int handle_request(int out_fd, const rheader_t *req, size_t length) {
+ assert(out_fd >= 0);
+ assert(req);
+ assert(length >= sizeof(rheader_t));
+ assert(length == req->length);
+
+ switch (req->type) {
+ case REQUEST_ADDRINFO: {
+ struct addrinfo ai, *result = NULL;
+ const addrinfo_request_t *ai_req = (const addrinfo_request_t*) req;
+ const char *node, *service;
+ int ret;
+
+ assert(length >= sizeof(addrinfo_request_t));
+ assert(length == sizeof(addrinfo_request_t) + ai_req->node_len + ai_req->service_len);
+
+ memset(&ai, 0, sizeof(ai));
+ ai.ai_flags = ai_req->ai_flags;
+ ai.ai_family = ai_req->ai_family;
+ ai.ai_socktype = ai_req->ai_socktype;
+ ai.ai_protocol = ai_req->ai_protocol;
+
+ node = ai_req->node_len ? (const char*) req + sizeof(addrinfo_request_t) : NULL;
+ service = ai_req->service_len ? (const char*) req + sizeof(addrinfo_request_t) + ai_req->node_len : NULL;
+
+ ret = getaddrinfo(node, service,
+ ai_req->hints_is_null ? NULL : &ai,
+ &result);
+
+ /* send_addrinfo_reply() frees result */
+ return send_addrinfo_reply(out_fd, req->id, ret, result, errno, h_errno);
+ }
+
+ case REQUEST_NAMEINFO: {
+ int ret;
+ const nameinfo_request_t *ni_req = (const nameinfo_request_t*) req;
+ char hostbuf[NI_MAXHOST], servbuf[NI_MAXSERV];
+ struct sockaddr_storage sa;
+
+ assert(length >= sizeof(nameinfo_request_t));
+ assert(length == sizeof(nameinfo_request_t) + ni_req->sockaddr_len);
+
+ memcpy(&sa, (const uint8_t *)req + sizeof(nameinfo_request_t), ni_req->sockaddr_len);
+
+ ret = getnameinfo((struct sockaddr *)&sa, ni_req->sockaddr_len,
+ ni_req->gethost ? hostbuf : NULL, ni_req->gethost ? sizeof(hostbuf) : 0,
+ ni_req->getserv ? servbuf : NULL, ni_req->getserv ? sizeof(servbuf) : 0,
+ ni_req->flags);
+
+ return send_nameinfo_reply(out_fd, req->id, ret,
+ ret == 0 && ni_req->gethost ? hostbuf : NULL,
+ ret == 0 && ni_req->getserv ? servbuf : NULL,
+ errno, h_errno);
+ }
+
+ case REQUEST_RES_QUERY:
+ case REQUEST_RES_SEARCH: {
+ int ret;
+ HEADER answer[BUFSIZE/sizeof(HEADER) + 1];
+ const res_request_t *res_req = (const res_request_t *)req;
+ const char *dname;
+
+ assert(length >= sizeof(res_request_t));
+ assert(length == sizeof(res_request_t) + res_req->dname_len);
+
+ dname = (const char *) req + sizeof(res_request_t);
+
+ if (req->type == REQUEST_RES_QUERY)
+ ret = res_query(dname, res_req->class, res_req->type, (unsigned char *) answer, BUFSIZE);
+ else
+ ret = res_search(dname, res_req->class, res_req->type, (unsigned char *) answer, BUFSIZE);
+
+ return send_res_reply(out_fd, req->id, (unsigned char *) answer, ret, errno, h_errno);
+ }
+
+ case REQUEST_TERMINATE:
+ /* Quit */
+ return -1;
+
+ default:
+ ;
+ }
+
+ return 0;
+}
+
+#ifndef HAVE_PTHREAD
+
+static int process_worker(int in_fd, int out_fd) {
+ int have_death_sig = 0;
+ int good_fds[3];
+ int ret = 1;
+
+ const int ignore_sigs[] = {
+ SIGINT,
+ SIGHUP,
+ SIGPIPE,
+ SIGUSR1,
+ SIGUSR2,
+ -1
+ };
+
+ assert(in_fd > 2);
+ assert(out_fd > 2);
+
+ close(0);
+ close(1);
+ close(2);
+
+ if (open("/dev/null", O_RDONLY) != 0)
+ goto fail;
+
+ if (open("/dev/null", O_WRONLY) != 1)
+ goto fail;
+
+ if (open("/dev/null", O_WRONLY) != 2)
+ goto fail;
+
+ if (chdir("/") < 0)
+ goto fail;
+
+ if (geteuid() == 0) {
+ struct passwd *pw;
+ int r;
+
+ if ((pw = getpwnam("nobody"))) {
+#ifdef HAVE_SETRESUID
+ r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
+#elif HAVE_SETREUID
+ r = setreuid(pw->pw_uid, pw->pw_uid);
+#else
+ if ((r = setuid(pw->pw_uid)) >= 0)
+ r = seteuid(pw->pw_uid);
+#endif
+ if (r < 0)
+ goto fail;
+ }
+ }
+
+ if (reset_sigsv(ignore_sigs) < 0)
+ goto fail;
+
+ if (ignore_sigsv(ignore_sigs) < 0)
+ goto fail;
+
+ good_fds[0] = in_fd; good_fds[1] = out_fd; good_fds[2] = -1;
+ if (close_allv(good_fds) < 0)
+ goto fail;
+
+#ifdef PR_SET_PDEATHSIG
+ if (prctl(PR_SET_PDEATHSIG, SIGTERM) >= 0)
+ have_death_sig = 1;
+#endif
+
+ if (!have_death_sig)
+ fd_nonblock(in_fd);
+
+ while (getppid() > 1) { /* if the parent PID is 1 our parent process died. */
+ rheader_t buf[BUFSIZE/sizeof(rheader_t) + 1];
+ ssize_t length;
+
+ if (!have_death_sig) {
+ fd_set fds;
+ struct timeval tv = { 0, 500000 };
+
+ FD_ZERO(&fds);
+ FD_SET(in_fd, &fds);
+
+ if (select(in_fd+1, &fds, NULL, NULL, &tv) < 0)
+ break;
+
+ if (getppid() == 1)
+ break;
+ }
+
+ if ((length = recv(in_fd, buf, sizeof(buf), 0)) <= 0) {
+
+ if (length < 0 &&
+ (errno == EAGAIN || errno == EINTR))
+ continue;
+
+ break;
+ }
+
+ if (handle_request(out_fd, buf, (size_t) length) < 0)
+ break;
+ }
+
+ ret = 0;
+
+fail:
+ send_died(out_fd);
+
+ return ret;
+}
+
+#else
+
+static void* thread_worker(void *p) {
+ asyncns_t *asyncns = p;
+ sigset_t fullset;
+
+ /* No signals in this thread please */
+ sigfillset(&fullset);
+ pthread_sigmask(SIG_BLOCK, &fullset, NULL);
+
+ while (!asyncns->dead) {
+ rheader_t buf[BUFSIZE/sizeof(rheader_t) + 1];
+ ssize_t length;
+
+ if ((length = recv(asyncns->fds[REQUEST_RECV_FD], buf, sizeof(buf), 0)) <= 0) {
+
+ if (length < 0 &&
+ (errno == EAGAIN || errno == EINTR))
+ continue;
+
+ break;
+ }
+
+ if (asyncns->dead)
+ break;
+
+ if (handle_request(asyncns->fds[RESPONSE_SEND_FD], buf, (size_t) length) < 0)
+ break;
+ }
+
+ send_died(asyncns->fds[RESPONSE_SEND_FD]);
+
+ return NULL;
+}
+
+#endif
+
+asyncns_t* asyncns_new(unsigned n_proc) {
+ asyncns_t *asyncns = NULL;
+ int i;
+ assert(n_proc >= 1);
+
+ if (n_proc > MAX_WORKERS)
+ n_proc = MAX_WORKERS;
+
+ if (!(asyncns = malloc(sizeof(asyncns_t)))) {
+ errno = ENOMEM;
+ goto fail;
+ }
+
+ asyncns->dead = 0;
+ asyncns->valid_workers = 0;
+
+ for (i = 0; i < MESSAGE_FD_MAX; i++)
+ asyncns->fds[i] = -1;
+
+ memset(asyncns->queries, 0, sizeof(asyncns->queries));
+
+ if (socketpair(PF_UNIX, SOCK_DGRAM, 0, asyncns->fds) < 0 ||
+ socketpair(PF_UNIX, SOCK_DGRAM, 0, asyncns->fds+2) < 0)
+ goto fail;
+
+ for (i = 0; i < MESSAGE_FD_MAX; i++)
+ fd_cloexec(asyncns->fds[i]);
+
+ for (asyncns->valid_workers = 0; asyncns->valid_workers < n_proc; asyncns->valid_workers++) {
+
+#ifndef HAVE_PTHREAD
+ if ((asyncns->workers[asyncns->valid_workers] = fork()) < 0)
+ goto fail;
+ else if (asyncns->workers[asyncns->valid_workers] == 0) {
+ int ret;
+
+ close(asyncns->fds[REQUEST_SEND_FD]);
+ close(asyncns->fds[RESPONSE_RECV_FD]);
+ ret = process_worker(asyncns->fds[REQUEST_RECV_FD], asyncns->fds[RESPONSE_SEND_FD]);
+ close(asyncns->fds[REQUEST_RECV_FD]);
+ close(asyncns->fds[RESPONSE_SEND_FD]);
+ _exit(ret);
+ }
+#else
+ int r;
+
+ if ((r = pthread_create(&asyncns->workers[asyncns->valid_workers], NULL, thread_worker, asyncns)) != 0) {
+ errno = r;
+ goto fail;
+ }
+#endif
+ }
+
+#ifndef HAVE_PTHREAD
+ close(asyncns->fds[REQUEST_RECV_FD]);
+ close(asyncns->fds[RESPONSE_SEND_FD]);
+ asyncns->fds[REQUEST_RECV_FD] = asyncns->fds[RESPONSE_SEND_FD] = -1;
+#endif
+
+ asyncns->current_index = asyncns->current_id = 0;
+ asyncns->done_head = asyncns->done_tail = NULL;
+ asyncns->n_queries = 0;
+
+ fd_nonblock(asyncns->fds[RESPONSE_RECV_FD]);
+
+ return asyncns;
+
+fail:
+ if (asyncns)
+ asyncns_free(asyncns);
+
+ return NULL;
+}
+
+void asyncns_free(asyncns_t *asyncns) {
+ int i;
+ int saved_errno = errno;
+ unsigned p;
+
+ assert(asyncns);
+
+ asyncns->dead = 1;
+
+ if (asyncns->fds[REQUEST_SEND_FD] >= 0) {
+ rheader_t req;
+
+ memset(&req, 0, sizeof(req));
+ req.type = REQUEST_TERMINATE;
+ req.length = sizeof(req);
+ req.id = 0;
+
+ /* Send one termination packet for each worker */
+ for (p = 0; p < asyncns->valid_workers; p++)
+ send(asyncns->fds[REQUEST_SEND_FD], &req, req.length, MSG_NOSIGNAL);
+ }
+
+ /* Now terminate them and wait until they are gone. */
+ for (p = 0; p < asyncns->valid_workers; p++) {
+#ifndef HAVE_PTHREAD
+ kill(asyncns->workers[p], SIGTERM);
+ for (;;) {
+ if (waitpid(asyncns->workers[p], NULL, 0) >= 0 || errno != EINTR)
+ break;
+ }
+#else
+ for (;;) {
+ if (pthread_join(asyncns->workers[p], NULL) != EINTR)
+ break;
+ }
+#endif
+ }
+
+ /* Close all communication channels */
+ for (i = 0; i < MESSAGE_FD_MAX; i++)
+ if (asyncns->fds[i] >= 0)
+ close(asyncns->fds[i]);
+
+ for (p = 0; p < MAX_QUERIES; p++)
+ if (asyncns->queries[p])
+ asyncns_cancel(asyncns, asyncns->queries[p]);
+
+ free(asyncns);
+
+ errno = saved_errno;
+}
+
+int asyncns_fd(asyncns_t *asyncns) {
+ assert(asyncns);
+
+ return asyncns->fds[RESPONSE_RECV_FD];
+}
+
+static asyncns_query_t *lookup_query(asyncns_t *asyncns, unsigned id) {
+ asyncns_query_t *q;
+ assert(asyncns);
+
+ if ((q = asyncns->queries[id % MAX_QUERIES]))
+ if (q->id == id)
+ return q;
+
+ return NULL;
+}
+
+static void complete_query(asyncns_t *asyncns, asyncns_query_t *q) {
+ assert(asyncns);
+ assert(q);
+ assert(!q->done);
+
+ q->done = 1;
+
+ if ((q->done_prev = asyncns->done_tail))
+ asyncns->done_tail->done_next = q;
+ else
+ asyncns->done_head = q;
+
+ asyncns->done_tail = q;
+ q->done_next = NULL;
+}
+
+static void *unserialize_addrinfo(void *p, struct addrinfo **ret_ai, size_t *length) {
+ addrinfo_serialization_t s;
+ size_t l;
+ struct addrinfo *ai;
+ assert(p);
+ assert(ret_ai);
+ assert(length);
+
+ if (*length < sizeof(addrinfo_serialization_t))
+ return NULL;
+
+ memcpy(&s, p, sizeof(s));
+
+ l = sizeof(addrinfo_serialization_t) + s.ai_addrlen + s.canonname_len;
+ if (*length < l)
+ return NULL;
+
+ if (!(ai = malloc(sizeof(struct addrinfo))))
+ goto fail;
+
+ ai->ai_addr = NULL;
+ ai->ai_canonname = NULL;
+ ai->ai_next = NULL;
+
+ if (s.ai_addrlen && !(ai->ai_addr = malloc(s.ai_addrlen)))
+ goto fail;
+
+ if (s.canonname_len && !(ai->ai_canonname = malloc(s.canonname_len)))
+ goto fail;
+
+ ai->ai_flags = s.ai_flags;
+ ai->ai_family = s.ai_family;
+ ai->ai_socktype = s.ai_socktype;
+ ai->ai_protocol = s.ai_protocol;
+ ai->ai_addrlen = s.ai_addrlen;
+
+ if (ai->ai_addr)
+ memcpy(ai->ai_addr, (uint8_t*) p + sizeof(addrinfo_serialization_t), s.ai_addrlen);
+
+ if (ai->ai_canonname)
+ memcpy(ai->ai_canonname, (uint8_t*) p + sizeof(addrinfo_serialization_t) + s.ai_addrlen, s.canonname_len);
+
+ *length -= l;
+ *ret_ai = ai;
+
+ return (uint8_t*) p + l;
+
+
+fail:
+ if (ai)
+ asyncns_freeaddrinfo(ai);
+
+ return NULL;
+}
+
+static int handle_response(asyncns_t *asyncns, rheader_t *resp, size_t length) {
+ asyncns_query_t *q;
+ assert(asyncns);
+ assert(resp);
+ assert(length >= sizeof(rheader_t));
+ assert(length == resp->length);
+
+ if (resp->type == RESPONSE_DIED) {
+ asyncns->dead = 1;
+ return 0;
+ }
+
+ if (!(q = lookup_query(asyncns, resp->id)))
+ return 0;
+
+ switch (resp->type) {
+ case RESPONSE_ADDRINFO: {
+ const addrinfo_response_t *ai_resp = (addrinfo_response_t*) resp;
+ void *p;
+ size_t l;
+ struct addrinfo *prev = NULL;
+
+ assert(length >= sizeof(addrinfo_response_t));
+ assert(q->type == REQUEST_ADDRINFO);
+
+ q->ret = ai_resp->ret;
+ q->_errno = ai_resp->_errno;
+ q->_h_errno = ai_resp->_h_errno;
+ l = length - sizeof(addrinfo_response_t);
+ p = (uint8_t*) resp + sizeof(addrinfo_response_t);
+
+ while (l > 0 && p) {
+ struct addrinfo *ai = NULL;
+ p = unserialize_addrinfo(p, &ai, &l);
+
+ if (!p || !ai) {
+ q->ret = EAI_MEMORY;
+ break;
+ }
+
+ if (prev)
+ prev->ai_next = ai;
+ else
+ q->addrinfo = ai;
+
+ prev = ai;
+ }
+
+ complete_query(asyncns, q);
+ break;
+ }
+
+ case RESPONSE_NAMEINFO: {
+ const nameinfo_response_t *ni_resp = (nameinfo_response_t*) resp;
+
+ assert(length >= sizeof(nameinfo_response_t));
+ assert(q->type == REQUEST_NAMEINFO);
+
+ q->ret = ni_resp->ret;
+ q->_errno = ni_resp->_errno;
+ q->_h_errno = ni_resp->_h_errno;
+
+ if (ni_resp->hostlen)
+ if (!(q->host = strndup((const char*) ni_resp + sizeof(nameinfo_response_t), ni_resp->hostlen-1)))
+ q->ret = EAI_MEMORY;
+
+ if (ni_resp->servlen)
+ if (!(q->serv = strndup((const char*) ni_resp + sizeof(nameinfo_response_t) + ni_resp->hostlen, ni_resp->servlen-1)))
+ q->ret = EAI_MEMORY;
+
+ complete_query(asyncns, q);
+ break;
+ }
+
+ case RESPONSE_RES: {
+ const res_response_t *res_resp = (res_response_t *)resp;
+
+ assert(length >= sizeof(res_response_t));
+ assert(q->type == REQUEST_RES_QUERY || q->type == REQUEST_RES_SEARCH);
+
+ q->ret = res_resp->ret;
+ q->_errno = res_resp->_errno;
+ q->_h_errno = res_resp->_h_errno;
+
+ if (res_resp->ret >= 0) {
+ if (!(q->serv = malloc(res_resp->ret))) {
+ q->ret = -1;
+ q->_errno = ENOMEM;
+ } else
+ memcpy(q->serv, (char *)resp + sizeof(res_response_t), res_resp->ret);
+ }
+
+ complete_query(asyncns, q);
+ break;
+ }
+
+ default:
+ ;
+ }
+
+ return 0;
+}
+
+int asyncns_wait(asyncns_t *asyncns, int block) {
+ int handled = 0;
+ assert(asyncns);
+
+ for (;;) {
+ rheader_t buf[BUFSIZE/sizeof(rheader_t) + 1];
+ ssize_t l;
+
+ if (asyncns->dead) {
+ errno = ECHILD;
+ return -1;
+ }
+
+ if (((l = recv(asyncns->fds[RESPONSE_RECV_FD], buf, sizeof(buf), 0)) < 0)) {
+ fd_set fds;
+
+ if (errno != EAGAIN)
+ return -1;
+
+ if (!block || handled)
+ return 0;
+
+ FD_ZERO(&fds);
+ FD_SET(asyncns->fds[RESPONSE_RECV_FD], &fds);
+
+ if (select(asyncns->fds[RESPONSE_RECV_FD]+1, &fds, NULL, NULL, NULL) < 0)
+ return -1;
+
+ continue;
+ }
+
+ if (handle_response(asyncns, buf, (size_t) l) < 0)
+ return -1;
+
+ handled = 1;
+ }
+}
+
+static asyncns_query_t *alloc_query(asyncns_t *asyncns) {
+ asyncns_query_t *q;
+ assert(asyncns);
+
+ if (asyncns->n_queries >= MAX_QUERIES) {
+ errno = ENOMEM;
+ return NULL;
+ }
+
+ while (asyncns->queries[asyncns->current_index]) {
+
+ asyncns->current_index++;
+ asyncns->current_id++;
+
+ while (asyncns->current_index >= MAX_QUERIES)
+ asyncns->current_index -= MAX_QUERIES;
+ }
+
+ if (!(q = asyncns->queries[asyncns->current_index] = malloc(sizeof(asyncns_query_t)))) {
+ errno = ENOMEM;
+ return NULL;
+ }
+
+ asyncns->n_queries++;
+
+ q->asyncns = asyncns;
+ q->done = 0;
+ q->id = asyncns->current_id;
+ q->done_next = q->done_prev = NULL;
+ q->ret = 0;
+ q->_errno = 0;
+ q->_h_errno = 0;
+ q->addrinfo = NULL;
+ q->userdata = NULL;
+ q->host = q->serv = NULL;
+
+ return q;
+}
+
+asyncns_query_t* asyncns_getaddrinfo(asyncns_t *asyncns, const char *node, const char *service, const struct addrinfo *hints) {
+ addrinfo_request_t data[BUFSIZE/sizeof(addrinfo_request_t) + 1];
+ addrinfo_request_t *req = data;
+ asyncns_query_t *q;
+ assert(asyncns);
+ assert(node || service);
+
+ if (asyncns->dead) {
+ errno = ECHILD;
+ return NULL;
+ }
+
+ if (!(q = alloc_query(asyncns)))
+ return NULL;
+
+ memset(req, 0, sizeof(addrinfo_request_t));
+
+ req->node_len = node ? strlen(node)+1 : 0;
+ req->service_len = service ? strlen(service)+1 : 0;
+
+ req->header.id = q->id;
+ req->header.type = q->type = REQUEST_ADDRINFO;
+ req->header.length = sizeof(addrinfo_request_t) + req->node_len + req->service_len;
+
+ if (req->header.length > BUFSIZE) {
+ errno = ENOMEM;
+ goto fail;
+ }
+
+ if (!(req->hints_is_null = !hints)) {
+ req->ai_flags = hints->ai_flags;
+ req->ai_family = hints->ai_family;
+ req->ai_socktype = hints->ai_socktype;
+ req->ai_protocol = hints->ai_protocol;
+ }
+
+ if (node)
+ strcpy((char*) req + sizeof(addrinfo_request_t), node);
+
+ if (service)
+ strcpy((char*) req + sizeof(addrinfo_request_t) + req->node_len, service);
+
+ if (send(asyncns->fds[REQUEST_SEND_FD], req, req->header.length, MSG_NOSIGNAL) < 0)
+ goto fail;
+
+ return q;
+
+fail:
+ if (q)
+ asyncns_cancel(asyncns, q);
+
+ return NULL;
+}
+
+int asyncns_getaddrinfo_done(asyncns_t *asyncns, asyncns_query_t* q, struct addrinfo **ret_res) {
+ int ret;
+ assert(asyncns);
+ assert(q);
+ assert(q->asyncns == asyncns);
+ assert(q->type == REQUEST_ADDRINFO);
+
+ if (asyncns->dead) {
+ errno = ECHILD;
+ return EAI_SYSTEM;
+ }
+
+ if (!q->done)
+ return EAI_AGAIN;
+
+ *ret_res = q->addrinfo;
+ q->addrinfo = NULL;
+
+ ret = q->ret;
+
+ if (ret == EAI_SYSTEM)
+ errno = q->_errno;
+
+ if (ret != 0)
+ h_errno = q->_h_errno;
+
+ asyncns_cancel(asyncns, q);
+
+ return ret;
+}
+
+asyncns_query_t* asyncns_getnameinfo(asyncns_t *asyncns, const struct sockaddr *sa, socklen_t salen, int flags, int gethost, int getserv) {
+ nameinfo_request_t data[BUFSIZE/sizeof(nameinfo_request_t) + 1];
+ nameinfo_request_t *req = data;
+ asyncns_query_t *q;
+
+ assert(asyncns);
+ assert(sa);
+ assert(salen > 0);
+
+ if (asyncns->dead) {
+ errno = ECHILD;
+ return NULL;
+ }
+
+ if (!(q = alloc_query(asyncns)))
+ return NULL;
+
+ memset(req, 0, sizeof(nameinfo_request_t));
+
+ req->header.id = q->id;
+ req->header.type = q->type = REQUEST_NAMEINFO;
+ req->header.length = sizeof(nameinfo_request_t) + salen;
+
+ if (req->header.length > BUFSIZE) {
+ errno = ENOMEM;
+ goto fail;
+ }
+
+ req->flags = flags;
+ req->sockaddr_len = salen;
+ req->gethost = gethost;
+ req->getserv = getserv;
+
+ memcpy((uint8_t*) req + sizeof(nameinfo_request_t), sa, salen);
+
+ if (send(asyncns->fds[REQUEST_SEND_FD], req, req->header.length, MSG_NOSIGNAL) < 0)
+ goto fail;
+
+ return q;
+
+fail:
+ if (q)
+ asyncns_cancel(asyncns, q);
+
+ return NULL;
+}
+
+int asyncns_getnameinfo_done(asyncns_t *asyncns, asyncns_query_t* q, char *ret_host, size_t hostlen, char *ret_serv, size_t servlen) {
+ int ret;
+ assert(asyncns);
+ assert(q);
+ assert(q->asyncns == asyncns);
+ assert(q->type == REQUEST_NAMEINFO);
+ assert(!ret_host || hostlen);
+ assert(!ret_serv || servlen);
+
+ if (asyncns->dead) {
+ errno = ECHILD;
+ return EAI_SYSTEM;
+ }
+
+ if (!q->done)
+ return EAI_AGAIN;
+
+ if (ret_host && q->host) {
+ strncpy(ret_host, q->host, hostlen);
+ ret_host[hostlen-1] = 0;
+ }
+
+ if (ret_serv && q->serv) {
+ strncpy(ret_serv, q->serv, servlen);
+ ret_serv[servlen-1] = 0;
+ }
+
+ ret = q->ret;
+
+ if (ret == EAI_SYSTEM)
+ errno = q->_errno;
+
+ if (ret != 0)
+ h_errno = q->_h_errno;
+
+ asyncns_cancel(asyncns, q);
+
+ return ret;
+}
+
+static asyncns_query_t * asyncns_res(asyncns_t *asyncns, query_type_t qtype, const char *dname, int class, int type) {
+ res_request_t data[BUFSIZE/sizeof(res_request_t) + 1];
+ res_request_t *req = data;
+ asyncns_query_t *q;
+
+ assert(asyncns);
+ assert(dname);
+
+ if (asyncns->dead) {
+ errno = ECHILD;
+ return NULL;
+ }
+
+ if (!(q = alloc_query(asyncns)))
+ return NULL;
+
+ memset(req, 0, sizeof(res_request_t));
+
+ req->dname_len = strlen(dname) + 1;
+
+ req->header.id = q->id;
+ req->header.type = q->type = qtype;
+ req->header.length = sizeof(res_request_t) + req->dname_len;
+
+ if (req->header.length > BUFSIZE) {
+ errno = ENOMEM;
+ goto fail;
+ }
+
+ req->class = class;
+ req->type = type;
+
+ strcpy((char*) req + sizeof(res_request_t), dname);
+
+ if (send(asyncns->fds[REQUEST_SEND_FD], req, req->header.length, MSG_NOSIGNAL) < 0)
+ goto fail;
+
+ return q;
+
+fail:
+ if (q)
+ asyncns_cancel(asyncns, q);
+
+ return NULL;
+}
+
+asyncns_query_t* asyncns_res_query(asyncns_t *asyncns, const char *dname, int class, int type) {
+ return asyncns_res(asyncns, REQUEST_RES_QUERY, dname, class, type);
+}
+
+asyncns_query_t* asyncns_res_search(asyncns_t *asyncns, const char *dname, int class, int type) {
+ return asyncns_res(asyncns, REQUEST_RES_SEARCH, dname, class, type);
+}
+
+int asyncns_res_done(asyncns_t *asyncns, asyncns_query_t* q, unsigned char **answer) {
+ int ret;
+ assert(asyncns);
+ assert(q);
+ assert(q->asyncns == asyncns);
+ assert(q->type == REQUEST_RES_QUERY || q->type == REQUEST_RES_SEARCH);
+ assert(answer);
+
+ if (asyncns->dead) {
+ errno = ECHILD;
+ return -ECHILD;
+ }
+
+ if (!q->done) {
+ errno = EAGAIN;
+ return -EAGAIN;
+ }
+
+ *answer = (unsigned char *)q->serv;
+ q->serv = NULL;
+
+ ret = q->ret;
+
+ if (ret < 0) {
+ errno = q->_errno;
+ h_errno = q->_h_errno;
+ }
+
+ asyncns_cancel(asyncns, q);
+
+ return ret < 0 ? -errno : ret;
+}
+
+asyncns_query_t* asyncns_getnext(asyncns_t *asyncns) {
+ assert(asyncns);
+ return asyncns->done_head;
+}
+
+int asyncns_getnqueries(asyncns_t *asyncns) {
+ assert(asyncns);
+ return asyncns->n_queries;
+}
+
+void asyncns_cancel(asyncns_t *asyncns, asyncns_query_t* q) {
+ int i;
+ int saved_errno = errno;
+
+ assert(asyncns);
+ assert(q);
+ assert(q->asyncns == asyncns);
+ assert(asyncns->n_queries > 0);
+
+ if (q->done) {
+
+ if (q->done_prev)
+ q->done_prev->done_next = q->done_next;
+ else
+ asyncns->done_head = q->done_next;
+
+ if (q->done_next)
+ q->done_next->done_prev = q->done_prev;
+ else
+ asyncns->done_tail = q->done_prev;
+ }
+
+ i = q->id % MAX_QUERIES;
+ assert(asyncns->queries[i] == q);
+ asyncns->queries[i] = NULL;
+
+ asyncns_freeaddrinfo(q->addrinfo);
+ free(q->host);
+ free(q->serv);
+
+ asyncns->n_queries--;
+ free(q);
+
+ errno = saved_errno;
+}
+
+void asyncns_freeaddrinfo(struct addrinfo *ai) {
+ int saved_errno = errno;
+
+ while (ai) {
+ struct addrinfo *next = ai->ai_next;
+
+ free(ai->ai_addr);
+ free(ai->ai_canonname);
+ free(ai);
+
+ ai = next;
+ }
+
+ errno = saved_errno;
+}
+
+void asyncns_freeanswer(unsigned char *answer) {
+ int saved_errno = errno;
+
+ if (!answer)
+ return;
+
+ /* Please note that this function is new in libasyncns 0.4. In
+ * older versions you were supposed to free the answer directly
+ * with free(). Hence, if this function is changed to do more than
+ * just a simple free() this must be considered ABI/API breakage! */
+
+ free(answer);
+
+ errno = saved_errno;
+}
+
+int asyncns_isdone(asyncns_t *asyncns, asyncns_query_t*q) {
+ assert(asyncns);
+ assert(q);
+ assert(q->asyncns == asyncns);
+
+ return q->done;
+}
+
+void asyncns_setuserdata(asyncns_t *asyncns, asyncns_query_t *q, void *userdata) {
+ assert(q);
+ assert(asyncns);
+ assert(q->asyncns = asyncns);
+
+ q->userdata = userdata;
+}
+
+void* asyncns_getuserdata(asyncns_t *asyncns, asyncns_query_t *q) {
+ assert(q);
+ assert(asyncns);
+ assert(q->asyncns = asyncns);
+
+ return q->userdata;
+}
diff --git a/lib/gibber/asyncns.h b/lib/gibber/asyncns.h
new file mode 100644
index 0000000..9f2cbd6
--- /dev/null
+++ b/lib/gibber/asyncns.h
@@ -0,0 +1,163 @@
+#ifndef fooasyncnshfoo
+#define fooasyncnshfoo
+
+/***
+ This file is part of libasyncns.
+
+ Copyright 2005-2008 Lennart Poettering
+
+ libasyncns 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.
+
+ libasyncns 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 libasyncns. If not, see
+ <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netdb.h>
+
+/** \mainpage
+ *
+ * \section moo Method of operation
+ *
+ * To use libasyncns allocate an asyncns_t object with
+ * asyncns_new(). This will spawn a number of worker threads (or processes, depending on what is available) which
+ * are subsequently used to process the queries the controlling
+ * program issues via asyncns_getaddrinfo() and
+ * asyncns_getnameinfo(). Use asyncns_free() to shut down the worker
+ * threads/processes.
+ *
+ * Since libasyncns may fork off new processes you have to make sure that
+ * your program is not irritated by spurious SIGCHLD signals.
+ */
+
+/** \example asyncns-test.c
+ * An example program */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** An opaque libasyncns session structure */
+typedef struct asyncns asyncns_t;
+
+/** An opaque libasyncns query structure */
+typedef struct asyncns_query asyncns_query_t;
+
+/** Allocate a new libasyncns session with n_proc worker processes/threads */
+asyncns_t* asyncns_new(unsigned n_proc);
+
+/** Free a libasyncns session. This destroys all attached
+ * asyncns_query_t objects automatically */
+void asyncns_free(asyncns_t *asyncns);
+
+/** Return the UNIX file descriptor to select() for readability
+ * on. Use this function to integrate libasyncns with your custom main
+ * loop. */
+int asyncns_fd(asyncns_t *asyncns);
+
+/** Process pending responses. After this function is called you can
+ * get the next completed query object(s) using asyncns_getnext(). If
+ * block is non-zero wait until at least one response has been
+ * processed. If block is zero, process all pending responses and
+ * return. */
+int asyncns_wait(asyncns_t *asyncns, int block);
+
+/** Issue a name to address query on the specified session. The
+ * arguments are compatible with the ones of libc's
+ * getaddrinfo(3). The function returns a new query object. When the
+ * query is completed you may retrieve the results using
+ * asyncns_getaddrinfo_done().*/
+asyncns_query_t* asyncns_getaddrinfo(asyncns_t *asyncns, const char *node, const char *service, const struct addrinfo *hints);
+
+/** Retrieve the results of a preceding asyncns_getaddrinfo()
+ * call. Returns a addrinfo structure and a return value compatible
+ * with libc's getaddrinfo(3). The query object q is destroyed by this
+ * call and may not be used any further. Make sure to free the
+ * returned addrinfo structure with asyncns_freeaddrinfo() and not
+ * libc's freeaddrinfo(3)! If the query is not completed yet EAI_AGAIN
+ * is returned.*/
+int asyncns_getaddrinfo_done(asyncns_t *asyncns, asyncns_query_t* q, struct addrinfo **ret_res);
+
+/** Issue an address to name query on the specified session. The
+ * arguments are compatible with the ones of libc's
+ * getnameinfo(3). The function returns a new query object. When the
+ * query is completed you may retrieve the results using
+ * asyncns_getnameinfo_done(). Set gethost (resp. getserv) to non-zero
+ * if you want to query the hostname (resp. the service name). */
+asyncns_query_t* asyncns_getnameinfo(asyncns_t *asyncns, const struct sockaddr *sa, socklen_t salen, int flags, int gethost, int getserv);
+
+/** Retrieve the results of a preceding asyncns_getnameinfo()
+ * call. Returns the hostname and the service name in ret_host and
+ * ret_serv. The query object q is destroyed by this call and may not
+ * be used any further. If the query is not completed yet EAI_AGAIN is
+ * returned. */
+int asyncns_getnameinfo_done(asyncns_t *asyncns, asyncns_query_t* q, char *ret_host, size_t hostlen, char *ret_serv, size_t servlen);
+
+/** Issue a resolver query on the specified session. The arguments are
+ * compatible with the ones of libc's res_query(3). The function returns a new
+ * query object. When the query is completed you may retrieve the results using
+ * asyncns_res_done(). */
+asyncns_query_t* asyncns_res_query(asyncns_t *asyncns, const char *dname, int class, int type);
+
+/** Issue an resolver query on the specified session. The arguments are
+ * compatible with the ones of libc's res_search(3). The function returns a new
+ * query object. When the query is completed you may retrieve the results using
+ * asyncns_res_done(). */
+asyncns_query_t* asyncns_res_search(asyncns_t *asyncns, const char *dname, int class, int type);
+
+/** Retrieve the results of a preceding asyncns_res_query() or
+ * asyncns_res_search call. The query object q is destroyed by this
+ * call and may not be used any further. Returns a pointer to the
+ * answer of the res_query call. If the query is not completed yet
+ * -EAGAIN is returned, on failure -errno is returned, otherwise the
+ * length of answer is returned. Make sure to free the answer is a
+ * call to asyncns_freeanswer(). */
+int asyncns_res_done(asyncns_t *asyncns, asyncns_query_t* q, unsigned char **answer);
+
+/** Return the next completed query object. If no query has been
+ * completed yet, return NULL. Please note that you need to run
+ * asyncns_wait() before this function will return sensible data. */
+asyncns_query_t* asyncns_getnext(asyncns_t *asyncns);
+
+/** Return the number of query objects (completed or not) attached to
+ * this session */
+int asyncns_getnqueries(asyncns_t *asyncns);
+
+/** Cancel a currently running query. q is is destroyed by this call
+ * and may not be used any futher. */
+void asyncns_cancel(asyncns_t *asyncns, asyncns_query_t* q);
+
+/** Free the addrinfo structure as returned by
+ * asyncns_getaddrinfo_done(). Make sure to use this functions instead
+ * of the libc's freeaddrinfo()! */
+void asyncns_freeaddrinfo(struct addrinfo *ai);
+
+/** Free the answer data as returned by asyncns_res_done().*/
+void asyncns_freeanswer(unsigned char *answer);
+
+/** Returns non-zero when the query operation specified by q has been completed */
+int asyncns_isdone(asyncns_t *asyncns, asyncns_query_t*q);
+
+/** Assign some opaque userdata with a query object */
+void asyncns_setuserdata(asyncns_t *asyncns, asyncns_query_t *q, void *userdata);
+
+/** Return userdata assigned to a query object. Use
+ * asyncns_setuserdata() to set this data. If no data has been set
+ * prior to this call it returns NULL. */
+void* asyncns_getuserdata(asyncns_t *asyncns, asyncns_query_t *q);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/lib/gibber/gibber-resolver-asyncns.c b/lib/gibber/gibber-resolver-asyncns.c
new file mode 100644
index 0000000..3624d85
--- /dev/null
+++ b/lib/gibber/gibber-resolver-asyncns.c
@@ -0,0 +1,415 @@
+/*
+ * gibber-resolver-asyncns.c - Source for GibberResolverAsyncns
+ * Copyright (C) 2008 Collabora Ltd.
+ * @author Sjoerd Simons <sjoerd.simons at collabora.co.uk>
+ *
+ * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <resolv.h>
+
+#include <asyncns.h>
+
+#include "gibber-resolver-asyncns.h"
+
+G_DEFINE_TYPE(GibberResolverAsyncns, gibber_resolver_asyncns,
+ GIBBER_TYPE_RESOLVER)
+
+/* private structure */
+typedef struct _GibberResolverAsyncnsPrivate GibberResolverAsyncnsPrivate;
+
+struct _GibberResolverAsyncnsPrivate
+{
+ asyncns_t *asyncns;
+ GIOChannel *asyncio;
+ int asyncns_fd;
+ guint watch_id;
+
+ gboolean dispose_has_run;
+};
+
+typedef enum {
+ GIBBER_RESOLVER_ASYNCNS_QUERY_TYPE_SRV,
+ GIBBER_RESOLVER_ASYNCNS_QUERY_TYPE_GETADDRINFO,
+ GIBBER_RESOLVER_ASYNCNS_QUERY_TYPE_GETNAMEINFO,
+} GibberResolverAsyncnsQueryType;
+
+typedef struct {
+ GibberResolverAsyncnsQueryType type;
+ guint jobid;
+ asyncns_query_t *query;
+} GibberResolverAsyncnsQuery;
+
+static gboolean asyncns_resolv_srv (GibberResolver *resolver, guint id,
+ const gchar *service_name, const char *service,
+ GibberResolverServiceType type);
+
+static gboolean asyncns_resolv_addrinfo (GibberResolver *resolver, guint id,
+ const gchar *hostname, const char *port, int address_family, int sock_type,
+ int protocol, int flags);
+
+static gboolean asyncns_resolv_nameinfo (GibberResolver *resolver, guint id,
+ const struct sockaddr *sa, socklen_t salen, gint flags);
+
+static void asyncns_resolv_cancel (GibberResolver *resolver, guint id);
+
+static gboolean asyncns_io_read_cb (GIOChannel *source,
+ GIOCondition condition, gpointer data);
+
+#define GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE(o) \
+ (G_TYPE_INSTANCE_GET_PRIVATE ((o), GIBBER_TYPE_RESOLVER_ASYNCNS, \
+ GibberResolverAsyncnsPrivate))
+
+static void
+gibber_resolver_asyncns_init (GibberResolverAsyncns *obj)
+{
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (obj);
+
+ priv->asyncns = asyncns_new (2);
+ priv->asyncns_fd = asyncns_fd (priv->asyncns);
+ priv->asyncio = g_io_channel_unix_new (priv->asyncns_fd);
+ priv->watch_id = g_io_add_watch (priv->asyncio, G_IO_IN, asyncns_io_read_cb,
+ obj);
+}
+
+static void gibber_resolver_asyncns_dispose (GObject *object);
+static void gibber_resolver_asyncns_finalize (GObject *object);
+
+static void
+gibber_resolver_asyncns_class_init (
+ GibberResolverAsyncnsClass *gibber_resolver_asyncns_class)
+{
+ GObjectClass *object_class = G_OBJECT_CLASS (gibber_resolver_asyncns_class);
+ GibberResolverClass *resolver_class = GIBBER_RESOLVER_CLASS
+ (gibber_resolver_asyncns_class);
+
+ g_type_class_add_private (gibber_resolver_asyncns_class,
+ sizeof (GibberResolverAsyncnsPrivate));
+
+ object_class->dispose = gibber_resolver_asyncns_dispose;
+ object_class->finalize = gibber_resolver_asyncns_finalize;
+
+ resolver_class->resolv_srv = asyncns_resolv_srv;
+ resolver_class->resolv_addrinfo = asyncns_resolv_addrinfo;
+ resolver_class->resolv_nameinfo = asyncns_resolv_nameinfo;
+ resolver_class->resolv_cancel = asyncns_resolv_cancel;
+}
+
+void
+gibber_resolver_asyncns_dispose (GObject *object)
+{
+ GibberResolverAsyncns *self = GIBBER_RESOLVER_ASYNCNS (object);
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (self);
+
+ if (priv->dispose_has_run)
+ return;
+
+ priv->dispose_has_run = TRUE;
+
+ if (priv->watch_id != 0)
+ g_source_remove (priv->watch_id);
+ priv->watch_id = 0;
+
+ if (priv->asyncio != NULL)
+ g_io_channel_shutdown (priv->asyncio, FALSE, NULL);
+ priv->asyncio = NULL;
+
+ if (priv->asyncns != NULL)
+ asyncns_free (priv->asyncns);
+ priv->asyncns = NULL;
+
+ /* release any references held by the object here */
+ if (G_OBJECT_CLASS (gibber_resolver_asyncns_parent_class)->dispose)
+ G_OBJECT_CLASS (gibber_resolver_asyncns_parent_class)->dispose (object);
+}
+
+void
+gibber_resolver_asyncns_finalize (GObject *object)
+{
+ /* free any data held directly by the object here */
+ G_OBJECT_CLASS (gibber_resolver_asyncns_parent_class)->finalize (object);
+}
+
+static void
+gibber_resolver_asyncns_query_add (GibberResolverAsyncns *resolver,
+ GibberResolverAsyncnsQueryType type, guint jobid, asyncns_query_t *query)
+{
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (resolver);
+ GibberResolverAsyncnsQuery *q = g_slice_new (GibberResolverAsyncnsQuery);
+
+ q->type = type;
+ q->jobid = jobid;
+ q->query = query;
+
+ asyncns_setuserdata (priv->asyncns, query, q);
+ gibber_resolver_set_data (GIBBER_RESOLVER (resolver), jobid, q);
+}
+
+static void
+gibber_resolver_asyncns_query_free (GibberResolverAsyncns *resolver,
+ GibberResolverAsyncnsQuery *query)
+{
+ g_slice_free (GibberResolverAsyncnsQuery, query);
+}
+
+static void
+gibber_resolver_syncns_srv_done (GibberResolverAsyncns *self,
+ asyncns_query_t *query, GibberResolverAsyncnsQuery *asyncquery)
+{
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (self);
+ int ret;
+ unsigned char *answer;
+ GList *entries = NULL;
+ GError *error = NULL;
+
+ ret = asyncns_res_done (priv->asyncns, query, &answer);
+
+ if (ret >= 0)
+ {
+ entries = gibber_resolver_res_query_to_list (answer, ret);
+ if (entries == NULL)
+ error = g_error_new (GIBBER_RESOLVER_ERROR,
+ GIBBER_RESOLVER_ERROR_RESOLVE_FAILURE, "Invalid reply received");
+ free (answer);
+ }
+ else
+ {
+ /* FIXME libasyncns actually returns -errno, but that's normally
+ * unusefull... libasyncns should be fixed here.. */
+ error = gibber_resolver_h_error_to_g_error (-ret);
+ }
+
+ gibber_resolver_srv_result (GIBBER_RESOLVER (self), asyncquery->jobid,
+ entries, error);
+
+ if (error != NULL)
+ g_error_free (error);
+
+ gibber_resolver_asyncns_query_free (self, asyncquery);
+}
+
+static void
+gibber_resolver_syncns_addrinfo_done (GibberResolverAsyncns *self,
+ asyncns_query_t *query, GibberResolverAsyncnsQuery *asyncquery)
+{
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (self);
+ int ret;
+ struct addrinfo *addrs;
+
+ ret = asyncns_getaddrinfo_done (priv->asyncns, query, &addrs);
+ if (ret != 0)
+ {
+ GError *err = gibber_resolver_gai_error_to_g_error (ret);
+ gibber_resolver_addrinfo_result (GIBBER_RESOLVER (self),
+ asyncquery->jobid, NULL, err);
+ g_error_free (err);
+ }
+ else
+ {
+ struct addrinfo *a;
+ GList *entries = NULL;
+
+ for (a = addrs; a != NULL; a = a->ai_next)
+ {
+ entries = g_list_append (entries,
+ gibber_resolver_addrinfo_new (a->ai_family, a->ai_socktype,
+ a->ai_protocol, a->ai_addr, a->ai_addrlen));
+ }
+ gibber_resolver_addrinfo_result (GIBBER_RESOLVER (self),
+ asyncquery->jobid, entries, NULL);
+ asyncns_freeaddrinfo (addrs);
+ }
+
+ gibber_resolver_asyncns_query_free (self, asyncquery);
+}
+
+static void
+gibber_resolver_syncns_nameinfo_done (GibberResolverAsyncns *self,
+ asyncns_query_t *query, GibberResolverAsyncnsQuery *asyncquery)
+{
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (self);
+ gchar host[NI_MAXHOST];
+ gchar serv[NI_MAXSERV];
+ int ret;
+
+ ret = asyncns_getnameinfo_done (priv->asyncns, query,
+ host, NI_MAXHOST, serv, NI_MAXSERV);
+
+ if (ret == 0)
+ {
+ gibber_resolver_nameinfo_result (GIBBER_RESOLVER (self),
+ asyncquery->jobid, g_strdup (host), g_strdup (serv), NULL);
+ }
+ else
+ {
+ GError *err = gibber_resolver_gai_error_to_g_error (ret);
+ gibber_resolver_nameinfo_result (GIBBER_RESOLVER (self),
+ asyncquery->jobid, NULL, NULL, err);
+ g_error_free (err);
+ }
+
+ gibber_resolver_asyncns_query_free (self, asyncquery);
+}
+
+static gboolean
+asyncns_io_read_cb (GIOChannel *source, GIOCondition condition, gpointer data)
+{
+ GibberResolverAsyncns *self = GIBBER_RESOLVER_ASYNCNS (data);
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (self);
+ asyncns_query_t *q;
+
+ asyncns_wait (priv->asyncns, 0);
+
+ while ((q = asyncns_getnext (priv->asyncns)) != NULL)
+ {
+ GibberResolverAsyncnsQuery *asyncquery;
+
+ asyncquery = (GibberResolverAsyncnsQuery *) asyncns_getuserdata (
+ priv->asyncns, q);
+
+ switch (asyncquery->type) {
+ case GIBBER_RESOLVER_ASYNCNS_QUERY_TYPE_SRV:
+ gibber_resolver_syncns_srv_done (self, q, asyncquery);
+ break;
+ case GIBBER_RESOLVER_ASYNCNS_QUERY_TYPE_GETADDRINFO:
+ gibber_resolver_syncns_addrinfo_done (self, q, asyncquery);
+ break;
+ case GIBBER_RESOLVER_ASYNCNS_QUERY_TYPE_GETNAMEINFO:
+ gibber_resolver_syncns_nameinfo_done (self, q, asyncquery);
+ break;
+ }
+ }
+
+ return TRUE;
+}
+
+static gboolean
+asyncns_resolv_srv (GibberResolver *resolver, guint id,
+ const gchar *service_name, const char *service,
+ GibberResolverServiceType type)
+{
+ GibberResolverAsyncns *self = GIBBER_RESOLVER_ASYNCNS (resolver);
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (self);
+ asyncns_query_t *query;
+ gchar *srv_str;
+
+ srv_str = g_strdup_printf ("_%s._%s.%s", service,
+ type == GIBBER_RESOLVER_SERVICE_TYPE_TCP ? "tcp" : "udp", service_name);
+
+ query = asyncns_res_query (priv->asyncns, srv_str, C_IN, T_SRV);
+
+ if (query == NULL)
+ {
+ GError e = { GIBBER_RESOLVER_ERROR, GIBBER_RESOLVER_ERROR_MEMORY,
+ "Failed to start asyncns query" };
+ gibber_resolver_srv_result (resolver, id, NULL, &e);
+ }
+ else
+ {
+ gibber_resolver_asyncns_query_add (self,
+ GIBBER_RESOLVER_ASYNCNS_QUERY_TYPE_SRV, id, query);
+ }
+
+ g_free (srv_str);
+
+ return query != NULL;
+}
+
+static gboolean asyncns_resolv_addrinfo (GibberResolver *resolver, guint id,
+ const gchar *hostname, const char *port, int address_family, int sock_type,
+ int protocol, int flags)
+{
+ GibberResolverAsyncns *self = GIBBER_RESOLVER_ASYNCNS (resolver);
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (self);
+ asyncns_query_t *query;
+ struct addrinfo hints;
+
+ memset (&hints, 0, sizeof (hints));
+ hints.ai_family = address_family;
+ hints.ai_socktype = sock_type;
+ hints.ai_protocol = protocol;
+ hints.ai_flags = flags;
+
+ query = asyncns_getaddrinfo (priv->asyncns, hostname, port, &hints);
+
+ if (query == NULL)
+ {
+ GError e = { GIBBER_RESOLVER_ERROR, GIBBER_RESOLVER_ERROR_MEMORY,
+ "Failed to start asyncns query" };
+ gibber_resolver_srv_result (resolver, id, NULL, &e);
+ }
+ else
+ {
+ gibber_resolver_asyncns_query_add (self,
+ GIBBER_RESOLVER_ASYNCNS_QUERY_TYPE_GETADDRINFO, id, query);
+ }
+
+ return query != NULL;
+}
+
+static gboolean
+asyncns_resolv_nameinfo (GibberResolver *resolver, guint id,
+ const struct sockaddr *sa, socklen_t salen, gint flags)
+{
+ GibberResolverAsyncns *self = GIBBER_RESOLVER_ASYNCNS (resolver);
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (self);
+ asyncns_query_t *query;
+
+ query = asyncns_getnameinfo (priv->asyncns, sa, salen, flags, TRUE, TRUE);
+
+ if (query == NULL)
+ {
+ GError e = { GIBBER_RESOLVER_ERROR, GIBBER_RESOLVER_ERROR_MEMORY,
+ "Failed to start asyncns query" };
+ gibber_resolver_srv_result (resolver, id, NULL, &e);
+ }
+ else
+ {
+ gibber_resolver_asyncns_query_add (self,
+ GIBBER_RESOLVER_ASYNCNS_QUERY_TYPE_GETNAMEINFO, id, query);
+ }
+
+ return query != NULL;
+}
+
+static void
+asyncns_resolv_cancel (GibberResolver *resolver, guint id)
+{
+ GibberResolverAsyncnsQuery *query;
+ GibberResolverAsyncns *self = GIBBER_RESOLVER_ASYNCNS (resolver);
+ GibberResolverAsyncnsPrivate *priv =
+ GIBBER_RESOLVER_ASYNCNS_GET_PRIVATE (self);
+
+ query = (GibberResolverAsyncnsQuery *) gibber_resolver_get_data (resolver,
+ id);
+
+ asyncns_cancel (priv->asyncns, query->query);
+
+ gibber_resolver_asyncns_query_free (self, query);
+}
diff --git a/lib/gibber/gibber-resolver-asyncns.h b/lib/gibber/gibber-resolver-asyncns.h
new file mode 100644
index 0000000..64b775c
--- /dev/null
+++ b/lib/gibber/gibber-resolver-asyncns.h
@@ -0,0 +1,59 @@
+/*
+ * gibber-resolver-asyncns.h - Header for GibberResolverAsyncns
+ * Copyright (C) 2008 Collabora Ltd.
+ * @author Sjoerd Simons <sjoerd.simons at collabora.co.uk>
+ *
+ * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef __GIBBER_RESOLVER_ASYNCNS_H__
+#define __GIBBER_RESOLVER_ASYNCNS_H__
+
+#include <glib-object.h>
+#include "gibber-resolver.h"
+
+G_BEGIN_DECLS
+
+typedef struct _GibberResolverAsyncns GibberResolverAsyncns;
+typedef struct _GibberResolverAsyncnsClass GibberResolverAsyncnsClass;
+
+struct _GibberResolverAsyncnsClass {
+ GibberResolverClass parent_class;
+};
+
+struct _GibberResolverAsyncns {
+ GibberResolver parent;
+};
+
+GType gibber_resolver_asyncns_get_type(void);
+
+/* TYPE MACROS */
+#define GIBBER_TYPE_RESOLVER_ASYNCNS \
+ (gibber_resolver_asyncns_get_type())
+#define GIBBER_RESOLVER_ASYNCNS(obj) \
+ (G_TYPE_CHECK_INSTANCE_CAST((obj), GIBBER_TYPE_RESOLVER_ASYNCNS, GibberResolverAsyncns))
+#define GIBBER_RESOLVER_ASYNCNS_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_CAST((klass), GIBBER_TYPE_RESOLVER_ASYNCNS, GibberResolverAsyncnsClass))
+#define GIBBER_IS_RESOLVER_ASYNCNS(obj) \
+ (G_TYPE_CHECK_INSTANCE_TYPE((obj), GIBBER_TYPE_RESOLVER_ASYNCNS))
+#define GIBBER_IS_RESOLVER_ASYNCNS_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_TYPE((klass), GIBBER_TYPE_RESOLVER_ASYNCNS))
+#define GIBBER_RESOLVER_ASYNCNS_GET_CLASS(obj) \
+ (G_TYPE_INSTANCE_GET_CLASS ((obj), GIBBER_TYPE_RESOLVER_ASYNCNS, GibberResolverAsyncnsClass))
+
+
+G_END_DECLS
+
+#endif /* #ifndef __GIBBER_RESOLVER_ASYNCNS_H__*/
diff --git a/lib/gibber/gibber-resolver.c b/lib/gibber/gibber-resolver.c
new file mode 100644
index 0000000..627e308
--- /dev/null
+++ b/lib/gibber/gibber-resolver.c
@@ -0,0 +1,899 @@
+/*
+ * gibber-resolver.c - Source for GibberResolver
+ * Copyright (C) 2008 Collabora Ltd.
+ * @author Sjoerd Simons <sjoerd.simons at collabora.co.uk>
+ *
+ * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <string.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <resolv.h>
+#include <sys/types.h>
+#include <netdb.h>
+
+#include <errno.h>
+
+#include "config.h"
+#include "gibber-resolver.h"
+
+#ifdef HAVE_LIBASYNCNS
+ #include "gibber-resolver-asyncns.h"
+#endif
+
+static GibberResolver *resolver_singleton = NULL;
+static GType resolver_singleton_type = 0;
+
+GibberResolver *
+gibber_resolver_get_resolver (void)
+{
+
+ if (resolver_singleton_type == 0)
+#ifdef HAVE_LIBASYNCNS
+ resolver_singleton_type = GIBBER_TYPE_RESOLVER_ASYNCNS;
+#else
+ resolver_singleton_type = GIBBER_TYPE_RESOLVER;
+#endif
+
+ if (resolver_singleton == NULL)
+ resolver_singleton = g_object_new (resolver_singleton_type, NULL);
+
+ return resolver_singleton;
+}
+
+void
+gibber_resolver_set_resolver (GType object_type)
+{
+ if (resolver_singleton_type != object_type && resolver_singleton != NULL)
+ {
+ g_object_unref (resolver_singleton);
+ resolver_singleton = NULL;
+ }
+
+ resolver_singleton_type = object_type;
+}
+
+
+
+G_DEFINE_TYPE(GibberResolver, gibber_resolver, G_TYPE_OBJECT)
+
+typedef struct {
+ guint jobid;
+ GibberResolver *resolver;
+
+ /* Data the user would like us to remember */
+ GCallback callback;
+ GDestroyNotify destroy;
+ gpointer user_data;
+ GObject *weak_object;
+
+ /* Field settable by implementations of GibberResolver */
+ gpointer data;
+} GibberResolverJob;
+
+/* private structure */
+typedef struct _GibberResolverPrivate GibberResolverPrivate;
+
+struct _GibberResolverPrivate
+{
+ gboolean dispose_has_run;
+ /* guint * -> GibberResolverJob struct */
+ GHashTable *jobs;
+};
+
+static gboolean resolver_resolv_srv (GibberResolver *resolver, guint id,
+ const gchar *service_name, const char *service,
+ GibberResolverServiceType type);
+
+static gboolean resolver_resolv_addrinfo (GibberResolver *resolver, guint id,
+ const gchar *hostname, const char *port, int address_family, int sock_type,
+ int protocol, int flags);
+
+static gboolean resolver_resolv_nameinfo (GibberResolver *resolver, guint id,
+ const struct sockaddr *sa, socklen_t salen, gint flags);
+
+static void resolver_resolv_cancel (GibberResolver *resolver, guint id);
+
+static void free_job (gpointer data);
+
+#define GIBBER_RESOLVER_GET_PRIVATE(o) \
+ (G_TYPE_INSTANCE_GET_PRIVATE ((o), GIBBER_TYPE_RESOLVER, \
+ GibberResolverPrivate))
+
+GQuark
+gibber_resolver_error_quark (void)
+{
+ static GQuark quark = 0;
+
+ if (!quark)
+ quark = g_quark_from_static_string ("gibber_resolver_error");
+
+ return quark;
+}
+
+static void
+gibber_resolver_init (GibberResolver *obj)
+{
+ GibberResolverPrivate *priv = GIBBER_RESOLVER_GET_PRIVATE (obj);
+
+ /* allocate any data required by the object here */
+ priv->jobs = g_hash_table_new_full (g_int_hash, g_int_equal,
+ NULL, free_job);
+}
+
+static void gibber_resolver_dispose (GObject *object);
+static void gibber_resolver_finalize (GObject *object);
+
+static void
+gibber_resolver_class_init (GibberResolverClass *gibber_resolver_class)
+{
+ GObjectClass *object_class = G_OBJECT_CLASS (gibber_resolver_class);
+
+ g_type_class_add_private (gibber_resolver_class,
+ sizeof (GibberResolverPrivate));
+
+ object_class->dispose = gibber_resolver_dispose;
+ object_class->finalize = gibber_resolver_finalize;
+
+ gibber_resolver_class->resolv_srv = resolver_resolv_srv;
+ gibber_resolver_class->resolv_addrinfo = resolver_resolv_addrinfo;
+ gibber_resolver_class->resolv_nameinfo = resolver_resolv_nameinfo;
+ gibber_resolver_class->resolv_cancel = resolver_resolv_cancel;
+}
+
+void
+gibber_resolver_dispose (GObject *object)
+{
+ GibberResolver *self = GIBBER_RESOLVER (object);
+ GibberResolverPrivate *priv = GIBBER_RESOLVER_GET_PRIVATE (self);
+
+ if (priv->dispose_has_run)
+ return;
+
+ priv->dispose_has_run = TRUE;
+
+ if (priv->jobs != NULL)
+ g_hash_table_destroy (priv->jobs);
+ priv->jobs = NULL;
+
+ /* release any references held by the object here */
+ if (G_OBJECT_CLASS (gibber_resolver_parent_class)->dispose)
+ G_OBJECT_CLASS (gibber_resolver_parent_class)->dispose (object);
+}
+
+void
+gibber_resolver_finalize (GObject *object)
+{
+
+ /* free any data held directly by the object here */
+
+ G_OBJECT_CLASS (gibber_resolver_parent_class)->finalize (object);
+}
+
+static void
+weak_object_destroyed (gpointer data, GObject *old_object)
+{
+ GibberResolverJob *job = (GibberResolverJob *) data;
+
+ g_assert (job->weak_object == old_object);
+
+ job->weak_object = NULL;
+
+ gibber_resolver_cancel (job->resolver, job->jobid);
+}
+
+static guint
+gibber_resolver_job_add (GibberResolver *resolver,
+ GCallback callback,
+ gpointer user_data,
+ GDestroyNotify destroy,
+ GObject *weak_object)
+{
+ GibberResolverPrivate *priv = GIBBER_RESOLVER_GET_PRIVATE (resolver);
+ GibberResolverJob *job;
+
+ job = g_slice_new0 (GibberResolverJob);
+ job->resolver = g_object_ref (resolver);
+
+ job->callback = callback;
+ job->destroy = destroy;
+ job->user_data = user_data;
+ job->weak_object = weak_object;
+
+ /* Now decide on a decent job id.. The pointer is a pretty good initial
+ * guess. A nicer solution would be to use an intset */
+ job->jobid = GPOINTER_TO_UINT (job);
+
+ /* Be carefull to skip 0 */
+ while (job->jobid == 0 ||
+ g_hash_table_lookup (priv->jobs, &(job->jobid)) != NULL)
+ job->jobid++;
+
+ g_hash_table_insert (priv->jobs, &(job->jobid), job);
+
+ if (weak_object != NULL)
+ {
+ g_object_weak_ref (weak_object, weak_object_destroyed, job);
+ }
+
+ return job->jobid;
+}
+
+static void free_job (gpointer data)
+{
+ GibberResolverJob *job = (GibberResolverJob *) data;
+
+ if (job->destroy)
+ job->destroy (job->user_data);
+
+ if (job->weak_object)
+ g_object_weak_unref (job->weak_object, weak_object_destroyed, job);
+
+ g_object_unref (job->resolver);
+ g_slice_free (GibberResolverJob, job);
+}
+
+GibberResolverAddrInfo *
+gibber_resolver_addrinfo_new (gint address_family,
+ gint socket_type,
+ gint protocol,
+ struct sockaddr *addr,
+ gsize sockaddr_len)
+{
+ GibberResolverAddrInfo *result;
+
+ result = g_slice_new (GibberResolverAddrInfo);
+
+ result->address_family = address_family;
+ result->socket_type = socket_type;
+ result->protocol = protocol;
+ memcpy (&(result->sockaddr), addr, sockaddr_len);
+ result->sockaddr_len = sockaddr_len;
+
+ return result;
+}
+
+void
+gibber_resolver_addrinfo_free (GibberResolverAddrInfo *addrinfo)
+{
+ g_slice_free (GibberResolverAddrInfo, addrinfo);
+}
+
+void
+gibber_resolver_addrinfo_list_free (GList *addrinfo_list)
+{
+ GList *t;
+ GibberResolverAddrInfo *a;
+
+ for (t = addrinfo_list ; t != NULL; t = g_list_delete_link (t, t))
+ {
+ a = (GibberResolverAddrInfo *) t->data;
+ gibber_resolver_addrinfo_free (a);
+ }
+}
+
+GibberResolverSrvRecord *
+gibber_resolver_srv_record_new (gchar *hostname,
+ guint16 port,
+ guint16 priority,
+ guint16 weight)
+{
+ GibberResolverSrvRecord *result;
+
+ result = g_slice_new (GibberResolverSrvRecord);
+ result->hostname = g_strdup (hostname);
+ result->port = port;
+ result->priority = priority;
+ result->weight = weight;
+
+ return result;
+}
+
+void
+gibber_resolver_srv_free (GibberResolverSrvRecord *srvrecord)
+{
+ g_free (srvrecord->hostname);
+ g_slice_free (GibberResolverSrvRecord, srvrecord);
+}
+
+void
+gibber_resolver_srv_list_free (GList *srv_list)
+{
+ GList *t;
+ GibberResolverSrvRecord *s;
+
+ for (t = srv_list ; t != NULL; t = g_list_delete_link (t, t))
+ {
+ s = (GibberResolverSrvRecord *) t->data;
+ gibber_resolver_srv_free (s);
+ }
+}
+
+
+guint
+gibber_resolver_srv (GibberResolver *resolver,
+ const gchar *service_name,
+ const char *service,
+ GibberResolverServiceType type,
+ gibber_resolver_srv_cb callback,
+ gpointer user_data,
+ GDestroyNotify destroy,
+ GObject *weak_object)
+{
+ GibberResolverClass *cls = GIBBER_RESOLVER_GET_CLASS (resolver);
+ gboolean ret;
+ guint jobid;
+
+ jobid = gibber_resolver_job_add (resolver, G_CALLBACK (callback), user_data,
+ destroy, weak_object);
+
+ ret = cls->resolv_srv (resolver, jobid, service_name, service, type);
+
+ return ret ? jobid : 0;
+}
+
+guint
+gibber_resolver_addrinfo (GibberResolver *resolver,
+ const gchar *hostname,
+ const char *port,
+ int address_family,
+ int sock_type,
+ int protocol,
+ int flags,
+ gibber_resolver_addrinfo_cb callback,
+ gpointer user_data,
+ GDestroyNotify destroy,
+ GObject *weak_object)
+{
+ GibberResolverClass *cls = GIBBER_RESOLVER_GET_CLASS (resolver);
+ gboolean ret;
+ guint jobid;
+
+ jobid = gibber_resolver_job_add (resolver, G_CALLBACK (callback),
+ user_data, destroy, weak_object);
+
+ ret = cls->resolv_addrinfo (resolver, jobid, hostname, port, address_family,
+ sock_type, protocol, flags);
+
+ return ret ? jobid : 0;
+}
+
+guint
+gibber_resolver_nameinfo (GibberResolver *resolver,
+ const struct sockaddr *sa,
+ socklen_t salen,
+ gint flags,
+ gibber_resolver_nameinfo_cb callback,
+ gpointer user_data,
+ GDestroyNotify destroy,
+ GObject *weak_object)
+{
+ GibberResolverClass *cls = GIBBER_RESOLVER_GET_CLASS (resolver);
+ gboolean ret;
+ guint jobid;
+
+ jobid = gibber_resolver_job_add (resolver, G_CALLBACK (callback), user_data,
+ destroy, weak_object);
+
+ ret = cls->resolv_nameinfo (resolver, jobid, sa, salen, flags);
+
+ return ret ? jobid : 0;
+}
+
+void
+gibber_resolver_cancel (GibberResolver *resolver, guint id)
+{
+ GibberResolverClass *cls = GIBBER_RESOLVER_GET_CLASS (resolver);
+ GibberResolverPrivate *priv = GIBBER_RESOLVER_GET_PRIVATE (resolver);
+
+ if (g_hash_table_lookup (priv->jobs, &id) == NULL)
+ {
+ g_warning ("Trying to cancel a non-existing resolver jobs");
+ return;
+ }
+
+ cls->resolv_cancel (resolver, id);
+ g_hash_table_remove (priv->jobs, &id);
+}
+
+gboolean
+gibber_resolver_sockaddr_to_str (const struct sockaddr *sa,
+ gsize salen,
+ gchar **address,
+ gchar **service,
+ GError **error)
+{
+ int ret;
+ gchar name[NI_MAXHOST], servicename[NI_MAXSERV];
+
+ ret = getnameinfo (sa, salen, name, NI_MAXHOST, servicename, NI_MAXSERV,
+ NI_NUMERICHOST | NI_NUMERICSERV);
+
+ if (ret != 0)
+ {
+ g_set_error (error, GIBBER_RESOLVER_ERROR, ret,
+ "getnameinfo failed: %s", gai_strerror (ret));
+ return FALSE;
+ }
+
+ if (address != NULL)
+ *address = g_strdup (name);
+
+ if (service != NULL)
+ *service = g_strdup (servicename);
+
+ return TRUE;
+}
+
+/* Utility function for classed implementing GibberResolver */
+void
+gibber_resolver_set_data (GibberResolver *resolver, guint id, gpointer data)
+{
+ GibberResolverPrivate *priv = GIBBER_RESOLVER_GET_PRIVATE (resolver);
+ GibberResolverJob *job;
+
+ job = g_hash_table_lookup (priv->jobs, &id);
+
+ g_assert (job != NULL);
+
+ job->data = data;
+}
+
+gpointer
+gibber_resolver_get_data (GibberResolver *resolver, guint id)
+{
+ GibberResolverPrivate *priv = GIBBER_RESOLVER_GET_PRIVATE (resolver);
+ GibberResolverJob *job;
+
+ job = g_hash_table_lookup (priv->jobs, &id);
+
+ g_assert (job != NULL);
+
+ return job->data;
+}
+
+static gint
+compare_srv_record (gconstpointer a, gconstpointer b)
+{
+ GibberResolverSrvRecord *asrv = (GibberResolverSrvRecord *) a;
+ GibberResolverSrvRecord *bsrv = (GibberResolverSrvRecord *) b;
+
+ if (asrv->priority != bsrv->priority)
+ return asrv->priority < bsrv->priority ? -1 : 1;
+
+ if (asrv->weight != 0 || bsrv->weight != 0)
+ return asrv->weight == 0 ? -1 : 1;
+
+ return 0;
+}
+
+
+static GList *
+weight_sort_srv_list_total (GList *srv_list, gint total)
+{
+ GList *l, *s;
+ gint num;
+ GibberResolverSrvRecord *srv;
+
+ if (srv_list == NULL)
+ return NULL;
+
+ num = g_random_int_range (0, total + 1);
+
+ for (l = srv_list ; l != NULL; l = g_list_next (l))
+ {
+ srv = (GibberResolverSrvRecord *) l->data;
+ num -= srv->weight;
+ if (num <= 0)
+ break;
+ }
+
+ g_assert (l != NULL);
+
+ s = g_list_remove_link (srv_list, l);
+
+ return g_list_concat (l,
+ weight_sort_srv_list_total (s, total - srv->weight));
+}
+
+static GList *
+weight_sort_srv_list (GList *srv_list)
+{
+ GList *l;
+ gint total = 0;
+ GibberResolverSrvRecord *srv;
+
+ /* Sort srv list of equal priority but with weight as specified in RFC2782 */
+ srv = (GibberResolverSrvRecord *) srv_list->data;
+
+ g_assert (srv_list != NULL);
+
+ for (l = srv_list; l != NULL; l = g_list_next (l))
+ {
+ srv = (GibberResolverSrvRecord *) l->data;
+ total += srv->weight;
+ }
+
+ return weight_sort_srv_list_total (srv_list, total);
+}
+
+static void
+cut_list (GList *link)
+{
+ if (link->prev != NULL)
+ link->prev->next = NULL;
+ link->prev = NULL;
+}
+
+static GList *
+sort_srv_list (GList *srv_list)
+{
+ GList *result = NULL;
+ GList *start, *end;
+ GList *sorted;
+ guint16 priority = 0;
+
+ sorted = g_list_sort (srv_list, compare_srv_record);
+
+ while (sorted != NULL)
+ {
+ end = NULL;
+
+ /* Find the start entry with a non-zero weight */
+ for (start = sorted ; start != NULL &&
+ ((GibberResolverSrvRecord *) start->data)->weight == 0;
+ start = start->next)
+ /* nothing */;
+
+ if (start != sorted)
+ result = g_list_concat (result, sorted);
+
+ if (start != NULL)
+ {
+ cut_list (start);
+ priority = ((GibberResolverSrvRecord *) start->data)->priority;
+ }
+
+ for (end = start ; end != NULL &&
+ ((GibberResolverSrvRecord *) end->data)->priority == priority;
+ end = end->next)
+ /* nothing */;
+
+ if (end != NULL)
+ cut_list (end);
+
+ sorted = end;
+
+ if (start != NULL)
+ {
+ /* We know have a sublist of entries with the same priority but
+ * different weights */
+ start = weight_sort_srv_list (start);
+ result = g_list_concat (result, start);
+ }
+ }
+
+ return result;
+}
+
+void
+gibber_resolver_srv_result (GibberResolver *resolver,
+ guint jobid,
+ GList *srv_list, GError *error)
+{
+ GibberResolverPrivate *priv = GIBBER_RESOLVER_GET_PRIVATE (resolver);
+ GibberResolverJob *job;
+ gibber_resolver_srv_cb callback;
+
+ job = g_hash_table_lookup (priv->jobs, &jobid);
+
+ g_assert (job != NULL);
+
+ srv_list = sort_srv_list (srv_list);
+
+ callback = (gibber_resolver_srv_cb) job->callback;
+ callback (resolver, srv_list, error, job->user_data, job->weak_object);
+
+ g_hash_table_remove (priv->jobs, &jobid);
+}
+
+void
+gibber_resolver_addrinfo_result (GibberResolver *resolver,
+ guint jobid,
+ GList *entries,
+ GError *error)
+{
+ GibberResolverPrivate *priv = GIBBER_RESOLVER_GET_PRIVATE (resolver);
+ GibberResolverJob *job;
+ gibber_resolver_addrinfo_cb callback;
+
+ job = g_hash_table_lookup (priv->jobs, &jobid);
+
+ g_assert (job != NULL);
+
+ callback = (gibber_resolver_addrinfo_cb)job->callback;
+ callback (resolver, entries, error, job->user_data, job->weak_object);
+
+ g_hash_table_remove (priv->jobs, &jobid);
+}
+
+void
+gibber_resolver_nameinfo_result (GibberResolver *resolver,
+ guint jobid,
+ const gchar *hostname,
+ const gchar *port,
+ GError *error)
+{
+ GibberResolverPrivate *priv = GIBBER_RESOLVER_GET_PRIVATE (resolver);
+ GibberResolverJob *job;
+ gibber_resolver_nameinfo_cb callback;
+
+ job = g_hash_table_lookup (priv->jobs, &jobid);
+
+ g_assert (job != NULL);
+
+ callback = (gibber_resolver_nameinfo_cb) job->callback;
+ callback (resolver, hostname, port, error,
+ job->user_data, job->weak_object);
+
+ g_hash_table_remove (priv->jobs, &jobid);
+}
+
+
+#define ANSWER_BUFSIZE 10240
+GList *
+gibber_resolver_res_query_to_list (guchar *answer, int length)
+{
+ GList *list = NULL;
+ int qdcount;
+ int ancount;
+ int len;
+ const unsigned char *pos = answer + sizeof (HEADER);
+ unsigned char *end = answer + length;
+ HEADER *head = (HEADER *) answer;
+ char name[256];
+
+ qdcount = ntohs (head->qdcount);
+ ancount = ntohs (head->ancount);
+
+ /* Ignore the questions */
+ while (qdcount-- > 0 && (len = dn_expand (answer, end, pos, name, 255)) >= 0)
+ {
+ pos += len + QFIXEDSZ;
+ }
+
+ /* Parse the answers */
+ while (ancount-- > 0
+ && (len = dn_expand (answer, end, pos, name, 255)) >= 0)
+ {
+ uint16_t pref, weight, port, class, type;
+
+ /* Ignore the initial string, which has the query in it */
+ pos += len;
+ NS_GET16 (type, pos);
+ NS_GET16 (class, pos);
+
+ if (type != T_SRV || class != C_IN)
+ goto failed;
+
+ /* skip ttl and dlen */
+ pos += 6;
+
+ NS_GET16 (pref, pos);
+ NS_GET16 (weight, pos);
+ NS_GET16 (port, pos);
+ len = dn_expand (answer, end, pos, name, 255);
+
+ list = g_list_prepend (list,
+ gibber_resolver_srv_record_new (name, port, pref, weight));
+
+ pos += len;
+ }
+
+ return list;
+
+failed:
+ gibber_resolver_srv_list_free (list);
+ return NULL;
+}
+
+GError *
+gibber_resolver_gai_error_to_g_error (int error)
+{
+ gint code;
+
+ switch (error) {
+ case EAI_BADFLAGS:
+ case EAI_SOCKTYPE:
+ case EAI_FAMILY:
+ case EAI_SERVICE:
+ code = GIBBER_RESOLVER_ERROR_INVALID_ARGUMENT;
+ break;
+
+ case EAI_AGAIN:
+ code = GIBBER_RESOLVER_ERROR_RESOLVE_TEMPORARY_FAILURE;
+ break;
+ case EAI_FAIL:
+ case EAI_NONAME:
+ code = GIBBER_RESOLVER_ERROR_RESOLVE_FAILURE;
+ break;
+
+ case EAI_MEMORY:
+ case EAI_OVERFLOW:
+ code = GIBBER_RESOLVER_ERROR_MEMORY;
+ break;
+
+ case EAI_SYSTEM:
+ default:
+ code = GIBBER_RESOLVER_ERROR_UNKNOWN;
+ }
+
+ return g_error_new_literal (GIBBER_RESOLVER_ERROR, code,
+ gai_strerror (error));
+}
+
+GError *
+gibber_resolver_h_error_to_g_error (int error)
+{
+ gint code;
+ gchar *message;
+
+ switch (error) {
+ case NO_RECOVERY:
+ code = GIBBER_RESOLVER_ERROR_RESOLVE_FAILURE,
+ message = "Non-recoverable error";
+ break;
+ case HOST_NOT_FOUND:
+ code = GIBBER_RESOLVER_ERROR_RESOLVE_FAILURE,
+ message = "Authoritative Answer Host not found";
+ break;
+ case NO_DATA:
+ code = GIBBER_RESOLVER_ERROR_RESOLVE_FAILURE;
+ message = "Valid name, no data record of requested type.";
+ break;
+ case TRY_AGAIN:
+ code = GIBBER_RESOLVER_ERROR_RESOLVE_TEMPORARY_FAILURE,
+ message = "Temporary resolver failure";
+ break;
+ default:
+ code = GIBBER_RESOLVER_ERROR_UNKNOWN;
+ message = "Unknown error";
+ }
+
+ return g_error_new_literal (GIBBER_RESOLVER_ERROR, code, message);
+}
+
+
+/* Default GibberResolver implementation (blocking) */
+static gboolean
+resolver_resolv_srv (GibberResolver *resolver,
+ guint id,
+ const gchar *service_name,
+ const char *service,
+ GibberResolverServiceType type)
+{
+ gchar *srv_str;
+ int ret;
+ GList *entries = NULL;
+ GError *error = NULL;
+ guchar answer[ANSWER_BUFSIZE];
+
+ srv_str = g_strdup_printf ("_%s._%s.%s", service,
+ type == GIBBER_RESOLVER_SERVICE_TYPE_TCP ? "tcp" : "udp", service_name);
+
+ ret = res_query (srv_str, C_IN, T_SRV, answer, ANSWER_BUFSIZE);
+
+ if (ret < 0)
+ error = gibber_resolver_h_error_to_g_error (h_errno);
+ else
+ {
+ entries = gibber_resolver_res_query_to_list (answer, ret);
+ if (entries == NULL)
+ error = g_error_new (GIBBER_RESOLVER_ERROR,
+ GIBBER_RESOLVER_ERROR_RESOLVE_FAILURE, "Invalid reply received");
+ }
+
+ gibber_resolver_srv_result (resolver, id, entries, error);
+
+ if (error != NULL)
+ g_error_free (error);
+
+ g_free (srv_str);
+
+ return FALSE;
+}
+
+static gboolean
+resolver_resolv_addrinfo (GibberResolver *resolver,
+ guint id,
+ const gchar *hostname,
+ const char *port,
+ int address_family,
+ int sock_type,
+ int protocol,
+ int flags)
+{
+ struct addrinfo req, *ans = NULL, *tmpaddr;
+ int ret;
+ GList *entries = NULL;
+
+ memset (&req, 0, sizeof (req));
+ req.ai_family = address_family;
+ req.ai_socktype = sock_type;
+ req.ai_protocol = protocol;
+ req.ai_flags = flags;
+
+ ret = getaddrinfo (hostname, port, &req, &ans);
+
+ if (ret != 0)
+ {
+ GError *e = gibber_resolver_gai_error_to_g_error (ret);
+ gibber_resolver_addrinfo_result (resolver, id, NULL, e);
+ g_error_free (e);
+ return FALSE;
+ }
+
+ for (tmpaddr = ans; tmpaddr != NULL; tmpaddr = tmpaddr->ai_next)
+ {
+ entries = g_list_append (entries,
+ gibber_resolver_addrinfo_new (tmpaddr->ai_family,
+ tmpaddr->ai_socktype, tmpaddr->ai_protocol,
+ tmpaddr->ai_addr, tmpaddr->ai_addrlen));
+ }
+
+ freeaddrinfo (ans);
+
+ gibber_resolver_addrinfo_result (resolver, id, entries, NULL);
+
+ return FALSE;
+}
+
+static gboolean
+resolver_resolv_nameinfo (GibberResolver *resolver,
+ guint id,
+ const struct sockaddr *sa,
+ socklen_t salen,
+ gint flags)
+{
+ int ret;
+ gchar name[NI_MAXHOST], servicename[NI_MAXSERV];
+
+ ret = getnameinfo (sa, salen, name, NI_MAXHOST, servicename, NI_MAXSERV,
+ flags);
+
+ if (ret != 0)
+ {
+ GError *e = gibber_resolver_gai_error_to_g_error (ret);
+
+ gibber_resolver_nameinfo_result (resolver, id, NULL, NULL, e);
+ g_error_free (e);
+ return FALSE;
+ }
+
+ gibber_resolver_nameinfo_result (resolver, id, g_strdup (name),
+ g_strdup (servicename), NULL);
+
+ return FALSE;
+}
+
+static void
+resolver_resolv_cancel (GibberResolver *resolver, guint id)
+{
+ return;
+}
diff --git a/lib/gibber/gibber-resolver.h b/lib/gibber/gibber-resolver.h
new file mode 100644
index 0000000..4046756
--- /dev/null
+++ b/lib/gibber/gibber-resolver.h
@@ -0,0 +1,176 @@
+/*
+ * gibber-resolver.h - Header for GibberResolver
+ * Copyright (C) 2006 Collabora Ltd.
+ * @author Sjoerd Simons <sjoerd at luon.net>
+ *
+ * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef __GIBBER_RESOLVER_H__
+#define __GIBBER_RESOLVER_H__
+
+#include <glib-object.h>
+
+#include <sys/socket.h>
+#include <netdb.h>
+
+G_BEGIN_DECLS
+
+GQuark gibber_resolver_error_quark (void);
+#define GIBBER_RESOLVER_ERROR \
+ gibber_resolver_error_quark ()
+
+typedef enum {
+ /* Invalid or unsupported arguments */
+ GIBBER_RESOLVER_ERROR_INVALID_ARGUMENT,
+ /* Temperary failure in name resolving */
+ GIBBER_RESOLVER_ERROR_RESOLVE_TEMPORARY_FAILURE,
+ /* Failed to resolve */
+ GIBBER_RESOLVER_ERROR_RESOLVE_FAILURE,
+ /* Failed to allocate memory or overflow */
+ GIBBER_RESOLVER_ERROR_MEMORY,
+ /* Unknown error */
+ GIBBER_RESOLVER_ERROR_UNKNOWN,
+} GibberResolverError;
+
+typedef enum {
+ GIBBER_RESOLVER_SERVICE_TYPE_UDP,
+ GIBBER_RESOLVER_SERVICE_TYPE_TCP
+} GibberResolverServiceType;
+
+typedef struct _GibberResolver GibberResolver;
+typedef struct _GibberResolverClass GibberResolverClass;
+
+struct _GibberResolverClass {
+ GObjectClass parent_class;
+
+ gboolean (*resolv_srv) (GibberResolver *resolver, guint id,
+ const gchar *service_name, const char *service,
+ GibberResolverServiceType type);
+ gboolean (*resolv_addrinfo) (GibberResolver *resolver, guint id,
+ const gchar *hostname, const char *port, int address_family, int sock_type,
+ int protocol, int flags);
+ gboolean (*resolv_nameinfo) (GibberResolver *resolver, guint id,
+ const struct sockaddr *sa, socklen_t salen, gint flags);
+ void (*resolv_cancel) (GibberResolver *resolver, guint id);
+};
+
+struct _GibberResolver {
+ GObject parent;
+};
+
+GType gibber_resolver_get_type (void);
+
+/* TYPE MACROS */
+#define GIBBER_TYPE_RESOLVER \
+ (gibber_resolver_get_type ())
+#define GIBBER_RESOLVER(obj) \
+ (G_TYPE_CHECK_INSTANCE_CAST((obj), GIBBER_TYPE_RESOLVER, GibberResolver))
+#define GIBBER_RESOLVER_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_CAST((klass), GIBBER_TYPE_RESOLVER, GibberResolverClass))
+#define GIBBER_IS_RESOLVER(obj) \
+ (G_TYPE_CHECK_INSTANCE_TYPE((obj), GIBBER_TYPE_RESOLVER))
+#define GIBBER_IS_RESOLVER_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_TYPE((klass), GIBBER_TYPE_RESOLVER))
+#define GIBBER_RESOLVER_GET_CLASS(obj) \
+ (G_TYPE_INSTANCE_GET_CLASS ((obj), GIBBER_TYPE_RESOLVER, GibberResolverClass))
+
+GibberResolver * gibber_resolver_get_resolver (void);
+void gibber_resolver_set_resolver (GType object_type);
+
+typedef struct {
+ gint address_family;
+ gint socket_type;
+ gint protocol;
+ struct sockaddr_storage sockaddr;
+ gsize sockaddr_len;
+} GibberResolverAddrInfo;
+
+typedef struct {
+ gchar *hostname;
+ guint16 port;
+ guint16 priority;
+ guint16 weight;
+} GibberResolverSrvRecord;
+
+GibberResolverAddrInfo * gibber_resolver_addrinfo_new (gint address_family,
+ gint socket_type, gint protocol, struct sockaddr *addr,
+ gsize sockaddr_len);
+
+void gibber_resolver_addrinfo_free (GibberResolverAddrInfo *addrinfo);
+
+void gibber_resolver_addrinfo_list_free (GList *addrinfo_list);
+
+GibberResolverSrvRecord * gibber_resolver_srv_record_new (gchar *hostname,
+ guint16 port, guint16 priority, guint16 weight);
+
+void gibber_resolver_srv_free (GibberResolverSrvRecord *srvrecord);
+
+void gibber_resolver_srv_list_free (GList *srv_list);
+
+typedef void (* gibber_resolver_srv_cb) (GibberResolver *resolver,
+ GList *srv_list, GError *error, gpointer user_data, GObject *weak_object);
+
+guint gibber_resolver_srv (GibberResolver *resolver,
+ const gchar *service_name, const char *service,
+ GibberResolverServiceType type,
+ gibber_resolver_srv_cb callback,
+ gpointer user_data, GDestroyNotify destroy, GObject *weak_object);
+
+/* entries is a GList of GibberResolverAddrInfo */
+typedef void (* gibber_resolver_addrinfo_cb) (GibberResolver *resolver,
+ GList *entries, GError *error, gpointer user_data, GObject *weak_object);
+
+guint gibber_resolver_addrinfo (GibberResolver *resolver,
+ const gchar *hostname, const char *port,
+ int address_family, int sock_type, int protocol, int flags,
+ gibber_resolver_addrinfo_cb callback,
+ gpointer user_data, GDestroyNotify destroy, GObject *weak_object);
+
+typedef void (* gibber_resolver_nameinfo_cb) (GibberResolver *resolver,
+ const gchar *host, const gchar *port, GError *error,
+ gpointer user_data, GObject *weak_object);
+
+guint gibber_resolver_nameinfo (GibberResolver *resolver,
+ const struct sockaddr *sa, socklen_t salen, gint flags,
+ gibber_resolver_nameinfo_cb callback,
+ gpointer user_data, GDestroyNotify destroy, GObject *weak_object);
+
+void gibber_resolver_cancel (GibberResolver *resolver, guint id);
+
+gboolean gibber_resolver_sockaddr_to_str (const struct sockaddr *sa,
+ gsize salen, gchar **address, gchar **port, GError **error);
+
+/* Utility function for classed implementing GibberResolver */
+void gibber_resolver_set_data (GibberResolver *resolver, guint id,
+ gpointer data);
+gpointer gibber_resolver_get_data (GibberResolver *resolver, guint id);
+
+void gibber_resolver_srv_result (GibberResolver *resolver, guint jobid,
+ GList *srv_list, GError *error);
+
+void gibber_resolver_addrinfo_result (GibberResolver *resolver, guint jobid,
+ GList *entries, GError *error);
+
+void gibber_resolver_nameinfo_result (GibberResolver *resolver, guint jobid,
+ const gchar *hostname, const gchar *port, GError *error);
+
+GList *gibber_resolver_res_query_to_list (guchar *answer, int length);
+GError *gibber_resolver_gai_error_to_g_error (int error);
+GError *gibber_resolver_h_error_to_g_error (int error);
+
+G_END_DECLS
+
+#endif /* #ifndef __GIBBER_RESOLVER_H__*/
--
1.5.6.5
More information about the telepathy-commits
mailing list