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