2008-09-20 [colin] 3.5.0cvs118
[claws.git] / src / common / socket.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #if (defined (_XOPEN_SOURCE) && !defined (_BSD_SOURCE))
25 #define _BSD_SOURCE
26 #endif
27
28 #include <glib.h>
29 #include <glib/gi18n.h>
30
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #ifdef G_OS_WIN32
34 #  include <winsock2.h>
35 #  ifndef EINPROGRESS
36 #    define EINPROGRESS WSAEINPROGRESS
37 #  endif
38 #else
39 #  if HAVE_SYS_WAIT_H
40 #    include <sys/wait.h>
41 #  endif
42 #  include <sys/socket.h>
43 #  include <sys/stat.h>
44 #  include <sys/un.h>
45 #  include <netinet/in.h>
46 #  include <arpa/inet.h>
47 #  include <resolv.h>
48 #  include <netdb.h>
49 #endif /* G_OS_WIN32 */
50 #include <unistd.h>
51 #include <stdio.h>
52 #include <string.h>
53 #include <stdarg.h>
54 #include <fcntl.h>
55 #include <errno.h>
56 #include <signal.h>
57 #include <setjmp.h>
58 #if HAVE_SYS_SELECT_H
59 #  include <sys/select.h>
60 #endif
61
62 #include "socket.h"
63 #include "utils.h"
64 #include "log.h"
65 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
66 #  include "ssl.h"
67 #endif
68
69 #if USE_GIO
70 #error USE_GIO is currently not supported
71 #endif
72
73 #if G_IO_WIN32
74 #define BUFFSIZE        8191
75 #else
76 #define BUFFSIZE        8192
77 #endif
78
79
80 typedef gint (*SockAddrFunc)    (GList          *addr_list,
81                                  gpointer        data);
82
83 typedef struct _SockConnectData SockConnectData;
84 typedef struct _SockLookupData  SockLookupData;
85 typedef struct _SockAddrData    SockAddrData;
86 typedef struct _SockSource      SockSource;
87
88 struct _SockConnectData {
89         gint id;
90         gchar *hostname;
91         gushort port;
92         GList *addr_list;
93         GList *cur_addr;
94         SockLookupData *lookup_data;
95         GIOChannel *channel;
96         guint io_tag;
97         SockConnectFunc func;
98         gpointer data;
99         gchar *canonical_name;
100 };
101
102 struct _SockLookupData {
103         gchar *hostname;
104         pid_t child_pid;
105         GIOChannel *channel;
106         guint io_tag;
107         SockAddrFunc func;
108         gpointer data;
109         gushort port;
110         gint pipe_fds[2];
111         gchar *canonical_name;
112 };
113
114 struct _SockAddrData {
115         gint family;
116         gint socktype;
117         gint protocol;
118         gint addr_len;
119         struct sockaddr *addr;
120 };
121
122 struct _SockSource {
123         GSource parent;
124         SockInfo *sock;
125 };
126
127 static guint io_timeout = 60;
128
129 static GList *sock_connect_data_list = NULL;
130
131 static gboolean sock_prepare            (GSource        *source,
132                                          gint           *timeout);
133 static gboolean sock_check              (GSource        *source);
134 static gboolean sock_dispatch           (GSource        *source,
135                                          GSourceFunc     callback,
136                                          gpointer        user_data);
137
138 GSourceFuncs sock_watch_funcs = {
139         sock_prepare,
140         sock_check,
141         sock_dispatch,
142         NULL
143 };
144
145 static gint sock_connect_with_timeout   (gint                    sock,
146                                          const struct sockaddr  *serv_addr,
147                                          gint                    addrlen,
148                                          guint                   timeout_secs);
149
150 #ifndef INET6
151 static gint sock_connect_by_hostname    (gint            sock,
152                                          const gchar    *hostname,
153                                          gushort         port);
154 #else
155 static gint sock_connect_by_getaddrinfo (const gchar    *hostname,
156                                          gushort         port);
157 #endif
158
159 static SockInfo *sockinfo_from_fd(const gchar *hostname,
160                                   gushort port,
161                                   gint sock);
162 static void sock_address_list_free              (GList          *addr_list);
163
164 static gboolean sock_connect_async_cb           (GIOChannel     *source,
165                                                  GIOCondition    condition,
166                                                  gpointer        data);
167 static gint sock_connect_async_get_address_info_cb
168                                                 (GList          *addr_list,
169                                                  gpointer        data);
170
171 static gint sock_connect_address_list_async     (SockConnectData *conn_data);
172
173 static gboolean sock_get_address_info_async_cb  (GIOChannel     *source,
174                                                  GIOCondition    condition,
175                                                  gpointer        data);
176 static SockLookupData *sock_get_address_info_async
177                                                 (const gchar    *hostname,
178                                                  gushort         port,
179                                                  SockAddrFunc    func,
180                                                  gpointer        data);
181 static gint sock_get_address_info_async_cancel  (SockLookupData *lookup_data);
182
183
184 gint sock_init(void)
185 {
186 #ifdef G_OS_WIN32
187         WSADATA wsadata;
188         gint result;
189
190         result = WSAStartup(MAKEWORD(2, 2), &wsadata);
191         if (result != NO_ERROR) {
192                 g_warning("WSAStartup() failed\n");
193                 return -1;
194         }
195 #endif
196         return 0;
197 }
198
199 gint sock_cleanup(void)
200 {
201 #ifdef G_OS_WIN32
202         WSACleanup();
203 #endif
204         return 0;
205 }
206
207 gint sock_set_io_timeout(guint sec)
208 {
209         io_timeout = sec;
210         return 0;
211 }
212
213 void refresh_resolvers(void)
214 {
215 #ifdef G_OS_UNIX
216         static time_t resolv_conf_changed = (time_t)NULL;
217         struct stat s;
218
219         /* This makes the glibc re-read resolv.conf, if it changed
220          * since our startup. Maybe that should be #ifdef'ed, I don't
221          * know if it'd work on BSDs.
222          * Why doesn't the glibc do it by itself?
223          */
224         if (stat("/etc/resolv.conf", &s) == 0) {
225                 if (s.st_mtime > resolv_conf_changed) {
226                         resolv_conf_changed = s.st_mtime;
227                         res_init();
228                 }
229         } /* else
230                 we'll have bigger problems. */
231 #endif /*G_OS_UNIX*/
232 }
233
234
235 /* Due to the fact that socket under Windows are not represented by
236    standard file descriptors, we sometimes need to check whether a
237    given file descriptor is actually a socket.  This is done by
238    testing for an error.  Returns true under W32 if FD is a socket. */
239 static int fd_is_w32_socket(gint fd)
240 {
241 #ifdef G_OS_WIN32
242         gint optval;
243         gint retval = sizeof(optval);
244         
245         return !getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*)&optval, &retval);
246 #else
247         return 0;
248 #endif 
249 }
250
251
252 gint fd_connect_unix(const gchar *path)
253 {
254 #ifdef G_OS_UNIX
255         gint sock;
256         struct sockaddr_un addr;
257
258         sock = socket(PF_UNIX, SOCK_STREAM, 0);
259         if (sock < 0) {
260                 perror("sock_connect_unix(): socket");
261                 return -1;
262         }
263
264         memset(&addr, 0, sizeof(addr));
265         addr.sun_family = AF_UNIX;
266         strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
267
268         if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
269                 close(sock);
270                 return -1;
271         }
272
273         return sock;
274 #else
275         return -1;
276 #endif
277 }
278
279 gint fd_open_unix(const gchar *path)
280 {
281 #ifdef G_OS_UNIX
282         gint sock;
283         struct sockaddr_un addr;
284
285         sock = socket(PF_UNIX, SOCK_STREAM, 0);
286
287         if (sock < 0) {
288                 perror("sock_open_unix(): socket");
289                 return -1;
290         }
291
292         memset(&addr, 0, sizeof(addr));
293         addr.sun_family = AF_UNIX;
294         strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
295
296         if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
297                 gchar *buf = g_strdup_printf("can't bind to %s", path);
298                 perror(buf);
299                 g_free(buf);
300                 close(sock);
301                 return -1;
302         }
303
304         if (listen(sock, 1) < 0) {
305                 gchar *buf = g_strdup_printf("can't listen on %s", path);
306                 perror(buf);
307                 g_free(buf);
308                 close(sock);
309                 return -1;              
310         }
311
312         return sock;
313 #else
314         return -1;
315 #endif
316 }
317
318 gint fd_accept(gint sock)
319 {
320         struct sockaddr_in caddr;
321         guint caddr_len;
322
323         caddr_len = sizeof(caddr);
324         return accept(sock, (struct sockaddr *)&caddr, &caddr_len);
325 }
326
327
328 static gint set_nonblocking_mode(gint fd, gboolean nonblock)
329 {
330 #ifdef G_OS_UNIX
331         gint flags;
332
333         flags = fcntl(fd, F_GETFL, 0);
334         if (flags < 0) {
335                 perror("fcntl");
336                 return -1;
337         }
338
339         if (nonblock)
340                 flags |= O_NONBLOCK;
341         else
342                 flags &= ~O_NONBLOCK;
343
344         return fcntl(fd, F_SETFL, flags);
345 #else
346         return -1;
347 #endif
348 }
349
350 gint sock_set_nonblocking_mode(SockInfo *sock, gboolean nonblock)
351 {
352         g_return_val_if_fail(sock != NULL, -1);
353
354         return set_nonblocking_mode(sock->sock, nonblock);
355 }
356
357 static gboolean is_nonblocking_mode(gint fd)
358 {
359 #ifdef G_OS_UNIX
360         gint flags;
361
362         flags = fcntl(fd, F_GETFL, 0);
363         if (flags < 0) {
364                 perror("fcntl");
365                 return FALSE;
366         }
367
368         return ((flags & O_NONBLOCK) != 0);
369 #else
370         return FALSE;
371 #endif
372 }
373
374 gboolean sock_is_nonblocking_mode(SockInfo *sock)
375 {
376         g_return_val_if_fail(sock != NULL, FALSE);
377
378         return is_nonblocking_mode(sock->sock);
379 }
380
381
382 static gboolean sock_prepare(GSource *source, gint *timeout)
383 {
384         *timeout = 1;
385         return FALSE;
386 }
387
388 static gboolean sock_check(GSource *source)
389 {
390         SockInfo *sock = ((SockSource *)source)->sock;
391         struct timeval timeout = {0, 0};
392         fd_set fds;
393         GIOCondition condition = sock->condition;
394         
395         if (!sock || !sock->sock)
396                 return FALSE;
397
398 #if USE_OPENSSL
399         if (sock->ssl) {
400                 if (condition & G_IO_IN) {
401                         if (SSL_pending(sock->ssl) > 0)
402                                 return TRUE;
403                         if (SSL_want_write(sock->ssl))
404                                 condition |= G_IO_OUT;
405                 }
406
407                 if (condition & G_IO_OUT) {
408                         if (SSL_want_read(sock->ssl))
409                                 condition |= G_IO_IN;
410                 }
411         }
412 #elif USE_GNUTLS
413 /* ?? */
414 #endif
415
416         FD_ZERO(&fds);
417         FD_SET(sock->sock, &fds);
418
419         select(sock->sock + 1,
420                (condition & G_IO_IN)  ? &fds : NULL,
421                (condition & G_IO_OUT) ? &fds : NULL,
422                NULL, &timeout);
423
424         return FD_ISSET(sock->sock, &fds) != 0;
425 }
426
427 static gboolean sock_dispatch(GSource *source, GSourceFunc callback,
428                               gpointer user_data)
429 {
430         SockInfo *sock = ((SockSource *)source)->sock;
431
432         if (!sock || !sock->callback || !sock->data)
433                 return FALSE;
434
435         return sock->callback(sock, sock->condition, sock->data);
436 }
437
438 static gboolean sock_watch_cb(GIOChannel *source, GIOCondition condition,
439                               gpointer data)
440 {
441         SockInfo *sock = (SockInfo *)data;
442
443         if ((condition & sock->condition) == 0)
444                 return TRUE;
445
446         return sock->callback(sock, sock->condition, sock->data);
447 }
448
449 guint sock_add_watch(SockInfo *sock, GIOCondition condition, SockFunc func,
450                      gpointer data)
451 {
452         if (!sock)
453                 return FALSE;
454
455         sock->callback = func;
456         sock->condition = condition;
457         sock->data = data;
458
459 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
460         if (sock->ssl)
461         {
462                 GSource *source = g_source_new(&sock_watch_funcs,
463                                                sizeof(SockSource));
464                 ((SockSource *) source)->sock = sock;
465                 g_source_set_priority(source, G_PRIORITY_DEFAULT);
466                 g_source_set_can_recurse(source, FALSE);
467                 sock->g_source = g_source_attach(source, NULL);
468                 g_source_unref (source); /* Refcount back down to 1 */
469                 return sock->g_source;
470         }
471 #endif
472
473         return g_io_add_watch(sock->sock_ch, condition, sock_watch_cb, sock);
474 }
475
476 static gint fd_check_io(gint fd, GIOCondition cond)
477 {
478         struct timeval timeout;
479         fd_set fds;
480
481         if (is_nonblocking_mode(fd))
482                 return 0;
483
484         timeout.tv_sec  = io_timeout;
485         timeout.tv_usec = 0;
486
487         FD_ZERO(&fds);
488         FD_SET(fd, &fds);
489
490         if (cond == G_IO_IN) {
491                 select(fd + 1, &fds, NULL, NULL,
492                        io_timeout > 0 ? &timeout : NULL);
493         } else {
494                 select(fd + 1, NULL, &fds, NULL,
495                        io_timeout > 0 ? &timeout : NULL);
496         }
497
498         if (FD_ISSET(fd, &fds)) {
499                 return 0;
500         } else {
501                 g_warning("Socket IO timeout\n");
502                 return -1;
503         }
504 }
505
506 #ifdef G_OS_UNIX
507 static sigjmp_buf jmpenv;
508
509 static void timeout_handler(gint sig)
510 {
511         siglongjmp(jmpenv, 1);
512 }
513 #endif /*G_OS_UNIX*/
514
515 static gint sock_connect_with_timeout(gint sock,
516                                       const struct sockaddr *serv_addr,
517                                       gint addrlen,
518                                       guint timeout_secs)
519 {
520         gint ret;
521 #ifdef G_OS_UNIX
522         void (*prev_handler)(gint);
523         
524         alarm(0);
525         prev_handler = signal(SIGALRM, timeout_handler);
526         if (sigsetjmp(jmpenv, 1)) {
527                 alarm(0);
528                 signal(SIGALRM, prev_handler);
529                 errno = ETIMEDOUT;
530                 return -1;
531         }
532         alarm(timeout_secs);
533 #endif
534
535         ret = connect(sock, serv_addr, addrlen);
536
537 #ifdef G_OS_UNIX
538         alarm(0);
539         signal(SIGALRM, prev_handler);
540 #endif
541
542         return ret;
543 }
544
545 struct hostent *my_gethostbyname(const gchar *hostname)
546 {
547         struct hostent *hp;
548 #ifdef G_OS_UNIX
549         void (*prev_handler)(gint);
550         
551         alarm(0);
552         prev_handler = signal(SIGALRM, timeout_handler);
553         if (sigsetjmp(jmpenv, 1)) {
554                 alarm(0);
555                 signal(SIGALRM, prev_handler);
556                 g_printerr("%s: host lookup timed out.\n", hostname);
557                 errno = 0;
558                 return NULL;
559         }
560         alarm(io_timeout);
561 #endif
562
563         if ((hp = gethostbyname(hostname)) == NULL) {
564 #ifdef G_OS_UNIX
565                 alarm(0);
566                 signal(SIGALRM, prev_handler);
567 #endif
568                 g_printerr("%s: unknown host.\n", hostname);
569                 errno = 0;
570                 return NULL;
571         }
572
573 #ifdef G_OS_UNIX
574         alarm(0);
575         signal(SIGALRM, prev_handler);
576 #endif
577
578         return hp;
579 }
580
581 #ifndef INET6
582 static gint my_inet_aton(const gchar *hostname, struct in_addr *inp)
583 {
584 #if HAVE_INET_ATON
585         return inet_aton(hostname, inp);
586 #else
587 #if HAVE_INET_ADDR
588         guint32 inaddr;
589
590         inaddr = inet_addr(hostname);
591         if (inaddr != -1) {
592                 memcpy(inp, &inaddr, sizeof(inaddr));
593                 return 1;
594         } else
595                 return 0;
596 #else
597         return 0;
598 #endif
599 #endif /* HAVE_INET_ATON */
600 }
601
602 static gint sock_connect_by_hostname(gint sock, const gchar *hostname,
603                                      gushort port)
604 {
605         struct hostent *hp;
606         struct sockaddr_in ad;
607
608         memset(&ad, 0, sizeof(ad));
609         ad.sin_family = AF_INET;
610         ad.sin_port = htons(port);
611
612         refresh_resolvers();
613
614         if (!my_inet_aton(hostname, &ad.sin_addr)) {
615                 if ((hp = my_gethostbyname(hostname)) == NULL) {
616                         g_printerr("%s: unknown host.\n", hostname);
617                         errno = 0;
618                         return -1;
619                 }
620
621                 if (hp->h_length != 4 && hp->h_length != 8) {
622                         g_printerr("illegal address length received for host %s\n", hostname);
623                         errno = 0;
624                         return -1;
625                 }
626
627                 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
628         }
629
630         return sock_connect_with_timeout(sock, (struct sockaddr *)&ad,
631                                          sizeof(ad), io_timeout);
632 }
633
634 #else /* INET6 */
635 static gint sock_connect_by_getaddrinfo(const gchar *hostname, gushort  port)
636 {
637         gint sock = -1, gai_error;
638         struct addrinfo hints, *res, *ai;
639         gchar port_str[6];
640
641         refresh_resolvers();
642
643         memset(&hints, 0, sizeof(hints));
644         /* hints.ai_flags = AI_CANONNAME; */
645         hints.ai_family = AF_UNSPEC;
646         hints.ai_socktype = SOCK_STREAM;
647         hints.ai_protocol = IPPROTO_TCP;
648
649         /* convert port from integer to string. */
650         g_snprintf(port_str, sizeof(port_str), "%d", port);
651
652         if ((gai_error = getaddrinfo(hostname, port_str, &hints, &res)) != 0) {
653                 g_printerr("getaddrinfo for %s:%s failed: %s\n",
654                         hostname, port_str, gai_strerror(gai_error));
655                 return -1;
656         }
657
658         for (ai = res; ai != NULL; ai = ai->ai_next) {
659                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
660                 if (sock < 0)
661                         continue;
662
663                 if (sock_connect_with_timeout
664                         (sock, ai->ai_addr, ai->ai_addrlen, io_timeout) == 0)
665                         break;
666
667                 close(sock);
668         }
669
670         if (res != NULL)
671                 freeaddrinfo(res);
672
673         if (ai == NULL)
674                 return -1;
675
676         return sock;
677 }
678 #endif /* !INET6 */
679
680 SockInfo *sock_connect(const gchar *hostname, gushort port)
681 {
682 #ifdef G_OS_WIN32
683         SOCKET sock;
684 #else
685         gint sock;
686 #endif
687
688 #ifdef INET6
689         if ((sock = sock_connect_by_getaddrinfo(hostname, port)) < 0)
690                 return NULL;
691 #else
692 #ifdef G_OS_WIN32
693         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
694                 g_warning("socket() failed: %d\n", WSAGetLastError());
695 #else
696         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
697                 perror("socket");
698 #endif /* G_OS_WIN32 */
699                 return NULL;
700         }
701
702         if (sock_connect_by_hostname(sock, hostname, port) < 0) {
703                 if (errno != 0) perror("connect");
704                 close(sock);
705                 return NULL;
706         }
707 #endif /* INET6 */
708
709         return sockinfo_from_fd(hostname, port, sock);
710 }
711
712
713 static void sock_address_list_free(GList *addr_list)
714 {
715         GList *cur;
716
717         for (cur = addr_list; cur != NULL; cur = cur->next) {
718                 SockAddrData *addr_data = (SockAddrData *)cur->data;
719                 g_free(addr_data->addr);
720                 g_free(addr_data);
721         }
722
723         g_list_free(addr_list);
724 }
725
726 /* asynchronous TCP connection */
727
728 static gboolean sock_connect_async_cb(GIOChannel *source,
729                                       GIOCondition condition, gpointer data)
730 {
731         SockConnectData *conn_data = (SockConnectData *)data;
732         gint fd;
733         gint val;
734         guint len;
735         SockInfo *sockinfo;
736
737         if (conn_data->io_tag == 0 && conn_data->channel == NULL)
738                 return FALSE;
739
740         fd = g_io_channel_unix_get_fd(source);
741
742         conn_data->io_tag = 0;
743         conn_data->channel = NULL;
744         g_io_channel_unref(source);
745
746         len = sizeof(val);
747         if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &len) < 0) {
748                 perror("getsockopt");
749                 close(fd);
750                 sock_connect_address_list_async(conn_data);
751                 return FALSE;
752         }
753
754         if (val != 0) {
755                 close(fd);
756                 sock_connect_address_list_async(conn_data);
757                 return FALSE;
758         }
759
760         sockinfo = g_new0(SockInfo, 1);
761         sockinfo->sock = fd;
762 #ifndef G_OS_WIN32
763         sockinfo->sock_ch = g_io_channel_unix_new(fd);
764 #else
765         sockinfo->sock_ch = g_io_channel_win32_new_socket(fd);
766 #endif
767         sockinfo->hostname = g_strdup(conn_data->hostname);
768         sockinfo->port = conn_data->port;
769         sockinfo->state = CONN_ESTABLISHED;
770         sockinfo->canonical_name = g_strdup(conn_data->canonical_name);
771
772         conn_data->func(sockinfo, conn_data->data);
773
774         sock_connect_async_cancel(conn_data->id);
775
776         return FALSE;
777 }
778
779 static gint sock_connect_async_get_address_info_cb(GList *addr_list,
780                                                    gpointer data)
781 {
782         SockConnectData *conn_data = (SockConnectData *)data;
783
784         conn_data->addr_list = addr_list;
785         conn_data->cur_addr = addr_list;
786         if (conn_data->lookup_data) {
787                 conn_data->canonical_name = conn_data->lookup_data->canonical_name;
788                 conn_data->lookup_data->canonical_name = NULL;
789                 conn_data->lookup_data = NULL;
790         }
791         return sock_connect_address_list_async(conn_data);
792 }
793
794 gint sock_connect_async(const gchar *hostname, gushort port,
795                         SockConnectFunc func, gpointer data)
796 {
797         static gint id = 1;
798         SockConnectData *conn_data;
799
800         conn_data = g_new0(SockConnectData, 1);
801         conn_data->id = id++;
802         conn_data->hostname = g_strdup(hostname);
803         conn_data->port = port;
804         conn_data->addr_list = NULL;
805         conn_data->cur_addr = NULL;
806         conn_data->io_tag = 0;
807         conn_data->func = func;
808         conn_data->data = data;
809
810         conn_data->lookup_data = sock_get_address_info_async
811                 (hostname, port, sock_connect_async_get_address_info_cb,
812                  conn_data);
813
814         if (conn_data->lookup_data == NULL) {
815                 g_free(conn_data->hostname);
816                 g_free(conn_data);
817                 return -1;
818         }
819
820         sock_connect_data_list = g_list_append(sock_connect_data_list,
821                                                conn_data);
822
823         return conn_data->id;
824 }
825
826 gint sock_connect_async_cancel(gint id)
827 {
828         SockConnectData *conn_data = NULL;
829         GList *cur;
830
831         for (cur = sock_connect_data_list; cur != NULL; cur = cur->next) {
832                 if (((SockConnectData *)cur->data)->id == id) {
833                         conn_data = (SockConnectData *)cur->data;
834                         break;
835                 }
836         }
837
838         if (conn_data) {
839                 sock_connect_data_list = g_list_remove(sock_connect_data_list,
840                                                        conn_data);
841
842                 if (conn_data->lookup_data)
843                         sock_get_address_info_async_cancel
844                                 (conn_data->lookup_data);
845
846                 if (conn_data->io_tag > 0)
847                         g_source_remove(conn_data->io_tag);
848                 if (conn_data->channel) {
849                         GError *err = NULL;
850                         g_io_channel_shutdown(conn_data->channel, TRUE, &err);
851                         if (err)
852                                 g_error_free(err);
853                         g_io_channel_unref(conn_data->channel);
854                 }
855
856                 sock_address_list_free(conn_data->addr_list);
857                 g_free(conn_data->canonical_name);
858                 g_free(conn_data->hostname);
859                 g_free(conn_data);
860         } else {
861                 g_warning("sock_connect_async_cancel: id %d not found.\n", id);
862                 return -1;
863         }
864
865         return 0;
866 }
867
868 static gint sock_connect_address_list_async(SockConnectData *conn_data)
869 {
870         SockAddrData *addr_data;
871         gint sock = -1;
872
873         for (; conn_data->cur_addr != NULL;
874              conn_data->cur_addr = conn_data->cur_addr->next) {
875                 addr_data = (SockAddrData *)conn_data->cur_addr->data;
876
877                 if ((sock = socket(addr_data->family, addr_data->socktype,
878                                    addr_data->protocol)) < 0) {
879                         perror("socket");
880                         continue;
881                 }
882
883                 set_nonblocking_mode(sock, TRUE);
884
885                 if (connect(sock, addr_data->addr, addr_data->addr_len) < 0) {
886                         if (EINPROGRESS == errno) {
887                                 break;
888                         } else {
889                                 perror("connect");
890                                 close(sock);
891                         }
892                 } else
893                         break;
894         }
895
896         if (conn_data->cur_addr == NULL) {
897                 g_warning("sock_connect_address_list_async: "
898                           "connection to %s:%d failed\n",
899                           conn_data->hostname, conn_data->port);
900                 conn_data->func(NULL, conn_data->data);
901                 sock_connect_async_cancel(conn_data->id);
902                 return -1;
903         }
904
905         conn_data->cur_addr = conn_data->cur_addr->next;
906
907 #ifndef G_OS_WIN32
908         conn_data->channel = g_io_channel_unix_new(sock);
909 #else
910         conn_data->channel = g_io_channel_win32_new_socket(sock);
911 #endif
912         conn_data->io_tag = g_io_add_watch(conn_data->channel, G_IO_IN|G_IO_OUT,
913                                            sock_connect_async_cb, conn_data);
914
915         return 0;
916 }
917
918 /* asynchronous DNS lookup */
919
920 static gboolean sock_get_address_info_async_cb(GIOChannel *source,
921                                                GIOCondition condition,
922                                                gpointer data)
923 {
924         SockLookupData *lookup_data = (SockLookupData *)data;
925         GList *addr_list = NULL;
926         SockAddrData *addr_data;
927         gsize bytes_read;
928         gint ai_member[4];
929         struct sockaddr *addr;
930         gchar *canonical_name = NULL;
931         gchar len = 0;
932         GError *err = NULL;
933         
934         g_io_channel_set_encoding(source, NULL, &err);
935         if (err) {
936                 g_warning("can unset encoding: %s\n", err->message);
937                 g_error_free(err);
938                 return FALSE;
939         }
940         g_io_channel_set_buffered(source, FALSE);
941         if (g_io_channel_read_chars(source, &len, sizeof(len),
942                               &bytes_read, &err) == G_IO_STATUS_NORMAL) {
943                 if (err != NULL) {
944                         g_warning("g_io_channel_read_chars: %s\n", err->message);
945                         g_error_free(err);
946                         return FALSE;
947                 } 
948                 if (bytes_read == sizeof(len) && len > 0) {
949                         gchar *cur = NULL;
950                         gint todo = len;
951                         canonical_name = g_malloc0(len + 1);
952                         cur = canonical_name;
953                         while (todo > 0) {
954                                 if (g_io_channel_read_chars(source, cur, todo,
955                                       &bytes_read, &err) != G_IO_STATUS_NORMAL) {
956                                         if (err) {
957                                               g_warning("canonical name not read %s\n", err->message);
958                                               g_free(canonical_name);
959                                               canonical_name = NULL;
960                                               g_error_free(err);
961                                               err = NULL;
962                                               break;
963                                         }
964                                 } else {
965                                         cur += bytes_read;
966                                         todo -= bytes_read;
967                                 }
968                                 if (bytes_read == 0) {
969                                       g_warning("canonical name not read\n");
970                                       g_free(canonical_name);
971                                       canonical_name = NULL;
972                                       break;
973                                 }
974                         }
975                 }             
976         }
977         for (;;) {
978                 if (g_io_channel_read_chars(source, (gchar *)ai_member,
979                                       sizeof(ai_member), &bytes_read, &err) 
980                     != G_IO_STATUS_NORMAL) {
981                         if (err != NULL) {
982                                 g_warning("g_io_channel_read_chars: addr len %s\n", err->message);
983                                 g_error_free(err);
984                                 err = NULL;
985                                 break;
986                         } 
987                 }
988
989                 if (bytes_read == 0 || bytes_read != sizeof(ai_member))
990                         break;
991
992                 if (ai_member[0] == AF_UNSPEC) {
993                         g_warning("DNS lookup failed\n");
994                         break;
995                 }
996
997                 addr = g_malloc(ai_member[3]);
998                 if (g_io_channel_read_chars(source, (gchar *)addr, ai_member[3],
999                                       &bytes_read, &err) 
1000                     != G_IO_STATUS_NORMAL) {
1001                         if (err != NULL) {
1002                                 g_warning("g_io_channel_read_chars: addr data read %s\n", err->message);
1003                                 g_error_free(err);
1004                                 err = NULL;
1005                                 g_free(addr);
1006                                 break;
1007                         } 
1008                 }
1009
1010                 if (bytes_read != ai_member[3]) {
1011                         g_warning("sock_get_address_info_async_cb: "
1012                                   "incomplete address data\n");
1013                         g_free(addr);
1014                         break;
1015                 }
1016
1017                 addr_data = g_new0(SockAddrData, 1);
1018                 addr_data->family = ai_member[0];
1019                 addr_data->socktype = ai_member[1];
1020                 addr_data->protocol = ai_member[2];
1021                 addr_data->addr_len = ai_member[3];
1022                 addr_data->addr = addr;
1023
1024                 addr_list = g_list_append(addr_list, addr_data);
1025         }
1026
1027         g_io_channel_shutdown(source, TRUE, &err);
1028         if (err)
1029                 g_error_free(err);
1030         g_io_channel_unref(source);
1031
1032 #ifdef G_OS_WIN32
1033         /* FIXME: We would need to cancel the thread. */
1034 #else
1035         kill(lookup_data->child_pid, SIGKILL);
1036         waitpid(lookup_data->child_pid, NULL, 0);
1037 #endif
1038         lookup_data->canonical_name = canonical_name;
1039
1040         lookup_data->func(addr_list, lookup_data->data);
1041
1042         g_free(lookup_data->canonical_name);
1043         g_free(lookup_data->hostname);
1044         g_free(lookup_data);
1045
1046         return FALSE;
1047 }
1048
1049
1050 /* For better readability we use a separate function to implement the
1051    child code of sock_get_address_info_async.  Note, that under W32
1052    this is actually not a child but a thread and this is the reason
1053    why we pass only a void pointer. */
1054 static void address_info_async_child(void *opaque)
1055 {
1056         SockLookupData *parm = opaque;
1057 #ifdef INET6
1058         gint gai_err;
1059         struct addrinfo hints, *res, *ai;
1060         gchar port_str[6];
1061 #else /* !INET6 */
1062         struct hostent *hp;
1063         gchar **addr_list_p;
1064         struct sockaddr_in ad;
1065 #endif /* INET6 */
1066         gint ai_member[4] = {AF_UNSPEC, 0, 0, 0};
1067
1068 #ifndef G_OS_WIN32
1069         close(parm->pipe_fds[0]);
1070         parm->pipe_fds[0] = -1;
1071 #endif
1072
1073 #ifdef INET6
1074         memset(&hints, 0, sizeof(hints));
1075         hints.ai_flags = AI_CANONNAME;
1076         hints.ai_family = AF_UNSPEC;
1077         hints.ai_socktype = SOCK_STREAM;
1078         hints.ai_protocol = IPPROTO_TCP;
1079
1080         g_snprintf(port_str, sizeof(port_str), "%d", parm->port);
1081
1082         gai_err = getaddrinfo(parm->hostname, port_str, &hints, &res);
1083         if (gai_err != 0) {
1084                 gchar len = 0;
1085                 g_warning("getaddrinfo for %s:%s failed: %s\n",
1086                           parm->hostname, port_str, gai_strerror(gai_err));
1087                 fd_write_all(parm->pipe_fds[1], &len,
1088                      sizeof(len));
1089                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1090                              sizeof(ai_member));
1091                 close(parm->pipe_fds[1]);
1092                 parm->pipe_fds[1] = -1;
1093 #ifdef G_OS_WIN32
1094                 _endthread();
1095 #else
1096                 _exit(1);
1097 #endif
1098         }
1099
1100         if (res != NULL) {
1101                 if (res->ai_canonname && strlen(res->ai_canonname) < 255) {
1102                         gchar len = strlen(res->ai_canonname);
1103                         fd_write_all(parm->pipe_fds[1], &len,
1104                              sizeof(len));
1105                         fd_write_all(parm->pipe_fds[1], res->ai_canonname,
1106                              len);                       
1107                 } else {
1108                         gchar len = 0;
1109                         fd_write_all(parm->pipe_fds[1], &len,
1110                              sizeof(len));
1111                 }
1112         } else {
1113                 gchar len = 0;
1114                 fd_write_all(parm->pipe_fds[1], &len,
1115                      sizeof(len));
1116         }
1117
1118         for (ai = res; ai != NULL; ai = ai->ai_next) {
1119                 ai_member[0] = ai->ai_family;
1120                 ai_member[1] = ai->ai_socktype;
1121                 ai_member[2] = ai->ai_protocol;
1122                 ai_member[3] = ai->ai_addrlen;
1123
1124                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1125                              sizeof(ai_member));
1126                 fd_write_all(parm->pipe_fds[1], (gchar *)ai->ai_addr,
1127                              ai->ai_addrlen);
1128         }
1129
1130         if (res != NULL)
1131                 freeaddrinfo(res);
1132 #else /* !INET6 */
1133         hp = my_gethostbyname(parm->hostname);
1134         if (hp == NULL || hp->h_addrtype != AF_INET) {
1135                 gchar len = 0;
1136                 fd_write_all(parm->pipe_fds[1], &len,
1137                      sizeof(len));
1138                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1139                              sizeof(ai_member));
1140                close(parm->pipe_fds[1]);
1141                 parm->pipe_fds[1] = -1;
1142 #ifdef G_OS_WIN32
1143                 _endthread();
1144 #else
1145                 _exit(1);
1146 #endif
1147         }
1148
1149         ai_member[0] = AF_INET;
1150         ai_member[1] = SOCK_STREAM;
1151         ai_member[2] = IPPROTO_TCP;
1152         ai_member[3] = sizeof(ad);
1153
1154         memset(&ad, 0, sizeof(ad));
1155         ad.sin_family = AF_INET;
1156         ad.sin_port = htons(parm->port);
1157
1158         if (hp->h_name && strlen(hp->h_name) < 255) {
1159                 gchar len = strlen(hp->h_name);
1160                 fd_write_all(parm->pipe_fds[1], &len,
1161                      sizeof(len));
1162                 fd_write_all(parm->pipe_fds[1], hp->h_name,
1163                      len);                       
1164         } else {
1165                 gchar len = 0;
1166                 fd_write_all(parm->pipe_fds[1], &len,
1167                      sizeof(len));
1168         }
1169         for (addr_list_p = hp->h_addr_list; *addr_list_p != NULL;
1170              addr_list_p++) {
1171                 memcpy(&ad.sin_addr, *addr_list_p, hp->h_length);
1172                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1173                              sizeof(ai_member));
1174                 fd_write_all(parm->pipe_fds[1], (gchar *)&ad, sizeof(ad));
1175         }
1176 #endif /* INET6 */
1177
1178         close(parm->pipe_fds[1]);
1179         parm->pipe_fds[1] = -1;
1180
1181 #ifdef G_OS_WIN32
1182         _endthread();
1183 #else
1184         _exit(0);
1185 #endif
1186 }
1187
1188 static SockLookupData *sock_get_address_info_async(const gchar *hostname,
1189                                                    gushort port,
1190                                                    SockAddrFunc func,
1191                                                    gpointer data)
1192 {
1193         SockLookupData *lookup_data = NULL;
1194         
1195         refresh_resolvers();
1196
1197         lookup_data = g_new0(SockLookupData, 1);
1198         lookup_data->hostname = g_strdup(hostname);
1199         lookup_data->func = func;
1200         lookup_data->data = data;
1201         lookup_data->port = port;
1202         lookup_data->child_pid = (pid_t)(-1);
1203         lookup_data->pipe_fds[0] = -1;
1204         lookup_data->pipe_fds[1] = -1;
1205
1206         if (pipe(lookup_data->pipe_fds) < 0) {
1207                 perror("pipe");
1208                 func(NULL, data);
1209                 g_free (lookup_data->hostname);
1210                 g_free (lookup_data);
1211                 return NULL;
1212         }
1213
1214 #ifndef G_OS_WIN32
1215         if ((lookup_data->child_pid = fork()) < 0) {
1216                 perror("fork");
1217                 func(NULL, data);
1218                 g_free (lookup_data->hostname);
1219                 g_free (lookup_data);
1220                 return NULL;
1221         }
1222
1223         if (lookup_data->child_pid == 0) {
1224                 /* Child process. */
1225                 address_info_async_child (lookup_data);
1226                 g_assert_not_reached ();
1227         }
1228         /* Parent process. */
1229         close(lookup_data->pipe_fds[1]);
1230         lookup_data->pipe_fds[1] = -1;
1231 #endif  /*!G_OS_WIN32 */
1232         
1233 #ifndef G_OS_WIN32
1234         lookup_data->channel = g_io_channel_unix_new(lookup_data->pipe_fds[0]);
1235 #else
1236         lookup_data->channel = g_io_channel_win32_new_fd(lookup_data->pipe_fds[0]);
1237 #endif
1238         lookup_data->io_tag = g_io_add_watch(lookup_data->channel, G_IO_IN,
1239                                              sock_get_address_info_async_cb,
1240                                              lookup_data);
1241 #ifdef G_OS_WIN32
1242         lookup_data->child_pid = _beginthread(
1243                 address_info_async_child, 0, lookup_data);
1244 #endif
1245
1246         return lookup_data;
1247 }
1248
1249 static gint sock_get_address_info_async_cancel(SockLookupData *lookup_data)
1250 {
1251         if (lookup_data->io_tag > 0)
1252                 g_source_remove(lookup_data->io_tag);
1253         if (lookup_data->channel) {
1254                 GError *err = NULL;
1255                 g_io_channel_shutdown(lookup_data->channel, TRUE, &err);
1256                 if (err)
1257                         g_error_free(err);
1258
1259                 g_io_channel_unref(lookup_data->channel);
1260         }
1261
1262         if (lookup_data->child_pid > 0) {
1263 #ifdef G_OS_WIN32
1264                 /* FIXME: Need a way to cancel the thread. */
1265 #else
1266                 kill(lookup_data->child_pid, SIGKILL);
1267                 waitpid(lookup_data->child_pid, NULL, 0);
1268 #endif
1269         }
1270
1271         g_free(lookup_data->canonical_name);
1272         g_free(lookup_data->hostname);
1273         g_free(lookup_data);
1274
1275         return 0;
1276 }
1277
1278
1279 static SockInfo *sockinfo_from_fd(const gchar *hostname,
1280                                   gushort port,
1281                                   gint sock)
1282 {
1283         SockInfo *sockinfo;
1284
1285         sockinfo = g_new0(SockInfo, 1);
1286         sockinfo->sock = sock;
1287 #ifndef G_OS_WIN32
1288         sockinfo->sock_ch = g_io_channel_unix_new(sock);
1289 #else
1290         sockinfo->sock_ch = g_io_channel_win32_new_socket(sock);
1291 #endif
1292         sockinfo->hostname = g_strdup(hostname);
1293         sockinfo->port = port;
1294         sockinfo->state = CONN_ESTABLISHED;
1295
1296         return sockinfo;
1297 }
1298
1299 static gint fd_read(gint fd, gchar *buf, gint len)
1300 {
1301         if (fd_check_io(fd, G_IO_IN) < 0)
1302                 return -1;
1303
1304         if (fd_is_w32_socket(fd))
1305                 return recv(fd, buf, len, 0);
1306         return read(fd, buf, len);
1307 }
1308
1309 #if USE_OPENSSL
1310 static gint ssl_read(SSL *ssl, gchar *buf, gint len)
1311 {
1312         gint err, ret;
1313
1314         if (SSL_pending(ssl) == 0) {
1315                 if (fd_check_io(SSL_get_rfd(ssl), G_IO_IN) < 0)
1316                         return -1;
1317         }
1318
1319         ret = SSL_read(ssl, buf, len);
1320
1321         switch ((err = SSL_get_error(ssl, ret))) {
1322         case SSL_ERROR_NONE:
1323                 return ret;
1324         case SSL_ERROR_WANT_READ:
1325         case SSL_ERROR_WANT_WRITE:
1326                 errno = EAGAIN;
1327                 return -1;
1328         case SSL_ERROR_ZERO_RETURN:
1329                 return 0;
1330         default:
1331                 g_warning("SSL_read() returned error %d, ret = %d\n", err, ret);
1332                 if (ret == 0)
1333                         return 0;
1334                 return -1;
1335         }
1336 }
1337 #elif USE_GNUTLS
1338 static gint ssl_read(gnutls_session ssl, gchar *buf, gint len)
1339 {
1340         gint r;
1341
1342         if (gnutls_record_check_pending(ssl) == 0) {
1343                 if (fd_check_io(GPOINTER_TO_INT(gnutls_transport_get_ptr(ssl)), G_IO_IN) < 0)
1344                         return -1;
1345         }
1346
1347         while (1) {
1348                 r = gnutls_record_recv(ssl, buf, len);
1349                 if (r > 0)
1350                         return r;
1351
1352                 switch (r) {
1353                 case 0: /* closed connection */
1354                         return -1;
1355
1356                 case GNUTLS_E_AGAIN:
1357                 case GNUTLS_E_INTERRUPTED:
1358                         errno = EAGAIN;
1359                         return -1;
1360                 break;
1361
1362                 default:
1363                         return -1;
1364                 }
1365         }
1366
1367 }
1368 #endif
1369
1370 gint sock_read(SockInfo *sock, gchar *buf, gint len)
1371 {
1372         gint ret;
1373
1374         g_return_val_if_fail(sock != NULL, -1);
1375
1376 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1377         if (sock->ssl)
1378                 ret = ssl_read(sock->ssl, buf, len);
1379         else
1380 #endif
1381                 ret = fd_read(sock->sock, buf, len);
1382         
1383         if (ret < 0)
1384                 sock->state = CONN_DISCONNECTED;
1385         return ret;
1386 }
1387
1388 gint fd_write(gint fd, const gchar *buf, gint len)
1389 {
1390         if (fd_check_io(fd, G_IO_OUT) < 0)
1391                 return -1;
1392
1393         if (fd_is_w32_socket (fd))
1394                 return send(fd, buf, len, 0);
1395         return write(fd, buf, len);
1396 }
1397
1398 #if USE_OPENSSL
1399 static gint ssl_write(SSL *ssl, const gchar *buf, gint len)
1400 {
1401         gint ret;
1402
1403         ret = SSL_write(ssl, buf, len);
1404
1405         switch (SSL_get_error(ssl, ret)) {
1406         case SSL_ERROR_NONE:
1407                 return ret;
1408         case SSL_ERROR_WANT_READ:
1409         case SSL_ERROR_WANT_WRITE:
1410                 errno = EAGAIN;
1411                 return -1;
1412         default:
1413                 return -1;
1414         }
1415 }
1416 #elif USE_GNUTLS
1417 static gint ssl_write(gnutls_session ssl, const gchar *buf, gint len)
1418 {
1419         gint ret;
1420
1421         if (fd_check_io(GPOINTER_TO_INT(gnutls_transport_get_ptr(ssl)), G_IO_OUT) < 0)
1422                 return -1;
1423
1424         ret = gnutls_record_send(ssl, buf, len);
1425
1426         switch (ret) {
1427         case 0:
1428                 return -1;
1429         case GNUTLS_E_AGAIN:
1430         case GNUTLS_E_INTERRUPTED:
1431                 return 0;
1432
1433         default:
1434                 return ret;
1435         }
1436 }
1437
1438 #endif
1439
1440 gint sock_write(SockInfo *sock, const gchar *buf, gint len)
1441 {
1442         gint ret;
1443
1444         g_return_val_if_fail(sock != NULL, -1);
1445
1446 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1447         if (sock->ssl)
1448                 ret = ssl_write(sock->ssl, buf, len);
1449         else
1450 #endif
1451                 ret = fd_write(sock->sock, buf, len);
1452
1453         if (ret < 0)
1454                 sock->state = CONN_DISCONNECTED;
1455         return ret;
1456 }
1457
1458 gint fd_write_all(gint fd, const gchar *buf, gint len)
1459 {
1460         gint n, wrlen = 0;
1461
1462         while (len) {
1463                 if (fd_check_io(fd, G_IO_OUT) < 0)
1464                         return -1;
1465 #ifndef G_OS_WIN32
1466                 signal(SIGPIPE, SIG_IGN);
1467 #endif
1468                 if (fd_is_w32_socket(fd))
1469                         n = send(fd, buf, len, 0);
1470                 else
1471                         n = write(fd, buf, len);
1472
1473                 if (n <= 0) {
1474                         log_error(LOG_PROTOCOL, _("write on fd%d: %s\n"), fd, strerror(errno));
1475                         return -1;
1476                 }
1477                 len -= n;
1478                 wrlen += n;
1479                 buf += n;
1480         }
1481
1482         return wrlen;
1483 }
1484
1485 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1486 #if USE_OPENSSL
1487 static gint ssl_write_all(SSL *ssl, const gchar *buf, gint len)
1488 #else
1489 static gint ssl_write_all(gnutls_session ssl, const gchar *buf, gint len)
1490 #endif
1491 {
1492         gint n, wrlen = 0;
1493
1494         while (len) {
1495                 n = ssl_write(ssl, buf, len);
1496                 if (n <= 0)
1497                         return -1;
1498                 len -= n;
1499                 wrlen += n;
1500                 buf += n;
1501         }
1502
1503         return wrlen;
1504 }
1505 #endif
1506
1507 gint sock_write_all(SockInfo *sock, const gchar *buf, gint len)
1508 {
1509         gint ret;
1510
1511         g_return_val_if_fail(sock != NULL, -1);
1512
1513 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1514         if (sock->ssl)
1515                 ret = ssl_write_all(sock->ssl, buf, len);
1516         else
1517 #endif
1518                 ret = fd_write_all(sock->sock, buf, len);
1519
1520         if (ret < 0)
1521                 sock->state = CONN_DISCONNECTED;
1522         return ret;
1523 }
1524
1525 static gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
1526 {
1527         if (fd_check_io(fd, G_IO_IN) < 0)
1528                 return -1;
1529
1530         return recv(fd, buf, len, flags);
1531 }
1532
1533 gint fd_gets(gint fd, gchar *buf, gint len)
1534 {
1535         gchar *newline, *bp = buf;
1536         gint n;
1537
1538         if (--len < 1)
1539                 return -1;
1540
1541 #ifdef G_OS_WIN32
1542         do {
1543 /*
1544 XXX:tm try nonblock
1545 MSKB Article ID: Q147714 
1546 Windows Sockets 2 Service Provider Interface Limitations
1547 Polling with recv(MSG_PEEK) to determine when a complete message 
1548 has arrived.
1549     Reason and Workaround not available.
1550
1551 Single-byte send() and recv(). 
1552     Reason: Couple one-byte sends with Nagle disabled.
1553     Workaround: Send modest amounts and receive as much as possible.
1554 (still unused)
1555 */
1556                 if (recv(fd, bp, 1, 0) <= 0)
1557                         return -1;
1558                 if (*bp == '\n')
1559                         break;
1560                 bp++;
1561                 len--;
1562         } while (0 < len);
1563 #else /*!G_OS_WIN32*/
1564         do {
1565                 if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
1566                         return -1;
1567                 if ((newline = memchr(bp, '\n', n)) != NULL)
1568                         n = newline - bp + 1;
1569                 if ((n = fd_read(fd, bp, n)) < 0)
1570                         return -1;
1571                 bp += n;
1572                 len -= n;
1573         } while (!newline && len);
1574 #endif /*!G_OS_WIN32*/
1575
1576         *bp = '\0';
1577         return bp - buf;
1578 }
1579
1580 gint sock_close(SockInfo *sock)
1581 {
1582         gint ret;
1583
1584         if (!sock)
1585                 return 0;
1586
1587         if (sock->sock_ch)
1588                 g_io_channel_unref(sock->sock_ch);
1589
1590 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1591         if (sock->ssl)
1592                 ssl_done_socket(sock);
1593         if (sock->g_source != 0)
1594                 g_source_remove(sock->g_source);
1595         sock->g_source = 0;
1596 #endif
1597 #ifdef G_OS_WIN32
1598         shutdown(sock->sock, 1); /* complete transfer before close */
1599         ret = closesocket(sock->sock);
1600 #else
1601         ret = fd_close(sock->sock); 
1602 #endif
1603
1604         g_free(sock->canonical_name);
1605         g_free(sock->hostname);
1606         g_free(sock);
1607
1608         return ret;
1609 }
1610
1611 gint fd_close(gint fd)
1612 {
1613         return close(fd);
1614 }