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