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