Index: configure.in
===================================================================
--- configure.in	(revision 7710)
+++ configure.in	(working copy)
@@ -953,6 +953,30 @@ AC_CHECK_FUNCS(_NSGetEnviron)
 AC_FUNC_VSNPRINTF_C99
 AC_FUNC_PRINTF_UNIX98
 
+# For gio/libasyncns
+if test $glib_native_win32 = no; then
+  AC_CHECK_FUNCS(strndup setresuid setreuid)
+  AC_CHECK_HEADERS(sys/prctl.h arpa/nameser_compat.h)
+  AC_CHECK_FUNC(res_query, ,
+    [AC_CHECK_LIB(resolv, res_query, [ LIBASYNCNS_LIBADD="-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)
+  	  LIBASYNCNS_LIBADD="-lresolv" ],
+          [ AC_MSG_RESULT(no)
+            AC_CHECK_LIB(bind, res_query,
+              [ LIBASYNCNS_LIBADD="-lbind" ],
+  	    [ AC_MSG_ERROR(res_query not found) ] ) ] )
+        LIBS="$save_libs"
+      ] )
+    ]
+  )
+  AC_SUBST(LIBASYNCNS_LIBADD)
+fi
+
 dnl
 dnl if statfs() takes 2 arguments (Posix) or 4 (Solaris)
 dnl
@@ -3336,6 +3360,7 @@ gthread/Makefile
 gio/Makefile
 gio/xdgmime/Makefile
 gio/inotify/Makefile
+gio/libasyncns/Makefile
 gio/fen/Makefile
 gio/fam/Makefile
 gio/win32/Makefile
Index: gio/ghostutils.h
===================================================================
--- gio/ghostutils.h	(revision 0)
+++ gio/ghostutils.h	(revision 0)
@@ -0,0 +1,41 @@
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#if !defined (__GIO_GIO_H_INSIDE__) && !defined (GIO_COMPILATION)
+#error "Only <gio/gio.h> can be included directly."
+#endif
+
+#ifndef __G_HOST_UTILS_H__
+#define __G_HOST_UTILS_H__
+
+#include <gio/giotypes.h>
+
+G_BEGIN_DECLS
+
+gboolean  g_hostname_is_non_ascii     (const char *hostname);
+gboolean  g_hostname_is_ascii_encoded (const char *hostname);
+gboolean  g_hostname_is_ip_address    (const char *hostname);
+
+char     *g_hostname_to_ascii         (const char *hostname);
+char     *g_hostname_to_unicode       (const char *hostname);
+
+G_END_DECLS
+
+#endif /* __G_HOST_UTILS_H__ */
Index: gio/ghostutils.c
===================================================================
--- gio/ghostutils.c	(revision 0)
+++ gio/ghostutils.c	(revision 0)
@@ -0,0 +1,652 @@
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
+
+/* GIO - GLib Input, Output and Streaming Library
+ * 
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#include "config.h"
+#include <glib.h>
+#include "glibintl.h"
+
+#include "ghostutils.h"
+#include "gnetworkaddress.h"
+
+#include <string.h>
+
+#include "gioalias.h"
+
+/**
+ * SECTION:ghostutils
+ * @short_description: Internet hostname utilities
+ * @include: gio/gio.h
+ *
+ * Functions for manipulating internet hostnames; in particular, for
+ * converting between Unicode and ASCII-encoded forms of
+ * Internationalized Domain Names (IDNs).
+ *
+ * The <ulink
+ * link="http://www.ietf.org/rfc/rfc3490.txt">Internationalized Domain
+ * Names for Applications (IDNA)</ulink> standards allow for the use
+ * of Unicode domain names in applications, while providing
+ * backward-compatibility with the old ASCII-only DNS, by defining an
+ * ASCII-Compatible Encoding of any given Unicode name, which can be
+ * used with non-IDN-aware applications and protocols. (For example,
+ * "Παν語.org" maps to "xn--4wa8awb4637h.org".)
+ *
+ * #GResolver accepts either Unicode or ASCII-encoded hostnames, and
+ * #GNetworkAddress provides access to both variants in resolved
+ * addresses.
+ **/
+
+#define IDNA_ACE_PREFIX     "xn--"
+#define IDNA_ACE_PREFIX_LEN 4
+
+/* Punycode constants, from RFC 3492. */
+
+#define PUNYCODE_BASE          36
+#define PUNYCODE_TMIN           1
+#define PUNYCODE_TMAX          26
+#define PUNYCODE_SKEW          38
+#define PUNYCODE_DAMP         700
+#define PUNYCODE_INITIAL_BIAS  72
+#define PUNYCODE_INITIAL_N   0x80
+
+#define PUNYCODE_IS_BASIC(cp) ((guint)(cp) < 0x80)
+
+/* Encode/decode a single base-36 digit */
+static inline char
+encode_digit (guint dig)
+{
+  if (dig < 26)
+    return dig + 'a';
+  else
+    return dig - 26 + '0';
+}
+
+static inline guint
+decode_digit (char dig)
+{
+  if (dig >= 'A' && dig <= 'Z')
+    return dig - 'A';
+  else if (dig >= 'a' && dig <= 'z')
+    return dig - 'a';
+  else if (dig >= '0' && dig <= '9')
+    return dig - '0' + 26;
+  else
+    return G_MAXUINT;
+}
+
+/* Punycode bias adaptation algorithm, RFC 3492 section 6.1 */
+static guint
+adapt (guint delta, guint numpoints, gboolean firsttime)
+{
+  guint k;
+
+  delta = firsttime ? delta / PUNYCODE_DAMP : delta / 2;
+  delta += delta / numpoints;
+
+  k = 0;
+  while (delta > ((PUNYCODE_BASE - PUNYCODE_TMIN) * PUNYCODE_TMAX) / 2)
+    {
+      delta /= PUNYCODE_BASE - PUNYCODE_TMIN;
+      k += PUNYCODE_BASE;
+    }
+
+  return k + ((PUNYCODE_BASE - PUNYCODE_TMIN + 1) * delta /
+	      (delta + PUNYCODE_SKEW));
+}
+
+/* Punycode encoder, RFC 3492 section 6.3. The algorithm is
+ * sufficiently bizarre that it's not really worth trying to explain
+ * here.
+ */
+static gboolean
+punycode_encode (const char *input_utf8, gsize input_utf8_length,
+		 GString *output)
+{
+  guint delta, handled_chars, num_basic_chars, bias, j, q, k, t, digit;
+  gunichar n, m, *input;
+  glong input_length;
+  gboolean success = FALSE;
+
+  /* Convert from UTF-8 to Unicode code points */
+  input = g_utf8_to_ucs4 (input_utf8, input_utf8_length, NULL,
+			  &input_length, NULL);
+  if (!input)
+    return FALSE;
+
+  /* Copy basic chars */
+  for (j = num_basic_chars = 0; j < input_length; j++)
+    {
+      if (PUNYCODE_IS_BASIC (input[j]))
+	{
+	  g_string_append_c (output, g_ascii_tolower (input[j]));
+	  num_basic_chars++;
+	}
+    }
+  if (num_basic_chars)
+    g_string_append_c (output, '-');
+
+  handled_chars = num_basic_chars;
+
+  /* Encode non-basic chars */
+  delta = 0;
+  bias = PUNYCODE_INITIAL_BIAS;
+  n = PUNYCODE_INITIAL_N;
+  while (handled_chars < input_length)
+    {
+      /* let m = the minimum {non-basic} code point >= n in the input */
+      for (m = G_MAXUINT, j = 0; j < input_length; j++)
+	{
+	  if (input[j] >= n && input[j] < m)
+	    m = input[j];
+	}
+
+      if (m - n > (G_MAXUINT - delta) / (handled_chars + 1))
+	goto fail;
+      delta += (m - n) * (handled_chars + 1);
+      n = m;
+
+      for (j = 0; j < input_length; j++)
+	{
+	  if (input[j] < n)
+	    {
+	      if (++delta == 0)
+		goto fail;
+	    }
+	  else if (input[j] == n)
+	    {
+	      q = delta;
+	      for (k = PUNYCODE_BASE; ; k += PUNYCODE_BASE)
+		{
+		  if (k <= bias)
+		    t = PUNYCODE_TMIN;
+		  else if (k >= bias + PUNYCODE_TMAX)
+		    t = PUNYCODE_TMAX;
+		  else
+		    t = k - bias;
+		  if (q < t)
+		    break;
+		  digit = t + (q - t) % (PUNYCODE_BASE - t);
+		  g_string_append_c (output, encode_digit (digit));
+		  q = (q - t) / (PUNYCODE_BASE - t);
+		}
+
+	      g_string_append_c (output, encode_digit (q));
+	      bias = adapt (delta, handled_chars + 1, handled_chars == num_basic_chars);
+	      delta = 0;
+	      handled_chars++;
+	    }
+	}
+
+      delta++;
+      n++;
+    }
+
+  success = TRUE;
+
+ fail:
+  g_free (input);
+  return success;
+}
+
+/* From RFC 3454, Table B.1 */
+#define idna_is_junk(ch) ((ch) == 0x00AD || (ch) == 0x1806 || (ch) == 0x200B || (ch) == 0x2060 || (ch) == 0xFEFF || (ch) == 0x034F || (ch) == 0x180B || (ch) == 0x180C || (ch) == 0x180D || (ch) == 0x200C || (ch) == 0x200D || ((ch) >= 0xFE00 && (ch) <= 0xFE0F))
+
+/* Scan @str for "junk" and return a cleaned-up string if any junk
+ * is found. Else return %NULL.
+ */
+static char *
+remove_junk (const char *str, int len)
+{
+  GString *cleaned = NULL;
+  const char *p;
+  gunichar ch;
+
+  for (p = str; len == -1 ? *p : p < str + len; p = g_utf8_next_char (p))
+    {
+      ch = g_utf8_get_char (p);
+      if (idna_is_junk (ch))
+	{
+	  if (!cleaned)
+	    {
+	      cleaned = g_string_new (NULL);
+	      g_string_append_len (cleaned, str, p - str);
+	    }
+	}
+      else if (cleaned)
+	g_string_append_unichar (cleaned, ch);
+    }
+
+  if (cleaned)
+    return g_string_free (cleaned, FALSE);
+  else
+    return NULL;
+}
+
+static inline gboolean
+contains_uppercase_letters (const char *str, int len)
+{
+  const char *p;
+
+  for (p = str; len == -1 ? *p : p < str + len; p = g_utf8_next_char (p))
+    {
+      if (g_unichar_isupper (g_utf8_get_char (p)))
+	return TRUE;
+    }
+  return FALSE;
+}
+
+static inline gboolean
+contains_non_ascii (const char *str, int len)
+{
+  const char *p;
+
+  for (p = str; len == -1 ? *p : p < str + len; p++)
+    {
+      if ((guchar)*p > 0x80)
+	return TRUE;
+    }
+  return FALSE;
+}
+
+/* RFC 3454, Appendix C. ish. */
+static inline gboolean
+idna_is_prohibited (gunichar ch)
+{
+  switch (g_unichar_type (ch))
+    {
+    case G_UNICODE_CONTROL:
+    case G_UNICODE_FORMAT:
+    case G_UNICODE_UNASSIGNED:
+    case G_UNICODE_PRIVATE_USE:
+    case G_UNICODE_SURROGATE:
+    case G_UNICODE_LINE_SEPARATOR:
+    case G_UNICODE_PARAGRAPH_SEPARATOR:
+    case G_UNICODE_SPACE_SEPARATOR:
+      return TRUE;
+
+    case G_UNICODE_OTHER_SYMBOL:
+      if (ch == 0xFFFC || ch == 0xFFFD ||
+	  (ch >= 0x2FF0 && ch <= 0x2FFB))
+	return TRUE;
+      return FALSE;
+
+    case G_UNICODE_NON_SPACING_MARK:
+      if (ch == 0x0340 || ch == 0x0341)
+	return TRUE;
+      return FALSE;
+
+    default:
+      return FALSE;
+    }
+}
+
+/* RFC 3491 IDN cleanup algorithm. */
+static char *
+nameprep (const char *hostname, int len)
+{
+  char *name, *tmp = NULL, *p;
+
+  /* It would be nice if we could do this without repeatedly
+   * allocating strings and converting back and forth between
+   * gunichars and UTF-8... The code does at least avoid doing most of
+   * the sub-operations when they would just be equivalent to a
+   * g_strdup().
+   */
+
+  /* Remove presentation-only characters */
+  name = remove_junk (hostname, len);
+  if (name)
+    {
+      tmp = name;
+      len = -1;
+    }
+  else
+    name = (char *)hostname;
+
+  /* Convert to lowercase */
+  if (contains_uppercase_letters (name, len))
+    {
+      name = g_utf8_strdown (name, len);
+      g_free (tmp);
+      tmp = name;
+      len = -1;
+    }
+
+  /* If there are no UTF8 characters, we're done. */
+  if (!contains_non_ascii (name, len))
+    {
+      if (name == (char *)hostname)
+        return len == -1 ? g_strdup (hostname) : g_strndup (hostname, len);
+      else
+        return name;
+    }
+
+  /* Normalize */
+  name = g_utf8_normalize (name, len, G_NORMALIZE_NFKC);
+  g_free (tmp);
+  tmp = name;
+
+  /* KC normalization may have created more capital letters (eg,
+   * angstrom -> capital A with ring). So we have to lowercasify a
+   * second time. (This is more-or-less how the nameprep algorithm
+   * does it. If tolower(nfkc(tolower(X))) is guaranteed to be the
+   * same as tolower(nfkc(X)), then we could skip the first tolower,
+   * but I'm not sure it is.)
+   */
+  if (contains_uppercase_letters (name, -1))
+    {
+      name = g_utf8_strdown (name, -1);
+      g_free (tmp);
+      tmp = name;
+    }
+
+  /* Check for prohibited characters */
+  for (p = name; *p; p = g_utf8_next_char (p))
+    {
+      if (idna_is_prohibited (g_utf8_get_char (p)))
+	{
+	  name = NULL;
+          g_free (tmp);
+	  goto done;
+	}
+    }
+
+  /* FIXME: We're supposed to verify certain constraints on bidi
+   * characters, but glib does not appear to have that information.
+   */
+
+ done:
+  return name;
+}
+
+/**
+ * g_hostname_to_ascii:
+ * @hostname: a valid UTF-8 or ASCII hostname
+ *
+ * Converts @hostname to its canonical ASCII form; an ASCII-only
+ * string containing no uppercase letters and not ending with a
+ * trailing dot.
+ *
+ * Return value: an ASCII hostname, which must be freed, or %NULL if
+ * @hostname is in some way invalid.
+ **/
+char *
+g_hostname_to_ascii (const char *hostname)
+{
+  char *name, *label, *p;
+  GString *out;
+  gssize llen, oldlen;
+  gboolean unicode;
+
+  out = g_string_new (NULL);
+  label = name = nameprep (hostname, -1);
+
+  do
+    {
+      unicode = FALSE;
+      for (p = label; *p && *p != '.'; p++)
+	{
+	  if ((guchar)*p > 0x80)
+	    unicode = TRUE;
+	}
+
+      oldlen = out->len;
+      llen = p - label;
+      if (unicode)
+	{
+          if (!strncmp (label, IDNA_ACE_PREFIX, IDNA_ACE_PREFIX_LEN))
+            goto fail;
+
+	  g_string_append (out, IDNA_ACE_PREFIX);
+	  if (!punycode_encode (label, llen, out))
+	    goto fail;
+	}
+      else
+        g_string_append_len (out, label, llen);
+
+      if (out->len - oldlen > 63)
+	goto fail;
+
+      label += llen;
+      if (*label && *++label)
+        g_string_append_c (out, '.');
+    }
+  while (*label);
+
+  g_free (name);
+  return g_string_free (out, FALSE);
+
+ fail:
+  g_free (name);
+  g_string_free (out, TRUE);
+  return NULL;
+}
+
+/**
+ * g_hostname_is_non_ascii:
+ * @hostname: a hostname
+ *
+ * Tests if @hostname contains Unicode characters. If this returns
+ * %TRUE, you need to encode the hostname with g_hostname_to_ascii()
+ * before using it in non-IDN-aware contexts.
+ *
+ * Note that a hostname might contain a mix of encoded and unencoded
+ * segments, and so it is possible for g_hostname_is_non_ascii() and
+ * g_hostname_is_ascii_encoded() to both return %TRUE for a name.
+ *
+ * Return value: %TRUE if @hostname contains any non-ASCII characters
+ **/
+gboolean
+g_hostname_is_non_ascii (const char *hostname)
+{
+  return contains_non_ascii (hostname, -1);
+}
+
+/* Punycode decoder, RFC 3492 section 6.2. As with punycode_encode(),
+ * read the RFC if you want to understand what this is actually doing.
+ */
+static gboolean
+punycode_decode (const char *input, gsize input_length, GString *output)
+{
+  GArray *output_chars;
+  gunichar n;
+  guint i, bias;
+  guint oldi, w, k, digit, t;
+  const char *split;
+
+  n = PUNYCODE_INITIAL_N;
+  i = 0;
+  bias = PUNYCODE_INITIAL_BIAS;
+
+  split = input + input_length - 1;
+  while (split > input && *split != '-')
+    split--;
+  if (split > input)
+    {
+      output_chars = g_array_sized_new (FALSE, FALSE, sizeof (gunichar),
+					split - input);
+      input_length -= (split - input) + 1;
+      while (input < split)
+	{
+	  gunichar ch = (gunichar)*input++;
+	  if (!PUNYCODE_IS_BASIC (ch))
+	    goto fail;
+	  g_array_append_val (output_chars, ch);
+	}
+      input++;
+    }
+  else
+    output_chars = g_array_new (FALSE, FALSE, sizeof (gunichar));
+
+  while (input_length)
+    {
+      oldi = i;
+      w = 1;
+      for (k = PUNYCODE_BASE; ; k += PUNYCODE_BASE)
+	{
+	  if (!input_length--)
+	    goto fail;
+	  digit = decode_digit (*input++);
+	  if (digit >= PUNYCODE_BASE)
+	    goto fail;
+	  if (digit > (G_MAXUINT - i) / w)
+	    goto fail;
+	  i += digit * w;
+	  if (k <= bias)
+	    t = PUNYCODE_TMIN;
+	  else if (k >= bias + PUNYCODE_TMAX)
+	    t = PUNYCODE_TMAX;
+	  else
+	    t = k - bias;
+	  if (digit < t)
+	    break;
+	  if (w > G_MAXUINT / (PUNYCODE_BASE - t))
+	    goto fail;
+	  w *= (PUNYCODE_BASE - t);
+	}
+
+      bias = adapt (i - oldi, output_chars->len + 1, oldi == 0);
+
+      if (i / (output_chars->len + 1) > G_MAXUINT - n)
+	goto fail;
+      n += i / (output_chars->len + 1);
+      i %= (output_chars->len + 1);
+
+      g_array_insert_val (output_chars, i++, n);
+    }
+
+  for (i = 0; i < output_chars->len; i++)
+    g_string_append_unichar (output, g_array_index (output_chars, gunichar, i));
+  g_array_free (output_chars, TRUE);
+  return TRUE;
+
+ fail:
+  g_array_free (output_chars, TRUE);
+  return FALSE;
+}
+
+/**
+ * g_hostname_to_unicode:
+ * @hostname: a valid UTF-8 or ASCII hostname
+ *
+ * Converts @hostname to its canonical presentation form; a UTF-8
+ * string in Unicode normalization form C, containing no uppercase
+ * letters, no forbidden characters, and no ASCII-encoded segments,
+ * and not ending with a trailing dot.
+ *
+ * Of course if @hostname is not an internationalized hostname, then
+ * the canonical presentation form will be entirely ASCII.
+ *
+ * Return value: a UTF-8 hostname, which must be freed, or %NULL if
+ * @hostname is in some way invalid.
+ **/
+char *
+g_hostname_to_unicode (const char *hostname)
+{
+  GString *out;
+  gssize llen;
+
+  out = g_string_new (NULL);
+
+  do
+    {
+      llen = strcspn (hostname, ".");
+      if (!g_ascii_strncasecmp (hostname, IDNA_ACE_PREFIX, IDNA_ACE_PREFIX_LEN))
+	{
+	  hostname += IDNA_ACE_PREFIX_LEN;
+	  llen -= IDNA_ACE_PREFIX_LEN;
+	  if (!punycode_decode (hostname, llen, out))
+	    {
+	      g_string_free (out, TRUE);
+	      return NULL;
+	    }
+	}
+      else
+        {
+          char *canonicalized = nameprep (hostname, llen);
+
+          g_string_append (out, canonicalized);
+          g_free (canonicalized);
+        }
+
+      hostname += llen;
+      if (*hostname && *++hostname)
+        g_string_append_c (out, '.');
+    }
+  while (*hostname);
+
+  return g_string_free (out, FALSE);
+}
+
+/**
+ * g_hostname_is_ascii_encoded:
+ * @hostname: a hostname
+ *
+ * Tests if @hostname contains segments with an ASCII-compatible
+ * encoding of an Internationalized Domain Name. If this returns
+ * %TRUE, you should decode the hostname with g_hostname_to_unicode()
+ * before displaying it to the user.
+ *
+ * Note that a hostname might contain a mix of encoded and unencoded
+ * segments, and so it is possible for g_hostname_is_non_ascii() and
+ * g_hostname_is_ascii_encoded() to both return %TRUE for a name.
+ *
+ * Return value: %TRUE if @hostname contains any ASCII-encoded
+ * segments.
+ **/
+gboolean
+g_hostname_is_ascii_encoded (const char *hostname)
+{
+  while (1)
+    {
+      if (!g_ascii_strncasecmp (hostname, IDNA_ACE_PREFIX, IDNA_ACE_PREFIX_LEN))
+	return TRUE;
+      hostname = strchr (hostname, '.');
+      if (!hostname++)
+	return FALSE;
+    }
+}
+
+/**
+ * g_hostname_is_ip_address:
+ * @hostname: a hostname (or IP address in string form)
+ *
+ * Tests if @hostname is the string form of an IPv4 or IPv6 address.
+ * (Eg, "192.168.0.1".)
+ *
+ * Return value: %TRUE if @hostname is an IP address
+ **/
+gboolean
+g_hostname_is_ip_address (const char *hostname)
+{
+  GSockaddr *sockaddr = g_sockaddr_new_from_string (hostname, 0);
+
+  if (sockaddr)
+    {
+      g_sockaddr_free (sockaddr);
+      return TRUE;
+    }
+  else
+    return FALSE;
+}
+
+#define __G_HOST_UTILS_C__
+#include "gioaliasdef.c"
Index: gio/gresolver.h
===================================================================
--- gio/gresolver.h	(revision 0)
+++ gio/gresolver.h	(revision 0)
@@ -0,0 +1,156 @@
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#if !defined (__GIO_GIO_H_INSIDE__) && !defined (GIO_COMPILATION)
+#error "Only <gio/gio.h> can be included directly."
+#endif
+
+#ifndef __G_RESOLVER_H__
+#define __G_RESOLVER_H__
+
+#include <gio/giotypes.h>
+
+G_BEGIN_DECLS
+
+#define G_TYPE_RESOLVER         (g_resolver_get_type ())
+#define G_RESOLVER(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_RESOLVER, GResolver))
+#define G_RESOLVER_CLASS(k)     (G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_RESOLVER, GResolverClass))
+#define G_IS_RESOLVER(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_RESOLVER))
+#define G_IS_RESOLVER_CLASS(k)  (G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_RESOLVER))
+#define G_RESOLVER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_TYPE_RESOLVER, GResolverClass))
+
+struct _GResolver {
+  GObject parent_instance;
+
+};
+
+typedef struct {
+  GObjectClass parent_class;
+
+  gboolean ( *lookup_name)           (GResolver           *resolver,
+				      GNetworkAddress     *address,
+				      GCancellable        *cancellable,
+				      GError             **error);
+  void     ( *lookup_name_async)     (GResolver           *resolver,
+				      GNetworkAddress     *address,
+				      GCancellable        *cancellable,
+				      GAsyncReadyCallback  callback,
+				      gpointer             user_data);
+  gboolean ( *lookup_name_finish)    (GResolver           *resolver,
+				      GAsyncResult        *result,
+				      GError             **error);
+
+  gboolean ( *lookup_address)        (GResolver           *resolver,
+				      GNetworkAddress     *address,
+				      GCancellable        *cancellable,
+				      GError             **error);
+  void     ( *lookup_address_async)  (GResolver           *resolver,
+				      GNetworkAddress     *address,
+				      GCancellable        *cancellable,
+				      GAsyncReadyCallback  callback,
+				      gpointer             user_data);
+  gboolean ( *lookup_address_finish) (GResolver           *resolver,
+				      GAsyncResult        *result,
+				      GError             **error);
+
+  gboolean ( *lookup_service)        (GResolver           *resolver,
+				      GNetworkService     *srv,
+				      GCancellable        *cancellable,
+				      GError             **error);
+  void     ( *lookup_service_async)  (GResolver           *resolver,
+				      GNetworkService     *srv,
+				      GCancellable        *cancellable,
+				      GAsyncReadyCallback  callback,
+				      gpointer             user_data);
+  gboolean ( *lookup_service_finish) (GResolver           *resolver,
+				      GAsyncResult        *result,
+				      GError             **error);
+
+  /* Padding for future expansion */
+  void (*_g_reserved1) (void);
+  void (*_g_reserved2) (void);
+  void (*_g_reserved3) (void);
+  void (*_g_reserved4) (void);
+  void (*_g_reserved5) (void);
+
+} GResolverClass;
+
+GType            g_resolver_get_type               (void) G_GNUC_CONST;
+GResolver       *g_resolver_get_default            (void);
+void             g_resolver_set_default            (GResolver           *resolver);
+
+GNetworkAddress *g_resolver_lookup_name            (GResolver           *resolver,
+						    const char          *hostname,
+						    gushort              port,
+						    GCancellable        *cancellable,
+						    GError             **error);
+void             g_resolver_lookup_name_async      (GResolver           *resolver,
+						    const char          *hostname,
+						    gushort              port,
+						    GCancellable        *cancellable,
+						    GAsyncReadyCallback  callback,
+						    gpointer             user_data);
+GNetworkAddress *g_resolver_lookup_name_finish     (GResolver           *resolver,
+						    GAsyncResult        *result,
+						    GError             **error);
+
+GNetworkAddress *g_resolver_lookup_address         (GResolver           *resolver,
+						    GSockaddr           *sockaddr,
+						    GCancellable        *cancellable,
+						    GError             **error);
+void             g_resolver_lookup_address_async   (GResolver           *resolver,
+						    GSockaddr           *sockaddr,
+						    GCancellable        *cancellable,
+						    GAsyncReadyCallback  callback,
+						    gpointer             user_data);
+GNetworkAddress *g_resolver_lookup_address_finish  (GResolver           *resolver,
+						    GAsyncResult        *result,
+						    GError             **error);
+
+GNetworkService *g_resolver_lookup_service         (GResolver           *resolver,
+						    const char          *service,
+						    const char          *protocol,
+						    const char          *domain,
+						    GCancellable        *cancellable,
+						    GError             **error);
+void             g_resolver_lookup_service_async   (GResolver           *resolver,
+						    const char          *service,
+						    const char          *protocol,
+						    const char          *domain,
+						    GCancellable        *cancellable,
+						    GAsyncReadyCallback  callback,
+						    gpointer             user_data);
+GNetworkService *g_resolver_lookup_service_finish  (GResolver           *resolver,
+						    GAsyncResult        *result,
+						    GError             **error);
+
+/**
+ * G_RESOLVER_ERROR:
+ *
+ * Error domain for #GResolver. Errors in this domain will be from the
+ * #GResolverError enumeration. See #GError for more information on
+ * error domains.
+ **/
+#define G_RESOLVER_ERROR (g_resolver_error_quark ())
+GQuark g_resolver_error_quark (void);
+
+G_END_DECLS
+
+#endif /* __G_RESOLVER_H__ */
Index: gio/gresolver.c
===================================================================
--- gio/gresolver.c	(revision 0)
+++ gio/gresolver.c	(revision 0)
@@ -0,0 +1,573 @@
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
+
+/* GIO - GLib Input, Output and Streaming Library
+ * 
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#include "config.h"
+#include <glib.h>
+#include "glibintl.h"
+
+#include "gresolver.h"
+#include "gresolverprivate.h"
+#include "gasyncresult.h"
+#include "gnetworkaddress.h"
+#include "gnetworkservice.h"
+#include "gsimpleasyncresult.h"
+
+#ifdef G_OS_UNIX
+#include "gunixresolver.h"
+#endif
+#ifdef G_OS_WIN32
+#include "gwin32resolver.h"
+#endif
+
+#include <stdlib.h>
+
+#include "gioalias.h"
+
+/**
+ * SECTION:gresolver
+ * @short_description: Asynchronous and cancellable DNS resolver
+ * @include: gio/gio.h
+ *
+ * #GResolver provides cancellable synchronous and asynchronous DNS
+ * resolution, for hostnames (g_resolver_lookup_address(),
+ * g_resolver_lookup_name() and their async variants) and SRV
+ * (service) records (g_resolver_lookup_service()).
+ **/
+
+G_DEFINE_TYPE (GResolver, g_resolver, G_TYPE_OBJECT)
+
+static void
+g_resolver_class_init (GResolverClass *resolver_class)
+{
+  g_resolver_os_init ();
+}
+
+static void
+g_resolver_init (GResolver *resolver)
+{
+  ;
+}
+
+#ifdef G_OS_WIN32
+void
+g_resolver_os_init (void)
+{
+  WSADATA wsadata;
+  if (WSAStartup (MAKEWORD (2, 0), &wsadata) != 0)
+    g_error ("Windows Sockets could not be initialized");
+}
+#endif
+
+static GResolver *default_resolver;
+
+/**
+ * g_resolver_get_default:
+ *
+ * Gets the default #GResolver.
+ *
+ * Return value: the #GResolver. You should unref it when you are done
+ * with it.
+ **/
+GResolver *
+g_resolver_get_default (void)
+{
+  if (!default_resolver)
+    {
+      if (g_thread_supported ())
+        default_resolver = g_object_new (G_TYPE_THREADED_RESOLVER, NULL);
+      else
+        {
+#if defined(G_OS_UNIX)
+          default_resolver = g_object_new (G_TYPE_UNIX_RESOLVER, NULL);
+#elif defined(G_OS_WIN32)
+          default_resolver = g_object_new (G_TYPE_WIN32_RESOLVER, NULL);
+#endif
+        }
+    }
+
+  return g_object_ref (default_resolver);
+}
+
+void
+g_resolver_set_default (GResolver *resolver)
+{
+  if (default_resolver)
+    g_object_unref (default_resolver);
+  default_resolver = g_object_ref (resolver);
+}
+
+
+/**
+ * g_resolver_lookup_name:
+ * @resolver: a #GResolver
+ * @hostname: the hostname to look up
+ * @port: the port to use in the returned #GSockAddr<!-- -->s. (Use %0
+ * if you don't care.)
+ * @cancellable: a #GCancellable, or %NULL
+ * @error: return location for a #GError, or %NULL
+ *
+ * Synchronously resolves @hostname to determine its associated IP
+ * address(es) and returns a #GNetworkAddress. (Unless @hostname is
+ * the textual form of an IP address, in which case
+ * g_resolver_lookup_name() will simply return a #GNetworkAddress with
+ * that address and no hostname; it will not try to reverse-resolve
+ * the IP address.)
+ *
+ * If the DNS resolution fails, @error (if non-%NULL) will be set to a
+ * value from #GResolverError.
+ *
+ * If @cancellable is non-%NULL, it can be used to cancel the
+ * operation, in which case @error (if non-%NULL) will be set to
+ * %G_IO_ERROR_CANCELLED.
+ *
+ * Return value: a #GNetworkAddress, or %NULL on error
+ **/
+GNetworkAddress *
+g_resolver_lookup_name (GResolver *resolver,
+                        const char *hostname, gushort port,
+                        GCancellable *cancellable, GError **error)
+{
+  GNetworkAddress *addr;
+  GSockaddr *sockaddr;
+
+  g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
+  g_return_val_if_fail (hostname != NULL, NULL);
+
+  /* Check if @hostname is just an IP address */
+  sockaddr = g_sockaddr_new_from_string (hostname, port);
+  if (sockaddr)
+    {
+      addr = g_object_new (G_TYPE_NETWORK_ADDRESS,
+                           "sockaddr", sockaddr,
+                           NULL);
+      g_sockaddr_free (sockaddr);
+      return addr;
+    }
+
+  addr = g_object_new (G_TYPE_NETWORK_ADDRESS,
+                       "hostname", hostname,
+                       "port", port,
+                       NULL);
+
+  if (!G_RESOLVER_GET_CLASS (resolver)->lookup_name (resolver, addr, cancellable, error))
+    {
+      g_object_unref (addr);
+      return NULL;
+    }
+  return addr;
+}
+
+static void
+lookup_name_async_callback (GObject *source, GAsyncResult *result,
+                            gpointer user_data)
+{
+  GResolver *resolver = G_RESOLVER (source);
+  GSimpleAsyncResult *simple = user_data;
+  GError *error = NULL;
+
+  if (!G_RESOLVER_GET_CLASS (resolver)->
+      lookup_name_finish (resolver, result, &error))
+    {
+      g_simple_async_result_set_from_error (simple, error);
+      g_error_free (error);
+    }
+
+  g_simple_async_result_complete (simple);
+}
+
+/**
+ * g_resolver_lookup_name_async:
+ * @resolver: a #GResolver
+ * @hostname: the hostname to look up the address of
+ * @port: the port to use in the returned #GSockAddr<!-- -->s. (Use %0
+ * if you don't care.)
+ * @cancellable: a #GCancellable, or %NULL
+ * @callback: callback to call after resolution completes
+ * @user_data: data for @callback
+ *
+ * Begins asynchronously resolving @hostname to determine its
+ * associated IP address(es), and eventually calls @callback, which
+ * must call g_resolver_lookup_name_finish() to get the result.
+ **/
+void
+g_resolver_lookup_name_async (GResolver *resolver,
+                              const char *hostname, gushort port,
+                              GCancellable *cancellable,
+                              GAsyncReadyCallback callback,
+                              gpointer user_data)
+{
+  GNetworkAddress *addr;
+  GSimpleAsyncResult *simple;
+  GSockaddr *sockaddr;
+
+  g_return_if_fail (G_IS_RESOLVER (resolver));
+  g_return_if_fail (hostname != NULL);
+
+  simple = g_simple_async_result_new (G_OBJECT (resolver), callback, user_data,
+                                      g_resolver_lookup_name_async);
+
+  /* Check if @hostname is just an IP address */
+  sockaddr = g_sockaddr_new_from_string (hostname, port);
+  if (sockaddr)
+    {
+      addr = g_object_new (G_TYPE_NETWORK_ADDRESS,
+                           "sockaddr", sockaddr,
+                           NULL);
+      g_sockaddr_free (sockaddr);
+
+      g_simple_async_result_set_op_res_gpointer (simple, addr, g_object_unref);
+      g_simple_async_result_complete_in_idle (simple);
+      return;
+    }
+
+  addr = g_object_new (G_TYPE_NETWORK_ADDRESS,
+                       "hostname", hostname,
+                       "port", port,
+                       NULL);
+  g_simple_async_result_set_op_res_gpointer (simple, addr, g_object_unref);
+
+  return G_RESOLVER_GET_CLASS (resolver)->
+    lookup_name_async (resolver, addr, cancellable,
+                       lookup_name_async_callback, simple);
+}
+
+/**
+ * g_resolver_lookup_name_finish:
+ * @resolver: a #GResolver
+ * @result: the result passed to your #GAsyncReadyCallback
+ * @error: return location for a #GError, or %NULL
+ *
+ * Retrieves the result of a call to
+ * g_resolver_lookup_name_async().
+ *
+ * If the DNS resolution failed, @error (if non-%NULL) will be set to
+ * a value from #GResolverError. If the operation was cancelled,
+ * @error will be set to %G_IO_ERROR_CANCELLED.
+ *
+ * Return value: a #GNetworkAddress, or %NULL on error
+ **/
+GNetworkAddress *
+g_resolver_lookup_name_finish (GResolver *resolver, GAsyncResult *result,
+                               GError **error)
+{
+  GSimpleAsyncResult *simple;
+  GNetworkAddress *addr;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), NULL);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == g_resolver_lookup_name_async, NULL);
+
+  addr = g_simple_async_result_get_op_res_gpointer (simple);
+  if (g_simple_async_result_propagate_error (simple, error))
+    return NULL;
+  else
+    return g_object_ref (addr);
+}
+
+
+/**
+ * g_resolver_lookup_address:
+ * @resolver: a #GResolver
+ * @sockaddr: the address to reverse-resolve
+ * @cancellable: a #GCancellable, or %NULL
+ * @error: return location for a #GError, or %NULL
+ *
+ * Synchronously reverse-resolves @sockaddr to determine its
+ * associated hostname.
+ *
+ * If the DNS resolution fails, @error (if non-%NULL) will be set to
+ * a value from #GResolverError.
+ *
+ * If @cancellable is non-%NULL, it can be used to cancel the
+ * operation, in which case @error (if non-%NULL) will be set to
+ * %G_IO_ERROR_CANCELLED.
+ *
+ * Return value: a #GNetworkAddress, or %NULL on error
+ **/
+GNetworkAddress *
+g_resolver_lookup_address (GResolver *resolver, GSockaddr *sockaddr,
+                           GCancellable *cancellable, GError **error)
+{
+  GNetworkAddress *addr;
+
+  g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
+  g_return_val_if_fail (sockaddr != NULL, NULL);
+
+  addr = g_object_new (G_TYPE_NETWORK_ADDRESS,
+                       "sockaddr", sockaddr,
+                       NULL);
+
+  if (!G_RESOLVER_GET_CLASS (resolver)->lookup_address (resolver, addr, cancellable, error))
+    {
+      g_object_unref (addr);
+      return NULL;
+    }
+  return addr;
+}
+
+static void
+lookup_address_async_callback (GObject *source, GAsyncResult *result,
+                               gpointer user_data)
+{
+  GResolver *resolver = G_RESOLVER (source);
+  GSimpleAsyncResult *simple = user_data;
+  GError *error = NULL;
+
+  if (!G_RESOLVER_GET_CLASS (resolver)->
+      lookup_address_finish (resolver, result, &error))
+    {
+      g_simple_async_result_set_from_error (simple, error);
+      g_error_free (error);
+    }
+
+  g_simple_async_result_complete (simple);
+}
+
+/**
+ * g_resolver_lookup_address_async:
+ * @resolver: a #GResolver
+ * @sockaddr: the address to reverse-resolve
+ * @cancellable: a #GCancellable, or %NULL
+ * @callback: callback to call after resolution completes
+ * @user_data: data for @callback
+ *
+ * Begins asynchronously reverse-resolving @sockaddr to determine its
+ * associated hostname, and eventually calls @callback, which must
+ * call g_resolver_lookup_address_finish() to get the final result.
+ **/
+void
+g_resolver_lookup_address_async (GResolver *resolver, GSockaddr *sockaddr,
+                                 GCancellable *cancellable,
+                                 GAsyncReadyCallback callback,
+                                 gpointer user_data)
+{
+  GNetworkAddress *addr;
+  GSimpleAsyncResult *simple;
+
+  g_return_if_fail (G_IS_RESOLVER (resolver));
+  g_return_if_fail (sockaddr != NULL);
+
+  addr = g_object_new (G_TYPE_NETWORK_ADDRESS,
+                       "sockaddr", sockaddr,
+                       NULL);
+
+  simple = g_simple_async_result_new (G_OBJECT (resolver), callback, user_data,
+                                      g_resolver_lookup_address_async);
+  g_simple_async_result_set_op_res_gpointer (simple, addr, g_object_unref);
+
+  return G_RESOLVER_GET_CLASS (resolver)->
+    lookup_address_async (resolver, addr, cancellable,
+                          lookup_address_async_callback, simple);
+}
+
+/**
+ * g_resolver_lookup_address_finish:
+ * @resolver: a #GResolver
+ * @result: the result passed to your #GAsyncReadyCallback
+ * @error: return location for a #GError, or %NULL
+ *
+ * Retrieves the result of a previous call to
+ * g_resolver_lookup_address_async().
+ *
+ * If the DNS resolution failed, @error (if non-%NULL) will be set to
+ * a value from #GResolverError. If the operation was cancelled,
+ * @error will be set to %G_IO_ERROR_CANCELLED.
+ *
+ * Return value: a #GNetworkAddress, or %NULL on error
+ **/
+GNetworkAddress *
+g_resolver_lookup_address_finish (GResolver *resolver,
+                                  GAsyncResult *result, GError **error)
+{
+  GSimpleAsyncResult *simple;
+  GNetworkAddress *addr;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), NULL);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == g_resolver_lookup_address_async, NULL);
+
+  addr = g_simple_async_result_get_op_res_gpointer (simple);
+  if (g_simple_async_result_propagate_error (simple, error))
+    return NULL;
+  else
+    return g_object_ref (addr);
+}
+
+/**
+ * g_resolver_lookup_service:
+ * @resolver: a #GResolver
+ * @service: the service type to look up (eg, "ldap")
+ * @protocol: the networking protocol to use for @service (eg, "tcp")
+ * @domain: the DNS domain to look up the service in
+ * @cancellable: a #GCancellable, or %NULL
+ * @error: return location for a #GError, or %NULL
+ *
+ * Synchronously performs a DNS SRV lookup for the given @service and
+ * @protocol in the given @domain and returns a #GNetworkService.
+ *
+ * If the DNS resolution fails, @error (if non-%NULL) will be set to
+ * a value from #GResolverError.
+ *
+ * If @cancellable is non-%NULL, it can be used to cancel the
+ * operation, in which case @error (if non-%NULL) will be set to
+ * %G_IO_ERROR_CANCELLED.
+ *
+ * Return value: a #GNetworkService, or %NULL on error.
+ **/
+GNetworkService *
+g_resolver_lookup_service (GResolver *resolver, const char *service,
+                           const char *protocol, const char *domain,
+                           GCancellable *cancellable, GError **error)
+{
+  GNetworkService *srv;
+
+  g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
+  g_return_val_if_fail (service != NULL, NULL);
+  g_return_val_if_fail (protocol != NULL, NULL);
+  g_return_val_if_fail (domain != NULL, NULL);
+
+  srv = g_object_new (G_TYPE_NETWORK_SERVICE,
+                      "service", service,
+                      "protocol", protocol,
+                      "domain", domain,
+                      NULL);
+
+  if (!G_RESOLVER_GET_CLASS (resolver)->lookup_service (resolver, srv, cancellable, error))
+    {
+      g_object_unref (srv);
+      return NULL;
+    }
+  return srv;
+}
+
+static void
+lookup_service_async_callback (GObject *source, GAsyncResult *result,
+                               gpointer user_data)
+{
+  GResolver *resolver = G_RESOLVER (source);
+  GSimpleAsyncResult *simple = user_data;
+  GError *error = NULL;
+
+  if (!G_RESOLVER_GET_CLASS (resolver)->
+      lookup_service_finish (resolver, result, &error))
+    {
+      g_simple_async_result_set_from_error (simple, error);
+      g_error_free (error);
+    }
+
+  g_simple_async_result_complete (simple);
+}
+
+/**
+ * g_resolver_lookup_service_async:
+ * @resolver: a #GResolver
+ * @service: the service type to look up (eg, "ldap")
+ * @protocol: the networking protocol to use for @service (eg, "tcp")
+ * @domain: the DNS domain to look up the service in
+ * @cancellable: a #GCancellable, or %NULL
+ * @callback: callback to call after resolution completes
+ * @user_data: data for @callback
+ *
+ * Begins asynchronously performing a DNS SRV lookup for the given
+ * @service and @protocol in the given @domain, and eventually calls
+ * @callback, which must call g_resolver_lookup_service_finish() to
+ * get the final result.
+ **/
+void
+g_resolver_lookup_service_async (GResolver *resolver, const char *service,
+                                 const char *protocol, const char *domain,
+                                 GCancellable *cancellable,
+                                 GAsyncReadyCallback callback,
+                                 gpointer user_data)
+{
+  GNetworkService *srv;
+  GSimpleAsyncResult *simple;
+
+  g_return_if_fail (G_IS_RESOLVER (resolver));
+  g_return_if_fail (service != NULL);
+  g_return_if_fail (protocol != NULL);
+  g_return_if_fail (domain != NULL);
+
+  srv = g_object_new (G_TYPE_NETWORK_SERVICE,
+                      "service", service,
+                      "protocol", protocol,
+                      "domain", domain,
+                      NULL);
+
+  simple = g_simple_async_result_new (G_OBJECT (resolver), callback, user_data,
+                                      g_resolver_lookup_service_async);
+  g_simple_async_result_set_op_res_gpointer (simple, srv, g_object_unref);
+
+  return G_RESOLVER_GET_CLASS (resolver)->
+    lookup_service_async (resolver, srv, cancellable,
+                          lookup_service_async_callback, simple);
+}
+
+/**
+ * g_resolver_lookup_service_finish:
+ * @resolver: a #GResolver
+ * @result: the result passed to your #GAsyncReadyCallback
+ * @error: return location for a #GError, or %NULL
+ *
+ * Retrieves the result of a previous call to
+ * g_resolver_lookup_service_async().
+ *
+ * If the DNS resolution failed, @error (if non-%NULL) will be set to
+ * a value from #GResolverError. If the operation was cancelled,
+ * @error will be set to %G_IO_ERROR_CANCELLED.
+ *
+ * Return value: a #GNetworkService, or %NULL on error.
+ **/
+GNetworkService *
+g_resolver_lookup_service_finish (GResolver *resolver, GAsyncResult *result,
+                                  GError **error)
+{
+  GSimpleAsyncResult *simple;
+  GNetworkService *srv;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), NULL);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == g_resolver_lookup_service_async, NULL);
+
+  srv = g_simple_async_result_get_op_res_gpointer (simple);
+  if (g_simple_async_result_propagate_error (simple, error))
+    return NULL;
+  else
+    return g_object_ref (srv);
+}
+
+
+/**
+ * g_resolver_error_quark:
+ * 
+ * Gets the #GResolver Error Quark.
+ *
+ * Return value: a #GQuark.
+ **/
+GQuark
+g_resolver_error_quark (void)
+{
+  return g_quark_from_static_string ("g-resolver-error-quark");
+}
+
+#define __G_RESOLVER_C__
+#include "gioaliasdef.c"
Index: gio/gresolverprivate.h
===================================================================
--- gio/gresolverprivate.h	(revision 0)
+++ gio/gresolverprivate.h	(revision 0)
@@ -0,0 +1,91 @@
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#ifndef __G_RESOLVERPRIVATE_H__
+#define __G_RESOLVERPRIVATE_H__
+
+#include "gresolver.h"
+
+#ifdef G_OS_WIN32
+
+#define WINVER 0x0501 // FIXME?
+#include <winsock2.h>
+#undef interface
+#include <ws2tcpip.h>
+#include <windns.h>
+
+#else /* !G_OS_WIN32 */
+
+#define BIND_4_COMPAT
+
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+/* We're supposed to define _GNU_SOURCE to get EAI_NODATA, but that
+ * won't actually work since <features.h> has already been included at
+ * this point. So we define __USE_GNU instead.
+ */
+#define __USE_GNU
+#include <netdb.h>
+#undef __USE_GNU
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <resolv.h>
+#include <sys/socket.h>
+
+#endif
+
+G_BEGIN_DECLS
+
+#ifdef G_OS_WIN32
+void      g_resolver_os_init                   (void);
+#else
+#define   g_resolver_os_init()
+#endif
+
+void      g_network_address_get_addrinfo_hints (GNetworkAddress  *addr,
+						char              service[8],
+						struct addrinfo  *hints);
+gboolean  g_network_address_set_from_addrinfo  (GNetworkAddress  *addr,
+						struct addrinfo  *res,
+						int               gai_retval,
+						GError          **error);
+
+gboolean  g_network_address_set_from_nameinfo  (GNetworkAddress  *addr,
+						const char       *name,
+						int               gni_retval,
+						GError          **error);
+
+char     *g_network_service_get_rrname         (GNetworkService  *srv);
+#if defined(G_OS_UNIX)
+gboolean  g_network_service_set_from_res_query (GNetworkService  *srv,
+						guchar           *answer,
+						int               len,
+						int               herr,
+						GError          **error);
+#elif defined(G_OS_WIN32)
+gboolean  g_network_service_set_from_DnsQuery  (GNetworkService  *srv,
+						DNS_STATUS        status,
+						DNS_RECORD       *results,
+						GError          **error);
+#endif
+
+G_END_DECLS
+
+#endif /* __G_RESOLVERPRIVATE_H__ */
Index: gio/gnetworkaddress.h
===================================================================
--- gio/gnetworkaddress.h	(revision 0)
+++ gio/gnetworkaddress.h	(revision 0)
@@ -0,0 +1,77 @@
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#if !defined (__GIO_GIO_H_INSIDE__) && !defined (GIO_COMPILATION)
+#error "Only <gio/gio.h> can be included directly."
+#endif
+
+#ifndef __G_NETWORK_ADDRESS_H__
+#define __G_NETWORK_ADDRESS_H__
+
+#include <gio/giotypes.h>
+
+G_BEGIN_DECLS
+
+#define G_TYPE_NETWORK_ADDRESS         (g_network_address_get_type ())
+#define G_NETWORK_ADDRESS(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_NETWORK_ADDRESS, GNetworkAddress))
+#define G_NETWORK_ADDRESS_CLASS(k)     (G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_NETWORK_ADDRESS, GNetworkAddressClass))
+#define G_IS_NETWORK_ADDRESS(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_NETWORK_ADDRESS))
+#define G_IS_NETWORK_ADDRESS_CLASS(k)  (G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_NETWORK_ADDRESS))
+#define G_NETWORK_ADDRESS_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_TYPE_NETWORK_ADDRESS, GNetworkAddressClass))
+
+typedef struct _GNetworkAddressClass   GNetworkAddressClass;
+typedef struct _GNetworkAddressPrivate GNetworkAddressPrivate;
+
+struct _GNetworkAddress
+{
+  GObject parent_instance;
+
+  /*< private >*/
+  GNetworkAddressPrivate *priv;
+};
+
+struct _GNetworkAddressClass
+{
+  GObjectClass parent_class;
+
+};
+
+GType             g_network_address_get_type       (void) G_GNUC_CONST;
+
+const char       *g_network_address_get_hostname   (GNetworkAddress  *addr);
+const char       *g_network_address_get_ascii_name (GNetworkAddress  *addr);
+gushort           g_network_address_get_port       (GNetworkAddress  *addr);
+GSockaddr       **g_network_address_get_sockaddrs  (GNetworkAddress  *addr);
+
+
+GType g_sockaddr_get_type (void) G_GNUC_CONST;
+#define G_TYPE_SOCKADDR (g_sockaddr_get_type ())
+
+GSockaddr        *g_sockaddr_new_from_string       (const char       *ip_addr,
+						    gushort           port);
+GSockaddr        *g_sockaddr_copy                  (GSockaddr        *sockaddr);
+void              g_sockaddr_free                  (GSockaddr        *sockaddr);
+gushort           g_sockaddr_get_port              (GSockaddr        *sockaddr);
+char             *g_sockaddr_to_string             (GSockaddr        *sockaddr);
+gsize             g_sockaddr_size                  (GSockaddr        *sockaddr);
+
+G_END_DECLS
+
+#endif /* __G_NETWORK_ADDRESS_H__ */
Index: gio/gnetworkaddress.c
===================================================================
--- gio/gnetworkaddress.c	(revision 0)
+++ gio/gnetworkaddress.c	(revision 0)
@@ -0,0 +1,663 @@
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
+
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#include "config.h"
+#include <glib.h>
+#include "glibintl.h"
+
+#include "gnetworkaddress.h"
+#include "gresolverprivate.h"
+#include "ghostutils.h"
+
+#include <string.h>
+
+#include "gioalias.h"
+
+/**
+ * SECTION:gnetworkaddress
+ * @short_description: IPv4 and IPv6 network address support
+ * @include: gio/gio.h
+ *
+ * IPv4 and IPv6 network address support
+ **/
+
+static GResolverError
+g_resolver_error_from_addrinfo_error (int err)
+{
+  switch (err)
+    {
+    case EAI_FAIL:
+    case EAI_NODATA:
+    case EAI_NONAME:
+      return G_RESOLVER_ERROR_NOT_FOUND;
+
+    case EAI_AGAIN:
+      return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
+
+    default:
+      return G_RESOLVER_ERROR_INTERNAL;
+    }
+}
+
+/**
+ * GNetworkAddress:
+ *
+ * An IPv4 or IPv6 internet address. #GResolver returns these as the
+ * result of resolving a hostname or reverse-resolving an IP address.
+ * (If you need to a create a #GNetworkAddress on your own, use
+ * g_object_new(), along with the appropriate object properties.)
+ *
+ * To use a #GNetworkAddress with low-level socket routines, call
+ * g_network_address_get_sockaddrs() to get the raw address data.
+ **/
+
+struct _GNetworkAddressPrivate {
+  char *hostname, *ascii_name;
+  gushort port;
+  GSockaddr **sockaddrs;
+};
+
+enum {
+  PROP_0,
+  PROP_HOSTNAME,
+  PROP_ASCII_NAME,
+  PROP_PORT,
+  PROP_SOCKADDR,
+  PROP_SOCKADDRS,
+};
+
+static void g_network_address_set_property (GObject      *object,
+                                            guint         prop_id,
+                                            const GValue *value,
+                                            GParamSpec   *pspec);
+static void g_network_address_get_property (GObject      *object,
+                                            guint         prop_id,
+                                            GValue       *value,
+                                            GParamSpec   *pspec);
+
+G_DEFINE_TYPE (GNetworkAddress, g_network_address, G_TYPE_OBJECT);
+
+static void
+g_network_address_finalize (GObject *object)
+{
+  GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
+  int i;
+
+  g_free (addr->priv->hostname);
+  g_free (addr->priv->ascii_name);
+
+  if (addr->priv->sockaddrs)
+    {
+      for (i = 0; addr->priv->sockaddrs[i]; i++)
+        g_sockaddr_free (addr->priv->sockaddrs[i]);
+      g_free (addr->priv->sockaddrs);
+    }
+
+  G_OBJECT_CLASS (g_network_address_parent_class)->finalize (object);
+}
+
+static void
+g_network_address_class_init (GNetworkAddressClass *klass)
+{
+  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
+
+  g_type_class_add_private (klass, sizeof (GNetworkAddressPrivate));
+
+  gobject_class->set_property = g_network_address_set_property;
+  gobject_class->get_property = g_network_address_get_property;
+  gobject_class->finalize = g_network_address_finalize;
+
+  g_object_class_install_property (gobject_class, PROP_HOSTNAME,
+                                   g_param_spec_string ("hostname",
+                                                        P_("Hostname"),
+                                                        P_("Presentation form of hostname"),
+                                                        NULL,
+                                                        G_PARAM_READWRITE));
+  g_object_class_install_property (gobject_class, PROP_ASCII_NAME,
+                                   g_param_spec_string ("ascii-name",
+                                                        P_("ASCII Hostname"),
+                                                        P_("ASCII form of hostname"),
+                                                        NULL,
+                                                        G_PARAM_READWRITE));
+  g_object_class_install_property (gobject_class, PROP_PORT,
+                                   g_param_spec_uint ("port",
+                                                      P_("Port"),
+                                                      P_("Network port"),
+                                                      0, 65535, 0,
+                                                      G_PARAM_READWRITE));
+  g_object_class_install_property (gobject_class, PROP_SOCKADDR,
+                                   g_param_spec_boxed ("sockaddr",
+                                                       P_("Sockaddr"),
+                                                       P_("Used to set a single sockaddr"),
+                                                       G_TYPE_SOCKADDR,
+                                                       G_PARAM_WRITABLE));
+  g_object_class_install_property (gobject_class, PROP_SOCKADDRS,
+                                   g_param_spec_pointer ("sockaddrs",
+                                                         P_("Sockaddrs"),
+                                                         P_("Sockaddrs for this address, an array of GSockaddr"),
+                                                         G_PARAM_READWRITE));
+}
+
+static void
+g_network_address_init (GNetworkAddress *addr)
+{
+  addr->priv = G_TYPE_INSTANCE_GET_PRIVATE (addr, G_TYPE_NETWORK_ADDRESS,
+                                            GNetworkAddressPrivate);
+}
+
+static void g_network_address_set_hostname (GNetworkAddress *addr,
+                                            const char *hostname);
+static void g_network_address_set_sockaddrs (GNetworkAddress *addr,
+                                             GSockaddr **sockaddrs);
+
+static void
+g_network_address_set_property (GObject      *object,
+                                guint         prop_id,
+                                const GValue *value,
+                                GParamSpec   *pspec)
+{
+  GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
+
+  switch (prop_id) 
+    {
+    case PROP_HOSTNAME:
+    case PROP_ASCII_NAME:
+      g_return_if_fail (addr->priv->hostname == NULL && addr->priv->ascii_name == NULL);
+      g_network_address_set_hostname (addr, g_value_get_string (value));
+      break;
+
+    case PROP_PORT:
+      addr->priv->port = g_value_get_uint (value);
+      break;
+
+    case PROP_SOCKADDR:
+      g_return_if_fail (addr->priv->sockaddrs == NULL);
+      addr->priv->sockaddrs = g_new0 (GSockaddr *, 2);
+      addr->priv->sockaddrs[0] = g_value_dup_boxed (value);
+      if (addr->priv->port == 0)
+        addr->priv->port = g_sockaddr_get_port (addr->priv->sockaddrs[0]);
+      break;
+
+    case PROP_SOCKADDRS:
+      g_return_if_fail (addr->priv->sockaddrs == NULL);
+      g_network_address_set_sockaddrs (addr, g_value_get_pointer (value));
+      break;
+
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+    }
+
+}
+
+static void
+g_network_address_get_property (GObject    *object,
+                                guint       prop_id,
+                                GValue     *value,
+                                GParamSpec *pspec)
+{
+  GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
+
+  switch (prop_id)
+    { 
+    case PROP_HOSTNAME:
+      g_value_set_string (value, g_network_address_get_hostname (addr));
+      break;
+
+    case PROP_ASCII_NAME:
+      g_value_set_string (value, g_network_address_get_ascii_name (addr));
+      break;
+
+    case PROP_PORT:
+      g_value_set_uint (value, addr->priv->port);
+      break;
+
+    case PROP_SOCKADDRS:
+      g_value_set_pointer (value, addr->priv->sockaddrs);
+      break;
+
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+    }
+
+}
+
+static void
+g_network_address_set_hostname (GNetworkAddress *addr,
+                                const char *hostname)
+{
+  g_return_if_fail (hostname != NULL);
+
+  /* If @addr already has a sockaddr set then we must have been doing
+   * reverse-resolution, and so the caller is most likely to want the
+   * display hostname. If @addr doesn't have a sockaddr, then we're
+   * probably going to do be doing forward resolution, so we'll need
+   * the ASCII hostname. We can generate the other version on the fly
+   * later if we end up needing it.
+   */
+  if (addr->priv->sockaddrs)
+    addr->priv->hostname = g_hostname_to_unicode (hostname);
+  else
+    addr->priv->ascii_name = g_hostname_to_ascii (hostname);
+}
+
+/* A gio-internal method to set the hostname from a getnameinfo()
+ * response.
+ */
+gboolean
+g_network_address_set_from_nameinfo (GNetworkAddress *addr,
+                                     const char *name,
+                                     int gni_retval,
+                                     GError **error)
+{
+  g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), FALSE);
+  g_return_val_if_fail (addr->priv->sockaddrs != NULL, FALSE);
+
+  if (gni_retval != 0)
+    {
+      char *phys;
+
+      phys = g_sockaddr_to_string (addr->priv->sockaddrs[0]);
+      g_set_error (error, G_RESOLVER_ERROR,
+                   g_resolver_error_from_addrinfo_error (gni_retval),
+                   _("Error reverse-resolving '%s': %s"),
+                   phys ? phys : "(unknown)", gai_strerror (gni_retval));
+      g_free (phys);
+      return FALSE;
+    }
+
+  g_network_address_set_hostname (addr, name);
+  return TRUE;
+}
+
+static void
+g_network_address_set_sockaddrs (GNetworkAddress *addr,
+                                 GSockaddr **sockaddrs)
+{
+  int n;
+  gushort port;
+
+  g_return_if_fail (sockaddrs != NULL && sockaddrs[0] != NULL);
+
+  if (addr->priv->port == 0)
+    port = g_sockaddr_get_port (sockaddrs[0]);
+  else
+    port = 0;
+
+  for (n = 1; sockaddrs[n]; n++)
+    ;
+  addr->priv->sockaddrs = g_new0 (GSockaddr *, n + 1);
+
+  for (n = 0; sockaddrs[n]; n++)
+    {
+      if (g_sockaddr_get_port (sockaddrs[n]) != port)
+        port = 0;
+      addr->priv->sockaddrs[n] = g_sockaddr_copy (sockaddrs[n]);
+    }
+
+  if (port != 0)
+    addr->priv->port = port;
+}
+
+/* Private method to prepare args to getaddrinfo() */
+void
+g_network_address_get_addrinfo_hints (GNetworkAddress *addr,
+                                      char service[8], struct addrinfo *hints)
+{
+  g_snprintf (service, sizeof (service), "%u", addr->priv->port);
+  memset (hints, 0, sizeof (struct addrinfo));
+#ifdef AI_NUMERICSERV
+  hints->ai_flags = AI_NUMERICSERV;
+#endif
+#ifdef AI_ADDRCONFIG
+  hints->ai_flags |= AI_ADDRCONFIG;
+#endif
+  /* These two don't actually matter, they just get copied into the
+   * returned addrinfo structures (and then we ignore them). But if
+   * we leave them unset, we'll get back duplicate answers.
+   */
+  hints->ai_socktype = SOCK_STREAM;
+  hints->ai_protocol = IPPROTO_TCP;
+}
+
+/* A private version of set_sockaddrs that sets them from
+ * a getaddrinfo() response.
+ */
+gboolean
+g_network_address_set_from_addrinfo  (GNetworkAddress *addr,
+                                      struct addrinfo *res,
+                                      int gai_retval,
+                                      GError **error)
+{
+  struct addrinfo *ai;
+  GSockaddr **sockaddrs;
+  int n;
+
+  g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), FALSE);
+
+  if (gai_retval != 0)
+    {
+      g_set_error (error, G_RESOLVER_ERROR,
+		   g_resolver_error_from_addrinfo_error (gai_retval),
+		   _("Error resolving '%s': %s"),
+		   g_network_address_get_hostname (addr),
+                   gai_strerror (gai_retval));
+      return FALSE;
+    }
+
+  g_return_val_if_fail (res != NULL, FALSE);
+
+  for (ai = res, n = 0; ai; ai = ai->ai_next, n++)
+    ;
+  sockaddrs = alloca ((n + 1) * sizeof (GSockaddr *));
+  for (ai = res, n = 0; ai; ai = ai->ai_next, n++)
+    sockaddrs[n] = (GSockaddr *)ai->ai_addr;
+  sockaddrs[n] = NULL;
+
+  g_network_address_set_sockaddrs (addr, sockaddrs);
+  return TRUE;
+}
+
+/**
+ * g_network_address_get_hostname:
+ * @addr: a #GNetworkAddress
+ *
+ * Gets @addr's (UTF-8) hostname. This is the version of the hostname
+ * that should be presented to the user; see also
+ * g_network_address_get_ascii_name().
+ *
+ * Return value: @addr's display hostname, or %NULL if @addr has
+ * only IP addresses
+ **/
+const char *
+g_network_address_get_hostname (GNetworkAddress *addr)
+{
+  g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
+
+  if (!addr->priv->hostname && addr->priv->ascii_name)
+    addr->priv->hostname = g_hostname_to_unicode (addr->priv->ascii_name);
+  return addr->priv->hostname;
+}
+
+/**
+ * g_network_address_get_ascii_name:
+ * @addr: a #GNetworkAddress
+ *
+ * Gets an ASCII version of @addr's hostname; either the hostname
+ * itself for non-Unicode hostnames, or else the ASCII-Compatible
+ * Encoding of the name for Unicode names. This is the version of the
+ * hostname that can be used in non-IDN-aware network protcols. See
+ * also g_network_address_get_hostname().
+ *
+ * Return value: @addr's ASCII hostname, or %NULL if @addr has
+ * only IP addresses
+ **/
+const char *
+g_network_address_get_ascii_name (GNetworkAddress *addr)
+{
+  g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
+
+  if (!addr->priv->ascii_name && addr->priv->hostname)
+    addr->priv->ascii_name = g_hostname_to_ascii (addr->priv->hostname);
+  return addr->priv->ascii_name;
+}
+
+/**
+ * g_network_address_get_port:
+ * @addr: a #GNetworkAddress
+ *
+ * Gets @addr's port number
+ *
+ * Return value: @addr's port (which may be %0)
+ **/
+gushort
+g_network_address_get_port (GNetworkAddress *addr)
+{
+  g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), 0);
+
+  return addr->priv->port;
+}
+
+/**
+ * g_network_address_get_sockaddrs:
+ * @addr: a #GNetworkAddress
+ *
+ * Gets @addr's array of #GSockaddr. These are assumed to be in the
+ * "correct" order, so you should attempt to connect to the first one
+ * first, then the second one if the first one fails, etc, until one
+ * succeeds.
+ *
+ * Return value: a %NULL-terminated array of #GSockaddr, or %NULL if
+ * @addr has only a hostname.
+ **/
+GSockaddr **
+g_network_address_get_sockaddrs (GNetworkAddress *addr)
+{
+  g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
+
+  return addr->priv->sockaddrs;
+}
+
+
+/**
+ * GSockaddr:
+ *
+ * A type representing an IP address and port.
+ *
+ * #GSockaddr is simply a typedef for the system <literal><type>struct
+ * sockaddr</type></literal> type, and you may freely cast a
+ * #GSockaddr to a <literal><type>struct sockaddr *</type></literal>
+ * in order to pass it to a low-level socket routine, or cast a
+ * pointer to a <literal><type>struct sockaddr_in</type></literal>, or
+ * <literal><type>struct sockaddr_in6</type></literal> to a #GSockaddr
+ * in order to pass it to a gio routine. (However, #GSockaddr<!-- -->s
+ * created with g_sockaddr_new_from_string() or g_sockaddr_copy() must
+ * be freed with g_sockaddr_free(), and other #GSockaddr<!-- -->s must
+ * not be.)
+ */
+
+GType
+g_sockaddr_get_type (void)
+{
+  static volatile gsize type_volatile = 0;
+
+  if (g_once_init_enter (&type_volatile))
+    {
+      GType type = g_boxed_type_register_static (
+                        g_intern_static_string ("GSockaddr"),
+			(GBoxedCopyFunc) g_sockaddr_copy,
+			(GBoxedFreeFunc) g_sockaddr_free);
+      g_once_init_leave (&type_volatile, type);
+    }
+  return type_volatile;
+}
+
+/**
+ * g_sockaddr_new_from_string:
+ * @ip_addr: an IPv4 or IPv6 numeric address
+ * @port: port to use in the #GSockaddr, or %0 if you don't care
+ *
+ * Parses @ip_addr and returns a corresponding #GSockaddr.
+ *
+ * Return value: a new #GSockaddr, or %NULL if @ip_addr is not an
+ * IPv4 or IPv6 address.
+ **/
+GSockaddr *
+g_sockaddr_new_from_string (const char *ip_addr, gushort port)
+{
+#ifdef G_OS_WIN32
+  int len;
+#endif
+  struct sockaddr_storage sa;
+  struct sockaddr_in *sin = (struct sockaddr_in *)&sa;
+  struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&sa;
+
+  memset (&sa, 0, sizeof (sa));
+  g_resolver_os_init ();
+
+#ifdef G_OS_WIN32
+  len = sizeof (sa);
+  if (WSAStringToAddress ((LPTSTR) ip_addr, AF_INET, NULL, (LPSOCKADDR) &sa, &len) == 0)
+    sin->sin_port = port;
+  else if (WSAStringToAddress ((LPTSTR) ip_addr, AF_INET6, NULL, (LPSOCKADDR) &sa, &len) == 0)
+    sin6->sin6_port = port;
+  else
+    return NULL;
+
+#else /* !G_OS_WIN32 */
+
+  if (inet_pton (AF_INET, ip_addr, &sin->sin_addr) > 0)
+    {
+      sin->sin_family = AF_INET;
+      sin->sin_port = port;
+    }
+  else if (inet_pton (AF_INET6, ip_addr, &sin6->sin6_addr) > 0)
+    {
+      sin6->sin6_family = AF_INET6;
+      sin6->sin6_port = port;
+    }
+  else
+    return NULL;
+#endif
+
+  return g_sockaddr_copy ((GSockaddr *)&sa);
+}
+
+/**
+ * g_sockaddr_copy:
+ * @sockaddr: a #GSockaddr
+ *
+ * Copies @sockaddr
+ *
+ * Return value: a copy of @sockaddr
+ **/
+GSockaddr *
+g_sockaddr_copy (GSockaddr *sockaddr)
+{
+  return g_slice_copy (g_sockaddr_size (sockaddr), sockaddr);
+}
+
+/**
+ * g_sockaddr_free:
+ * @sockaddr: a #GSockaddr
+ *
+ * Frees @sockaddr
+ **/
+void
+g_sockaddr_free (GSockaddr *sockaddr)
+{
+  g_slice_free1 (g_sockaddr_size (sockaddr), sockaddr);
+}
+
+/**
+ * g_sockaddr_get_port:
+ * @sockaddr: a #GSockaddr
+ *
+ * Gets @sockaddr's port number
+ *
+ * Return value: @sockaddr's port (which may be %0)
+ **/
+gushort
+g_sockaddr_get_port (GSockaddr *sockaddr)
+{
+  struct sockaddr *sa = (struct sockaddr *)sockaddr;
+
+  if (sa->sa_family == AF_INET)
+    return ((struct sockaddr_in *)sa)->sin_port;
+  else if (sa->sa_family == AF_INET6)
+    return ((struct sockaddr_in6 *)sa)->sin6_port;
+  else
+    g_return_val_if_reached (0);
+}
+
+/**
+ * g_sockaddr_to_string:
+ * @sockaddr: a #GSockaddr
+ *
+ * Converts @sockaddr to string form (ignoring its port)
+ *
+ * Return value: the string form of @sockaddr, which must be freed
+ **/
+char *
+g_sockaddr_to_string (GSockaddr *sockaddr)
+{
+  struct sockaddr *sa = (struct sockaddr *)sockaddr;
+  char buffer[INET6_ADDRSTRLEN];
+#ifdef G_OS_WIN32
+  DWORD buflen = sizeof (buffer);
+#else
+  struct sockaddr_in *sin = (struct sockaddr_in *)sockaddr;
+  struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sockaddr;
+#endif
+
+  g_resolver_os_init ();
+
+#ifdef G_OS_WIN32
+  if (WSAAddressToString ((LPSOCKADDR) sa, g_sockaddr_size (sockaddr), NULL,
+			  buffer, &buflen) == 0)
+    return g_strdup (buffer);
+  else
+    return NULL;
+
+#else /* !G_OS_WIN32 */
+
+  switch (sa->sa_family)
+    {
+    case AF_INET:
+      inet_ntop (AF_INET, &sin->sin_addr, buffer, sizeof (buffer));
+      return g_strdup (buffer);
+
+    case AF_INET6:
+      inet_ntop (AF_INET6, &sin6->sin6_addr, buffer, sizeof (buffer));
+      return g_strdup (buffer);
+
+    default:
+      return NULL;
+    }
+#endif
+}
+
+/**
+ * g_sockaddr_size:
+ * @sockaddr: a #GSockaddr
+ *
+ * Determines the size of @sockaddr, which is needed as a parameter to
+ * some standard library routines like bind() or connect().
+ *
+ * Return value: the size of @sockaddr
+ **/
+gsize
+g_sockaddr_size (GSockaddr *sockaddr)
+{
+  struct sockaddr *sa = (struct sockaddr *)sockaddr;
+
+  if (sa->sa_family == AF_INET)
+    return sizeof (struct sockaddr_in);
+  else if (sa->sa_family == AF_INET6)
+    return sizeof (struct sockaddr_in6);
+  else
+    g_return_val_if_reached (0);
+}
+
+#define __G_NETWORK_ADDRESS_C__
+#include "gioaliasdef.c"
Index: gio/gnetworkservice.h
===================================================================
--- gio/gnetworkservice.h	(revision 0)
+++ gio/gnetworkservice.h	(revision 0)
@@ -0,0 +1,83 @@
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#if !defined (__GIO_GIO_H_INSIDE__) && !defined (GIO_COMPILATION)
+#error "Only <gio/gio.h> can be included directly."
+#endif
+
+#ifndef __G_NETWORK_SERVICE_H__
+#define __G_NETWORK_SERVICE_H__
+
+#include <gio/giotypes.h>
+
+G_BEGIN_DECLS
+
+#define G_TYPE_NETWORK_SERVICE         (g_network_service_get_type ())
+#define G_NETWORK_SERVICE(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_NETWORK_SERVICE, GNetworkService))
+#define G_NETWORK_SERVICE_CLASS(k)     (G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_NETWORK_SERVICE, GNetworkServiceClass))
+#define G_IS_NETWORK_SERVICE(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_NETWORK_SERVICE))
+#define G_IS_NETWORK_SERVICE_CLASS(k)  (G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_NETWORK_SERVICE))
+#define G_NETWORK_SERVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_TYPE_NETWORK_SERVICE, GNetworkServiceClass))
+
+typedef struct _GNetworkServiceClass   GNetworkServiceClass;
+typedef struct _GNetworkServicePrivate GNetworkServicePrivate;
+
+struct _GNetworkService
+{
+  GObject parent_instance;
+
+  /*< private >*/
+  GNetworkServicePrivate *priv;
+};
+
+struct _GNetworkServiceClass
+{
+  GObjectClass parent_class;
+
+};
+
+GType             g_network_service_get_type      (void) G_GNUC_CONST;
+
+const char       *g_network_service_get_service   (GNetworkService  *srv);
+const char       *g_network_service_get_protocol  (GNetworkService  *srv);
+const char       *g_network_service_get_domain    (GNetworkService  *srv);
+GSrvTarget      **g_network_service_get_targets   (GNetworkService  *srv);
+time_t            g_network_service_get_expires   (GNetworkService  *srv);
+
+GType g_srv_target_get_type (void) G_GNUC_CONST;
+#define G_TYPE_SRV_TARGET (g_srv_target_get_type ())
+
+GSrvTarget       *g_srv_target_new                (const char       *hostname,
+						   gushort           port,
+						   gushort           priority,
+						   gushort           weight,
+						   time_t            expires);
+GSrvTarget       *g_srv_target_copy               (GSrvTarget       *target);
+void              g_srv_target_free               (GSrvTarget       *target);
+
+const char       *g_srv_target_get_hostname       (GSrvTarget       *target);
+gushort           g_srv_target_get_port           (GSrvTarget       *target);
+gushort           g_srv_target_get_priority       (GSrvTarget       *target);
+gushort           g_srv_target_get_weight         (GSrvTarget       *target);
+
+G_END_DECLS
+
+#endif /* __G_NETWORK_SERVICE_H__ */
+
Index: gio/gnetworkservice.c
===================================================================
--- gio/gnetworkservice.c	(revision 0)
+++ gio/gnetworkservice.c	(revision 0)
@@ -0,0 +1,757 @@
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
+
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#include "config.h"
+#include <glib.h>
+#include "glibintl.h"
+
+#include "gnetworkservice.h"
+#include "gresolverprivate.h"
+#include "ghostutils.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "gioalias.h"
+
+/**
+ * SECTION:gnetworkservice
+ * @short_description: DNS SRV record support
+ * @include: gio/gio.h
+ *
+ * SRV (service) records are used by some network protocols to provide
+ * service-specific aliasing and load-balancing. For example, XMPP
+ * (Jabber) uses SRV records to locate the XMPP server for a domain;
+ * rather than connecting directly to "example.com" or assuming a
+ * specific server hostname like "xmpp.example.com", an XMPP client
+ * would look up the "xmpp-client" SRV record for "example.com", and
+ * then connect to whatever host was pointed to by that record.
+ **/
+
+struct _GSrvTarget {
+  char    *hostname;
+  gushort  port;
+
+  gushort  priority;
+  gushort  weight;
+  time_t   expires;
+};
+
+static void sort_targets (GSrvTarget **targets, int num_targets);
+
+/**
+ * GNetworkService:
+ *
+ * A description of a network service. #GResolver returns these as the
+ * result of looking up a SRV record. (If you need to a create a
+ * #GNetworkService on your own, use g_object_new(), along with the
+ * appropriate object properties.)
+ **/
+
+struct _GNetworkServicePrivate
+{
+  char *service, *protocol, *domain;
+  GSrvTarget **targets;
+};
+
+enum {
+  PROP_0,
+  PROP_SERVICE,
+  PROP_PROTOCOL,
+  PROP_DOMAIN,
+  PROP_TARGETS,
+};
+
+static void g_network_service_set_property (GObject      *object,
+                                            guint         prop_id,
+                                            const GValue *value,
+                                            GParamSpec   *pspec);
+static void g_network_service_get_property (GObject      *object,
+                                            guint         prop_id,
+                                            GValue       *value,
+                                            GParamSpec   *pspec);
+
+G_DEFINE_TYPE (GNetworkService, g_network_service, G_TYPE_OBJECT)
+
+static void
+g_network_service_finalize (GObject *object)
+{
+  GNetworkService *srv = G_NETWORK_SERVICE (object);
+  int i;
+
+  g_free (srv->priv->service);
+  g_free (srv->priv->protocol);
+  g_free (srv->priv->domain);
+
+  if (srv->priv->targets)
+    {
+      for (i = 0; srv->priv->targets[i]; i++)
+        g_srv_target_free (srv->priv->targets[i]);
+      g_free (srv->priv->targets);
+    }
+
+  G_OBJECT_CLASS (g_network_service_parent_class)->finalize (object);
+}
+
+static void
+g_network_service_class_init (GNetworkServiceClass *klass)
+{
+  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
+
+  g_type_class_add_private (klass, sizeof (GNetworkServicePrivate));
+
+  gobject_class->set_property = g_network_service_set_property;
+  gobject_class->get_property = g_network_service_get_property;
+  gobject_class->finalize = g_network_service_finalize;
+
+  g_object_class_install_property (gobject_class, PROP_SERVICE,
+                                   g_param_spec_string ("service",
+                                                        P_("Service"),
+                                                        P_("Service name, eg \"ldap\""),
+                                                        NULL,
+                                                        G_PARAM_READWRITE));
+  g_object_class_install_property (gobject_class, PROP_PROTOCOL,
+                                   g_param_spec_string ("protocol",
+                                                        P_("Protocol"),
+                                                        P_("Network protocol, eg \"tcp\""),
+                                                        NULL,
+                                                        G_PARAM_READWRITE));
+  g_object_class_install_property (gobject_class, PROP_DOMAIN,
+                                   g_param_spec_string ("domain",
+                                                        P_("domain"),
+                                                        P_("Network domain, eg, \"example.com\""),
+                                                        NULL,
+                                                        G_PARAM_READWRITE));
+  g_object_class_install_property (gobject_class, PROP_TARGETS,
+                                   g_param_spec_pointer ("targets",
+                                                         P_("Targets"),
+                                                         P_("Targets for this service, an array of GSrvTarget"),
+                                                         G_PARAM_READWRITE));
+}
+
+static void
+g_network_service_init (GNetworkService *srv)
+{
+  srv->priv = G_TYPE_INSTANCE_GET_PRIVATE (srv, G_TYPE_NETWORK_SERVICE,
+                                           GNetworkServicePrivate);
+}
+
+static void g_network_service_set_targets (GNetworkService *srv,
+                                           GSrvTarget **targets,
+                                           gboolean take);
+
+static void
+g_network_service_set_property (GObject      *object,
+                                guint         prop_id,
+                                const GValue *value,
+                                GParamSpec   *pspec)
+{
+  GNetworkService *srv = G_NETWORK_SERVICE (object);
+
+  switch (prop_id) 
+    {
+    case PROP_SERVICE:
+      g_return_if_fail (srv->priv->service == NULL);
+      srv->priv->service = g_value_dup_string (value);
+      break;
+
+    case PROP_PROTOCOL:
+      g_return_if_fail (srv->priv->protocol == NULL);
+      srv->priv->protocol = g_value_dup_string (value);
+      break;
+
+    case PROP_DOMAIN:
+      g_return_if_fail (srv->priv->domain == NULL);
+      if (g_hostname_is_non_ascii (g_value_get_string (value)))
+        srv->priv->domain = g_hostname_to_ascii (g_value_get_string (value));
+      else
+        srv->priv->domain = g_value_dup_string (value);
+      break;
+
+    case PROP_TARGETS:
+      g_return_if_fail (srv->priv->targets == NULL);
+      g_network_service_set_targets (srv, g_value_get_pointer (value), FALSE);
+      break;
+
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+    }
+
+}
+
+static void
+g_network_service_get_property (GObject    *object,
+                                guint       prop_id,
+                                GValue     *value,
+                                GParamSpec *pspec)
+{
+  GNetworkService *srv = G_NETWORK_SERVICE (object);
+
+  switch (prop_id)
+    { 
+    case PROP_SERVICE:
+      g_value_set_string (value, g_network_service_get_service (srv));
+      break;
+
+    case PROP_PROTOCOL:
+      g_value_set_string (value, g_network_service_get_protocol (srv));
+      break;
+
+    case PROP_DOMAIN:
+      g_value_set_string (value, g_network_service_get_domain (srv));
+      break;
+
+    case PROP_TARGETS:
+      g_value_set_pointer (value, srv->priv->targets);
+      break;
+
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+    }
+
+}
+
+static void
+g_network_service_set_targets (GNetworkService *srv,
+                               GSrvTarget **targets,
+                               gboolean take)
+{
+  int n;
+
+  g_return_if_fail (G_IS_NETWORK_SERVICE (srv));
+  g_return_if_fail (srv->priv->targets == NULL);
+  g_return_if_fail (targets != NULL && targets[0] != NULL);
+
+  for (n = 1; targets[n]; n++)
+    ;
+
+  if (take)
+    srv->priv->targets = targets;
+  else
+    {
+      srv->priv->targets = g_new0 (GSrvTarget *, n + 1);
+
+      for (n = 0; targets[n]; n++)
+        srv->priv->targets[n] = g_srv_target_copy (targets[n]);
+    }
+
+  if (n == 1 && !strcmp (srv->priv->targets[0]->hostname, "."))
+    {
+      /* 'A Target of "." means that the service is decidedly not
+       * available at this domain.'
+       */
+      g_srv_target_free (srv->priv->targets[0]);
+      srv->priv->targets[0] = NULL;
+      return;
+    }
+
+  /* Sort by priority and weight */
+  sort_targets (srv->priv->targets, n);
+}
+
+#if defined(G_OS_UNIX)
+
+/* Internal method to set a service's targets from the results of a
+ * res_query() call.
+ */
+gboolean
+g_network_service_set_from_res_query (GNetworkService *srv,
+                                      guchar *answer, int len,
+                                      int herr, GError **error)
+{
+  int count;
+  char namebuf[1024];
+  guchar *end, *p;
+  guint16 type, qclass, rdlength, priority, weight, port;
+  guint32 ttl;
+  HEADER *header;
+  time_t now = time (NULL);
+  GSrvTarget *target;
+  GPtrArray *targets;
+
+  if (len < 0)
+    {
+      GResolverError errnum;
+
+      if (herr == HOST_NOT_FOUND || herr == NO_DATA)
+        errnum = G_RESOLVER_ERROR_NOT_FOUND;
+      else if (herr == TRY_AGAIN)
+        errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
+      else
+        errnum = G_RESOLVER_ERROR_INTERNAL;
+
+      g_set_error (error, G_RESOLVER_ERROR, errnum,
+		   errnum == G_RESOLVER_ERROR_NOT_FOUND ?
+                   _("No '%s' service for '%s'") :
+                   _("Error resolving '%s' service for '%s'"),
+		   g_network_service_get_service (srv),
+		   g_network_service_get_domain (srv));
+      return FALSE;
+    }
+
+  targets = g_ptr_array_new ();
+
+  header = (HEADER *)answer;
+  p = answer + sizeof (HEADER);
+  end = answer + len;
+
+  /* Skip query */
+  count = ntohs (header->qdcount);
+  while (count-- && p < end)
+    {
+      p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
+      p += 4;
+    }
+
+  /* Read answers */
+  count = ntohs (header->ancount);
+  while (count-- && p < end)
+    {
+      p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
+      GETSHORT (type, p);
+      GETSHORT (qclass, p);
+      GETLONG  (ttl, p);
+      GETSHORT (rdlength, p);
+
+      if (type != T_SRV || qclass != C_IN)
+        {
+          p += rdlength;
+          continue;
+        }
+
+      GETSHORT (priority, p);
+      GETSHORT (weight, p);
+      GETSHORT (port, p);
+      p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
+
+      target = g_srv_target_new (namebuf, port, priority, weight, now + ttl);
+      g_ptr_array_add (targets, target);
+    }
+
+  g_ptr_array_add (targets, NULL);
+  g_network_service_set_targets (srv, (GSrvTarget **)targets->pdata, TRUE);
+  g_ptr_array_free (targets, FALSE);
+  return TRUE;
+}
+
+#elif defined(G_OS_WIN32)
+
+/* Internal method to set a service's targets from the results of a
+ * DnsQuery() call.
+ */
+gboolean
+g_network_service_set_from_DnsQuery (GNetworkService *srv,
+                                     DNS_STATUS status, DNS_RECORD *results,
+                                     GError **error)
+{
+  DNS_RECORD *rec;
+  GSrvTarget *target;
+  GPtrArray *targets;
+  time_t now = time (NULL);
+
+  if (status != ERROR_SUCCESS)
+    {
+      GResolverError errnum;
+
+      if (status == DNS_ERROR_RCODE_NAME_ERROR)
+        errnum = G_RESOLVER_ERROR_NOT_FOUND;
+      else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
+        errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
+      else
+        errnum = G_RESOLVER_ERROR_INTERNAL;
+
+      g_set_error (error, G_RESOLVER_ERROR, errnum,
+		   errnum == G_RESOLVER_ERROR_NOT_FOUND ?
+                   _("No '%s' service for '%s'") :
+                   _("Error resolving '%s' service for '%s'"),
+		   g_network_service_get_service (srv),
+		   g_network_service_get_domain (srv));
+      return FALSE;
+    }
+
+  targets = g_ptr_array_new ();
+  for (rec = results; rec; rec = rec->pNext)
+    {
+      if (rec->wType != DNS_TYPE_SRV)
+        continue;
+
+      target = g_srv_target_new (rec->Data.SRV.pNameTarget,
+                                 rec->Data.SRV.wPort,
+                                 rec->Data.SRV.wPriority,
+                                 rec->Data.SRV.wWeight,
+                                 now + rec->dwTtl);
+      g_ptr_array_add (targets, target);
+    }
+  g_ptr_array_add (targets, NULL);
+  g_network_service_set_targets (srv, (GSrvTarget **)targets->pdata, TRUE);
+  g_ptr_array_free (targets, FALSE);
+  return TRUE;
+}
+
+#endif
+
+/**
+ * g_network_service_get_service:
+ * @srv: a #GNetworkService
+ *
+ * Gets @srv's service name (eg, "ldap").
+ *
+ * Return value: @srv's service name
+ **/
+const char *
+g_network_service_get_service (GNetworkService *srv)
+{
+  g_return_val_if_fail (G_IS_NETWORK_SERVICE (srv), NULL);
+
+  return srv->priv->service;
+}
+
+/**
+ * g_network_service_get_protocol:
+ * @srv: a #GNetworkService
+ *
+ * Gets @srv's protocol name (eg, "tcp").
+ *
+ * Return value: @srv's protocol name
+ **/
+const char *
+g_network_service_get_protocol (GNetworkService *srv)
+{
+  g_return_val_if_fail (G_IS_NETWORK_SERVICE (srv), NULL);
+
+  return srv->priv->protocol;
+}
+
+/**
+ * g_network_service_get_domain:
+ * @srv: a #GNetworkService
+ *
+ * Gets the domain that @srv serves.
+ *
+ * Return value: @srv's domain name
+ **/
+const char *
+g_network_service_get_domain (GNetworkService *srv)
+{
+  g_return_val_if_fail (G_IS_NETWORK_SERVICE (srv), NULL);
+
+  return srv->priv->domain;
+}
+
+/**
+ * g_network_service_get_targets:
+ * @srv: a #GNetworkService
+ *
+ * Gets @srv's array of #GSrvTarget. These are sorted into the correct
+ * order by weight and priority, so you should attempt to connect to
+ * the first one first, then the second one if the first one fails,
+ * etc, until one succeeds.
+ *
+ * Note that it is possible for a SRV lookup to succeed but for it to
+ * contain no targets (indicating that the domain is aware of the
+ * existence of that service, and wishes to explicitly indicate that
+ * it doesn't provide it). In this case,
+ * g_network_service_get_targets() will return an array of 0 elements
+ * (ie, an array whose first element is %NULL).
+ *
+ * Return value: a %NULL-terminated array of #GSrvTarget (or %NULL if
+ * @srv has not been successfully resolved)
+ **/
+GSrvTarget **
+g_network_service_get_targets (GNetworkService *srv)
+{
+  g_return_val_if_fail (G_IS_NETWORK_SERVICE (srv), NULL);
+
+  return srv->priv->targets;
+}
+
+/**
+ * g_network_service_get_expires:
+ * @srv: a #GNetworkService
+ *
+ * Gets the expiration time of the target in @srv with the shortest
+ * time-to-live.
+ *
+ * Return value: @srv's expiration time, or %0 if @srv has no targets.
+ **/
+time_t
+g_network_service_get_expires (GNetworkService *srv)
+{
+  time_t expires;
+  int i;
+
+  g_return_val_if_fail (G_IS_NETWORK_SERVICE (srv), 0);
+
+  if (!srv->priv->targets)
+    return 0;
+  expires = srv->priv->targets[0]->expires;
+
+  for (i = 1; srv->priv->targets[i]; i++)
+    {
+      if (srv->priv->targets[i]->expires < expires)
+        expires = srv->priv->targets[i]->expires;
+    }
+  return expires;
+}
+
+/* Internal method that gets the resource record name to be looked up
+ * in DNS for @srv.
+ */
+char *
+g_network_service_get_rrname (GNetworkService *srv)
+{
+  g_return_val_if_fail (G_IS_NETWORK_SERVICE (srv), NULL);
+
+  return g_strdup_printf ("_%s._%s.%s",
+                          srv->priv->service, srv->priv->protocol,
+                          srv->priv->domain);
+}
+
+
+/**
+ * GSrvTarget:
+ *
+ * A single target host/port that a network service is running on.
+ */
+
+GType
+g_srv_target_get_type (void)
+{
+  static volatile gsize type_volatile = 0;
+
+  if (g_once_init_enter (&type_volatile))
+    {
+      GType type = g_boxed_type_register_static (
+                        g_intern_static_string ("GSrvTarget"),
+			(GBoxedCopyFunc) g_srv_target_copy,
+			(GBoxedFreeFunc) g_srv_target_free);
+      g_once_init_leave (&type_volatile, type);
+    }
+  return type_volatile;
+}
+
+/**
+ * g_srv_target_new:
+ * @hostname: the host that the service is running on
+ * @port: the port that the service is running on
+ * @priority: the target's priority
+ * @weight: the target's weight
+ * @expires: the target's expiration time
+ *
+ * Creates a new #GSrvTarget with the given parameters.
+ *
+ * Return value: a new #GSrvTarget.
+ **/
+GSrvTarget *
+g_srv_target_new (const char *hostname, gushort port,
+                  gushort priority, gushort weight, time_t expires)
+{
+  GSrvTarget *target = g_slice_new0 (GSrvTarget);
+
+  target->hostname = g_strdup (hostname);
+  target->port = port;
+  target->priority = priority;
+  target->weight = weight;
+  target->expires = expires;
+
+  return target;
+}
+
+/**
+ * g_srv_target_copy:
+ * @target: a #GSrvTarget
+ *
+ * Copies @target
+ *
+ * Return value: a copy of @target
+ **/
+GSrvTarget *
+g_srv_target_copy (GSrvTarget *target)
+{
+  return g_srv_target_new (target->hostname, target->port,
+                           target->priority, target->weight,
+                           target->expires);
+}
+
+/**
+ * g_srv_target_free:
+ * @target: a #GSrvTarget
+ *
+ * Frees @target
+ **/
+void
+g_srv_target_free (GSrvTarget *target)
+{
+  g_free (target->hostname);
+  g_slice_free (GSrvTarget, target);
+}
+
+/**
+ * g_srv_target_get_hostname:
+ * @target: a #GSrvTarget
+ *
+ * Gets @target's hostname (in ASCII form; if you are going to present
+ * this to the user, you should use g_hostname_is_ascii_encoded() to
+ * check if it contains encoded Unicode segments, and use
+ * g_hostname_to_unicode() to convert it if it does.)
+ *
+ * Return value: @target's hostname
+ **/
+const char *
+g_srv_target_get_hostname (GSrvTarget *target)
+{
+  return target->hostname;
+}
+
+/**
+ * g_srv_target_get_port:
+ * @target: a #GSrvTarget
+ *
+ * Gets @target's port
+ *
+ * Return value: @target's port
+ **/
+gushort
+g_srv_target_get_port (GSrvTarget *target)
+{
+  return target->port;
+}
+
+/**
+ * g_srv_target_get_priority:
+ * @target: a #GSrvTarget
+ *
+ * Gets @target's priority. You should not need to look at this;
+ * #GNetworkService already sorts the targets according to the
+ * algorithm in RFC 2782.
+ *
+ * Return value: @target's priority
+ **/
+gushort
+g_srv_target_get_priority (GSrvTarget *target)
+{
+  return target->priority;
+}
+
+/**
+ * g_srv_target_get_weight:
+ * @target: a #GSrvTarget
+ *
+ * Gets @target's weight. You should not need to look at this;
+ * #GNetworkService already sorts the targets according to the
+ * algorithm in RFC 2782.
+ *
+ * Return value: @target's weight
+ **/
+gushort
+g_srv_target_get_weight (GSrvTarget *target)
+{
+  return target->weight;
+}
+
+int
+compare_target (const void *a, const void *b)
+{
+  GSrvTarget *ta = *(GSrvTarget **)a;
+  GSrvTarget *tb = *(GSrvTarget **)b;
+
+  if (ta->priority == tb->priority)
+    {
+      /* Arrange targets of the same priority "in any order, except
+       * that all those with weight 0 are placed at the beginning of
+       * the list"
+       */
+      if (ta->weight == 0)
+        return -1;
+      else if (tb->weight == 0)
+        return 1;
+      else
+        return g_random_int_range (-1, 1);
+    }
+  else
+    return ta->priority - tb->priority;
+}
+
+static void
+sort_targets (GSrvTarget **targets, int num_targets)
+{
+  int first, last, i, n, sum;
+  GSrvTarget *tmp;
+
+  /* Sort by priority, and partly by weight */
+  qsort (targets, num_targets, sizeof (GSrvTarget *), compare_target);
+
+  /* For each group of targets with the same priority, rebalance them
+   * according to weight.
+   */
+  for (first = last = 0; first < num_targets; first = last + 1)
+    {
+      /* Skip @first to a non-0-weight target. */
+      while (first < num_targets && targets[first]->weight == 0)
+        first++;
+      if (first == num_targets)
+        break;
+
+      /* Skip @last to the last target of the same priority. */
+      last = first;
+      while (last < num_targets - 1 &&
+             targets[last + 1]->priority == targets[last]->priority)
+        last++;
+
+      /* If there's only one non-0 weight target at this priority,
+       * we can move on to the next priority level.
+       */
+      if (last == first)
+        continue;
+
+      /* Randomly reorder the non-0 weight targets, giving precedence
+       * to the ones with higher weight. RFC 2782 describes this in
+       * terms of assigning a running sum to each target and building
+       * a new list. We do things slightly differently, but should get
+       * the same result.
+       */
+      for (i = first, sum = 0; i <= last; i++)
+        sum += targets[i]->weight;
+      while (first < last)
+        {
+          n = g_random_int_range (0, sum);
+          for (i = first; i < last; i++)
+            {
+              if (n < targets[i]->weight)
+                break;
+              n -= targets[i]->weight;
+            }
+
+          tmp = targets[first];
+          targets[first] = targets[i];
+          targets[i] = tmp;
+
+          sum -= tmp->weight;
+          first++;
+        }
+    }
+}
+
+#define __G_NETWORK_SERVICE_C__
+#include "gioaliasdef.c"
Index: gio/gthreadedresolver.h
===================================================================
--- gio/gthreadedresolver.h	(revision 0)
+++ gio/gthreadedresolver.h	(revision 0)
@@ -0,0 +1,50 @@
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#ifndef __G_THREADED_RESOLVER_H__
+#define __G_THREADED_RESOLVER_H__
+
+#include <gio/gresolver.h>
+
+G_BEGIN_DECLS
+
+#define G_TYPE_THREADED_RESOLVER         (g_threaded_resolver_get_type ())
+#define G_THREADED_RESOLVER(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_THREADED_RESOLVER, GThreadedResolver))
+#define G_THREADED_RESOLVER_CLASS(k)     (G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_THREADED_RESOLVER, GThreadedResolverClass))
+#define G_IS_THREADED_RESOLVER(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_THREADED_RESOLVER))
+#define G_IS_THREADED_RESOLVER_CLASS(k)  (G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_THREADED_RESOLVER))
+#define G_THREADED_RESOLVER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_TYPE_THREADED_RESOLVER, GThreadedResolverClass))
+
+typedef struct {
+  GResolver parent_instance;
+
+  GThreadPool *thread_pool;
+} GThreadedResolver;
+
+typedef struct {
+  GResolverClass parent_class;
+
+} GThreadedResolverClass;
+
+GType g_threaded_resolver_get_type (void) G_GNUC_CONST;
+
+G_END_DECLS
+
+#endif /* __G_RESOLVER_H__ */
Index: gio/gthreadedresolver.c
===================================================================
--- gio/gthreadedresolver.c	(revision 0)
+++ gio/gthreadedresolver.c	(revision 0)
@@ -0,0 +1,546 @@
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
+
+/* GIO - GLib Input, Output and Streaming Library
+ * 
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#include "config.h"
+#include <glib.h>
+#include "glibintl.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#include "gthreadedresolver.h"
+#include "gresolverprivate.h"
+
+#include "gcancellable.h"
+#include "gnetworkaddress.h"
+#include "gnetworkservice.h"
+#include "gsimpleasyncresult.h"
+
+#include "gioalias.h"
+
+G_DEFINE_TYPE (GThreadedResolver, g_threaded_resolver, G_TYPE_RESOLVER)
+
+static void threaded_resolver_thread (gpointer thread_data, gpointer pool_data);
+
+static void
+g_threaded_resolver_init (GThreadedResolver *gtr)
+{
+  if (g_thread_supported ())
+    {
+      gtr->thread_pool = g_thread_pool_new (threaded_resolver_thread, gtr,
+					    -1, FALSE, NULL);
+    }
+}
+
+static void
+finalize (GObject *object)
+{
+  GThreadedResolver *gtr = G_THREADED_RESOLVER (object);
+
+  g_thread_pool_free (gtr->thread_pool, FALSE, FALSE);
+
+  G_OBJECT_CLASS (g_threaded_resolver_parent_class)->finalize (object);
+}
+
+/* A GThreadedResolverRequest represents a request in progress
+ * (usually, but see case 1). It is refcounted, to make sure that it
+ * doesn't get freed too soon. In particular, it can't be freed until
+ * (a) the resolver thread has finished resolving, (b) the calling
+ * thread has received an answer, and (c) no other thread could be in
+ * the process of trying to cancel it.
+ *
+ * The possibilities:
+ *
+ * 1. Synchronous non-cancellable request: in this case, the request
+ *    is simply done in the calling thread, without using
+ *    GThreadedResolverRequest at all.
+ *
+ * 2. Synchronous cancellable request: A req is created with a GCond,
+ *    and 3 refs (for the resolution thread, the calling thread, and
+ *    the cancellation signal handler).
+ *
+ *      a. If the resolution completes successfully, the thread pool
+ *         function (threaded_resolver_thread()) will call
+ *         g_threaded_resolver_request_complete(), which will detach
+ *         the "cancelled" signal handler (dropping one ref on req)
+ *         and signal the GCond, and then unref the req. The calling
+ *         thread receives the signal from the GCond, processes the
+ *         response, and unrefs the req, causing it to be freed.
+ *
+ *      b. If the resolution is cancelled before completing,
+ *         request_cancelled() will call
+ *         g_threaded_resolver_request_complete(), which will detach
+ *         the signal handler (as above, unreffing the req), set
+ *         req->error to indicate that it was cancelled, and signal
+ *         the GCond. The calling thread receives the signal from the
+ *         GCond, processes the response, and unrefs the req.
+ *         Eventually, the resolver thread finishes resolving (or
+ *         times out in the resolver) and calls
+ *         g_threaded_resolver_request_complete() again, but
+ *         _request_complete() does nothing this time since the
+ *         request is already complete. The thread pool func then
+ *         unrefs the req, causing it to be freed.
+ *
+ * 3. Asynchronous request: A req is created with a GSimpleAsyncResult
+ *    (and no GCond). The calling thread's ref on req is set up to be
+ *    automatically dropped when the async_result is freed. Two
+ *    sub-possibilities:
+ *
+ *      a. If the resolution completes, the thread pool function
+ *         (threaded_resolver_thread()) will call
+ *         g_threaded_resolver_request_complete(), which will detach
+ *         the "cancelled" signal handler (if it was present)
+ *         (unreffing the req), queue the async_result to complete in
+ *         an idle handler, unref the async_result (which is still
+ *         reffed by the idle handler though), and then unref the req.
+ *         The main thread then invokes the async_result's callback
+ *         and processes the response. When it finishes, the
+ *         async_result drops the ref that was taken by
+ *         g_simple_async_result_complete_in_idle(), which causes the
+ *         async_result to be freed, which causes req to be unreffed
+ *         and freed.
+ *
+ *      b. If the resolution is cancelled, request_cancelled() will
+ *         call g_threaded_resolver_request_complete(), which will
+ *         detach the signal handler (as above, unreffing the req) set
+ *         req->error to indicate that it was cancelled, and queue and
+ *         unref the async_result. The main thread completes the
+ *         async_request and unrefs it and the req, as above.
+ *         Eventually, the resolver thread finishes resolving (or
+ *         times out in the resolver) and calls
+ *         g_threaded_resolver_request_complete() again, but
+ *         _request_complete() does nothing this time since the
+ *         request is already complete. The thread pool func then
+ *         unrefs the req, causing it to be freed.
+ *
+ * g_threaded_resolver_request_complete() ensures that if the request
+ * completes and cancels "at the same time" that only one of the two
+ * conditions gets processed.
+ */
+
+typedef gboolean (*GThreadedResolverResolveFunc) (gpointer, GError **);
+
+typedef struct {
+  gpointer resolvable;
+  GThreadedResolverResolveFunc resolve_func;
+
+  GCancellable *cancellable;
+  GError *error;
+
+  GMutex *mutex;
+  guint ref_count;
+
+  GCond *cond;
+  GSimpleAsyncResult *async_result;
+  gboolean complete;
+
+} GThreadedResolverRequest;
+
+static void g_threaded_resolver_request_unref (GThreadedResolverRequest *req);
+static void request_cancelled (GCancellable *cancellable, gpointer req);
+static void request_cancelled_disconnect_notify (gpointer req, GClosure *closure);
+
+static GThreadedResolverRequest *
+g_threaded_resolver_request_new (gpointer resolvable,
+				 GThreadedResolverResolveFunc resolve_func,
+				 GCancellable *cancellable,
+				 GSimpleAsyncResult *async_result)
+{
+  GThreadedResolverRequest *req;
+
+  req = g_slice_new0 (GThreadedResolverRequest);
+  req->resolvable = g_object_ref (resolvable);
+  req->resolve_func = resolve_func;
+
+  /* Initial refcount is 2; one for the caller and one for resolve_func */
+  req->ref_count = 2;
+
+  req->mutex = g_mutex_new ();
+  /* Initially locked; caller must unlock */
+  g_mutex_lock (req->mutex);
+
+  if (cancellable)
+    {
+      req->ref_count++;
+      req->cancellable = g_object_ref (cancellable);
+      g_signal_connect_data (cancellable, "cancelled",
+			     G_CALLBACK (request_cancelled), req,
+			     request_cancelled_disconnect_notify, 0);
+    }
+
+  if (async_result)
+    {
+      req->async_result = g_object_ref (async_result);
+      /* Drop the caller's ref when @async_result is destroyed */
+      g_simple_async_result_set_op_res_gpointer (req->async_result, req, (GDestroyNotify)g_threaded_resolver_request_unref);
+    }
+  else
+    req->cond = g_cond_new ();
+
+  return req;
+}
+
+static void
+g_threaded_resolver_request_unref (GThreadedResolverRequest *req)
+{
+  guint ref_count;
+
+  g_mutex_lock (req->mutex);
+  ref_count = --req->ref_count;
+  g_mutex_unlock (req->mutex);
+  if (ref_count > 0)
+    return;
+
+  if (req->resolvable)
+    g_object_unref (req->resolvable);
+
+  g_mutex_free (req->mutex);
+
+  if (req->cond)
+    g_cond_free (req->cond);
+
+  if (req->error)
+    g_error_free (req->error);
+
+  /* We don't have to free req->cancellable or req->async_result,
+   * since (if set), they must already have been freed by
+   * request_complete() in order to get here.
+   */
+
+  g_slice_free (GThreadedResolverRequest, req);
+}
+
+static void
+g_threaded_resolver_request_complete (GThreadedResolverRequest *req,
+				      gboolean cancelled)
+{
+  g_mutex_lock (req->mutex);
+  if (req->complete)
+    {
+      /* The req was cancelled, and now it has finished resolving as
+       * well. But we have nowhere to send the result, so just return.
+       */
+      g_mutex_unlock (req->mutex);
+      return;
+    }
+
+  req->complete = TRUE;
+  g_mutex_unlock (req->mutex);
+
+  if (req->cancellable)
+    {
+      /* Possibly propagate a cancellation error */
+      if (cancelled && !req->error)
+        g_cancellable_set_error_if_cancelled (req->cancellable, &req->error);
+
+      /* Drop the signal handler's ref on @req */
+      g_signal_handlers_disconnect_by_func (req->cancellable, request_cancelled, req);
+      g_object_unref (req->cancellable);
+      req->cancellable = NULL;
+    }
+
+  if (req->cond)
+    g_cond_signal (req->cond);
+  else if (req->async_result)
+    {
+      if (req->error)
+        g_simple_async_result_set_from_error (req->async_result, req->error);
+      g_simple_async_result_complete_in_idle (req->async_result);
+
+      /* Drop our ref on the async_result, which will eventually cause
+       * it to drop its ref on req.
+       */
+      g_object_unref (req->async_result);
+      req->async_result = NULL;
+    }
+}
+
+static void
+request_cancelled (GCancellable *cancellable, gpointer user_data)
+{
+  GThreadedResolverRequest *req = user_data;
+
+  g_threaded_resolver_request_complete (req, TRUE);
+
+  /* We can't actually cancel the resolver thread; it will eventually
+   * complete on its own and call request_complete() again, which will
+   * do nothing the second time.
+   */
+}
+
+static void
+request_cancelled_disconnect_notify (gpointer req, GClosure *closure)
+{
+  g_threaded_resolver_request_unref (req);
+}
+
+static void
+threaded_resolver_thread (gpointer thread_data, gpointer pool_data)
+{
+  GThreadedResolverRequest *req = thread_data;
+
+  req->resolve_func (req->resolvable, &req->error);
+  g_threaded_resolver_request_complete (req, FALSE);
+  g_threaded_resolver_request_unref (req);
+}  
+
+static gboolean
+resolve_sync (GThreadedResolver *gtr,
+	      gpointer resolvable, GThreadedResolverResolveFunc resolve_func,
+	      GCancellable *cancellable, GError **error)
+{
+  GThreadedResolverRequest *req;
+  gboolean success;
+
+  if (!cancellable || !gtr->thread_pool)
+    return resolve_func (resolvable, error);
+
+  req = g_threaded_resolver_request_new (resolvable, resolve_func,
+					 cancellable, NULL);
+  g_thread_pool_push (gtr->thread_pool, req, NULL);
+  g_cond_wait (req->cond, req->mutex);
+  g_mutex_unlock (req->mutex);
+
+  if (req->error)
+    {
+      g_propagate_error (error, req->error);
+      req->error = NULL;
+      success = FALSE;
+    }
+  else
+    success = TRUE;
+
+  g_threaded_resolver_request_unref (req);
+  return success;
+}
+
+static void
+resolve_async (GThreadedResolver *gtr,
+	       gpointer resolvable, GThreadedResolverResolveFunc resolve_func,
+	       GCancellable *cancellable, GAsyncReadyCallback callback,
+	       gpointer user_data, gpointer tag)
+{
+  GThreadedResolverRequest *req;
+  GSimpleAsyncResult *result;
+
+  result = g_simple_async_result_new (G_OBJECT (gtr), callback, user_data, tag);
+  req = g_threaded_resolver_request_new (resolvable, resolve_func,
+					 cancellable, result);
+  g_object_unref (result);
+
+  g_thread_pool_push (gtr->thread_pool, req, NULL);
+  g_mutex_unlock (req->mutex);
+}
+
+static gboolean
+resolve_finish (GResolver *resolver, GAsyncResult *result,
+		gpointer tag, GError **error)
+{
+  GSimpleAsyncResult *simple;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == tag, FALSE);
+
+  return !g_simple_async_result_propagate_error (simple, error);
+}
+
+static gboolean
+do_lookup_name (gpointer data, GError **error)
+{
+  GNetworkAddress *addr = data;
+  struct addrinfo hints, *res = NULL;
+  char service[8];
+  int retval;
+
+  g_network_address_get_addrinfo_hints (addr, service, &hints);
+  retval = getaddrinfo (g_network_address_get_ascii_name (addr),
+                        service, &hints, &res);
+  g_network_address_set_from_addrinfo (addr, res, retval, error);
+  if (res)
+    freeaddrinfo (res);
+  return retval == 0;
+}
+
+static gboolean
+lookup_name (GResolver *resolver, GNetworkAddress *addr,
+             GCancellable *cancellable, GError **error)
+{
+  GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
+
+  if (!cancellable || !gtr->thread_pool)
+    return do_lookup_name (addr, error);
+  else
+    return resolve_sync (gtr, addr, do_lookup_name, cancellable, error);
+}
+
+static void
+lookup_name_async (GResolver *resolver, GNetworkAddress *addr,
+		   GCancellable *cancellable, GAsyncReadyCallback callback,
+		   gpointer user_data)
+{
+  GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
+
+  resolve_async (gtr, addr, do_lookup_name, cancellable,
+		 callback, user_data, lookup_name_async);
+}
+
+static gboolean
+lookup_name_finish (GResolver *resolver, GAsyncResult *result,
+		    GError **error)
+{
+  return resolve_finish (resolver, result, lookup_name_async, error);
+}
+
+
+static gboolean
+do_lookup_address (gpointer data, GError **error)
+{
+  GNetworkAddress *addr = data;
+  GSockaddr **sockaddrs;
+  char name[NI_MAXHOST];
+  int retval;
+
+  sockaddrs = g_network_address_get_sockaddrs (addr);
+  g_return_val_if_fail (sockaddrs && sockaddrs[0], FALSE);
+
+  retval = getnameinfo ((struct sockaddr *)sockaddrs[0],
+                        g_sockaddr_size (sockaddrs[0]),
+                        name, sizeof (name), NULL, 0, NI_NAMEREQD);
+  g_network_address_set_from_nameinfo (addr, name, retval, error);
+  return retval == 0;
+}
+
+static gboolean
+lookup_address (GResolver *resolver, GNetworkAddress *addr,
+		GCancellable *cancellable, GError **error)
+{
+  GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
+
+  if (!cancellable || !gtr->thread_pool)
+    return do_lookup_address (addr, error);
+  else
+    return resolve_sync (gtr, addr, do_lookup_address, cancellable, error);
+}
+
+static void
+lookup_address_async (GResolver *resolver, GNetworkAddress *addr,
+		      GCancellable *cancellable, GAsyncReadyCallback callback,
+		      gpointer user_data)
+{
+  GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
+
+  resolve_async (gtr, addr, do_lookup_address, cancellable,
+		 callback, user_data, lookup_address_async);
+}
+
+static gboolean
+lookup_address_finish (GResolver *resolver, GAsyncResult *result,
+		       GError **error)
+{
+  return resolve_finish (resolver, result, lookup_address_async, error);
+}
+
+
+static gboolean
+do_lookup_service (gpointer data, GError **error)
+{
+  GNetworkService *srv = data;
+  gboolean success;
+  char *dname;
+#if defined(G_OS_UNIX)
+  int len, herr;
+  guchar answer[1024];
+#elif defined(G_OS_WIN32)
+  DNS_STATUS status;
+  DNS_RECORD *results;
+#endif
+
+  dname = g_network_service_get_rrname (srv);
+
+#if defined(G_OS_UNIX)
+  len = res_query (dname, C_IN, T_SRV, answer, sizeof (answer));
+  herr = h_errno;
+  success = g_network_service_set_from_res_query (srv, answer, len, herr, error);
+#elif defined(G_OS_WIN32)
+  status = DnsQuery_A (dname, DNS_TYPE_SRV, DNS_QUERY_STANDARD,
+                       NULL, &results, NULL);
+  success = g_network_service_set_from_DnsQuery (srv, status, results, error);
+  DnsRecordListFree (results, DnsFreeRecordList);
+#endif
+
+  g_free (dname);
+  return success;
+}
+
+static gboolean
+lookup_service (GResolver *resolver, GNetworkService *srv,
+		GCancellable *cancellable, GError **error)
+{
+  GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
+
+  if (!cancellable || !gtr->thread_pool)
+    return do_lookup_service (srv, error);
+  else
+    return resolve_sync (gtr, srv, do_lookup_service, cancellable, error);
+}
+
+static void
+lookup_service_async (GResolver *resolver, GNetworkService *srv,
+		      GCancellable *cancellable, GAsyncReadyCallback callback,
+		      gpointer user_data)
+{
+  GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
+
+  resolve_async (gtr, srv, do_lookup_service, cancellable,
+		 callback, user_data, lookup_service_async);
+}
+
+static gboolean
+lookup_service_finish (GResolver *resolver, GAsyncResult *result,
+		       GError **error)
+{
+  return resolve_finish (resolver, result, lookup_service_async, error);
+}
+
+
+static void
+g_threaded_resolver_class_init (GThreadedResolverClass *threaded_class)
+{
+  GResolverClass *resolver_class = G_RESOLVER_CLASS (threaded_class);
+  GObjectClass *object_class = G_OBJECT_CLASS (threaded_class);
+
+  resolver_class->lookup_name           = lookup_name;
+  resolver_class->lookup_name_async     = lookup_name_async;
+  resolver_class->lookup_name_finish    = lookup_name_finish;
+  resolver_class->lookup_address        = lookup_address;
+  resolver_class->lookup_address_async  = lookup_address_async;
+  resolver_class->lookup_address_finish = lookup_address_finish;
+  resolver_class->lookup_service        = lookup_service;
+  resolver_class->lookup_service_async  = lookup_service_async;
+  resolver_class->lookup_service_finish = lookup_service_finish;
+
+  object_class->finalize = finalize;
+}
+
+#define __G_THREADED_RESOLVER_C__
+#include "gioaliasdef.c"
Index: gio/gunixresolver.h
===================================================================
--- gio/gunixresolver.h	(revision 0)
+++ gio/gunixresolver.h	(revision 0)
@@ -0,0 +1,53 @@
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#ifndef __G_UNIX_RESOLVER_H__
+#define __G_UNIX_RESOLVER_H__
+
+#include <gio/gthreadedresolver.h>
+#include "libasyncns/asyncns.h"
+
+G_BEGIN_DECLS
+
+#define G_TYPE_UNIX_RESOLVER         (g_unix_resolver_get_type ())
+#define G_UNIX_RESOLVER(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_UNIX_RESOLVER, GUnixResolver))
+#define G_UNIX_RESOLVER_CLASS(k)     (G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_UNIX_RESOLVER, GUnixResolverClass))
+#define G_IS_UNIX_RESOLVER(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_UNIX_RESOLVER))
+#define G_IS_UNIX_RESOLVER_CLASS(k)  (G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_UNIX_RESOLVER))
+#define G_UNIX_RESOLVER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_TYPE_UNIX_RESOLVER, GUnixResolverClass))
+
+typedef struct {
+  GThreadedResolver parent_instance;
+
+  _g_asyncns_t *asyncns;
+  guint watch;
+
+} GUnixResolver;
+
+typedef struct {
+  GThreadedResolverClass parent_class;
+
+} GUnixResolverClass;
+
+GType g_unix_resolver_get_type (void) G_GNUC_CONST;
+
+G_END_DECLS
+
+#endif /* __G_RESOLVER_H__ */
Index: gio/gunixresolver.c
===================================================================
--- gio/gunixresolver.c	(revision 0)
+++ gio/gunixresolver.c	(revision 0)
@@ -0,0 +1,398 @@
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
+
+/* GIO - GLib Input, Output and Streaming Library
+ * 
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#include "config.h"
+#include <glib.h>
+#include "glibintl.h"
+
+#include <resolv.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "gunixresolver.h"
+#include "gresolverprivate.h"
+
+#include "gcancellable.h"
+#include "ghostutils.h"
+#include "gnetworkaddress.h"
+#include "gnetworkservice.h"
+#include "gsimpleasyncresult.h"
+
+#include "gioalias.h"
+
+G_DEFINE_TYPE (GUnixResolver, g_unix_resolver, G_TYPE_THREADED_RESOLVER)
+
+static gboolean g_unix_resolver_watch (GIOChannel *iochannel,
+                                       GIOCondition condition,
+                                       gpointer user_data);
+
+static void
+g_unix_resolver_init (GUnixResolver *gur)
+{
+  int fd;
+  GIOChannel *io;
+
+  /* FIXME: how many workers? */
+  gur->asyncns = _g_asyncns_new (2);
+
+  fd = _g_asyncns_fd (gur->asyncns);
+  io = g_io_channel_unix_new (fd);
+  gur->watch = g_io_add_watch (io, G_IO_IN | G_IO_HUP | G_IO_ERR,
+                               g_unix_resolver_watch, gur);
+  g_io_channel_unref (io);
+}
+
+static void
+g_unix_resolver_finalize (GObject *object)
+{
+  GUnixResolver *gur = G_UNIX_RESOLVER (object);
+
+  if (gur->watch)
+    g_source_remove (gur->watch);
+  _g_asyncns_free (gur->asyncns);
+
+  G_OBJECT_CLASS (g_unix_resolver_parent_class)->finalize (object);
+}
+
+/* The various request possibilities:
+ *
+ * 1. Synchronous: handed off to the base class (GThreadedResolver);
+ *    since it's never possible to cancel a synchronous request in a
+ *    single-threaded program, the request is done in the calling
+ *    thread.
+ *
+ * 2. Asynchronous: An appropriate _g_asyncns_query_t is created, and
+ *    then a GUnixResolverRequest is created with that query and a
+ *    GSimpleAsyncResult. Two sub-possibilities:
+ *
+ *      a. The resolution completes: g_unix_resolver_watch() sees that
+ *         the request has completed, and calls
+ *         g_unix_resolver_request_complete(), which detaches the
+ *         "cancelled" signal handler (if it was present) and then
+ *         immediately completes the async_result (since
+ *         g_unix_resolver_watch() is already run from main-loop
+ *         time.) After completing the async_result, it unrefs it,
+ *         causing the req to be freed as well.
+ *
+ *      b. The resolution is cancelled: request_cancelled() calls
+ *         _g_asyncns_cancel() to cancel the resolution. Then it calls
+ *         g_unix_resolver_request_complete(), which detaches the
+ *         signal handler, and queues async_result to complete in an
+ *         idle handler. It then unrefs the async_result to ensure
+ *         that after its callback runs, it will be destroyed, in turn
+ *         causing the req to be freed. Because the asyncns resolution
+ *         was cancelled, g_unix_resolver_watch() will never be
+ *         triggered for this req.
+ *
+ *    Since there's only a single thread, it's not possible for the
+ *    request to both complete and be cancelled "at the same time",
+ *    and each of the two possibilities takes steps to block the other
+ *    from being able to happen later, so it's always safe to free req
+ *    after the async_result completes.
+ */
+
+typedef struct {
+  GUnixResolver *gur;
+
+  _g_asyncns_query_t *qy;
+  gpointer resolvable;
+
+  GCancellable *cancellable;
+  GSimpleAsyncResult *async_result;
+
+} GUnixResolverRequest;
+
+static void g_unix_resolver_request_free (GUnixResolverRequest *req);
+static void request_cancelled (GCancellable *cancellable, gpointer user_data);
+
+static GUnixResolverRequest *
+g_unix_resolver_request_new (GUnixResolver *gur,
+                             gpointer resolvable,
+                             _g_asyncns_query_t *qy,
+                             GCancellable *cancellable,
+                             GSimpleAsyncResult *async_result)
+{
+  GUnixResolverRequest *req;
+
+  req = g_slice_new0 (GUnixResolverRequest);
+  req->gur = g_object_ref (gur);
+  req->qy = qy;
+  req->resolvable = g_object_ref (resolvable);
+
+  if (cancellable)
+    {
+      req->cancellable = g_object_ref (cancellable);
+      g_signal_connect (cancellable, "cancelled",
+                        G_CALLBACK (request_cancelled), req);
+    }
+
+  req->async_result = g_object_ref (async_result);
+
+  g_simple_async_result_set_op_res_gpointer (req->async_result, req, (GDestroyNotify)g_unix_resolver_request_free);
+
+  return req;
+}
+
+static void
+g_unix_resolver_request_free (GUnixResolverRequest *req)
+{
+  g_object_unref (req->resolvable);
+
+  /* We don't have to free req->cancellable and req->async_result,
+   * since they must already have been freed if we're here.
+   */
+
+  g_slice_free (GUnixResolverRequest, req);
+}
+
+static void
+g_unix_resolver_request_complete (GUnixResolverRequest *req,
+                                  gboolean need_idle)
+{
+  if (req->cancellable)
+    {
+      g_signal_handlers_disconnect_by_func (req->cancellable, request_cancelled, req);
+      g_object_unref (req->cancellable);
+      req->cancellable = NULL;
+    }
+
+  if (need_idle)
+    g_simple_async_result_complete_in_idle (req->async_result);
+  else
+    g_simple_async_result_complete (req->async_result);
+
+  /* If we completed_in_idle, that will have taken an extra ref on
+   * req->async_result; if not, then we're already done. Either way we
+   * need to unref the async_result to make sure it eventually is
+   * destroyed, causing req to be freed.
+   */
+  g_object_unref (req->async_result);
+}
+
+static void
+request_cancelled (GCancellable *cancellable, gpointer user_data)
+{
+  GUnixResolverRequest *req = user_data;
+  GError *error = NULL;
+
+  _g_asyncns_cancel (req->gur->asyncns, req->qy);
+  req->qy = NULL;
+
+  g_cancellable_set_error_if_cancelled (cancellable, &error);
+  g_simple_async_result_set_from_error (req->async_result, error);
+  g_error_free (error);
+
+  g_unix_resolver_request_complete (req, TRUE);
+}
+
+static gboolean
+g_unix_resolver_watch (GIOChannel *iochannel, GIOCondition condition,
+                       gpointer user_data)
+{
+  GUnixResolver *gur = user_data;
+  _g_asyncns_query_t *qy;
+  GUnixResolverRequest *req;
+
+  if (condition & (G_IO_HUP | G_IO_ERR))
+    {
+      /* Shouldn't happen. Should we create a new asyncns? FIXME */
+      g_warning ("asyncns died");
+      gur->watch = 0;
+      return FALSE;
+    }
+
+  while (_g_asyncns_wait (gur->asyncns, FALSE) == 0 &&
+         (qy = _g_asyncns_getnext (gur->asyncns)) != NULL)
+    {
+      req = _g_asyncns_getuserdata (gur->asyncns, qy);
+      g_unix_resolver_request_complete (req, FALSE);
+    }
+
+  return TRUE;
+}
+
+static void
+resolve_async (GUnixResolver *gur, gpointer resolvable,
+               _g_asyncns_query_t *qy, GCancellable *cancellable,
+               GAsyncReadyCallback callback, gpointer user_data,
+               gpointer tag)
+{
+  GSimpleAsyncResult *result;
+  GUnixResolverRequest *req;
+
+  result = g_simple_async_result_new (G_OBJECT (gur), callback, user_data, tag);
+  req = g_unix_resolver_request_new (gur, resolvable, qy, cancellable, result);
+  g_object_unref (result);
+  _g_asyncns_setuserdata (gur->asyncns, qy, req);
+}
+
+static void
+lookup_name_async (GResolver *resolver, GNetworkAddress *addr,
+		   GCancellable *cancellable, GAsyncReadyCallback callback,
+		   gpointer user_data)
+{
+  GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
+  _g_asyncns_query_t *qy;
+  struct addrinfo hints;
+  char service[8];
+
+  g_network_address_get_addrinfo_hints (addr, service, &hints);
+  qy = _g_asyncns_getaddrinfo (gur->asyncns,
+                               g_network_address_get_ascii_name (addr),
+                               service, &hints);
+  resolve_async (gur, addr, qy, cancellable,
+                 callback, user_data, lookup_name_async);
+}
+
+static gboolean
+lookup_name_finish (GResolver *resolver, GAsyncResult *result,
+		    GError **error)
+{
+  GSimpleAsyncResult *simple;
+  GUnixResolverRequest *req;
+  struct addrinfo *res;
+  int retval;
+  gboolean success;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == lookup_name_async, FALSE);
+
+  if (g_simple_async_result_propagate_error (simple, error))
+    return FALSE;
+
+  req = g_simple_async_result_get_op_res_gpointer (simple);
+  retval = _g_asyncns_getaddrinfo_done (req->gur->asyncns, req->qy, &res);
+  success = g_network_address_set_from_addrinfo (req->resolvable, res, retval, error);
+  if (res)
+    freeaddrinfo (res);
+
+  return success;
+}
+
+
+static void
+lookup_address_async (GResolver *resolver, GNetworkAddress *addr,
+		      GCancellable *cancellable, GAsyncReadyCallback callback,
+		      gpointer user_data)
+{
+  GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
+  _g_asyncns_query_t *qy;
+  GSockaddr *sockaddr;
+  int socklen;
+
+  sockaddr = g_network_address_get_sockaddrs (addr)[0];
+  socklen = g_sockaddr_size (sockaddr);
+  qy = _g_asyncns_getnameinfo (gur->asyncns,
+                               (struct sockaddr *)sockaddr, socklen,
+                               NI_NAMEREQD, TRUE, FALSE);
+  resolve_async (gur, addr, qy, cancellable,
+                 callback, user_data, lookup_address_async);
+}
+
+static gboolean
+lookup_address_finish (GResolver *resolver, GAsyncResult *result,
+		       GError **error)
+{
+  GSimpleAsyncResult *simple;
+  GUnixResolverRequest *req;
+  char host[NI_MAXHOST];
+  int retval;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == lookup_address_async, FALSE);
+
+  if (g_simple_async_result_propagate_error (simple, error))
+    return FALSE;
+
+  req = g_simple_async_result_get_op_res_gpointer (simple);
+  retval = _g_asyncns_getnameinfo_done (req->gur->asyncns, req->qy,
+                                        host, sizeof (host), NULL, 0);
+  return g_network_address_set_from_nameinfo (req->resolvable, host, retval, error);
+}
+
+
+static void
+lookup_service_async (GResolver *resolver, GNetworkService *srv,
+		      GCancellable *cancellable, GAsyncReadyCallback callback,
+		      gpointer user_data)
+{
+  GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
+  _g_asyncns_query_t *qy;
+  char *dname;
+
+  dname = g_network_service_get_rrname (srv);
+  qy = _g_asyncns_res_query (gur->asyncns, dname, C_IN, T_SRV);
+  g_free (dname);
+  resolve_async (gur, srv, qy, cancellable,
+                 callback, user_data, lookup_service_async);
+}
+
+static gboolean
+lookup_service_finish (GResolver *resolver, GAsyncResult *result,
+		       GError **error)
+{
+  GSimpleAsyncResult *simple;
+  GUnixResolverRequest *req;
+  guchar *answer;
+  int len, herr;
+  gboolean success;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == lookup_service_async, FALSE);
+
+  if (g_simple_async_result_propagate_error (simple, error))
+    return FALSE;
+
+  req = g_simple_async_result_get_op_res_gpointer (simple);
+  len = _g_asyncns_res_done (req->gur->asyncns, req->qy, &answer);
+  if (len < 0)
+    herr = h_errno;
+  else
+    herr = 0;
+
+  success = g_network_service_set_from_res_query (req->resolvable, answer, len, herr, error);
+  _g_asyncns_freeanswer (answer);
+  return success;
+}
+
+
+static void
+g_unix_resolver_class_init (GUnixResolverClass *unix_class)
+{
+  GResolverClass *resolver_class = G_RESOLVER_CLASS (unix_class);
+  GObjectClass *object_class = G_OBJECT_CLASS (unix_class);
+
+  resolver_class->lookup_name_async     = lookup_name_async;
+  resolver_class->lookup_name_finish    = lookup_name_finish;
+  resolver_class->lookup_address_async  = lookup_address_async;
+  resolver_class->lookup_address_finish = lookup_address_finish;
+  resolver_class->lookup_service_async  = lookup_service_async;
+  resolver_class->lookup_service_finish = lookup_service_finish;
+
+  object_class->finalize = g_unix_resolver_finalize;
+}
+
+#define __G_UNIX_RESOLVER_C__
+#include "gioaliasdef.c"
Index: gio/gwin32resolver.h
===================================================================
--- gio/gwin32resolver.h	(revision 0)
+++ gio/gwin32resolver.h	(revision 0)
@@ -0,0 +1,49 @@
+/* GIO - GLib Input, Output and Streaming Library
+ *
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#ifndef __G_WIN32_RESOLVER_H__
+#define __G_WIN32_RESOLVER_H__
+
+#include <gio/gthreadedresolver.h>
+
+G_BEGIN_DECLS
+
+#define G_TYPE_WIN32_RESOLVER         (g_win32_resolver_get_type ())
+#define G_WIN32_RESOLVER(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_WIN32_RESOLVER, GWin32Resolver))
+#define G_WIN32_RESOLVER_CLASS(k)     (G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_WIN32_RESOLVER, GWin32ResolverClass))
+#define G_IS_WIN32_RESOLVER(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_WIN32_RESOLVER))
+#define G_IS_WIN32_RESOLVER_CLASS(k)  (G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_WIN32_RESOLVER))
+#define G_WIN32_RESOLVER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_TYPE_WIN32_RESOLVER, GWin32ResolverClass))
+
+typedef struct {
+  GThreadedResolver parent_instance;
+
+} GWin32Resolver;
+
+typedef struct {
+  GThreadedResolverClass parent_class;
+
+} GWin32ResolverClass;
+
+GType g_win32_resolver_get_type (void) G_GNUC_CONST;
+
+G_END_DECLS
+
+#endif /* __G_RESOLVER_H__ */
Index: gio/gwin32resolver.c
===================================================================
--- gio/gwin32resolver.c	(revision 0)
+++ gio/gwin32resolver.c	(revision 0)
@@ -0,0 +1,485 @@
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
+
+/* GIO - GLib Input, Output and Streaming Library
+ * 
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#include "config.h"
+#include <glib.h>
+#include "glibintl.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#include "gwin32resolver.h"
+#include "gresolverprivate.h"
+
+#include "gcancellable.h"
+#include "ghostutils.h"
+#include "gnetworkaddress.h"
+#include "gnetworkservice.h"
+#include "gsimpleasyncresult.h"
+
+#include "gioalias.h"
+
+G_DEFINE_TYPE (GWin32Resolver, g_win32_resolver, G_TYPE_THREADED_RESOLVER)
+
+static void
+g_win32_resolver_init (GWin32Resolver *gwr)
+{
+}
+
+/* This is simpler than GThreadedResolver since we don't have to worry
+ * about multiple application-level threads, but more complicated than
+ * GUnixResolver, since we do have to deal with multiple threads of
+ * our own.
+ *
+ * The various request possibilities:
+ *
+ * 1. Synchronous: handed off to the base class (GThreadedResolver);
+ *    since it's never possible to cancel a synchronous request in a
+ *    single-threaded program, the request is done in the calling
+ *    thread.
+ *
+ * 2. Asynchronous: A GWin32ResolverRequest is created with
+ *    appropriate query-specific information, a Windows event handle,
+ *    and a GSimpleAsyncResult. This is then handed to the
+ *    Windows-internal thread pool, which does the raw DNS query part
+ *    of the operation (being careful to not call any glib methods
+ *    that might fail when called from another thread when
+ *    g_thread_init() has not been called). The main thread sets up a
+ *    GSource to asynchronously poll the event handle. There are two
+ *    sub-possibilities:
+ *
+ *      a. The resolution completes: the threadpool function calls
+ *         SetEvent() on the event handle and then returns.
+ *
+ *      b. The resolution is cancelled: request_cancelled()
+ *         disconnects the "cancelled" signal handler, and queues an
+ *         idle handler to complete the async_result.
+ *
+ *    Since we can't free the request from the threadpool thread
+ *    (because of glib locking issues), we *always* have to have it
+ *    call SetEvent and trigger the callback to indicate that it is
+ *    done. But this means that it's possible for the request to be
+ *    cancelled (queuing an idle handler to return that result) and
+ *    then have the resolution thread complete before the idle handler
+ *    runs. So the event callback and the idle handler need to both
+ *    watch out for this, making sure we don't complete the same
+ *    result twice.
+ */
+
+typedef struct GWin32ResolverRequest GWin32ResolverRequest;
+typedef void (*GWin32ResolverRequestFreeFunc) (GWin32ResolverRequest *);
+
+struct GWin32ResolverRequest {
+  gpointer resolvable;
+  GWin32ResolverRequestFreeFunc free_func;
+
+  GCancellable *cancellable;
+  GError *error;
+
+  HANDLE *event;
+  GSimpleAsyncResult *async_result;
+  gboolean complete;
+  guint cancelled_idle;
+
+  union {
+    struct {
+      const char *name;
+      char service[8];
+      struct addrinfo hints;
+      int retval;
+      struct addrinfo *res;
+    } name;
+
+    struct {
+      struct sockaddr *addr;
+      int addrlen;
+      int retval;
+      char *namebuf;
+    } address;
+
+    struct {
+      char *dname;
+      DNS_STATUS retval;
+      DNS_RECORD *results;
+    } service;
+  } u;
+
+};
+
+static GSource *g_win32_handle_source_add (HANDLE handle, GSourceFunc callback, gpointer user_data);
+static gboolean request_completed (gpointer user_data);
+static void request_cancelled (GCancellable *cancellable, gpointer user_data);
+
+GWin32ResolverRequest *
+g_win32_resolver_request_new (GResolver *resolver,
+                              gpointer resolvable,
+                              GWin32ResolverRequestFreeFunc free_func,
+                              GCancellable *cancellable,
+                              GAsyncReadyCallback callback,
+                              gpointer user_data, gpointer tag)
+{
+  GWin32ResolverRequest *req;
+
+  req = g_slice_new0 (GWin32ResolverRequest);
+  req->resolvable = g_object_ref (resolvable);
+  req->free_func = free_func;
+
+  req->async_result = g_simple_async_result_new (G_OBJECT (resolver), callback,
+                                                 user_data, tag);
+  g_simple_async_result_set_op_res_gpointer (req->async_result, req, NULL);
+
+  req->event = CreateEvent (NULL, FALSE, FALSE, NULL);
+  g_win32_handle_source_add (req->event, request_completed, req);  
+
+  if (cancellable)
+    {
+      req->cancellable = g_object_ref (cancellable);
+      g_signal_connect (cancellable, "cancelled",
+                        G_CALLBACK (request_cancelled), req);
+    }
+
+  return req;
+}
+
+static gboolean
+request_completed (gpointer user_data)
+{
+  GWin32ResolverRequest *req = user_data;
+
+  /* Clean up cancellation-related stuff first */
+  if (req->cancelled_idle)
+    {
+      g_source_remove (req->cancelled_idle);
+      req->cancelled_idle = 0;
+    }
+  if (req->cancellable)
+    {
+      g_signal_handlers_disconnect_by_func (req->cancellable, request_cancelled, req);
+      g_object_unref (req->cancellable);
+    }
+
+  /* Now complete the result (assuming it wasn't already completed) */
+  if (req->async_result)
+    {
+      g_simple_async_result_complete (req->async_result);
+      g_object_unref (req->async_result);
+    }
+
+  /* And free req */
+  g_object_unref (req->resolvable);
+  CloseHandle (req->event);
+  req->free_func (req);
+  g_slice_free (GWin32ResolverRequest, req);
+
+  return FALSE;
+}
+
+static gboolean
+request_cancelled_idle (gpointer user_data)
+{
+  GWin32ResolverRequest *req = user_data;
+  GError *error = NULL;
+
+  req->cancelled_idle = 0;
+
+  g_cancellable_set_error_if_cancelled (req->cancellable, &error);
+  g_simple_async_result_set_from_error (req->async_result, error);
+  g_simple_async_result_complete (req->async_result);
+
+  g_object_unref (req->async_result);
+  req->async_result = NULL;
+
+  /* request_completed will eventually be called to free req */
+
+  return FALSE;
+}
+
+static void
+request_cancelled (GCancellable *cancellable, gpointer user_data)
+{
+  GWin32ResolverRequest *req = user_data;
+
+  if (req->cancellable)
+    {
+      g_signal_handlers_disconnect_by_func (req->cancellable, request_cancelled, req);
+      g_object_unref (req->cancellable);
+      req->cancellable = NULL;
+    }
+
+  /* We need to wait until main-loop-time to actually complete the
+   * result; we don't use _complete_in_idle() here because we need to
+   * keep track of the source id.
+   */
+  req->cancelled_idle = g_idle_add (request_cancelled_idle, req);
+}
+
+static DWORD WINAPI
+lookup_name_in_thread (LPVOID data)
+{
+  GWin32ResolverRequest *req = data;
+
+  req->u.name.retval = getaddrinfo (req->u.name.name, req->u.name.service,
+                                    &req->u.name.hints, &req->u.name.res);
+  SetEvent (req->event);
+  return 0;
+}
+
+static void
+free_lookup_name (GWin32ResolverRequest *req)
+{
+  if (req->u.name.res)
+    freeaddrinfo (req->u.name.res);
+}
+
+static void
+lookup_name_async (GResolver *resolver, GNetworkAddress *addr,
+		   GCancellable *cancellable, GAsyncReadyCallback callback,
+		   gpointer user_data)
+{
+  GWin32ResolverRequest *req;
+  const char *name;
+
+  name = g_network_address_get_ascii_name (addr);
+  g_return_if_fail (name != NULL);
+
+  req = g_win32_resolver_request_new (resolver, addr, free_lookup_name,
+                                      cancellable, callback, user_data,
+                                      lookup_name_async);
+  req->u.name.name = name;
+  g_network_address_get_addrinfo_hints (addr, req->u.name.service,
+                                        &req->u.name.hints);
+
+  QueueUserWorkItem (lookup_name_in_thread, req, 0);
+}
+
+static gboolean
+lookup_name_finish (GResolver *resolver, GAsyncResult *result,
+		    GError **error)
+{
+  GSimpleAsyncResult *simple;
+  GWin32ResolverRequest *req;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == lookup_name_async, FALSE);
+
+  if (g_simple_async_result_propagate_error (simple, error))
+    return FALSE;
+
+  req = g_simple_async_result_get_op_res_gpointer (simple);
+  return g_network_address_set_from_addrinfo (req->resolvable, req->u.name.res,
+                                              req->u.name.retval, error);
+}
+
+
+static DWORD WINAPI
+lookup_addresses_in_thread (LPVOID data)
+{
+  GWin32ResolverRequest *req = data;
+
+  req->u.address.retval =
+    getnameinfo (req->u.address.addr, req->u.address.addrlen,
+                 req->u.address.namebuf, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
+  SetEvent (req->event);
+  return 0;
+}
+
+static void
+free_lookup_address (GWin32ResolverRequest *req)
+{
+  g_free (req->u.address.namebuf);
+}
+
+static void
+lookup_address_async (GResolver *resolver, GNetworkAddress *addr,
+		      GCancellable *cancellable, GAsyncReadyCallback callback,
+		      gpointer user_data)
+{
+  GWin32ResolverRequest *req;
+  GSockaddr **addrs;
+
+  addrs = g_network_address_get_sockaddrs (addr);
+  g_return_if_fail (addrs != NULL && addrs[0] != NULL);
+
+  req = g_win32_resolver_request_new (resolver, addr, free_lookup_address,
+                                      cancellable, callback, user_data,
+                                      lookup_address_async);
+  req->u.address.addr = (struct sockaddr *)addrs[0];
+  req->u.address.addrlen = g_sockaddr_size (addrs[0]);
+  req->u.address.namebuf = g_malloc (NI_MAXHOST);
+
+  QueueUserWorkItem (lookup_addresses_in_thread, req, 0);
+}
+
+static gboolean
+lookup_address_finish (GResolver *resolver, GAsyncResult *result,
+		       GError **error)
+{
+  GSimpleAsyncResult *simple;
+  GWin32ResolverRequest *req;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == lookup_address_async, FALSE);
+
+  if (g_simple_async_result_propagate_error (simple, error))
+    return FALSE;
+
+  req = g_simple_async_result_get_op_res_gpointer (simple);
+  return g_network_address_set_from_nameinfo (req->resolvable,
+                                              req->u.address.namebuf,
+                                              req->u.address.retval, error);
+}
+
+
+static DWORD WINAPI
+lookup_service_in_thread (LPVOID data)
+{
+  GWin32ResolverRequest *req = data;
+
+  req->u.service.retval =
+    DnsQuery_A (req->u.service.dname, DNS_TYPE_SRV, DNS_QUERY_STANDARD,
+                NULL, &req->u.service.results, NULL);
+  SetEvent (req->event);
+  return 0;
+}
+
+static void
+free_lookup_service (GWin32ResolverRequest *req)
+{
+  g_free (req->u.service.dname);
+  if (req->u.service.results)
+    DnsRecordListFree (req->u.service.results, DnsFreeRecordList);
+}
+
+static void
+lookup_service_async (GResolver *resolver, GNetworkService *srv,
+		      GCancellable *cancellable, GAsyncReadyCallback callback,
+		      gpointer user_data)
+{
+  GWin32ResolverRequest *req;
+
+  req = g_win32_resolver_request_new (resolver, srv, free_lookup_service,
+                                      cancellable, callback, user_data,
+                                      lookup_service_async);
+  req->u.service.dname = g_network_service_get_rrname (srv);
+
+  QueueUserWorkItem (lookup_service_in_thread, req, 0);
+}
+
+static gboolean
+lookup_service_finish (GResolver *resolver, GAsyncResult *result,
+		       GError **error)
+{
+  GSimpleAsyncResult *simple;
+  GWin32ResolverRequest *req;
+
+  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
+  simple = G_SIMPLE_ASYNC_RESULT (result);
+  g_return_val_if_fail (g_simple_async_result_get_source_tag (simple) == lookup_service_async, FALSE);
+
+  if (g_simple_async_result_propagate_error (simple, error))
+    return FALSE;
+
+  req = g_simple_async_result_get_op_res_gpointer (simple);
+
+  return g_network_service_set_from_DnsQuery (req->resolvable,
+                                              req->u.service.retval,
+                                              req->u.service.results, error);
+}
+
+
+static void
+g_win32_resolver_class_init (GWin32ResolverClass *win32_class)
+{
+  GResolverClass *resolver_class = G_RESOLVER_CLASS (win32_class);
+
+  resolver_class->lookup_name_async     = lookup_name_async;
+  resolver_class->lookup_name_finish    = lookup_name_finish;
+  resolver_class->lookup_address_async  = lookup_address_async;
+  resolver_class->lookup_address_finish = lookup_address_finish;
+  resolver_class->lookup_service_async  = lookup_service_async;
+  resolver_class->lookup_service_finish = lookup_service_finish;
+}
+
+
+/* Windows HANDLE GSource */
+
+typedef struct {
+  GSource source;
+  GPollFD pollfd;
+} GWin32HandleSource;
+
+static gboolean
+g_win32_handle_source_prepare (GSource *source, gint *timeout)
+{
+  *timeout = -1;
+  return FALSE;
+}
+
+static gboolean
+g_win32_handle_source_check (GSource *source)
+{
+  GWin32HandleSource *hsource = (GWin32HandleSource *)source;
+
+  return hsource->pollfd.revents;
+}
+
+static gboolean
+g_win32_handle_source_dispatch (GSource *source, GSourceFunc callback, gpointer user_data)
+{
+  return (*callback) (user_data);
+}
+
+static void
+g_win32_handle_source_finalize (GSource *source)
+{
+  ;
+}
+
+GSourceFuncs g_win32_handle_source_funcs = {
+  g_win32_handle_source_prepare,
+  g_win32_handle_source_check,
+  g_win32_handle_source_dispatch,
+  g_win32_handle_source_finalize
+};
+
+static GSource *
+g_win32_handle_source_add (HANDLE handle, GSourceFunc callback, gpointer user_data)
+{
+  GWin32HandleSource *hsource;
+  GSource *source;
+
+  source = g_source_new (&g_win32_handle_source_funcs, sizeof (GWin32HandleSource));
+  hsource = (GWin32HandleSource *)source;
+  hsource->pollfd.fd = (int)handle;
+  hsource->pollfd.events = G_IO_IN;
+  hsource->pollfd.revents = 0;
+  g_source_add_poll (source, &hsource->pollfd);
+
+  g_source_set_callback (source, callback, user_data, NULL);
+  g_source_attach (source, NULL);
+  return source;
+}
+
+#define __G_WIN32_RESOLVER_C__
+#include "gioaliasdef.c"
Index: gio/giotypes.h
===================================================================
--- gio/giotypes.h	(revision 7710)
+++ gio/giotypes.h	(working copy)
@@ -104,6 +104,17 @@ typedef struct _GThemedIcon             
 typedef struct _GVfs                          GVfs; /* Dummy typedef */
 
 /**
+ * GResolver:
+ *
+ * Network address/service resolver
+ **/
+typedef struct _GResolver                     GResolver;
+typedef struct _GNetworkAddress               GNetworkAddress;
+typedef struct _GNetworkService               GNetworkService;
+typedef struct _GSockaddr                     GSockaddr;
+typedef struct _GSrvTarget                    GSrvTarget;
+
+/**
  * GVolume:
  *
  * Opaque mountable volume object.
Index: gio/gio.symbols
===================================================================
--- gio/gio.symbols	(revision 7710)
+++ gio/gio.symbols	(working copy)
@@ -837,3 +837,65 @@ g_emblem_get_origin
 #endif
 #endif
 
+#if IN_HEADER(__G_RESOLVER_H__)
+#if IN_FILE(__G_RESOLVER_C__)
+g_resolver_get_type G_GNUC_CONST
+g_resolver_get_default
+g_resolver_set_default
+g_resolver_lookup_name
+g_resolver_lookup_name_async
+g_resolver_lookup_name_finish
+g_resolver_lookup_address
+g_resolver_lookup_address_async
+g_resolver_lookup_address_finish
+g_resolver_lookup_service
+g_resolver_lookup_service_async
+g_resolver_lookup_service_finish
+#endif
+#endif
+
+#if IN_HEADER(__G_HOST_UTILS_H__)
+#if IN_FILE(__G_HOST_UTILS_C__)
+g_hostname_is_non_ascii
+g_hostname_is_ascii_encoded
+g_hostname_is_ip_address
+g_hostname_to_ascii
+g_hostname_to_unicode
+#endif
+#endif
+
+#if IN_HEADER(__G_NETWORK_ADDRESS_H__)
+#if IN_FILE(__G_NETWORK_ADDRESS_C__)
+g_network_address_get_type G_GNUC_CONST
+g_network_address_get_hostname
+g_network_address_get_ascii_name
+g_network_address_get_port
+g_network_address_get_sockaddrs
+g_sockaddr_get_type G_GNUC_CONST
+g_sockaddr_new_from_string
+g_sockaddr_copy
+g_sockaddr_free
+g_sockaddr_get_port
+g_sockaddr_to_string
+g_sockaddr_size
+#endif
+#endif
+
+#if IN_HEADER(__G_NETWORK_SERVICE_H__)
+#if IN_FILE(__G_NETWORK_SERVICE_C__)
+g_network_service_get_type G_GNUC_CONST
+g_network_service_get_service
+g_network_service_get_protocol
+g_network_service_get_domain
+g_network_service_get_targets
+g_network_service_get_expires
+g_srv_target_get_type G_GNUC_CONST
+g_srv_target_new
+g_srv_target_copy
+g_srv_target_free
+g_srv_target_get_hostname
+g_srv_target_get_port
+g_srv_target_get_priority
+g_srv_target_get_weight
+#endif
+#endif
Index: gio/gio.h
===================================================================
--- gio/gio.h	(revision 7710)
+++ gio/gio.h	(working copy)
@@ -48,6 +48,7 @@
 #include <gio/gfileoutputstream.h>
 #include <gio/gfilterinputstream.h>
 #include <gio/gfilteroutputstream.h>
+#include <gio/ghostutils.h>
 #include <gio/gicon.h>
 #include <gio/ginputstream.h>
 #include <gio/gioenums.h>
@@ -61,7 +62,10 @@
 #include <gio/gmount.h>
 #include <gio/gmountoperation.h>
 #include <gio/gnativevolumemonitor.h>
+#include <gio/gnetworkaddress.h>
+#include <gio/gnetworkservice.h>
 #include <gio/goutputstream.h>
+#include <gio/gresolver.h>
 #include <gio/gseekable.h>
 #include <gio/gsimpleasyncresult.h>
 #include <gio/gthemedicon.h>
Index: gio/gioenums.h
===================================================================
--- gio/gioenums.h	(revision 7710)
+++ gio/gioenums.h	(working copy)
@@ -462,6 +462,20 @@ typedef enum  {
   G_EMBLEM_ORIGIN_TAG
 } GEmblemOrigin;
 
+/**
+ * GResolverError:
+ * @G_RESOLVER_ERROR_NOT_FOUND: the requested name/address/service was not found
+ * @G_RESOLVER_ERROR_TEMPORARY_FAILURE: the requested information could not be looked up due to a network error or similar problem
+ * @G_RESOLVER_ERROR_INTERNAL: unknown error
+ *
+ * An error code used with %G_RESOLVER_ERROR in a #GError returned
+ * from a #GResolver routine.
+ */
+typedef enum {
+  G_RESOLVER_ERROR_NOT_FOUND,
+  G_RESOLVER_ERROR_TEMPORARY_FAILURE,
+  G_RESOLVER_ERROR_INTERNAL
+} GResolverError;
 
 G_END_DECLS
 
Index: gio/Makefile.am
===================================================================
--- gio/Makefile.am	(revision 7710)
+++ gio/Makefile.am	(working copy)
@@ -5,7 +5,7 @@ NULL =
 SUBDIRS=
 
 if OS_UNIX
-SUBDIRS += xdgmime
+SUBDIRS += libasyncns xdgmime
 endif
 
 if OS_WIN32_AND_DLL_COMPILATION
@@ -125,13 +125,15 @@ endif
 
 if OS_UNIX
 appinfo_sources += gdesktopappinfo.c gdesktopappinfo.h
-platform_libadd += xdgmime/libxdgmime.la
-platform_deps += xdgmime/libxdgmime.la
+platform_libadd += libasyncns/libasyncns.la xdgmime/libxdgmime.la
+platform_deps += libasyncns/libasyncns.la xdgmime/libxdgmime.la
 unix_sources = \
 	gunixmount.c		\
 	gunixmount.h		\
 	gunixmounts.c 		\
 	gunixmounts.h 		\
+	gunixresolver.c		\
+	gunixresolver.h		\
 	gunixvolume.c 		\
 	gunixvolume.h 		\
 	gunixvolumemonitor.c 	\
@@ -152,10 +154,12 @@ endif
 
 if OS_WIN32
 appinfo_sources += gwin32appinfo.c gwin32appinfo.h
-platform_libadd += -lshlwapi
+platform_libadd += -lshlwapi -lws2_32 -ldnsapi
 win32_sources = \
 	gwin32mount.c \
 	gwin32mount.h \
+	gwin32resolver.c \
+	gwin32resolver.h \
 	gwin32volumemonitor.c \
 	gwin32volumemonitor.h \
 	$(NULL)
@@ -195,6 +199,7 @@ libgio_2_0_la_SOURCES =		\
 	gfileoutputstream.c 	\
 	gfilterinputstream.c 	\
 	gfilteroutputstream.c 	\
+	ghostutils.c		\
 	gicon.c 		\
 	ginputstream.c 		\
 	gioenums.h		\
@@ -209,12 +214,18 @@ libgio_2_0_la_SOURCES =		\
 	gmountoperation.c 	\
 	gnativevolumemonitor.c 	\
 	gnativevolumemonitor.h 	\
+	gnetworkaddress.c	\
+	gnetworkservice.c	\
 	goutputstream.c 	\
 	gpollfilemonitor.c 	\
 	gpollfilemonitor.h 	\
+	gresolver.c		\
+	gresolverprivate.h	\
 	gseekable.c 		\
 	gsimpleasyncresult.c 	\
 	gthemedicon.c 		\
+	gthreadedresolver.c	\
+	gthreadedresolver.h	\
 	gunionvolumemonitor.c 	\
 	gunionvolumemonitor.h 	\
 	gvfs.c 			\
@@ -298,6 +309,7 @@ gio_headers =			\
 	gfileoutputstream.h 	\
 	gfilterinputstream.h 	\
 	gfilteroutputstream.h 	\
+	ghostutils.h		\
 	gicon.h 		\
 	ginputstream.h 		\
 	gio.h			\
@@ -312,7 +324,10 @@ gio_headers =			\
 	gmemoryoutputstream.h 	\
 	gmountoperation.h 	\
 	gnativevolumemonitor.h 	\
+	gnetworkaddress.h	\
+	gnetworkservice.h	\
 	goutputstream.h 	\
+	gresolver.h		\
 	gseekable.h 		\
 	gsimpleasyncresult.h 	\
 	gthemedicon.h 		\
Index: gio/tests/hostutils.c
===================================================================
--- gio/tests/hostutils.c	(revision 0)
+++ gio/tests/hostutils.c	(revision 0)
@@ -0,0 +1,105 @@
+/* 
+ * Copyright (C) 2008 Red Hat, Inc
+ *
+ * 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 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.
+ */
+
+#include <glib/glib.h>
+#include <gio/gio.h>
+
+#include <stdlib.h>
+#include <string.h>
+
+static const struct {
+  const char *ascii_name, *unicode_name;
+} idn_test_domains[] = {
+  /* "example.test" in various languages */
+  { "xn--mgbh0fb.xn--kgbechtv", "\xd9\x85\xd8\xab\xd8\xa7\xd9\x84.\xd8\xa5\xd8\xae\xd8\xaa\xd8\xa8\xd8\xa7\xd8\xb1" },
+  { "xn--fsqu00a.xn--0zwm56d", "\xe4\xbe\x8b\xe5\xad\x90.\xe6\xb5\x8b\xe8\xaf\x95" },
+  { "xn--fsqu00a.xn--g6w251d", "\xe4\xbe\x8b\xe5\xad\x90.\xe6\xb8\xac\xe8\xa9\xa6" },
+  { "xn--hxajbheg2az3al.xn--jxalpdlp", "\xcf\x80\xce\xb1\xcf\x81\xce\xac\xce\xb4\xce\xb5\xce\xb9\xce\xb3\xce\xbc\xce\xb1.\xce\xb4\xce\xbf\xce\xba\xce\xb9\xce\xbc\xce\xae" },
+  { "xn--p1b6ci4b4b3a.xn--11b5bs3a9aj6g", "\xe0\xa4\x89\xe0\xa4\xa6\xe0\xa4\xbe\xe0\xa4\xb9\xe0\xa4\xb0\xe0\xa4\xa3.\xe0\xa4\xaa\xe0\xa4\xb0\xe0\xa5\x80\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7\xe0\xa4\xbe" },
+  { "xn--r8jz45g.xn--zckzah", "\xe4\xbe\x8b\xe3\x81\x88.\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88" },
+  { "xn--9n2bp8q.xn--9t4b11yi5a", "\xec\x8b\xa4\xeb\xa1\x80.\xed\x85\x8c\xec\x8a\xa4\xed\x8a\xb8" },
+  { "xn--mgbh0fb.xn--hgbk6aj7f53bba", "\xd9\x85\xd8\xab\xd8\xa7\xd9\x84.\xd8\xa2\xd8\xb2\xd9\x85\xd8\xa7\xdb\x8c\xd8\xb4\xdb\x8c" },
+  { "xn--e1afmkfd.xn--80akhbyknj4f", "\xd0\xbf\xd1\x80\xd0\xb8\xd0\xbc\xd0\xb5\xd1\x80.\xd0\xb8\xd1\x81\xd0\xbf\xd1\x8b\xd1\x82\xd0\xb0\xd0\xbd\xd0\xb8\xd0\xb5" },
+  { "xn--zkc6cc5bi7f6e.xn--hlcj6aya9esc7a", "\xe0\xae\x89\xe0\xae\xa4\xe0\xae\xbe\xe0\xae\xb0\xe0\xae\xa3\xe0\xae\xae\xe0\xaf\x8d.\xe0\xae\xaa\xe0\xae\xb0\xe0\xae\xbf\xe0\xae\x9f\xe0\xaf\x8d\xe0\xae\x9a\xe0\xaf\x88" },
+  { "xn--fdbk5d8ap9b8a8d.xn--deba0ad", "\xd7\x91\xd7\xb2\xd6\xb7\xd7\xa9\xd7\xa4\xd6\xbc\xd7\x99\xd7\x9c.\xd7\x98\xd7\xa2\xd7\xa1\xd7\x98" },
+
+  /* further examples without their own IDN-ized TLD */
+  { "xn--1xd0bwwra.idn.icann.org", "\xe1\x8a\xa0\xe1\x88\x9b\xe1\x88\xad\xe1\x8a\x9b.idn.icann.org" },
+  { "xn--54b7fta0cc.idn.icann.org", "\xe0\xa6\xac\xe0\xa6\xbe\xe0\xa6\x82\xe0\xa6\xb2\xe0\xa6\xbe.idn.icann.org" },
+  { "xn--5dbqzzl.idn.icann.org", "\xd7\xa2\xd7\x91\xd7\xa8\xd7\x99\xd7\xaa.idn.icann.org" },
+  { "xn--j2e7beiw1lb2hqg.idn.icann.org", "\xe1\x9e\x97\xe1\x9e\xb6\xe1\x9e\x9f\xe1\x9e\xb6\xe1\x9e\x81\xe1\x9f\x92\xe1\x9e\x98\xe1\x9f\x82\xe1\x9e\x9a.idn.icann.org" },
+  { "xn--o3cw4h.idn.icann.org", "\xe0\xb9\x84\xe0\xb8\x97\xe0\xb8\xa2.idn.icann.org" },
+  { "xn--mgbqf7g.idn.icann.org", "\xd8\xa7\xd8\xb1\xd8\xaf\xd9\x88.idn.icann.org" }
+};
+static const int num_idn_test_domains = G_N_ELEMENTS (idn_test_domains);
+
+static void
+test_to_ascii (void)
+{
+  int i;
+  char *ascii;
+
+  for (i = 0; i < num_idn_test_domains; i++)
+    {
+      g_assert (g_hostname_is_non_ascii (idn_test_domains[i].unicode_name));
+      ascii = g_hostname_to_ascii (idn_test_domains[i].unicode_name);
+      g_assert_cmpstr (idn_test_domains[i].ascii_name, ==, ascii);
+      g_free (ascii);
+
+      ascii = g_hostname_to_ascii (idn_test_domains[i].ascii_name);
+      g_assert_cmpstr (idn_test_domains[i].ascii_name, ==, ascii);
+      g_free (ascii);
+    }
+}
+
+static void
+test_to_unicode (void)
+{
+  int i;
+  char *unicode;
+
+  for (i = 0; i < num_idn_test_domains; i++)
+    {
+      g_assert (g_hostname_is_ascii_encoded (idn_test_domains[i].ascii_name));
+      unicode = g_hostname_to_unicode (idn_test_domains[i].ascii_name);
+      g_assert_cmpstr (idn_test_domains[i].unicode_name, ==, unicode);
+      g_free (unicode);
+
+      unicode = g_hostname_to_unicode (idn_test_domains[i].unicode_name);
+      g_assert_cmpstr (idn_test_domains[i].unicode_name, ==, unicode);
+      g_free (unicode);
+    }
+}
+
+/* FIXME: test g_hostname_is_ip_addr() */
+/* FIXME: test names with both unicode and ACE-encoded labels */
+/* FIXME: test invalid unicode names */
+
+int
+main (int   argc,
+      char *argv[])
+{
+  g_type_init ();
+  g_test_init (&argc, &argv, NULL);
+  
+  g_test_add_func ("/hostutils/to_ascii", test_to_ascii);
+  g_test_add_func ("/hostutils/to_unicode", test_to_unicode);
+
+  return g_test_run ();
+}
Index: gio/tests/resolver.c
===================================================================
--- gio/tests/resolver.c	(revision 0)
+++ gio/tests/resolver.c	(revision 0)
@@ -0,0 +1,337 @@
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
+
+/* GIO - GLib Input, Output and Streaming Library
+ * 
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+
+#include "config.h"
+#include <glib.h>
+#include "glibintl.h"
+
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <gio/gio.h>
+
+static GResolver *resolver;
+static GCancellable *cancellable;
+static GMainLoop *loop;
+static int nlookups = 0;
+
+static void
+usage (void)
+{
+	fprintf (stderr, "Usage: resolver [-t | -T] [hostname | IP | service/protocol/domain ] ...\n");
+	fprintf (stderr, "       Use -t for asynchronous lookups in a thread-enabled program.\n");
+	fprintf (stderr, "       Use -T for synchronous lookups in separate threads.\n");
+	fprintf (stderr, "       (Use neither for asynchronous lookups in a non-threaded program.)\n");
+	exit (1);
+}
+
+G_LOCK_DEFINE_STATIC (response);
+
+static void
+print_resolved_name (const char *phys, GNetworkAddress *addr,
+		     GError *error)
+{
+  G_LOCK (response);
+  printf ("Address: %s\n", phys);
+  if (error)
+    {
+      printf ("Error:   %s\n", error->message);
+      g_error_free (error);
+    }
+  else
+    {
+      printf ("Name:    %s\n", g_network_address_get_hostname (addr));
+      g_object_unref (addr);
+    }
+  printf ("\n");
+
+  nlookups--;
+  if (nlookups == 0)
+    g_main_loop_quit (loop);
+  G_UNLOCK (response);
+}
+
+static void
+print_resolved_addresses (const char *name, GNetworkAddress *addr,
+			  GError *error)
+{
+  GSockaddr **addrs;
+  char *phys;
+  int i;
+
+  G_LOCK (response);
+  printf ("Name:    %s\n", name);
+  if (error)
+    {
+      printf ("Error:   %s\n", error->message);
+      g_error_free (error);
+    }
+  else
+    {
+      addrs = g_network_address_get_sockaddrs (addr);
+      for (i = 0; addrs[i]; i++)
+	{
+	  phys = g_sockaddr_to_string (addrs[i]);
+	  printf ("Address: %s\n", phys);
+	  g_free (phys);
+	}
+      g_object_unref (addr);
+    }
+  printf ("\n");
+
+  nlookups--;
+  if (nlookups == 0)
+    g_main_loop_quit (loop);
+  G_UNLOCK (response);
+}
+
+static void
+print_resolved_service (const char *service, GNetworkService *srv,
+			GError *error)
+{
+  GSrvTarget **targets;
+  int i;
+
+  G_LOCK (response);
+  printf ("Service: %s\n", service);
+  if (error)
+    {
+      printf ("Error: %s\n", error->message);
+      g_error_free (error);
+    }
+  else
+    {
+      targets = g_network_service_get_targets (srv);
+      for (i = 0; targets[i]; i++)
+	{
+	  printf ("%s:%u (pri %u, weight %u)\n",
+		  g_srv_target_get_hostname (targets[i]),
+		  g_srv_target_get_port (targets[i]),
+		  g_srv_target_get_priority (targets[i]),
+		  g_srv_target_get_weight (targets[i]));
+	}
+      g_object_unref (srv);
+    }
+  printf ("\n");
+
+  nlookups--;
+  if (nlookups == 0)
+    g_main_loop_quit (loop);
+  G_UNLOCK (response);
+}
+
+static gpointer
+lookup_thread (gpointer data)
+{
+  const char *arg = data;
+  GError *error = NULL;
+  GNetworkAddress *addr;
+  GNetworkService *srv;
+
+  if (strchr (arg, '/'))
+    {
+      /* service/protocol/domain */
+      char **parts = g_strsplit (arg, "/", 3);
+
+      if (!parts || !parts[2])
+	usage ();
+
+      srv = g_resolver_lookup_service (resolver, parts[0], parts[1], parts[2],
+				       cancellable, &error);
+      print_resolved_service (arg, srv, error);
+    }
+  else if (g_hostname_is_ip_address (arg))
+    {
+      GSockaddr *sockaddr = g_sockaddr_new_from_string (arg, 0);
+      addr = g_resolver_lookup_address (resolver, sockaddr, cancellable, &error);
+      print_resolved_name (arg, addr, error);
+      g_sockaddr_free (sockaddr);
+    }
+  else
+    {
+      addr = g_resolver_lookup_name (resolver, arg, 0, cancellable, &error);
+      print_resolved_addresses (arg, addr, error);
+    }
+
+  return NULL;
+}
+
+static void
+start_threaded_lookups (char **argv, int argc)
+{
+  int i;
+
+  for (i = 0; i < argc; i++)
+    g_thread_create (lookup_thread, argv[i], FALSE, NULL);
+}
+
+static void
+lookup_addr_callback (GObject *source, GAsyncResult *result,
+		      gpointer user_data)
+{
+  const char *phys = user_data;
+  GError *error = NULL;
+  GNetworkAddress *addr;
+
+  addr = g_resolver_lookup_address_finish (resolver, result, &error);
+  print_resolved_name (phys, addr, error);
+}
+
+static void
+lookup_name_callback (GObject *source, GAsyncResult *result,
+		      gpointer user_data)
+{
+  const char *name = user_data;
+  GError *error = NULL;
+  GNetworkAddress *addr;
+
+  addr = g_resolver_lookup_name_finish (resolver, result, &error);
+  print_resolved_addresses (name, addr, error);
+}
+
+static void
+lookup_service_callback (GObject *source, GAsyncResult *result,
+			 gpointer user_data)
+{
+  const char *service = user_data;
+  GError *error = NULL;
+  GNetworkService *srv;
+
+  srv = g_resolver_lookup_service_finish (resolver, result, &error);
+  print_resolved_service (service, srv, error);
+}
+
+static void
+start_async_lookups (char **argv, int argc)
+{
+  int i;
+
+  for (i = 0; i < argc; i++)
+    {
+      if (strchr (argv[i], '/'))
+	{
+	  /* service/protocol/domain */
+	  char **parts = g_strsplit (argv[i], "/", 3);
+
+	  if (!parts || !parts[2])
+	    usage ();
+
+	  g_resolver_lookup_service_async (resolver,
+					   parts[0], parts[1], parts[2],
+					   cancellable,
+					   lookup_service_callback, argv[i]);
+	}
+      else if (g_hostname_is_ip_address (argv[i]))
+	{
+	  GSockaddr *addr = g_sockaddr_new_from_string (argv[i], 0);
+	  g_resolver_lookup_address_async (resolver, addr, cancellable,
+					   lookup_addr_callback, argv[i]);
+	  g_sockaddr_free (addr);
+	}
+      else
+	{
+	  g_resolver_lookup_name_async (resolver, argv[i], 0, cancellable,
+					lookup_name_callback,
+					argv[i]);
+	}
+    }
+}
+
+#ifdef G_OS_UNIX
+static int cancel_fds[2];
+
+static void
+interrupted (int sig)
+{
+  signal (SIGINT, SIG_DFL);
+  write (cancel_fds[1], "x", 1);
+}
+
+static gboolean
+async_cancel (GIOChannel *source, GIOCondition cond, gpointer cancellable)
+{
+  g_cancellable_cancel (cancellable);
+  return FALSE;
+}
+#endif
+
+int
+main (int argc, char **argv)
+{
+  gboolean threaded = FALSE;
+#ifdef G_OS_UNIX
+  GIOChannel *chan;
+  guint watch;
+#endif
+
+  if (argc >= 2 && (!strcmp (argv[1], "-t") || !strcmp (argv[1], "-T")))
+    {
+      g_thread_init (NULL);
+      threaded = argv[1][1] == 'T';
+      argv++;
+      argc--;
+    }
+  g_type_init ();
+
+  if (argc < 2)
+    usage ();
+
+  resolver = g_resolver_get_default ();
+
+  cancellable = g_cancellable_new ();
+
+#ifdef G_OS_UNIX
+  /* Set up cancellation; we want to cancel if the user ^C's the
+   * program, but we can't cancel directly from an interrupt.
+   */
+  signal (SIGINT, interrupted);
+
+  if (pipe (cancel_fds) == -1)
+    {
+      perror ("pipe");
+      exit (1);
+    }
+  chan = g_io_channel_unix_new (cancel_fds[0]);
+  watch = g_io_add_watch (chan, G_IO_IN, async_cancel, cancellable);
+  g_io_channel_unref (chan);
+#endif
+
+  nlookups = argc - 1;
+  if (threaded)
+    start_threaded_lookups (argv + 1, argc - 1);
+  else
+    start_async_lookups (argv + 1, argc - 1);
+
+  loop = g_main_loop_new (NULL, TRUE);
+  g_main_run (loop);
+  g_main_loop_unref (loop);
+
+#ifdef G_OS_UNIX
+  g_source_remove (watch);
+#endif
+  g_object_unref (cancellable);
+
+  return 0;
+}
Index: gio/tests/Makefile.am
===================================================================
--- gio/tests/Makefile.am	(revision 7710)
+++ gio/tests/Makefile.am	(working copy)
@@ -9,7 +9,7 @@ INCLUDES = 			\
 	-I$(top_srcdir)/gio 	\
 	$(GLIB_DEBUG_FLAGS)
 
-noinst_PROGRAMS = $(TEST_PROGS)
+noinst_PROGRAMS = $(TEST_PROGS) $(SAMPLE_PROGS)
 progs_ldadd     = 					\
 	$(top_builddir)/glib/libglib-2.0.la 		\
 	$(top_builddir)/gobject/libgobject-2.0.la	\
@@ -24,7 +24,10 @@ TEST_PROGS +=	 		\
 	data-input-stream 	\
 	data-output-stream 	\
 	g-icon			\
-	buffered-input-stream
+	buffered-input-stream	\
+	hostutils
+
+SAMPLE_PROGS = resolver
 
 if OS_UNIX
 TEST_PROGS += live-g-file unix-streams desktop-app-info
@@ -63,3 +66,10 @@ desktop_app_info_LDADD	  = $(progs_ldadd
 unix_streams_SOURCES	  = unix-streams.c
 unix_streams_LDADD	  = $(progs_ldadd) \
 	$(top_builddir)/gthread/libgthread-2.0.la
+
+hostutils_SOURCES	  = hostutils.c
+hostutils_LDADD		  = $(progs_ldadd)
+
+resolver_SOURCES	  = resolver.c
+resolver_LDADD		  = $(progs_ldadd) \
+	$(top_builddir)/gthread/libgthread-2.0.la
Index: gio/libasyncns/asyncns.c
===================================================================
--- gio/libasyncns/asyncns.c	(revision 0)
+++ gio/libasyncns/asyncns.c	(revision 0)
@@ -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 "g-asyncns.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;
+    _g_asyncns_query_t* queries[MAX_QUERIES];
+
+    _g_asyncns_query_t *done_head, *done_tail;
+
+    int n_queries;
+    int dead;
+};
+
+struct _g_asyncns_query {
+    _g_asyncns_t *asyncns;
+    int done;
+    unsigned id;
+    query_type_t type;
+    _g_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) {
+    _g_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
+
+_g_asyncns_t* _g_asyncns_new(unsigned n_proc) {
+    _g_asyncns_t *asyncns = NULL;
+    int i;
+    assert(n_proc >= 1);
+
+    if (n_proc > MAX_WORKERS)
+        n_proc = MAX_WORKERS;
+
+    if (!(asyncns = malloc(sizeof(_g_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)
+        _g_asyncns_free(asyncns);
+
+    return NULL;
+}
+
+void _g_asyncns_free(_g_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])
+            _g_asyncns_cancel(asyncns, asyncns->queries[p]);
+
+    free(asyncns);
+
+    errno = saved_errno;
+}
+
+int _g_asyncns_fd(_g_asyncns_t *asyncns) {
+    assert(asyncns);
+
+    return asyncns->fds[RESPONSE_RECV_FD];
+}
+
+static _g_asyncns_query_t *lookup_query(_g_asyncns_t *asyncns, unsigned id) {
+    _g_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(_g_asyncns_t *asyncns, _g_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)
+        _g_asyncns_freeaddrinfo(ai);
+
+    return NULL;
+}
+
+static int handle_response(_g_asyncns_t *asyncns, rheader_t *resp, size_t length) {
+    _g_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 _g_asyncns_wait(_g_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 _g_asyncns_query_t *alloc_query(_g_asyncns_t *asyncns) {
+    _g_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(_g_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;
+}
+
+_g_asyncns_query_t* _g_asyncns_getaddrinfo(_g_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;
+    _g_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)
+        _g_asyncns_cancel(asyncns, q);
+
+    return NULL;
+}
+
+int _g_asyncns_getaddrinfo_done(_g_asyncns_t *asyncns, _g_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;
+
+    _g_asyncns_cancel(asyncns, q);
+
+    return ret;
+}
+
+_g_asyncns_query_t* _g_asyncns_getnameinfo(_g_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;
+    _g_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)
+        _g_asyncns_cancel(asyncns, q);
+
+    return NULL;
+}
+
+int _g_asyncns_getnameinfo_done(_g_asyncns_t *asyncns, _g_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;
+
+    _g_asyncns_cancel(asyncns, q);
+
+    return ret;
+}
+
+static _g_asyncns_query_t * _g_asyncns_res(_g_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;
+    _g_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)
+        _g_asyncns_cancel(asyncns, q);
+
+    return NULL;
+}
+
+_g_asyncns_query_t* _g_asyncns_res_query(_g_asyncns_t *asyncns, const char *dname, int class, int type) {
+    return _g_asyncns_res(asyncns, REQUEST_RES_QUERY, dname, class, type);
+}
+
+_g_asyncns_query_t* _g_asyncns_res_search(_g_asyncns_t *asyncns, const char *dname, int class, int type) {
+    return _g_asyncns_res(asyncns, REQUEST_RES_SEARCH, dname, class, type);
+}
+
+int _g_asyncns_res_done(_g_asyncns_t *asyncns, _g_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;
+    }
+
+    _g_asyncns_cancel(asyncns, q);
+
+    return ret < 0 ? -errno : ret;
+}
+
+_g_asyncns_query_t* _g_asyncns_getnext(_g_asyncns_t *asyncns) {
+    assert(asyncns);
+    return asyncns->done_head;
+}
+
+int _g_asyncns_getnqueries(_g_asyncns_t *asyncns) {
+    assert(asyncns);
+    return asyncns->n_queries;
+}
+
+void _g_asyncns_cancel(_g_asyncns_t *asyncns, _g_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;
+
+    _g_asyncns_freeaddrinfo(q->addrinfo);
+    free(q->host);
+    free(q->serv);
+
+    asyncns->n_queries--;
+    free(q);
+
+    errno = saved_errno;
+}
+
+void _g_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 _g_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 _g_asyncns_isdone(_g_asyncns_t *asyncns, _g_asyncns_query_t*q) {
+    assert(asyncns);
+    assert(q);
+    assert(q->asyncns == asyncns);
+
+    return q->done;
+}
+
+void _g_asyncns_setuserdata(_g_asyncns_t *asyncns, _g_asyncns_query_t *q, void *userdata) {
+    assert(q);
+    assert(asyncns);
+    assert(q->asyncns = asyncns);
+
+    q->userdata = userdata;
+}
+
+void* _g_asyncns_getuserdata(_g_asyncns_t *asyncns, _g_asyncns_query_t *q) {
+    assert(q);
+    assert(asyncns);
+    assert(q->asyncns = asyncns);
+
+    return q->userdata;
+}
Index: gio/libasyncns/asyncns.h
===================================================================
--- gio/libasyncns/asyncns.h	(revision 0)
+++ gio/libasyncns/asyncns.h	(revision 0)
@@ -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 _g_asyncns_t object with
+ * _g_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 _g_asyncns_getaddrinfo() and
+ * _g_asyncns_getnameinfo(). Use _g_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 _g_asyncns_t;
+
+/** An opaque libasyncns query structure */
+typedef struct _g_asyncns_query _g_asyncns_query_t;
+
+/** Allocate a new libasyncns session with n_proc worker processes/threads */
+_g_asyncns_t* _g_asyncns_new(unsigned n_proc);
+
+/** Free a libasyncns session. This destroys all attached
+ * _g_asyncns_query_t objects automatically */
+void _g_asyncns_free(_g_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 _g_asyncns_fd(_g_asyncns_t *asyncns);
+
+/** Process pending responses. After this function is called you can
+ * get the next completed query object(s) using _g_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 _g_asyncns_wait(_g_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
+ * _g_asyncns_getaddrinfo_done().*/
+_g_asyncns_query_t* _g_asyncns_getaddrinfo(_g_asyncns_t *asyncns, const char *node, const char *service, const struct addrinfo *hints);
+
+/** Retrieve the results of a preceding _g_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 _g_asyncns_freeaddrinfo() and not
+ * libc's freeaddrinfo(3)! If the query is not completed yet EAI_AGAIN
+ * is returned.*/
+int _g_asyncns_getaddrinfo_done(_g_asyncns_t *asyncns, _g_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
+ * _g_asyncns_getnameinfo_done(). Set gethost (resp. getserv) to non-zero
+ * if you want to query the hostname (resp. the service name). */
+_g_asyncns_query_t* _g_asyncns_getnameinfo(_g_asyncns_t *asyncns, const struct sockaddr *sa, socklen_t salen, int flags, int gethost, int getserv);
+
+/** Retrieve the results of a preceding _g_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 _g_asyncns_getnameinfo_done(_g_asyncns_t *asyncns, _g_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
+ * _g_asyncns_res_done().  */
+_g_asyncns_query_t* _g_asyncns_res_query(_g_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
+ * _g_asyncns_res_done().  */
+_g_asyncns_query_t* _g_asyncns_res_search(_g_asyncns_t *asyncns, const char *dname, int class, int type);
+
+/** Retrieve the results of a preceding _g_asyncns_res_query() or
+ * _g_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 _g_asyncns_freeanswer(). */
+int _g_asyncns_res_done(_g_asyncns_t *asyncns, _g_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
+ * _g_asyncns_wait() before this function will return sensible data.  */
+_g_asyncns_query_t* _g_asyncns_getnext(_g_asyncns_t *asyncns);
+
+/** Return the number of query objects (completed or not) attached to
+ * this session */
+int _g_asyncns_getnqueries(_g_asyncns_t *asyncns);
+
+/** Cancel a currently running query. q is is destroyed by this call
+ * and may not be used any futher. */
+void _g_asyncns_cancel(_g_asyncns_t *asyncns, _g_asyncns_query_t* q);
+
+/** Free the addrinfo structure as returned by
+ * _g_asyncns_getaddrinfo_done(). Make sure to use this functions instead
+ * of the libc's freeaddrinfo()! */
+void _g_asyncns_freeaddrinfo(struct addrinfo *ai);
+
+/** Free the answer data as returned by _g_asyncns_res_done().*/
+void _g_asyncns_freeanswer(unsigned char *answer);
+
+/** Returns non-zero when the query operation specified by q has been completed */
+int _g_asyncns_isdone(_g_asyncns_t *asyncns, _g_asyncns_query_t*q);
+
+/** Assign some opaque userdata with a query object */
+void _g_asyncns_setuserdata(_g_asyncns_t *asyncns, _g_asyncns_query_t *q, void *userdata);
+
+/** Return userdata assigned to a query object. Use
+ * _g_asyncns_setuserdata() to set this data. If no data has been set
+ * prior to this call it returns NULL. */
+void* _g_asyncns_getuserdata(_g_asyncns_t *asyncns, _g_asyncns_query_t *q);
+
+#ifdef  __cplusplus
+}
+#endif
+
+#endif
Index: gio/libasyncns/g-asyncns.h
===================================================================
--- gio/libasyncns/g-asyncns.h	(revision 0)
+++ gio/libasyncns/g-asyncns.h	(revision 0)
@@ -0,0 +1,28 @@
+/* GLIB - Library of useful routines for C programming
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * 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 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.
+ */
+#ifndef __G_ASYNCNS_H__
+
+#include "config.h"
+
+#define _GNU_SOURCE
+#undef HAVE_PTHREAD
+
+#include "asyncns.h"
+
+#endif
Index: gio/libasyncns/Makefile.am
===================================================================
--- gio/libasyncns/Makefile.am	(revision 0)
+++ gio/libasyncns/Makefile.am	(revision 0)
@@ -0,0 +1,15 @@
+## Process this file with automake to produce Makefile.in
+include $(top_srcdir)/Makefile.decl
+
+INCLUDES = -I$(top_srcdir)
+
+noinst_LTLIBRARIES = libasyncns.la
+
+libasyncns_la_SOURCES = \
+	asyncns.c \
+	asyncns.h \
+	g-asyncns.h
+
+libasyncns_la_LIBADD = $(LIBASYNCNS_LIBADD)
+
+EXTRA_DIST += README update.sh
Index: gio/libasyncns/update.sh
===================================================================
--- gio/libasyncns/update.sh	(revision 0)
+++ gio/libasyncns/update.sh	(revision 0)
@@ -0,0 +1,20 @@
+#!/bin/sh
+
+if test $# = 1 ; then 
+  ORIGINAL=$1
+else
+  echo "Usage: update.sh /path/to/libasyncns" 1>&2
+  exit 1
+fi
+
+if test -f $ORIGINAL/libasyncns/asyncns.c ; then : ; else
+  echo "Usage: update.sh /path/to/libasyncns" 1>&2
+  exit 1
+fi
+
+for i in asyncns.c asyncns.h ; do
+  sed -e 's/\([^a-z]\)asyncns_/\1_g_asyncns_/g' \
+      -e 's/^asyncns_/_g_asyncns_/' \
+      -e 's/<config\.h>/"g-asyncns\.h"/' \
+    $ORIGINAL/libasyncns/$i > $i
+done

Property changes on: gio/libasyncns/update.sh
___________________________________________________________________
Added: svn:executable
   + *

Index: gio/libasyncns/README
===================================================================
--- gio/libasyncns/README	(revision 0)
+++ gio/libasyncns/README	(revision 0)
@@ -0,0 +1,7 @@
+The sources are derived from Lennart Poettering's libasyncns library:
+
+ http://0pointer.de/lennart/projects/libasyncns/
+
+The 'update.sh' script in this directory, when pointed at
+the original sources updates the files in this directory
+to the new version
