2008-11-05 [colin] 3.6.1cvs18
[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 #  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         g_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         g_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 = sock->condition;
472         
473         if (!sock || !sock->sock)
474                 return FALSE;
475
476         FD_ZERO(&fds);
477         FD_SET(sock->sock, &fds);
478
479         select(sock->sock + 1,
480                (condition & G_IO_IN)  ? &fds : NULL,
481                (condition & G_IO_OUT) ? &fds : NULL,
482                NULL, &timeout);
483
484         return FD_ISSET(sock->sock, &fds) != 0;
485 }
486
487 static gboolean sock_dispatch(GSource *source, GSourceFunc callback,
488                               gpointer user_data)
489 {
490         SockInfo *sock = ((SockSource *)source)->sock;
491
492         if (!sock || !sock->callback || !sock->data)
493                 return FALSE;
494
495         return sock->callback(sock, sock->condition, sock->data);
496 }
497
498 static gboolean sock_watch_cb(GIOChannel *source, GIOCondition condition,
499                               gpointer data)
500 {
501         SockInfo *sock = (SockInfo *)data;
502
503         if ((condition & sock->condition) == 0)
504                 return TRUE;
505
506         return sock->callback(sock, sock->condition, sock->data);
507 }
508
509 guint sock_add_watch(SockInfo *sock, GIOCondition condition, SockFunc func,
510                      gpointer data)
511 {
512         if (!sock)
513                 return FALSE;
514
515         sock->callback = func;
516         sock->condition = condition;
517         sock->data = data;
518
519 #ifdef USE_GNUTLS
520         if (sock->ssl)
521         {
522                 GSource *source = g_source_new(&sock_watch_funcs,
523                                                sizeof(SockSource));
524                 ((SockSource *) source)->sock = sock;
525                 g_source_set_priority(source, G_PRIORITY_DEFAULT);
526                 g_source_set_can_recurse(source, FALSE);
527                 sock->g_source = g_source_attach(source, NULL);
528                 g_source_unref (source); /* Refcount back down to 1 */
529                 return sock->g_source;
530         }
531 #endif
532
533         return g_io_add_watch(sock->sock_ch, condition, sock_watch_cb, sock);
534 }
535
536 static gint fd_check_io(gint fd, GIOCondition cond)
537 {
538         struct timeval timeout;
539         fd_set fds;
540
541         if (is_nonblocking_mode(fd))
542                 return 0;
543
544         timeout.tv_sec  = io_timeout;
545         timeout.tv_usec = 0;
546
547         FD_ZERO(&fds);
548         FD_SET(fd, &fds);
549
550         if (cond == G_IO_IN) {
551                 select(fd + 1, &fds, NULL, NULL,
552                        io_timeout > 0 ? &timeout : NULL);
553         } else {
554                 select(fd + 1, NULL, &fds, NULL,
555                        io_timeout > 0 ? &timeout : NULL);
556         }
557
558         if (FD_ISSET(fd, &fds)) {
559                 return 0;
560         } else {
561                 g_warning("Socket IO timeout\n");
562                 return -1;
563         }
564 }
565
566 #ifdef G_OS_UNIX
567 static sigjmp_buf jmpenv;
568
569 static void timeout_handler(gint sig)
570 {
571         siglongjmp(jmpenv, 1);
572 }
573 #endif /*G_OS_UNIX*/
574
575 static gint sock_connect_with_timeout(gint sock,
576                                       const struct sockaddr *serv_addr,
577                                       gint addrlen,
578                                       guint timeout_secs)
579 {
580         gint ret;
581 #ifdef G_OS_UNIX
582         void (*prev_handler)(gint);
583         
584         alarm(0);
585         prev_handler = signal(SIGALRM, timeout_handler);
586         if (sigsetjmp(jmpenv, 1)) {
587                 alarm(0);
588                 signal(SIGALRM, prev_handler);
589                 errno = ETIMEDOUT;
590                 return -1;
591         }
592         alarm(timeout_secs);
593 #endif
594
595         ret = connect(sock, serv_addr, addrlen);
596
597 #ifdef G_OS_UNIX
598         alarm(0);
599         signal(SIGALRM, prev_handler);
600 #endif
601
602         return ret;
603 }
604
605 struct hostent *my_gethostbyname(const gchar *hostname)
606 {
607         struct hostent *hp;
608 #ifdef G_OS_UNIX
609         void (*prev_handler)(gint);
610         
611         alarm(0);
612         prev_handler = signal(SIGALRM, timeout_handler);
613         if (sigsetjmp(jmpenv, 1)) {
614                 alarm(0);
615                 signal(SIGALRM, prev_handler);
616                 g_printerr("%s: host lookup timed out.\n", hostname);
617                 errno = 0;
618                 return NULL;
619         }
620         alarm(io_timeout);
621 #endif
622
623         if ((hp = gethostbyname(hostname)) == NULL) {
624 #ifdef G_OS_UNIX
625                 alarm(0);
626                 signal(SIGALRM, prev_handler);
627 #endif
628                 g_printerr("%s: unknown host.\n", hostname);
629                 errno = 0;
630                 return NULL;
631         }
632
633 #ifdef G_OS_UNIX
634         alarm(0);
635         signal(SIGALRM, prev_handler);
636 #endif
637
638         return hp;
639 }
640
641 #ifndef INET6
642 static gint my_inet_aton(const gchar *hostname, struct in_addr *inp)
643 {
644 #if HAVE_INET_ATON
645         return inet_aton(hostname, inp);
646 #else
647 #if HAVE_INET_ADDR
648         guint32 inaddr;
649
650         inaddr = inet_addr(hostname);
651         if (inaddr != -1) {
652                 memcpy(inp, &inaddr, sizeof(inaddr));
653                 return 1;
654         } else
655                 return 0;
656 #else
657         return 0;
658 #endif
659 #endif /* HAVE_INET_ATON */
660 }
661
662 static gint sock_connect_by_hostname(gint sock, const gchar *hostname,
663                                      gushort port)
664 {
665         struct hostent *hp;
666         struct sockaddr_in ad;
667
668         memset(&ad, 0, sizeof(ad));
669         ad.sin_family = AF_INET;
670         ad.sin_port = htons(port);
671
672         refresh_resolvers();
673
674         if (!my_inet_aton(hostname, &ad.sin_addr)) {
675                 if ((hp = my_gethostbyname(hostname)) == NULL) {
676                         g_printerr("%s: unknown host.\n", hostname);
677                         errno = 0;
678                         return -1;
679                 }
680
681                 if (hp->h_length != 4 && hp->h_length != 8) {
682                         g_printerr("illegal address length received for host %s\n", hostname);
683                         errno = 0;
684                         return -1;
685                 }
686
687                 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
688         }
689
690         return sock_connect_with_timeout(sock, (struct sockaddr *)&ad,
691                                          sizeof(ad), io_timeout);
692 }
693
694 #else /* INET6 */
695 static gint sock_connect_by_getaddrinfo(const gchar *hostname, gushort  port)
696 {
697         gint sock = -1, gai_error;
698         struct addrinfo hints, *res, *ai;
699         gchar port_str[6];
700
701         refresh_resolvers();
702
703         memset(&hints, 0, sizeof(hints));
704         /* hints.ai_flags = AI_CANONNAME; */
705         hints.ai_family = AF_UNSPEC;
706         hints.ai_socktype = SOCK_STREAM;
707         hints.ai_protocol = IPPROTO_TCP;
708
709         /* convert port from integer to string. */
710         g_snprintf(port_str, sizeof(port_str), "%d", port);
711
712         if ((gai_error = getaddrinfo(hostname, port_str, &hints, &res)) != 0) {
713                 g_printerr("getaddrinfo for %s:%s failed: %s\n",
714                         hostname, port_str, gai_strerror(gai_error));
715                 return -1;
716         }
717
718         for (ai = res; ai != NULL; ai = ai->ai_next) {
719                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
720                 if (sock < 0)
721                         continue;
722
723                 if (sock_connect_with_timeout
724                         (sock, ai->ai_addr, ai->ai_addrlen, io_timeout) == 0)
725                         break;
726
727                 close(sock);
728         }
729
730         if (res != NULL)
731                 freeaddrinfo(res);
732
733         if (ai == NULL)
734                 return -1;
735
736         return sock;
737 }
738 #endif /* !INET6 */
739
740 SockInfo *sock_connect(const gchar *hostname, gushort port)
741 {
742 #ifdef G_OS_WIN32
743         SOCKET sock;
744 #else
745         gint sock;
746 #endif
747
748 #ifdef INET6
749         if ((sock = sock_connect_by_getaddrinfo(hostname, port)) < 0)
750                 return NULL;
751 #else
752 #ifdef G_OS_WIN32
753         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
754                 g_warning("socket() failed: %d\n", WSAGetLastError());
755 #else
756         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
757                 perror("socket");
758 #endif /* G_OS_WIN32 */
759                 return NULL;
760         }
761
762         if (sock_connect_by_hostname(sock, hostname, port) < 0) {
763                 if (errno != 0) perror("connect");
764                 close(sock);
765                 return NULL;
766         }
767 #endif /* INET6 */
768
769         return sockinfo_from_fd(hostname, port, sock);
770 }
771
772
773 static void sock_address_list_free(GList *addr_list)
774 {
775         GList *cur;
776
777         for (cur = addr_list; cur != NULL; cur = cur->next) {
778                 SockAddrData *addr_data = (SockAddrData *)cur->data;
779                 g_free(addr_data->addr);
780                 g_free(addr_data);
781         }
782
783         g_list_free(addr_list);
784 }
785
786 /* asynchronous TCP connection */
787
788 static gboolean sock_connect_async_cb(GIOChannel *source,
789                                       GIOCondition condition, gpointer data)
790 {
791         SockConnectData *conn_data = (SockConnectData *)data;
792         gint fd;
793         gint val;
794         guint len;
795         SockInfo *sockinfo;
796
797         if (conn_data->io_tag == 0 && conn_data->channel == NULL)
798                 return FALSE;
799
800         fd = g_io_channel_unix_get_fd(source);
801
802         conn_data->io_tag = 0;
803         conn_data->channel = NULL;
804         g_io_channel_unref(source);
805
806         len = sizeof(val);
807         if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &len) < 0) {
808                 perror("getsockopt");
809                 close(fd);
810                 sock_connect_address_list_async(conn_data);
811                 return FALSE;
812         }
813
814         if (val != 0) {
815                 close(fd);
816                 sock_connect_address_list_async(conn_data);
817                 return FALSE;
818         }
819
820         sockinfo = g_new0(SockInfo, 1);
821         sockinfo->sock = fd;
822 #ifndef G_OS_WIN32
823         sockinfo->sock_ch = g_io_channel_unix_new(fd);
824 #else
825         sockinfo->sock_ch = g_io_channel_win32_new_socket(fd);
826 #endif
827         sockinfo->hostname = g_strdup(conn_data->hostname);
828         sockinfo->port = conn_data->port;
829         sockinfo->state = CONN_ESTABLISHED;
830         sockinfo->canonical_name = g_strdup(conn_data->canonical_name);
831
832         conn_data->func(sockinfo, conn_data->data);
833
834         sock_connect_async_cancel(conn_data->id);
835
836         return FALSE;
837 }
838
839 static gint sock_connect_async_get_address_info_cb(GList *addr_list,
840                                                    gpointer data)
841 {
842         SockConnectData *conn_data = (SockConnectData *)data;
843
844         conn_data->addr_list = addr_list;
845         conn_data->cur_addr = addr_list;
846         if (conn_data->lookup_data) {
847                 conn_data->canonical_name = conn_data->lookup_data->canonical_name;
848                 conn_data->lookup_data->canonical_name = NULL;
849                 conn_data->lookup_data = NULL;
850         }
851         return sock_connect_address_list_async(conn_data);
852 }
853
854 gint sock_connect_async(const gchar *hostname, gushort port,
855                         SockConnectFunc func, gpointer data)
856 {
857         static gint id = 1;
858         SockConnectData *conn_data;
859
860         conn_data = g_new0(SockConnectData, 1);
861         conn_data->id = id++;
862         conn_data->hostname = g_strdup(hostname);
863         conn_data->port = port;
864         conn_data->addr_list = NULL;
865         conn_data->cur_addr = NULL;
866         conn_data->io_tag = 0;
867         conn_data->func = func;
868         conn_data->data = data;
869
870         conn_data->lookup_data = sock_get_address_info_async
871                 (hostname, port, sock_connect_async_get_address_info_cb,
872                  conn_data);
873
874         if (conn_data->lookup_data == NULL) {
875                 g_free(conn_data->hostname);
876                 g_free(conn_data);
877                 return -1;
878         }
879
880         sock_connect_data_list = g_list_append(sock_connect_data_list,
881                                                conn_data);
882
883         return conn_data->id;
884 }
885
886 gint sock_connect_async_cancel(gint id)
887 {
888         SockConnectData *conn_data = NULL;
889         GList *cur;
890
891         for (cur = sock_connect_data_list; cur != NULL; cur = cur->next) {
892                 if (((SockConnectData *)cur->data)->id == id) {
893                         conn_data = (SockConnectData *)cur->data;
894                         break;
895                 }
896         }
897
898         if (conn_data) {
899                 sock_connect_data_list = g_list_remove(sock_connect_data_list,
900                                                        conn_data);
901
902                 if (conn_data->lookup_data)
903                         sock_get_address_info_async_cancel
904                                 (conn_data->lookup_data);
905
906                 if (conn_data->io_tag > 0)
907                         g_source_remove(conn_data->io_tag);
908                 if (conn_data->channel) {
909                         GError *err = NULL;
910                         g_io_channel_shutdown(conn_data->channel, TRUE, &err);
911                         if (err)
912                                 g_error_free(err);
913                         g_io_channel_unref(conn_data->channel);
914                 }
915
916                 sock_address_list_free(conn_data->addr_list);
917                 g_free(conn_data->canonical_name);
918                 g_free(conn_data->hostname);
919                 g_free(conn_data);
920         } else {
921                 g_warning("sock_connect_async_cancel: id %d not found.\n", id);
922                 return -1;
923         }
924
925         return 0;
926 }
927
928 static gint sock_connect_address_list_async(SockConnectData *conn_data)
929 {
930         SockAddrData *addr_data;
931         gint sock = -1;
932
933         for (; conn_data->cur_addr != NULL;
934              conn_data->cur_addr = conn_data->cur_addr->next) {
935                 addr_data = (SockAddrData *)conn_data->cur_addr->data;
936
937                 if ((sock = socket(addr_data->family, addr_data->socktype,
938                                    addr_data->protocol)) < 0) {
939                         perror("socket");
940                         continue;
941                 }
942
943                 set_nonblocking_mode(sock, TRUE);
944
945                 if (connect(sock, addr_data->addr, addr_data->addr_len) < 0) {
946                         if (EINPROGRESS == errno) {
947                                 break;
948                         } else {
949                                 perror("connect");
950                                 close(sock);
951                         }
952                 } else
953                         break;
954         }
955
956         if (conn_data->cur_addr == NULL) {
957                 g_warning("sock_connect_address_list_async: "
958                           "connection to %s:%d failed\n",
959                           conn_data->hostname, conn_data->port);
960                 conn_data->func(NULL, conn_data->data);
961                 sock_connect_async_cancel(conn_data->id);
962                 return -1;
963         }
964
965         conn_data->cur_addr = conn_data->cur_addr->next;
966
967 #ifndef G_OS_WIN32
968         conn_data->channel = g_io_channel_unix_new(sock);
969 #else
970         conn_data->channel = g_io_channel_win32_new_socket(sock);
971 #endif
972         conn_data->io_tag = g_io_add_watch(conn_data->channel, G_IO_IN|G_IO_OUT,
973                                            sock_connect_async_cb, conn_data);
974
975         return 0;
976 }
977
978 /* asynchronous DNS lookup */
979
980 static gboolean sock_get_address_info_async_cb(GIOChannel *source,
981                                                GIOCondition condition,
982                                                gpointer data)
983 {
984         SockLookupData *lookup_data = (SockLookupData *)data;
985         GList *addr_list = NULL;
986         SockAddrData *addr_data;
987         gsize bytes_read;
988         gint ai_member[4];
989         struct sockaddr *addr;
990         gchar *canonical_name = NULL;
991         gchar len = 0;
992         GError *err = NULL;
993         
994         g_io_channel_set_encoding(source, NULL, &err);
995         if (err) {
996                 g_warning("can unset encoding: %s\n", err->message);
997                 g_error_free(err);
998                 return FALSE;
999         }
1000         g_io_channel_set_buffered(source, FALSE);
1001         if (g_io_channel_read_chars(source, &len, sizeof(len),
1002                               &bytes_read, &err) == G_IO_STATUS_NORMAL) {
1003                 if (err != NULL) {
1004                         g_warning("g_io_channel_read_chars: %s\n", err->message);
1005                         g_error_free(err);
1006                         return FALSE;
1007                 } 
1008                 if (bytes_read == sizeof(len) && len > 0) {
1009                         gchar *cur = NULL;
1010                         gint todo = len;
1011                         canonical_name = g_malloc0(len + 1);
1012                         cur = canonical_name;
1013                         while (todo > 0) {
1014                                 if (g_io_channel_read_chars(source, cur, todo,
1015                                       &bytes_read, &err) != G_IO_STATUS_NORMAL) {
1016                                         if (err) {
1017                                               g_warning("canonical name not read %s\n", err->message);
1018                                               g_free(canonical_name);
1019                                               canonical_name = NULL;
1020                                               g_error_free(err);
1021                                               err = NULL;
1022                                               break;
1023                                         }
1024                                 } else {
1025                                         cur += bytes_read;
1026                                         todo -= bytes_read;
1027                                 }
1028                                 if (bytes_read == 0) {
1029                                       g_warning("canonical name not read\n");
1030                                       g_free(canonical_name);
1031                                       canonical_name = NULL;
1032                                       break;
1033                                 }
1034                         }
1035                 }             
1036         }
1037         for (;;) {
1038                 if (g_io_channel_read_chars(source, (gchar *)ai_member,
1039                                       sizeof(ai_member), &bytes_read, &err) 
1040                     != G_IO_STATUS_NORMAL) {
1041                         if (err != NULL) {
1042                                 g_warning("g_io_channel_read_chars: addr len %s\n", err->message);
1043                                 g_error_free(err);
1044                                 err = NULL;
1045                                 break;
1046                         } 
1047                 }
1048
1049                 if (bytes_read == 0 || bytes_read != sizeof(ai_member))
1050                         break;
1051
1052                 if (ai_member[0] == AF_UNSPEC) {
1053                         g_warning("DNS lookup failed\n");
1054                         break;
1055                 }
1056
1057                 addr = g_malloc(ai_member[3]);
1058                 if (g_io_channel_read_chars(source, (gchar *)addr, ai_member[3],
1059                                       &bytes_read, &err) 
1060                     != G_IO_STATUS_NORMAL) {
1061                         if (err != NULL) {
1062                                 g_warning("g_io_channel_read_chars: addr data read %s\n", err->message);
1063                                 g_error_free(err);
1064                                 err = NULL;
1065                                 g_free(addr);
1066                                 break;
1067                         } 
1068                 }
1069
1070                 if (bytes_read != ai_member[3]) {
1071                         g_warning("sock_get_address_info_async_cb: "
1072                                   "incomplete address data\n");
1073                         g_free(addr);
1074                         break;
1075                 }
1076
1077                 addr_data = g_new0(SockAddrData, 1);
1078                 addr_data->family = ai_member[0];
1079                 addr_data->socktype = ai_member[1];
1080                 addr_data->protocol = ai_member[2];
1081                 addr_data->addr_len = ai_member[3];
1082                 addr_data->addr = addr;
1083
1084                 addr_list = g_list_append(addr_list, addr_data);
1085         }
1086
1087         g_io_channel_shutdown(source, TRUE, &err);
1088         if (err)
1089                 g_error_free(err);
1090         g_io_channel_unref(source);
1091
1092 #ifdef G_OS_WIN32
1093         /* FIXME: We would need to cancel the thread. */
1094 #else
1095         kill(lookup_data->child_pid, SIGKILL);
1096         waitpid(lookup_data->child_pid, NULL, 0);
1097 #endif
1098         lookup_data->canonical_name = canonical_name;
1099
1100         lookup_data->func(addr_list, lookup_data->data);
1101
1102         g_free(lookup_data->canonical_name);
1103         g_free(lookup_data->hostname);
1104         g_free(lookup_data);
1105
1106         return FALSE;
1107 }
1108
1109
1110 /* For better readability we use a separate function to implement the
1111    child code of sock_get_address_info_async.  Note, that under W32
1112    this is actually not a child but a thread and this is the reason
1113    why we pass only a void pointer. */
1114 static void address_info_async_child(void *opaque)
1115 {
1116         SockLookupData *parm = opaque;
1117 #ifdef INET6
1118         gint gai_err;
1119         struct addrinfo hints, *res, *ai;
1120         gchar port_str[6];
1121 #else /* !INET6 */
1122         struct hostent *hp;
1123         gchar **addr_list_p;
1124         struct sockaddr_in ad;
1125 #endif /* INET6 */
1126         gint ai_member[4] = {AF_UNSPEC, 0, 0, 0};
1127
1128 #ifndef G_OS_WIN32
1129         close(parm->pipe_fds[0]);
1130         parm->pipe_fds[0] = -1;
1131 #endif
1132
1133 #ifdef INET6
1134         memset(&hints, 0, sizeof(hints));
1135         hints.ai_flags = AI_CANONNAME;
1136         hints.ai_family = AF_UNSPEC;
1137         hints.ai_socktype = SOCK_STREAM;
1138         hints.ai_protocol = IPPROTO_TCP;
1139
1140         g_snprintf(port_str, sizeof(port_str), "%d", parm->port);
1141
1142         gai_err = getaddrinfo(parm->hostname, port_str, &hints, &res);
1143         if (gai_err != 0) {
1144                 gchar len = 0;
1145                 g_warning("getaddrinfo for %s:%s failed: %s\n",
1146                           parm->hostname, port_str, gai_strerror(gai_err));
1147                 fd_write_all(parm->pipe_fds[1], &len,
1148                      sizeof(len));
1149                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1150                              sizeof(ai_member));
1151                 close(parm->pipe_fds[1]);
1152                 parm->pipe_fds[1] = -1;
1153 #ifdef G_OS_WIN32
1154                 _endthread();
1155 #else
1156                 _exit(1);
1157 #endif
1158         }
1159
1160         if (res != NULL) {
1161                 if (res->ai_canonname && strlen(res->ai_canonname) < 255) {
1162                         gchar len = strlen(res->ai_canonname);
1163                         fd_write_all(parm->pipe_fds[1], &len,
1164                              sizeof(len));
1165                         fd_write_all(parm->pipe_fds[1], res->ai_canonname,
1166                              len);                       
1167                 } else {
1168                         gchar len = 0;
1169                         fd_write_all(parm->pipe_fds[1], &len,
1170                              sizeof(len));
1171                 }
1172         } else {
1173                 gchar len = 0;
1174                 fd_write_all(parm->pipe_fds[1], &len,
1175                      sizeof(len));
1176         }
1177
1178         for (ai = res; ai != NULL; ai = ai->ai_next) {
1179                 ai_member[0] = ai->ai_family;
1180                 ai_member[1] = ai->ai_socktype;
1181                 ai_member[2] = ai->ai_protocol;
1182                 ai_member[3] = ai->ai_addrlen;
1183
1184                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1185                              sizeof(ai_member));
1186                 fd_write_all(parm->pipe_fds[1], (gchar *)ai->ai_addr,
1187                              ai->ai_addrlen);
1188         }
1189
1190         if (res != NULL)
1191                 freeaddrinfo(res);
1192 #else /* !INET6 */
1193         hp = my_gethostbyname(parm->hostname);
1194         if (hp == NULL || hp->h_addrtype != AF_INET) {
1195                 gchar len = 0;
1196                 fd_write_all(parm->pipe_fds[1], &len,
1197                      sizeof(len));
1198                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1199                              sizeof(ai_member));
1200                close(parm->pipe_fds[1]);
1201                 parm->pipe_fds[1] = -1;
1202 #ifdef G_OS_WIN32
1203                 _endthread();
1204 #else
1205                 _exit(1);
1206 #endif
1207         }
1208
1209         ai_member[0] = AF_INET;
1210         ai_member[1] = SOCK_STREAM;
1211         ai_member[2] = IPPROTO_TCP;
1212         ai_member[3] = sizeof(ad);
1213
1214         memset(&ad, 0, sizeof(ad));
1215         ad.sin_family = AF_INET;
1216         ad.sin_port = htons(parm->port);
1217
1218         if (hp->h_name && strlen(hp->h_name) < 255) {
1219                 gchar len = strlen(hp->h_name);
1220                 fd_write_all(parm->pipe_fds[1], &len,
1221                      sizeof(len));
1222                 fd_write_all(parm->pipe_fds[1], hp->h_name,
1223                      len);                       
1224         } else {
1225                 gchar len = 0;
1226                 fd_write_all(parm->pipe_fds[1], &len,
1227                      sizeof(len));
1228         }
1229         for (addr_list_p = hp->h_addr_list; *addr_list_p != NULL;
1230              addr_list_p++) {
1231                 memcpy(&ad.sin_addr, *addr_list_p, hp->h_length);
1232                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1233                              sizeof(ai_member));
1234                 fd_write_all(parm->pipe_fds[1], (gchar *)&ad, sizeof(ad));
1235         }
1236 #endif /* INET6 */
1237
1238         close(parm->pipe_fds[1]);
1239         parm->pipe_fds[1] = -1;
1240
1241 #ifdef G_OS_WIN32
1242         _endthread();
1243 #else
1244         _exit(0);
1245 #endif
1246 }
1247
1248 static SockLookupData *sock_get_address_info_async(const gchar *hostname,
1249                                                    gushort port,
1250                                                    SockAddrFunc func,
1251                                                    gpointer data)
1252 {
1253         SockLookupData *lookup_data = NULL;
1254         
1255         refresh_resolvers();
1256
1257         lookup_data = g_new0(SockLookupData, 1);
1258         lookup_data->hostname = g_strdup(hostname);
1259         lookup_data->func = func;
1260         lookup_data->data = data;
1261         lookup_data->port = port;
1262         lookup_data->child_pid = (pid_t)(-1);
1263         lookup_data->pipe_fds[0] = -1;
1264         lookup_data->pipe_fds[1] = -1;
1265
1266         if (pipe(lookup_data->pipe_fds) < 0) {
1267                 perror("pipe");
1268                 func(NULL, data);
1269                 g_free (lookup_data->hostname);
1270                 g_free (lookup_data);
1271                 return NULL;
1272         }
1273
1274 #ifndef G_OS_WIN32
1275         if ((lookup_data->child_pid = fork()) < 0) {
1276                 perror("fork");
1277                 func(NULL, data);
1278                 g_free (lookup_data->hostname);
1279                 g_free (lookup_data);
1280                 return NULL;
1281         }
1282
1283         if (lookup_data->child_pid == 0) {
1284                 /* Child process. */
1285                 address_info_async_child (lookup_data);
1286                 g_assert_not_reached ();
1287         }
1288         /* Parent process. */
1289         close(lookup_data->pipe_fds[1]);
1290         lookup_data->pipe_fds[1] = -1;
1291 #endif  /*!G_OS_WIN32 */
1292         
1293 #ifndef G_OS_WIN32
1294         lookup_data->channel = g_io_channel_unix_new(lookup_data->pipe_fds[0]);
1295 #else
1296         lookup_data->channel = g_io_channel_win32_new_fd(lookup_data->pipe_fds[0]);
1297 #endif
1298         lookup_data->io_tag = g_io_add_watch(lookup_data->channel, G_IO_IN,
1299                                              sock_get_address_info_async_cb,
1300                                              lookup_data);
1301 #ifdef G_OS_WIN32
1302         lookup_data->child_pid = _beginthread(
1303                 address_info_async_child, 0, lookup_data);
1304 #endif
1305
1306         return lookup_data;
1307 }
1308
1309 static gint sock_get_address_info_async_cancel(SockLookupData *lookup_data)
1310 {
1311         if (lookup_data->io_tag > 0)
1312                 g_source_remove(lookup_data->io_tag);
1313         if (lookup_data->channel) {
1314                 GError *err = NULL;
1315                 g_io_channel_shutdown(lookup_data->channel, TRUE, &err);
1316                 if (err)
1317                         g_error_free(err);
1318
1319                 g_io_channel_unref(lookup_data->channel);
1320         }
1321
1322         if (lookup_data->child_pid > 0) {
1323 #ifdef G_OS_WIN32
1324                 /* FIXME: Need a way to cancel the thread. */
1325 #else
1326                 kill(lookup_data->child_pid, SIGKILL);
1327                 waitpid(lookup_data->child_pid, NULL, 0);
1328 #endif
1329         }
1330
1331         g_free(lookup_data->canonical_name);
1332         g_free(lookup_data->hostname);
1333         g_free(lookup_data);
1334
1335         return 0;
1336 }
1337
1338
1339 static SockInfo *sockinfo_from_fd(const gchar *hostname,
1340                                   gushort port,
1341                                   gint sock)
1342 {
1343         SockInfo *sockinfo;
1344
1345         sockinfo = g_new0(SockInfo, 1);
1346         sockinfo->sock = sock;
1347 #ifndef G_OS_WIN32
1348         sockinfo->sock_ch = g_io_channel_unix_new(sock);
1349 #else
1350         sockinfo->sock_ch = g_io_channel_win32_new_socket(sock);
1351 #endif
1352         sockinfo->hostname = g_strdup(hostname);
1353         sockinfo->port = port;
1354         sockinfo->state = CONN_ESTABLISHED;
1355
1356         return sockinfo;
1357 }
1358
1359 static gint fd_read(gint fd, gchar *buf, gint len)
1360 {
1361         if (fd_check_io(fd, G_IO_IN) < 0)
1362                 return -1;
1363
1364         if (fd_is_w32_socket(fd))
1365                 return recv(fd, buf, len, 0);
1366         return read(fd, buf, len);
1367 }
1368
1369 #if USE_GNUTLS
1370 static gint ssl_read(gnutls_session ssl, gchar *buf, gint len)
1371 {
1372         gint r;
1373
1374         if (gnutls_record_check_pending(ssl) == 0) {
1375                 if (fd_check_io(GPOINTER_TO_INT(gnutls_transport_get_ptr(ssl)), G_IO_IN) < 0)
1376                         return -1;
1377         }
1378
1379         while (1) {
1380                 r = gnutls_record_recv(ssl, buf, len);
1381                 if (r > 0)
1382                         return r;
1383
1384                 switch (r) {
1385                 case 0: /* closed connection */
1386                         return -1;
1387
1388                 case GNUTLS_E_AGAIN:
1389                 case GNUTLS_E_INTERRUPTED:
1390                         errno = EAGAIN;
1391                         return -1;
1392                 break;
1393
1394                 default:
1395                         return -1;
1396                 }
1397         }
1398
1399 }
1400 #endif
1401
1402 gint sock_read(SockInfo *sock, gchar *buf, gint len)
1403 {
1404         gint ret;
1405
1406         g_return_val_if_fail(sock != NULL, -1);
1407
1408 #ifdef USE_GNUTLS
1409         if (sock->ssl)
1410                 ret = ssl_read(sock->ssl, buf, len);
1411         else
1412 #endif
1413                 ret = fd_read(sock->sock, buf, len);
1414         
1415         if (ret < 0)
1416                 sock->state = CONN_DISCONNECTED;
1417         return ret;
1418 }
1419
1420 gint fd_write(gint fd, const gchar *buf, gint len)
1421 {
1422         if (fd_check_io(fd, G_IO_OUT) < 0)
1423                 return -1;
1424
1425         if (fd_is_w32_socket (fd))
1426                 return send(fd, buf, len, 0);
1427         return write(fd, buf, len);
1428 }
1429
1430 #if USE_GNUTLS
1431 static gint ssl_write(gnutls_session ssl, const gchar *buf, gint len)
1432 {
1433         gint ret;
1434
1435         if (fd_check_io(GPOINTER_TO_INT(gnutls_transport_get_ptr(ssl)), G_IO_OUT) < 0)
1436                 return -1;
1437
1438         ret = gnutls_record_send(ssl, buf, len);
1439
1440         switch (ret) {
1441         case 0:
1442                 return -1;
1443         case GNUTLS_E_AGAIN:
1444         case GNUTLS_E_INTERRUPTED:
1445                 return 0;
1446
1447         default:
1448                 return ret;
1449         }
1450 }
1451
1452 #endif
1453
1454 gint sock_write(SockInfo *sock, const gchar *buf, gint len)
1455 {
1456         gint ret;
1457
1458         g_return_val_if_fail(sock != NULL, -1);
1459
1460 #ifdef USE_GNUTLS
1461         if (sock->ssl)
1462                 ret = ssl_write(sock->ssl, buf, len);
1463         else
1464 #endif
1465                 ret = fd_write(sock->sock, buf, len);
1466
1467         if (ret < 0)
1468                 sock->state = CONN_DISCONNECTED;
1469         return ret;
1470 }
1471
1472 gint fd_write_all(gint fd, const gchar *buf, gint len)
1473 {
1474         gint n, wrlen = 0;
1475
1476         while (len) {
1477                 if (fd_check_io(fd, G_IO_OUT) < 0)
1478                         return -1;
1479 #ifndef G_OS_WIN32
1480                 signal(SIGPIPE, SIG_IGN);
1481 #endif
1482                 if (fd_is_w32_socket(fd))
1483                         n = send(fd, buf, len, 0);
1484                 else
1485                         n = write(fd, buf, len);
1486
1487                 if (n <= 0) {
1488                         log_error(LOG_PROTOCOL, _("write on fd%d: %s\n"), fd, strerror(errno));
1489                         return -1;
1490                 }
1491                 len -= n;
1492                 wrlen += n;
1493                 buf += n;
1494         }
1495
1496         return wrlen;
1497 }
1498
1499 #ifdef USE_GNUTLS
1500 static gint ssl_write_all(gnutls_session ssl, const gchar *buf, gint len)
1501 {
1502         gint n, wrlen = 0;
1503
1504         while (len) {
1505                 n = ssl_write(ssl, buf, len);
1506                 if (n <= 0)
1507                         return -1;
1508                 len -= n;
1509                 wrlen += n;
1510                 buf += n;
1511         }
1512
1513         return wrlen;
1514 }
1515 #endif
1516
1517 gint sock_write_all(SockInfo *sock, const gchar *buf, gint len)
1518 {
1519         gint ret;
1520
1521         g_return_val_if_fail(sock != NULL, -1);
1522
1523 #ifdef USE_GNUTLS
1524         if (sock->ssl)
1525                 ret = ssl_write_all(sock->ssl, buf, len);
1526         else
1527 #endif
1528                 ret = fd_write_all(sock->sock, buf, len);
1529
1530         if (ret < 0)
1531                 sock->state = CONN_DISCONNECTED;
1532         return ret;
1533 }
1534
1535 static gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
1536 {
1537         if (fd_check_io(fd, G_IO_IN) < 0)
1538                 return -1;
1539
1540         return recv(fd, buf, len, flags);
1541 }
1542
1543 gint fd_gets(gint fd, gchar *buf, gint len)
1544 {
1545         gchar *newline, *bp = buf;
1546         gint n;
1547
1548         if (--len < 1)
1549                 return -1;
1550
1551 #ifdef G_OS_WIN32
1552         do {
1553 /*
1554 XXX:tm try nonblock
1555 MSKB Article ID: Q147714 
1556 Windows Sockets 2 Service Provider Interface Limitations
1557 Polling with recv(MSG_PEEK) to determine when a complete message 
1558 has arrived.
1559     Reason and Workaround not available.
1560
1561 Single-byte send() and recv(). 
1562     Reason: Couple one-byte sends with Nagle disabled.
1563     Workaround: Send modest amounts and receive as much as possible.
1564 (still unused)
1565 */
1566                 if (recv(fd, bp, 1, 0) <= 0)
1567                         return -1;
1568                 if (*bp == '\n')
1569                         break;
1570                 bp++;
1571                 len--;
1572         } while (0 < len);
1573 #else /*!G_OS_WIN32*/
1574         do {
1575                 if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
1576                         return -1;
1577                 if ((newline = memchr(bp, '\n', n)) != NULL)
1578                         n = newline - bp + 1;
1579                 if ((n = fd_read(fd, bp, n)) < 0)
1580                         return -1;
1581                 bp += n;
1582                 len -= n;
1583         } while (!newline && len);
1584 #endif /*!G_OS_WIN32*/
1585
1586         *bp = '\0';
1587         return bp - buf;
1588 }
1589
1590 gint sock_close(SockInfo *sock)
1591 {
1592         gint ret;
1593
1594         if (!sock)
1595                 return 0;
1596
1597         if (sock->sock_ch)
1598                 g_io_channel_unref(sock->sock_ch);
1599
1600 #ifdef USE_GNUTLS
1601         if (sock->ssl)
1602                 ssl_done_socket(sock);
1603         if (sock->g_source != 0)
1604                 g_source_remove(sock->g_source);
1605         sock->g_source = 0;
1606 #endif
1607 #ifdef G_OS_WIN32
1608         shutdown(sock->sock, 1); /* complete transfer before close */
1609         ret = closesocket(sock->sock);
1610 #else
1611         ret = fd_close(sock->sock); 
1612 #endif
1613
1614         g_free(sock->canonical_name);
1615         g_free(sock->hostname);
1616         g_free(sock);
1617
1618         return ret;
1619 }
1620
1621 gint fd_close(gint fd)
1622 {
1623         return close(fd);
1624 }