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