Fix bug #3139, "Mainwindow unresponsive due to a busy loop"
[claws.git] / src / common / socket.c
index 337a3da3e065c8dc59d05c58369c05590486e7d9..1d6638d07afe6882493786a3e9a1b2c0c40c4947 100644 (file)
@@ -1,10 +1,10 @@
 /*
  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
- * Copyright (C) 1999-2004 Hiroyuki Yamamoto
+ * Copyright (C) 1999-2012 Hiroyuki Yamamoto and the Claws Mail team
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
+ * the Free Software Foundation; either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * 
  */
 
 #ifdef HAVE_CONFIG_H
 #  include "config.h"
+#include "claws-features.h"
+#endif
+
+#if (defined (_XOPEN_SOURCE) && !defined (_BSD_SOURCE))
+#define _BSD_SOURCE
 #endif
 
 #include <glib.h>
+#include <glib/gi18n.h>
+
 #include <sys/time.h>
 #include <sys/types.h>
 #ifdef G_OS_WIN32
 #  include <winsock2.h>
+#  ifndef EINPROGRESS
+#    define EINPROGRESS WSAEINPROGRESS
+#  endif
+#  include "w32lib.h"
 #else
 #  if HAVE_SYS_WAIT_H
 #    include <sys/wait.h>
@@ -53,7 +64,7 @@
 #include "socket.h"
 #include "utils.h"
 #include "log.h"
-#if USE_OPENSSL
+#ifdef USE_GNUTLS
 #  include "ssl.h"
 #endif
 
 #error USE_GIO is currently not supported
 #endif
 
+#if G_IO_WIN32
+#define BUFFSIZE       8191
+#else
 #define BUFFSIZE       8192
+#endif
+
 
 typedef gint (*SockAddrFunc)   (GList          *addr_list,
                                 gpointer        data);
@@ -82,6 +98,7 @@ struct _SockConnectData {
        guint io_tag;
        SockConnectFunc func;
        gpointer data;
+       gchar *canonical_name;
 };
 
 struct _SockLookupData {
@@ -91,6 +108,9 @@ struct _SockLookupData {
        guint io_tag;
        SockAddrFunc func;
        gpointer data;
+       gushort port;
+        gint pipe_fds[2];
+       gchar *canonical_name;
 };
 
 struct _SockAddrData {
@@ -110,19 +130,21 @@ static guint io_timeout = 60;
 
 static GList *sock_connect_data_list = NULL;
 
-static gboolean sock_prepare           (GSource        *source,
+static gboolean ssl_sock_prepare       (GSource        *source,
                                         gint           *timeout);
-static gboolean sock_check             (GSource        *source);
-static gboolean sock_dispatch          (GSource        *source,
+static gboolean ssl_sock_check         (GSource        *source);
+static gboolean ssl_sock_dispatch      (GSource        *source,
                                         GSourceFunc     callback,
                                         gpointer        user_data);
 
-GSourceFuncs sock_watch_funcs = {
-       sock_prepare,
-       sock_check,
-       sock_dispatch,
+#ifdef USE_GNUTLS
+GSourceFuncs ssl_watch_funcs = {
+       ssl_sock_prepare,
+       ssl_sock_check,
+       ssl_sock_dispatch,
        NULL
 };
+#endif
 
 static gint sock_connect_with_timeout  (gint                    sock,
                                         const struct sockaddr  *serv_addr,
@@ -141,7 +163,6 @@ static gint sock_connect_by_getaddrinfo     (const gchar    *hostname,
 static SockInfo *sockinfo_from_fd(const gchar *hostname,
                                  gushort port,
                                  gint sock);
-#ifdef G_OS_UNIX
 static void sock_address_list_free             (GList          *addr_list);
 
 static gboolean sock_connect_async_cb          (GIOChannel     *source,
@@ -162,7 +183,6 @@ static SockLookupData *sock_get_address_info_async
                                                 SockAddrFunc    func,
                                                 gpointer        data);
 static gint sock_get_address_info_async_cancel (SockLookupData *lookup_data);
-#endif /* G_OS_UNIX */
 
 
 gint sock_init(void)
@@ -215,6 +235,101 @@ void refresh_resolvers(void)
 #endif /*G_OS_UNIX*/
 }
 
+#ifdef G_OS_WIN32
+#define SOCKET_IS_VALID(s)      ((s) != INVALID_SOCKET)
+#else
+#define SOCKET_IS_VALID(s)     TRUE
+#endif
+
+/* Due to the fact that socket under Windows are not represented by
+   standard file descriptors, we sometimes need to check whether a
+   given file descriptor is actually a socket.  This is done by
+   testing for an error.  Returns true under W32 if FD is a socket. */
+static int fd_is_w32_socket(gint fd)
+{
+#ifdef G_OS_WIN32
+        gint optval;
+        gint retval = sizeof(optval);
+        
+        return !getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*)&optval, &retval);
+#else
+        return 0;
+#endif 
+}
+
+gint fd_connect_inet(gushort port)
+{
+       gint sock;
+       struct sockaddr_in addr;
+
+       sock = socket(AF_INET, SOCK_STREAM, 0);
+       if (!SOCKET_IS_VALID(sock)) {
+#ifdef G_OS_WIN32
+               debug_print("fd_connect_inet(): socket() failed: %d\n",
+                         WSAGetLastError());
+#else
+               perror("fd_connect_inet(): socket");
+#endif
+               return -1;
+       }
+
+       memset(&addr, 0, sizeof(addr));
+       addr.sin_family = AF_INET;
+       addr.sin_port = htons(port);
+       addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+
+       if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
+               fd_close(sock);
+               return -1;
+       }
+
+       return sock;
+}
+gint fd_open_inet(gushort port)
+{
+       gint sock;
+       struct sockaddr_in addr;
+       gint val;
+
+       sock = socket(AF_INET, SOCK_STREAM, 0);
+       if (!SOCKET_IS_VALID(sock)) {
+#ifdef G_OS_WIN32
+               g_warning("fd_open_inet(): socket() failed: %d\n",
+                         WSAGetLastError());
+#else
+               perror("fd_open_inet(): socket");
+#endif
+               return -1;
+       }
+
+       val = 1;
+       if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val,
+                      sizeof(val)) < 0) {
+               perror("setsockopt");
+               fd_close(sock);
+               return -1;
+       }
+
+       memset(&addr, 0, sizeof(addr));
+       addr.sin_family = AF_INET;
+       addr.sin_port = htons(port);
+       addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+
+       if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
+               perror("bind");
+               fd_close(sock);
+               return -1;
+       }
+
+       if (listen(sock, 1) < 0) {
+               perror("listen");
+               fd_close(sock);
+               return -1;
+       }
+
+       return sock;
+}
+
 gint fd_connect_unix(const gchar *path)
 {
 #ifdef G_OS_UNIX
@@ -260,13 +375,17 @@ gint fd_open_unix(const gchar *path)
        strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
 
        if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
-               perror("bind");
+               gchar *buf = g_strdup_printf("can't bind to %s", path);
+               perror(buf);
+               g_free(buf);
                close(sock);
                return -1;
        }
 
        if (listen(sock, 1) < 0) {
-               perror("listen");
+               gchar *buf = g_strdup_printf("can't listen on %s", path);
+               perror(buf);
+               g_free(buf);
                close(sock);
                return -1;              
        }
@@ -279,15 +398,11 @@ gint fd_open_unix(const gchar *path)
 
 gint fd_accept(gint sock)
 {
-#ifdef G_OS_UNIX
        struct sockaddr_in caddr;
        guint caddr_len;
 
        caddr_len = sizeof(caddr);
        return accept(sock, (struct sockaddr *)&caddr, &caddr_len);
-#else
-       return -1;
-#endif
 }
 
 
@@ -315,7 +430,7 @@ static gint set_nonblocking_mode(gint fd, gboolean nonblock)
 
 gint sock_set_nonblocking_mode(SockInfo *sock, gboolean nonblock)
 {
-       g_return_val_if_fail(sock != NULL, -1);
+       cm_return_val_if_fail(sock != NULL, -1);
 
        return set_nonblocking_mode(sock->sock, nonblock);
 }
@@ -339,43 +454,34 @@ static gboolean is_nonblocking_mode(gint fd)
 
 gboolean sock_is_nonblocking_mode(SockInfo *sock)
 {
-       g_return_val_if_fail(sock != NULL, FALSE);
+       cm_return_val_if_fail(sock != NULL, FALSE);
 
        return is_nonblocking_mode(sock->sock);
 }
 
 
-static gboolean sock_prepare(GSource *source, gint *timeout)
+#ifdef USE_GNUTLS
+static gboolean ssl_sock_prepare(GSource *source, gint *timeout)
 {
        *timeout = 1;
        return FALSE;
 }
 
-static gboolean sock_check(GSource *source)
+static gboolean ssl_sock_check(GSource *source)
 {
        SockInfo *sock = ((SockSource *)source)->sock;
        struct timeval timeout = {0, 0};
        fd_set fds;
-       GIOCondition condition = sock->condition;
-
+       GIOCondition condition = 0;
+        
        if (!sock || !sock->sock)
                return FALSE;
 
-#if USE_OPENSSL
-       if (sock->ssl) {
-               if (condition & G_IO_IN) {
-                       if (SSL_pending(sock->ssl) > 0)
-                               return TRUE;
-                       if (SSL_want_write(sock->ssl))
-                               condition |= G_IO_OUT;
-               }
+       condition = sock->condition;
 
-               if (condition & G_IO_OUT) {
-                       if (SSL_want_read(sock->ssl))
-                               condition |= G_IO_IN;
-               }
-       }
-#endif
+       if ((condition & G_IO_IN) == G_IO_IN &&
+           gnutls_record_check_pending(sock->ssl) != 0)
+               return TRUE;
 
        FD_ZERO(&fds);
        FD_SET(sock->sock, &fds);
@@ -388,7 +494,7 @@ static gboolean sock_check(GSource *source)
        return FD_ISSET(sock->sock, &fds) != 0;
 }
 
-static gboolean sock_dispatch(GSource *source, GSourceFunc callback,
+static gboolean ssl_sock_dispatch(GSource *source, GSourceFunc callback,
                              gpointer user_data)
 {
        SockInfo *sock = ((SockSource *)source)->sock;
@@ -398,6 +504,7 @@ static gboolean sock_dispatch(GSource *source, GSourceFunc callback,
 
        return sock->callback(sock, sock->condition, sock->data);
 }
+#endif
 
 static gboolean sock_watch_cb(GIOChannel *source, GIOCondition condition,
                              gpointer data)
@@ -413,14 +520,17 @@ static gboolean sock_watch_cb(GIOChannel *source, GIOCondition condition,
 guint sock_add_watch(SockInfo *sock, GIOCondition condition, SockFunc func,
                     gpointer data)
 {
+       if (!sock)
+               return FALSE;
+
        sock->callback = func;
        sock->condition = condition;
        sock->data = data;
 
-#if USE_OPENSSL
+#ifdef USE_GNUTLS
        if (sock->ssl)
        {
-               GSource *source = g_source_new(&sock_watch_funcs,
+               GSource *source = g_source_new(&ssl_watch_funcs,
                                               sizeof(SockSource));
                ((SockSource *) source)->sock = sock;
                g_source_set_priority(source, G_PRIORITY_DEFAULT);
@@ -460,6 +570,7 @@ static gint fd_check_io(gint fd, GIOCondition cond)
                return 0;
        } else {
                g_warning("Socket IO timeout\n");
+               log_error(LOG_PROTOCOL, _("Socket IO timeout.\n"));
                return -1;
        }
 }
@@ -471,7 +582,7 @@ static void timeout_handler(gint sig)
 {
        siglongjmp(jmpenv, 1);
 }
-#endif
+#endif /*G_OS_UNIX*/
 
 static gint sock_connect_with_timeout(gint sock,
                                      const struct sockaddr *serv_addr,
@@ -488,6 +599,7 @@ static gint sock_connect_with_timeout(gint sock,
                alarm(0);
                signal(SIGALRM, prev_handler);
                errno = ETIMEDOUT;
+               log_error(LOG_PROTOCOL, _("Connection timed out.\n"));
                return -1;
        }
        alarm(timeout_secs);
@@ -514,7 +626,8 @@ struct hostent *my_gethostbyname(const gchar *hostname)
        if (sigsetjmp(jmpenv, 1)) {
                alarm(0);
                signal(SIGALRM, prev_handler);
-               fprintf(stderr, "%s: host lookup timed out.\n", hostname);
+               g_printerr("%s: host lookup timed out.\n", hostname);
+               log_error(LOG_PROTOCOL, _("%s: host lookup timed out.\n"), hostname);
                errno = 0;
                return NULL;
        }
@@ -526,7 +639,8 @@ struct hostent *my_gethostbyname(const gchar *hostname)
                alarm(0);
                signal(SIGALRM, prev_handler);
 #endif
-               fprintf(stderr, "%s: unknown host.\n", hostname);
+               g_printerr("%s: unknown host.\n", hostname);
+               log_error(LOG_PROTOCOL, _("%s: unknown host.\n"), hostname);
                errno = 0;
                return NULL;
        }
@@ -574,13 +688,13 @@ static gint sock_connect_by_hostname(gint sock, const gchar *hostname,
 
        if (!my_inet_aton(hostname, &ad.sin_addr)) {
                if ((hp = my_gethostbyname(hostname)) == NULL) {
-                       fprintf(stderr, "%s: unknown host.\n", hostname);
+                       g_printerr("%s: unknown host.\n", hostname);
                        errno = 0;
                        return -1;
                }
 
                if (hp->h_length != 4 && hp->h_length != 8) {
-                       fprintf(stderr, "illegal address length received for host %s\n", hostname);
+                       g_printerr("illegal address length received for host %s\n", hostname);
                        errno = 0;
                        return -1;
                }
@@ -611,7 +725,7 @@ static gint sock_connect_by_getaddrinfo(const gchar *hostname, gushort      port)
        g_snprintf(port_str, sizeof(port_str), "%d", port);
 
        if ((gai_error = getaddrinfo(hostname, port_str, &hints, &res)) != 0) {
-               fprintf(stderr, "getaddrinfo for %s:%s failed: %s\n",
+               g_printerr("getaddrinfo for %s:%s failed: %s\n",
                        hostname, port_str, gai_strerror(gai_error));
                return -1;
        }
@@ -638,40 +752,6 @@ static gint sock_connect_by_getaddrinfo(const gchar *hostname, gushort     port)
 }
 #endif /* !INET6 */
 
-
-/* Open a connection using an external program.  May be useful when
- * you need to tunnel through a SOCKS or other firewall, or to
- * establish an IMAP-over-SSH connection. */
-/* TODO: Recreate this for sock_connect_thread() */
-SockInfo *sock_connect_cmd(const gchar *hostname, const gchar *tunnelcmd)
-{
-#ifdef G_OS_UNIX
-       gint fd[2];
-       int r;
-                    
-       if ((r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) == -1) {
-               perror("socketpair");
-               return NULL;
-       }
-       log_message("launching tunnel command \"%s\"\n", tunnelcmd);
-       if (fork() == 0) {
-               close(fd[0]);
-               close(0);
-               close(1);
-               dup(fd[1]);     /* set onto stdin */
-               dup(fd[1]);
-               execlp("/bin/sh", "/bin/sh", "-c", tunnelcmd, NULL);
-       }
-
-       close(fd[1]);
-       return sockinfo_from_fd(hostname, 0, fd[0]);
-#else
-        /* We would need a special implementaion for W32. */
-        return NULL;
-#endif
-}
-
-
 SockInfo *sock_connect(const gchar *hostname, gushort port)
 {
 #ifdef G_OS_WIN32
@@ -704,7 +784,7 @@ SockInfo *sock_connect(const gchar *hostname, gushort port)
        return sockinfo_from_fd(hostname, port, sock);
 }
 
-#ifdef G_OS_UNIX
+
 static void sock_address_list_free(GList *addr_list)
 {
        GList *cur;
@@ -748,16 +828,24 @@ static gboolean sock_connect_async_cb(GIOChannel *source,
 
        if (val != 0) {
                close(fd);
+               log_error(LOG_PROTOCOL, _("%s:%d: connection failed (%s).\n"),
+                         conn_data->hostname, conn_data->port,
+                         strerror(val));
                sock_connect_address_list_async(conn_data);
                return FALSE;
        }
 
        sockinfo = g_new0(SockInfo, 1);
        sockinfo->sock = fd;
+#ifndef G_OS_WIN32
        sockinfo->sock_ch = g_io_channel_unix_new(fd);
+#else
+       sockinfo->sock_ch = g_io_channel_win32_new_socket(fd);
+#endif
        sockinfo->hostname = g_strdup(conn_data->hostname);
        sockinfo->port = conn_data->port;
        sockinfo->state = CONN_ESTABLISHED;
+       sockinfo->canonical_name = g_strdup(conn_data->canonical_name);
 
        conn_data->func(sockinfo, conn_data->data);
 
@@ -773,8 +861,11 @@ static gint sock_connect_async_get_address_info_cb(GList *addr_list,
 
        conn_data->addr_list = addr_list;
        conn_data->cur_addr = addr_list;
-       conn_data->lookup_data = NULL;
-
+       if (conn_data->lookup_data) {
+               conn_data->canonical_name = conn_data->lookup_data->canonical_name;
+               conn_data->lookup_data->canonical_name = NULL;
+               conn_data->lookup_data = NULL;
+       }
        return sock_connect_address_list_async(conn_data);
 }
 
@@ -833,11 +924,15 @@ gint sock_connect_async_cancel(gint id)
                if (conn_data->io_tag > 0)
                        g_source_remove(conn_data->io_tag);
                if (conn_data->channel) {
-                       g_io_channel_close(conn_data->channel);
+                       GError *err = NULL;
+                       g_io_channel_shutdown(conn_data->channel, TRUE, &err);
+                       if (err)
+                               g_error_free(err);
                        g_io_channel_unref(conn_data->channel);
                }
 
                sock_address_list_free(conn_data->addr_list);
+               g_free(conn_data->canonical_name);
                g_free(conn_data->hostname);
                g_free(conn_data);
        } else {
@@ -860,6 +955,7 @@ static gint sock_connect_address_list_async(SockConnectData *conn_data)
                if ((sock = socket(addr_data->family, addr_data->socktype,
                                   addr_data->protocol)) < 0) {
                        perror("socket");
+
                        continue;
                }
 
@@ -872,14 +968,12 @@ static gint sock_connect_address_list_async(SockConnectData *conn_data)
                                perror("connect");
                                close(sock);
                        }
-               } else
+               } else {
                        break;
+               }
        }
 
        if (conn_data->cur_addr == NULL) {
-               g_warning("sock_connect_address_list_async: "
-                         "connection to %s:%d failed\n",
-                         conn_data->hostname, conn_data->port);
                conn_data->func(NULL, conn_data->data);
                sock_connect_async_cancel(conn_data->id);
                return -1;
@@ -887,7 +981,11 @@ static gint sock_connect_address_list_async(SockConnectData *conn_data)
 
        conn_data->cur_addr = conn_data->cur_addr->next;
 
+#ifndef G_OS_WIN32
        conn_data->channel = g_io_channel_unix_new(sock);
+#else
+       conn_data->channel = g_io_channel_win32_new_socket(sock);
+#endif
        conn_data->io_tag = g_io_add_watch(conn_data->channel, G_IO_IN|G_IO_OUT,
                                           sock_connect_async_cb, conn_data);
 
@@ -906,14 +1004,63 @@ static gboolean sock_get_address_info_async_cb(GIOChannel *source,
        gsize bytes_read;
        gint ai_member[4];
        struct sockaddr *addr;
-
+       gchar *canonical_name = NULL;
+       gchar len = 0;
+       GError *err = NULL;
+       
+       g_io_channel_set_encoding(source, NULL, &err);
+       if (err) {
+               g_warning("can unset encoding: %s\n", err->message);
+               g_error_free(err);
+               return FALSE;
+       }
+       g_io_channel_set_buffered(source, FALSE);
+       if (g_io_channel_read_chars(source, &len, sizeof(len),
+                             &bytes_read, &err) == G_IO_STATUS_NORMAL) {
+               if (err != NULL) {
+                       g_warning("g_io_channel_read_chars: %s\n", err->message);
+                       g_error_free(err);
+                       return FALSE;
+               } 
+               if (bytes_read == sizeof(len) && len > 0) {
+                       gchar *cur = NULL;
+                       gint todo = len;
+                       canonical_name = g_malloc0(len + 1);
+                       cur = canonical_name;
+                       while (todo > 0) {
+                               if (g_io_channel_read_chars(source, cur, todo,
+                                     &bytes_read, &err) != G_IO_STATUS_NORMAL) {
+                                       if (err) {
+                                             g_warning("canonical name not read %s\n", err->message);
+                                             g_free(canonical_name);
+                                             canonical_name = NULL;
+                                             g_error_free(err);
+                                             err = NULL;
+                                             break;
+                                       }
+                               } else {
+                                       cur += bytes_read;
+                                       todo -= bytes_read;
+                               }
+                               if (bytes_read == 0) {
+                                     g_warning("canonical name not read\n");
+                                     g_free(canonical_name);
+                                     canonical_name = NULL;
+                                     break;
+                               }
+                       }
+               }             
+       }
        for (;;) {
-               if (g_io_channel_read(source, (gchar *)ai_member,
-                                     sizeof(ai_member), &bytes_read)
-                   != G_IO_ERROR_NONE) {
-                       g_warning("sock_get_address_info_async_cb: "
-                                 "address length read error\n");
-                       break;
+               if (g_io_channel_read_chars(source, (gchar *)ai_member,
+                                     sizeof(ai_member), &bytes_read, &err) 
+                   != G_IO_STATUS_NORMAL) {
+                       if (err != NULL) {
+                               g_warning("g_io_channel_read_chars: addr len %s\n", err->message);
+                               g_error_free(err);
+                               err = NULL;
+                               break;
+                       } 
                }
 
                if (bytes_read == 0 || bytes_read != sizeof(ai_member))
@@ -921,17 +1068,22 @@ static gboolean sock_get_address_info_async_cb(GIOChannel *source,
 
                if (ai_member[0] == AF_UNSPEC) {
                        g_warning("DNS lookup failed\n");
+                       log_error(LOG_PROTOCOL, _("%s:%d: unknown host.\n"),
+                               lookup_data->hostname, lookup_data->port);
                        break;
                }
 
                addr = g_malloc(ai_member[3]);
-               if (g_io_channel_read(source, (gchar *)addr, ai_member[3],
-                                     &bytes_read)
-                   != G_IO_ERROR_NONE) {
-                       g_warning("sock_get_address_info_async_cb: "
-                                 "address data read error\n");
-                       g_free(addr);
-                       break;
+               if (g_io_channel_read_chars(source, (gchar *)addr, ai_member[3],
+                                     &bytes_read, &err) 
+                   != G_IO_STATUS_NORMAL) {
+                       if (err != NULL) {
+                               g_warning("g_io_channel_read_chars: addr data read %s\n", err->message);
+                               g_error_free(err);
+                               err = NULL;
+                               g_free(addr);
+                               break;
+                       } 
                }
 
                if (bytes_read != ai_member[3]) {
@@ -951,135 +1103,226 @@ static gboolean sock_get_address_info_async_cb(GIOChannel *source,
                addr_list = g_list_append(addr_list, addr_data);
        }
 
-       g_io_channel_close(source);
+       g_io_channel_shutdown(source, TRUE, &err);
+       if (err)
+               g_error_free(err);
        g_io_channel_unref(source);
 
+#ifdef G_OS_WIN32
+        /* FIXME: We would need to cancel the thread. */
+#else
        kill(lookup_data->child_pid, SIGKILL);
        waitpid(lookup_data->child_pid, NULL, 0);
+#endif
+       lookup_data->canonical_name = canonical_name;
 
        lookup_data->func(addr_list, lookup_data->data);
 
+       g_free(lookup_data->canonical_name);
        g_free(lookup_data->hostname);
        g_free(lookup_data);
 
        return FALSE;
 }
 
+
+/* For better readability we use a separate function to implement the
+   child code of sock_get_address_info_async.  Note, that under W32
+   this is actually not a child but a thread and this is the reason
+   why we pass only a void pointer. */
+static void address_info_async_child(void *opaque)
+{
+        SockLookupData *parm = opaque;
+#ifdef INET6
+        gint gai_err;
+        struct addrinfo hints, *res, *ai;
+        gchar port_str[6];
+#else /* !INET6 */
+        struct hostent *hp;
+        gchar **addr_list_p;
+        struct sockaddr_in ad;
+#endif /* INET6 */
+        gint ai_member[4] = {AF_UNSPEC, 0, 0, 0};
+
+#ifndef G_OS_WIN32
+        close(parm->pipe_fds[0]);
+        parm->pipe_fds[0] = -1;
+#endif
+
+#ifdef INET6
+        memset(&hints, 0, sizeof(hints));
+        hints.ai_flags = AI_CANONNAME;
+        hints.ai_family = AF_UNSPEC;
+        hints.ai_socktype = SOCK_STREAM;
+        hints.ai_protocol = IPPROTO_TCP;
+
+        g_snprintf(port_str, sizeof(port_str), "%d", parm->port);
+
+        gai_err = getaddrinfo(parm->hostname, port_str, &hints, &res);
+        if (gai_err != 0) {
+               gchar len = 0;
+                g_warning("getaddrinfo for %s:%s failed: %s\n",
+                          parm->hostname, port_str, gai_strerror(gai_err));
+               log_error(LOG_PROTOCOL, _("%s:%s: host lookup failed (%s).\n"),
+                         parm->hostname, port_str, gai_strerror(gai_err));
+               fd_write_all(parm->pipe_fds[1], &len,
+                     sizeof(len));
+                fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
+                             sizeof(ai_member));
+                close(parm->pipe_fds[1]);
+                parm->pipe_fds[1] = -1;
+#ifdef G_OS_WIN32
+                _endthread();
+#else
+                _exit(1);
+#endif
+        }
+
+       if (res != NULL) {
+               if (res->ai_canonname && strlen(res->ai_canonname) < 255) {
+                       gchar len = strlen(res->ai_canonname);
+                       fd_write_all(parm->pipe_fds[1], &len,
+                             sizeof(len));
+                       fd_write_all(parm->pipe_fds[1], res->ai_canonname,
+                             len);                      
+               } else {
+                       gchar len = 0;
+                       fd_write_all(parm->pipe_fds[1], &len,
+                             sizeof(len));
+               }
+       } else {
+               gchar len = 0;
+               fd_write_all(parm->pipe_fds[1], &len,
+                     sizeof(len));
+       }
+
+        for (ai = res; ai != NULL; ai = ai->ai_next) {
+                ai_member[0] = ai->ai_family;
+                ai_member[1] = ai->ai_socktype;
+                ai_member[2] = ai->ai_protocol;
+                ai_member[3] = ai->ai_addrlen;
+
+                fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
+                             sizeof(ai_member));
+                fd_write_all(parm->pipe_fds[1], (gchar *)ai->ai_addr,
+                             ai->ai_addrlen);
+        }
+
+        if (res != NULL)
+                freeaddrinfo(res);
+#else /* !INET6 */
+        hp = my_gethostbyname(parm->hostname);
+        if (hp == NULL || hp->h_addrtype != AF_INET) {
+               gchar len = 0;
+               fd_write_all(parm->pipe_fds[1], &len,
+                     sizeof(len));
+                fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
+                             sizeof(ai_member));
+               close(parm->pipe_fds[1]);
+                parm->pipe_fds[1] = -1;
+#ifdef G_OS_WIN32
+                _endthread();
+#else
+                _exit(1);
+#endif
+        }
+
+        ai_member[0] = AF_INET;
+        ai_member[1] = SOCK_STREAM;
+        ai_member[2] = IPPROTO_TCP;
+        ai_member[3] = sizeof(ad);
+
+        memset(&ad, 0, sizeof(ad));
+        ad.sin_family = AF_INET;
+        ad.sin_port = htons(parm->port);
+
+       if (hp->h_name && strlen(hp->h_name) < 255) {
+               gchar len = strlen(hp->h_name);
+               fd_write_all(parm->pipe_fds[1], &len,
+                     sizeof(len));
+               fd_write_all(parm->pipe_fds[1], hp->h_name,
+                     len);                      
+       } else {
+               gchar len = 0;
+               fd_write_all(parm->pipe_fds[1], &len,
+                     sizeof(len));
+       }
+        for (addr_list_p = hp->h_addr_list; *addr_list_p != NULL;
+             addr_list_p++) {
+                memcpy(&ad.sin_addr, *addr_list_p, hp->h_length);
+                fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
+                             sizeof(ai_member));
+                fd_write_all(parm->pipe_fds[1], (gchar *)&ad, sizeof(ad));
+        }
+#endif /* INET6 */
+
+        close(parm->pipe_fds[1]);
+        parm->pipe_fds[1] = -1;
+
+#ifdef G_OS_WIN32
+        _endthread();
+#else
+        _exit(0);
+#endif
+}
+
 static SockLookupData *sock_get_address_info_async(const gchar *hostname,
                                                   gushort port,
                                                   SockAddrFunc func,
                                                   gpointer data)
 {
        SockLookupData *lookup_data = NULL;
-       gint pipe_fds[2];
-       pid_t pid;
        
        refresh_resolvers();
 
-       if (pipe(pipe_fds) < 0) {
+        lookup_data = g_new0(SockLookupData, 1);
+        lookup_data->hostname = g_strdup(hostname);
+        lookup_data->func = func;
+        lookup_data->data = data;
+        lookup_data->port = port;
+        lookup_data->child_pid = (pid_t)(-1);
+        lookup_data->pipe_fds[0] = -1;
+        lookup_data->pipe_fds[1] = -1;
+
+       if (pipe(lookup_data->pipe_fds) < 0) {
                perror("pipe");
                func(NULL, data);
+                g_free (lookup_data->hostname);
+                g_free (lookup_data);
                return NULL;
        }
 
-       if ((pid = fork()) < 0) {
+#ifndef G_OS_WIN32
+       if ((lookup_data->child_pid = fork()) < 0) {
                perror("fork");
                func(NULL, data);
+                g_free (lookup_data->hostname);
+                g_free (lookup_data);
                return NULL;
        }
 
-       /* child process */
-       if (pid == 0) {
-#ifdef INET6
-               gint gai_err;
-               struct addrinfo hints, *res, *ai;
-               gchar port_str[6];
-#else /* !INET6 */
-               struct hostent *hp;
-               gchar **addr_list_p;
-               struct sockaddr_in ad;
-#endif /* INET6 */
-               gint ai_member[4] = {AF_UNSPEC, 0, 0, 0};
-
-               close(pipe_fds[0]);
-
-#ifdef INET6
-               memset(&hints, 0, sizeof(hints));
-               /* hints.ai_flags = AI_CANONNAME; */
-               hints.ai_family = AF_UNSPEC;
-               hints.ai_socktype = SOCK_STREAM;
-               hints.ai_protocol = IPPROTO_TCP;
-
-               g_snprintf(port_str, sizeof(port_str), "%d", port);
-
-               gai_err = getaddrinfo(hostname, port_str, &hints, &res);
-               if (gai_err != 0) {
-                       g_warning("getaddrinfo for %s:%s failed: %s\n",
-                                 hostname, port_str, gai_strerror(gai_err));
-                       fd_write_all(pipe_fds[1], (gchar *)ai_member,
-                                    sizeof(ai_member));
-                       close(pipe_fds[1]);
-                       _exit(1);
-               }
-
-               for (ai = res; ai != NULL; ai = ai->ai_next) {
-                       ai_member[0] = ai->ai_family;
-                       ai_member[1] = ai->ai_socktype;
-                       ai_member[2] = ai->ai_protocol;
-                       ai_member[3] = ai->ai_addrlen;
-
-                       fd_write_all(pipe_fds[1], (gchar *)ai_member,
-                                    sizeof(ai_member));
-                       fd_write_all(pipe_fds[1], (gchar *)ai->ai_addr,
-                                    ai->ai_addrlen);
-               }
-
-               if (res != NULL)
-                       freeaddrinfo(res);
-#else /* !INET6 */
-               hp = my_gethostbyname(hostname);
-               if (hp == NULL || hp->h_addrtype != AF_INET) {
-                       fd_write_all(pipe_fds[1], (gchar *)ai_member,
-                                    sizeof(ai_member));
-                       close(pipe_fds[1]);
-                       _exit(1);
-               }
-
-               ai_member[0] = AF_INET;
-               ai_member[1] = SOCK_STREAM;
-               ai_member[2] = IPPROTO_TCP;
-               ai_member[3] = sizeof(ad);
-
-               memset(&ad, 0, sizeof(ad));
-               ad.sin_family = AF_INET;
-               ad.sin_port = htons(port);
-
-               for (addr_list_p = hp->h_addr_list; *addr_list_p != NULL;
-                    addr_list_p++) {
-                       memcpy(&ad.sin_addr, *addr_list_p, hp->h_length);
-                       fd_write_all(pipe_fds[1], (gchar *)ai_member,
-                                    sizeof(ai_member));
-                       fd_write_all(pipe_fds[1], (gchar *)&ad, sizeof(ad));
-               }
-#endif /* INET6 */
-
-               close(pipe_fds[1]);
-
-               _exit(0);
-       } else {
-               close(pipe_fds[1]);
-
-               lookup_data = g_new0(SockLookupData, 1);
-               lookup_data->hostname = g_strdup(hostname);
-               lookup_data->child_pid = pid;
-               lookup_data->func = func;
-               lookup_data->data = data;
-
-               lookup_data->channel = g_io_channel_unix_new(pipe_fds[0]);
-               lookup_data->io_tag = g_io_add_watch
-                       (lookup_data->channel, G_IO_IN,
-                        sock_get_address_info_async_cb, lookup_data);
+       if (lookup_data->child_pid == 0) {
+                /* Child process. */
+                address_info_async_child (lookup_data);
+                g_assert_not_reached ();
        }
+        /* Parent process. */
+        close(lookup_data->pipe_fds[1]);
+        lookup_data->pipe_fds[1] = -1;
+#endif  /*!G_OS_WIN32 */
+        
+#ifndef G_OS_WIN32
+        lookup_data->channel = g_io_channel_unix_new(lookup_data->pipe_fds[0]);
+#else
+        lookup_data->channel = g_io_channel_win32_new_fd(lookup_data->pipe_fds[0]);
+#endif
+        lookup_data->io_tag = g_io_add_watch(lookup_data->channel, G_IO_IN,
+                                             sock_get_address_info_async_cb,
+                                             lookup_data);
+#ifdef G_OS_WIN32
+       lookup_data->child_pid = _beginthread(
+               address_info_async_child, 0, lookup_data);
+#endif
 
        return lookup_data;
 }
@@ -1089,21 +1332,29 @@ static gint sock_get_address_info_async_cancel(SockLookupData *lookup_data)
        if (lookup_data->io_tag > 0)
                g_source_remove(lookup_data->io_tag);
        if (lookup_data->channel) {
-               g_io_channel_close(lookup_data->channel);
+               GError *err = NULL;
+               g_io_channel_shutdown(lookup_data->channel, TRUE, &err);
+               if (err)
+                       g_error_free(err);
+
                g_io_channel_unref(lookup_data->channel);
        }
 
        if (lookup_data->child_pid > 0) {
+#ifdef G_OS_WIN32
+                /* FIXME: Need a way to cancel the thread. */
+#else
                kill(lookup_data->child_pid, SIGKILL);
                waitpid(lookup_data->child_pid, NULL, 0);
+#endif
        }
 
+       g_free(lookup_data->canonical_name);
        g_free(lookup_data->hostname);
        g_free(lookup_data);
 
        return 0;
 }
-#endif /* G_OS_UNIX */
 
 
 static SockInfo *sockinfo_from_fd(const gchar *hostname,
@@ -1114,7 +1365,11 @@ static SockInfo *sockinfo_from_fd(const gchar *hostname,
 
        sockinfo = g_new0(SockInfo, 1);
        sockinfo->sock = sock;
+#ifndef G_OS_WIN32
        sockinfo->sock_ch = g_io_channel_unix_new(sock);
+#else
+       sockinfo->sock_ch = g_io_channel_win32_new_socket(sock);
+#endif
        sockinfo->hostname = g_strdup(hostname);
        sockinfo->port = port;
        sockinfo->state = CONN_ESTABLISHED;
@@ -1122,57 +1377,52 @@ static SockInfo *sockinfo_from_fd(const gchar *hostname,
        return sockinfo;
 }
 
-gint sock_printf(SockInfo *sock, const gchar *format, ...)
-{
-       va_list args;
-       gchar buf[BUFFSIZE];
-
-       va_start(args, format);
-       g_vsnprintf(buf, sizeof(buf), format, args);
-       va_end(args);
-
-       return sock_write_all(sock, buf, strlen(buf));
-}
-
-gint fd_read(gint fd, gchar *buf, gint len)
+static gint fd_read(gint fd, gchar *buf, gint len)
 {
        if (fd_check_io(fd, G_IO_IN) < 0)
                return -1;
 
-#ifdef G_OS_WIN32
-       return recv(fd, buf, len, 0);
-#else
+        if (fd_is_w32_socket(fd))
+                return recv(fd, buf, len, 0);
        return read(fd, buf, len);
-#endif
 }
 
-#if USE_OPENSSL
-gint ssl_read(SSL *ssl, gchar *buf, gint len)
+#if USE_GNUTLS
+static gint ssl_read(gnutls_session_t ssl, gchar *buf, gint len)
 {
-       gint err, ret;
+       gint r;
 
-       if (SSL_pending(ssl) == 0) {
-               if (fd_check_io(SSL_get_rfd(ssl), G_IO_IN) < 0)
+       if (gnutls_record_check_pending(ssl) == 0) {
+               if (fd_check_io(GPOINTER_TO_INT(gnutls_transport_get_ptr(ssl)), G_IO_IN) < 0)
                        return -1;
        }
 
-       ret = SSL_read(ssl, buf, len);
+       while (1) {
+               r = gnutls_record_recv(ssl, buf, len);
+               if (r > 0)
+                       return r;
 
-       switch ((err = SSL_get_error(ssl, ret))) {
-       case SSL_ERROR_NONE:
-               return ret;
-       case SSL_ERROR_WANT_READ:
-       case SSL_ERROR_WANT_WRITE:
-               errno = EAGAIN;
-               return -1;
-       case SSL_ERROR_ZERO_RETURN:
-               return 0;
-       default:
-               g_warning("SSL_read() returned error %d, ret = %d\n", err, ret);
-               if (ret == 0)
-                       return 0;
-               return -1;
+               switch (r) {
+               case 0: /* closed connection */
+                       return -1;
+
+               case GNUTLS_E_REHANDSHAKE:
+                       do {
+                               r = gnutls_handshake(ssl);
+                       } while (r == GNUTLS_E_AGAIN || r == GNUTLS_E_INTERRUPTED);
+                       break; /* re-receive */
+               case GNUTLS_E_AGAIN:
+               case GNUTLS_E_INTERRUPTED:
+                       errno = EAGAIN;
+                       return -1;
+
+               default:
+                       debug_print("Unexpected SSL read result %d\n", r);
+                       errno = EIO;
+                       return -1;
+               }
        }
+
 }
 #endif
 
@@ -1180,9 +1430,9 @@ gint sock_read(SockInfo *sock, gchar *buf, gint len)
 {
        gint ret;
 
-       g_return_val_if_fail(sock != NULL, -1);
+       cm_return_val_if_fail(sock != NULL, -1);
 
-#if USE_OPENSSL
+#ifdef USE_GNUTLS
        if (sock->ssl)
                ret = ssl_read(sock->ssl, buf, len);
        else
@@ -1199,40 +1449,42 @@ gint fd_write(gint fd, const gchar *buf, gint len)
        if (fd_check_io(fd, G_IO_OUT) < 0)
                return -1;
 
-#ifdef G_OS_WIN32
-       return send(fd, buf, len, 0);
-#else
+        if (fd_is_w32_socket (fd))
+                return send(fd, buf, len, 0);
        return write(fd, buf, len);
-#endif
 }
 
-#if USE_OPENSSL
-gint ssl_write(SSL *ssl, const gchar *buf, gint len)
+#if USE_GNUTLS
+static gint ssl_write(gnutls_session_t ssl, const gchar *buf, gint len)
 {
        gint ret;
 
-       ret = SSL_write(ssl, buf, len);
+       if (fd_check_io(GPOINTER_TO_INT(gnutls_transport_get_ptr(ssl)), G_IO_OUT) < 0)
+               return -1;
 
-       switch (SSL_get_error(ssl, ret)) {
-       case SSL_ERROR_NONE:
-               return ret;
-       case SSL_ERROR_WANT_READ:
-       case SSL_ERROR_WANT_WRITE:
-               errno = EAGAIN;
+       ret = gnutls_record_send(ssl, buf, len);
+
+       switch (ret) {
+       case 0:
                return -1;
+       case GNUTLS_E_AGAIN:
+       case GNUTLS_E_INTERRUPTED:
+               return 0;
+
        default:
-               return -1;
+               return ret;
        }
 }
+
 #endif
 
 gint sock_write(SockInfo *sock, const gchar *buf, gint len)
 {
        gint ret;
 
-       g_return_val_if_fail(sock != NULL, -1);
+       cm_return_val_if_fail(sock != NULL, -1);
 
-#if USE_OPENSSL
+#ifdef USE_GNUTLS
        if (sock->ssl)
                ret = ssl_write(sock->ssl, buf, len);
        else
@@ -1254,9 +1506,13 @@ gint fd_write_all(gint fd, const gchar *buf, gint len)
 #ifndef G_OS_WIN32
                signal(SIGPIPE, SIG_IGN);
 #endif
-               n = write(fd, buf, len);
+               if (fd_is_w32_socket(fd))
+                       n = send(fd, buf, len, 0);
+               else
+                        n = write(fd, buf, len);
+
                if (n <= 0) {
-                       log_error("write on fd%d: %s\n", fd, strerror(errno));
+                       log_error(LOG_PROTOCOL, _("write on fd%d: %s\n"), fd, strerror(errno));
                        return -1;
                }
                len -= n;
@@ -1267,8 +1523,8 @@ gint fd_write_all(gint fd, const gchar *buf, gint len)
        return wrlen;
 }
 
-#if USE_OPENSSL
-gint ssl_write_all(SSL *ssl, const gchar *buf, gint len)
+#ifdef USE_GNUTLS
+static gint ssl_write_all(gnutls_session_t ssl, const gchar *buf, gint len)
 {
        gint n, wrlen = 0;
 
@@ -1289,9 +1545,9 @@ gint sock_write_all(SockInfo *sock, const gchar *buf, gint len)
 {
        gint ret;
 
-       g_return_val_if_fail(sock != NULL, -1);
+       cm_return_val_if_fail(sock != NULL, -1);
 
-#if USE_OPENSSL
+#ifdef USE_GNUTLS
        if (sock->ssl)
                ret = ssl_write_all(sock->ssl, buf, len);
        else
@@ -1303,7 +1559,7 @@ gint sock_write_all(SockInfo *sock, const gchar *buf, gint len)
        return ret;
 }
 
-gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
+static gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
 {
        if (fd_check_io(fd, G_IO_IN) < 0)
                return -1;
@@ -1318,183 +1574,46 @@ gint fd_gets(gint fd, gchar *buf, gint len)
 
        if (--len < 1)
                return -1;
+
+#ifdef G_OS_WIN32
+       fd_check_io(fd, G_IO_IN);
        do {
-               if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
-                       return -1;
-               if ((newline = memchr(bp, '\n', n)) != NULL)
-                       n = newline - bp + 1;
-               if ((n = fd_read(fd, bp, n)) < 0)
+/*
+XXX:tm try nonblock
+MSKB Article ID: Q147714 
+Windows Sockets 2 Service Provider Interface Limitations
+Polling with recv(MSG_PEEK) to determine when a complete message 
+has arrived.
+    Reason and Workaround not available.
+
+Single-byte send() and recv(). 
+    Reason: Couple one-byte sends with Nagle disabled.
+    Workaround: Send modest amounts and receive as much as possible.
+(still unused)
+*/
+               if (recv(fd, bp, 1, 0) <= 0)
                        return -1;
-               bp += n;
-               len -= n;
-       } while (!newline && len);
-
-       *bp = '\0';
-       return bp - buf;
-}
-
-#if USE_OPENSSL
-gint ssl_gets(SSL *ssl, gchar *buf, gint len)
-{
-       gchar *newline, *bp = buf;
-       gint n;
-
-       if (--len < 1)
-               return -1;
+               if (*bp == '\n')
+                       break;
+               bp++;
+               len--;
+       } while (0 < len);
+#else /*!G_OS_WIN32*/
        do {
-               if ((n = ssl_peek(ssl, bp, len)) <= 0)
+               if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
                        return -1;
                if ((newline = memchr(bp, '\n', n)) != NULL)
                        n = newline - bp + 1;
-               if ((n = ssl_read(ssl, bp, n)) < 0)
+               if ((n = fd_read(fd, bp, n)) < 0)
                        return -1;
                bp += n;
                len -= n;
        } while (!newline && len);
+#endif /*!G_OS_WIN32*/
 
        *bp = '\0';
        return bp - buf;
 }
-#endif
-
-gint sock_gets(SockInfo *sock, gchar *buf, gint len)
-{
-       gint ret;
-
-       g_return_val_if_fail(sock != NULL, -1);
-
-#if USE_OPENSSL
-       if (sock->ssl)
-               return ssl_gets(sock->ssl, buf, len);
-       else
-#endif
-               return fd_gets(sock->sock, buf, len);
-
-       if (ret < 0)
-               sock->state = CONN_DISCONNECTED;
-       return ret;
-}
-
-gint fd_getline(gint fd, gchar **str)
-{
-       gchar buf[BUFFSIZE];
-       gint len;
-       gulong size = 1;
-
-       while ((len = fd_gets(fd, buf, sizeof(buf))) > 0) {
-               size += len;
-               if (!*str)
-                       *str = g_strdup(buf);
-               else {
-                       *str = g_realloc(*str, size);
-                       strcat(*str, buf);
-               }
-               if (buf[len - 1] == '\n')
-                       break;
-       }
-       if (len == -1 && *str)
-               g_free(*str);
-
-       return len;
-}
-
-#if USE_OPENSSL
-gint ssl_getline(SSL *ssl, gchar **str)
-{
-       gchar buf[BUFFSIZE];
-       gint len;
-       gulong size = 1;
-
-       while ((len = ssl_gets(ssl, buf, sizeof(buf))) > 0) {
-               size += len;
-               if (!*str)
-                       *str = g_strdup(buf);
-               else {
-                       *str = g_realloc(*str, size);
-                       strcat(*str, buf);
-               }
-               if (buf[len - 1] == '\n')
-                       break;
-       }
-       if (len == -1 && *str)
-               g_free(*str);
-
-       return len;
-}
-#endif
-
-gchar *sock_getline(SockInfo *sock)
-{
-       gint ret;
-       gchar *str = NULL;
-
-       g_return_val_if_fail(sock != NULL, NULL);
-
-#if USE_OPENSSL
-       if (sock->ssl)
-               ret = ssl_getline(sock->ssl, &str);
-       else
-#endif
-               ret = fd_getline(sock->sock, &str);
-
-       if (ret < 0)
-               sock->state = CONN_DISCONNECTED;
-       return str;
-}
-
-gint sock_puts(SockInfo *sock, const gchar *buf)
-{
-       gint ret;
-
-       if ((ret = sock_write_all(sock, buf, strlen(buf))) < 0)
-               return ret;
-       return sock_write_all(sock, "\r\n", 2);
-}
-
-/* peek at the socket data without actually reading it */
-#if USE_OPENSSL
-gint ssl_peek(SSL *ssl, gchar *buf, gint len)
-{
-       gint err, ret;
-
-       if (SSL_pending(ssl) == 0) {
-               if (fd_check_io(SSL_get_rfd(ssl), G_IO_IN) < 0)
-                       return -1;
-       }
-
-       ret = SSL_peek(ssl, buf, len);
-
-       switch ((err = SSL_get_error(ssl, ret))) {
-       case SSL_ERROR_NONE:
-               return ret;
-       case SSL_ERROR_WANT_READ:
-       case SSL_ERROR_WANT_WRITE:
-               errno = EAGAIN;
-               return -1;
-       case SSL_ERROR_ZERO_RETURN:
-               return 0;
-       case SSL_ERROR_SYSCALL:
-               g_warning("SSL_peek() returned syscall error. errno=%d\n", errno);
-               return -1;
-       default:
-               g_warning("SSL_peek() returned error %d, ret = %d\n", err, ret);
-               if (ret == 0)
-                       return 0;
-               return -1;
-       }
-}
-#endif
-
-gint sock_peek(SockInfo *sock, gchar *buf, gint len)
-{
-       g_return_val_if_fail(sock != NULL, -1);
-
-#if USE_OPENSSL
-       if (sock->ssl)
-               return ssl_peek(sock->ssl, buf, len);
-#endif
-       return fd_recv(sock->sock, buf, len, MSG_PEEK);
-}
 
 gint sock_close(SockInfo *sock)
 {
@@ -1506,14 +1625,21 @@ gint sock_close(SockInfo *sock)
        if (sock->sock_ch)
                g_io_channel_unref(sock->sock_ch);
 
-#if USE_OPENSSL
+#ifdef USE_GNUTLS
        if (sock->ssl)
                ssl_done_socket(sock);
        if (sock->g_source != 0)
                g_source_remove(sock->g_source);
        sock->g_source = 0;
 #endif
+#ifdef G_OS_WIN32
+       shutdown(sock->sock, 1); /* complete transfer before close */
+       ret = closesocket(sock->sock);
+#else
        ret = fd_close(sock->sock); 
+#endif
+
+       g_free(sock->canonical_name);
        g_free(sock->hostname);
        g_free(sock);