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