81ff2f96c8210984c5767b1a2ffd49448a553907
[claws.git] / src / common / socket.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #if (defined (_XOPEN_SOURCE) && !defined (_BSD_SOURCE))
25 #define _BSD_SOURCE
26 #endif
27
28 #include <glib.h>
29 #include <glib/gi18n.h>
30
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #ifdef G_OS_WIN32
34 #  include <winsock2.h>
35 #  ifndef EINPROGRESS
36 #    define EINPROGRESS WSAEINPROGRESS
37 #  endif
38 #else
39 #  if HAVE_SYS_WAIT_H
40 #    include <sys/wait.h>
41 #  endif
42 #  include <sys/socket.h>
43 #  include <sys/stat.h>
44 #  include <sys/un.h>
45 #  include <netinet/in.h>
46 #  include <arpa/inet.h>
47 #  include <resolv.h>
48 #  include <netdb.h>
49 #endif /* G_OS_WIN32 */
50 #include <unistd.h>
51 #include <stdio.h>
52 #include <string.h>
53 #include <stdarg.h>
54 #include <fcntl.h>
55 #include <errno.h>
56 #include <signal.h>
57 #include <setjmp.h>
58 #if HAVE_SYS_SELECT_H
59 #  include <sys/select.h>
60 #endif
61
62 #include "socket.h"
63 #include "utils.h"
64 #include "log.h"
65 #if 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                 g_printerr("%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                 g_printerr("%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                         g_printerr("%s: unknown host.\n", hostname);
615                         errno = 0;
616                         return -1;
617                 }
618
619                 if (hp->h_length != 4 && hp->h_length != 8) {
620                         g_printerr("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                 g_printerr("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         if (conn_data->lookup_data) {
815                 conn_data->canonical_name = conn_data->lookup_data->canonical_name;
816                 conn_data->lookup_data->canonical_name = NULL;
817                 conn_data->lookup_data = NULL;
818         }
819         return sock_connect_address_list_async(conn_data);
820 }
821
822 gint sock_connect_async(const gchar *hostname, gushort port,
823                         SockConnectFunc func, gpointer data)
824 {
825         static gint id = 1;
826         SockConnectData *conn_data;
827
828         conn_data = g_new0(SockConnectData, 1);
829         conn_data->id = id++;
830         conn_data->hostname = g_strdup(hostname);
831         conn_data->port = port;
832         conn_data->addr_list = NULL;
833         conn_data->cur_addr = NULL;
834         conn_data->io_tag = 0;
835         conn_data->func = func;
836         conn_data->data = data;
837
838         conn_data->lookup_data = sock_get_address_info_async
839                 (hostname, port, sock_connect_async_get_address_info_cb,
840                  conn_data);
841
842         if (conn_data->lookup_data == NULL) {
843                 g_free(conn_data->hostname);
844                 g_free(conn_data);
845                 return -1;
846         }
847
848         sock_connect_data_list = g_list_append(sock_connect_data_list,
849                                                conn_data);
850
851         return conn_data->id;
852 }
853
854 gint sock_connect_async_cancel(gint id)
855 {
856         SockConnectData *conn_data = NULL;
857         GList *cur;
858
859         for (cur = sock_connect_data_list; cur != NULL; cur = cur->next) {
860                 if (((SockConnectData *)cur->data)->id == id) {
861                         conn_data = (SockConnectData *)cur->data;
862                         break;
863                 }
864         }
865
866         if (conn_data) {
867                 sock_connect_data_list = g_list_remove(sock_connect_data_list,
868                                                        conn_data);
869
870                 if (conn_data->lookup_data)
871                         sock_get_address_info_async_cancel
872                                 (conn_data->lookup_data);
873
874                 if (conn_data->io_tag > 0)
875                         g_source_remove(conn_data->io_tag);
876                 if (conn_data->channel) {
877                         g_io_channel_close(conn_data->channel);
878                         g_io_channel_unref(conn_data->channel);
879                 }
880
881                 sock_address_list_free(conn_data->addr_list);
882                 g_free(conn_data->canonical_name);
883                 g_free(conn_data->hostname);
884                 g_free(conn_data);
885         } else {
886                 g_warning("sock_connect_async_cancel: id %d not found.\n", id);
887                 return -1;
888         }
889
890         return 0;
891 }
892
893 static gint sock_connect_address_list_async(SockConnectData *conn_data)
894 {
895         SockAddrData *addr_data;
896         gint sock = -1;
897
898         for (; conn_data->cur_addr != NULL;
899              conn_data->cur_addr = conn_data->cur_addr->next) {
900                 addr_data = (SockAddrData *)conn_data->cur_addr->data;
901
902                 if ((sock = socket(addr_data->family, addr_data->socktype,
903                                    addr_data->protocol)) < 0) {
904                         perror("socket");
905                         continue;
906                 }
907
908                 set_nonblocking_mode(sock, TRUE);
909
910                 if (connect(sock, addr_data->addr, addr_data->addr_len) < 0) {
911                         if (EINPROGRESS == errno) {
912                                 break;
913                         } else {
914                                 perror("connect");
915                                 close(sock);
916                         }
917                 } else
918                         break;
919         }
920
921         if (conn_data->cur_addr == NULL) {
922                 g_warning("sock_connect_address_list_async: "
923                           "connection to %s:%d failed\n",
924                           conn_data->hostname, conn_data->port);
925                 conn_data->func(NULL, conn_data->data);
926                 sock_connect_async_cancel(conn_data->id);
927                 return -1;
928         }
929
930         conn_data->cur_addr = conn_data->cur_addr->next;
931
932         conn_data->channel = g_io_channel_unix_new(sock);
933         conn_data->io_tag = g_io_add_watch(conn_data->channel, G_IO_IN|G_IO_OUT,
934                                            sock_connect_async_cb, conn_data);
935
936         return 0;
937 }
938
939 /* asynchronous DNS lookup */
940
941 static gboolean sock_get_address_info_async_cb(GIOChannel *source,
942                                                GIOCondition condition,
943                                                gpointer data)
944 {
945         SockLookupData *lookup_data = (SockLookupData *)data;
946         GList *addr_list = NULL;
947         SockAddrData *addr_data;
948         gsize bytes_read;
949         gint ai_member[4];
950         struct sockaddr *addr;
951         gchar *canonical_name = NULL;
952         gchar len = 0;
953
954         if (g_io_channel_read(source, &len, sizeof(len),
955                               &bytes_read) == G_IO_ERROR_NONE) {
956                 if (bytes_read == sizeof(len) && len > 0) {
957                         gchar *cur = NULL;
958                         gint todo = len;
959                         canonical_name = g_malloc0(len + 1);
960                         cur = canonical_name;
961                         while (todo > 0) {
962                                 if (g_io_channel_read(source, cur, todo,
963                                       &bytes_read) != G_IO_ERROR_NONE) {
964                                       g_warning("canonical name not read\n");
965                                       g_free(canonical_name);
966                                       canonical_name = NULL;
967                                       break;
968                                 } else {
969                                         cur += bytes_read;
970                                         todo -= bytes_read;
971                                 }
972                                 if (bytes_read == 0) {
973                                       g_warning("canonical name not read\n");
974                                       g_free(canonical_name);
975                                       canonical_name = NULL;
976                                       break;
977                                 }
978                         }
979                 }             
980         }
981         for (;;) {
982                 if (g_io_channel_read(source, (gchar *)ai_member,
983                                       sizeof(ai_member), &bytes_read)
984                     != G_IO_ERROR_NONE) {
985                         g_warning("sock_get_address_info_async_cb: "
986                                   "address length read error\n");
987                         break;
988                 }
989
990                 if (bytes_read == 0 || bytes_read != sizeof(ai_member))
991                         break;
992
993                 if (ai_member[0] == AF_UNSPEC) {
994                         g_warning("DNS lookup failed\n");
995                         break;
996                 }
997
998                 addr = g_malloc(ai_member[3]);
999                 if (g_io_channel_read(source, (gchar *)addr, ai_member[3],
1000                                       &bytes_read)
1001                     != G_IO_ERROR_NONE) {
1002                         g_warning("sock_get_address_info_async_cb: "
1003                                   "address data read error\n");
1004                         g_free(addr);
1005                         break;
1006                 }
1007
1008                 if (bytes_read != ai_member[3]) {
1009                         g_warning("sock_get_address_info_async_cb: "
1010                                   "incomplete address data\n");
1011                         g_free(addr);
1012                         break;
1013                 }
1014
1015                 addr_data = g_new0(SockAddrData, 1);
1016                 addr_data->family = ai_member[0];
1017                 addr_data->socktype = ai_member[1];
1018                 addr_data->protocol = ai_member[2];
1019                 addr_data->addr_len = ai_member[3];
1020                 addr_data->addr = addr;
1021
1022                 addr_list = g_list_append(addr_list, addr_data);
1023         }
1024
1025         g_io_channel_close(source);
1026         g_io_channel_unref(source);
1027
1028 #ifdef G_OS_WIN32
1029         /* FIXME: We would need to cancel the thread. */
1030 #else
1031         kill(lookup_data->child_pid, SIGKILL);
1032         waitpid(lookup_data->child_pid, NULL, 0);
1033 #endif
1034         lookup_data->canonical_name = canonical_name;
1035
1036         lookup_data->func(addr_list, lookup_data->data);
1037
1038         g_free(lookup_data->canonical_name);
1039         g_free(lookup_data->hostname);
1040         g_free(lookup_data);
1041
1042         return FALSE;
1043 }
1044
1045
1046 /* For better readability we use a separate function to implement the
1047    child code of sock_get_address_info_async.  Note, that under W32
1048    this is actually not a child but a thread and this is the reason
1049    why we pass only a void pointer. */
1050 static void address_info_async_child(void *opaque)
1051 {
1052         SockLookupData *parm = opaque;
1053 #ifdef INET6
1054         gint gai_err;
1055         struct addrinfo hints, *res, *ai;
1056         gchar port_str[6];
1057 #else /* !INET6 */
1058         struct hostent *hp;
1059         gchar **addr_list_p;
1060         struct sockaddr_in ad;
1061 #endif /* INET6 */
1062         gint ai_member[4] = {AF_UNSPEC, 0, 0, 0};
1063
1064 #ifndef G_OS_WIN32
1065         close(parm->pipe_fds[0]);
1066         parm->pipe_fds[0] = -1;
1067 #endif
1068
1069 #ifdef INET6
1070         memset(&hints, 0, sizeof(hints));
1071         hints.ai_flags = AI_CANONNAME;
1072         hints.ai_family = AF_UNSPEC;
1073         hints.ai_socktype = SOCK_STREAM;
1074         hints.ai_protocol = IPPROTO_TCP;
1075
1076         g_snprintf(port_str, sizeof(port_str), "%d", parm->port);
1077
1078         gai_err = getaddrinfo(parm->hostname, port_str, &hints, &res);
1079         if (gai_err != 0) {
1080                 gchar len = 0;
1081                 g_warning("getaddrinfo for %s:%s failed: %s\n",
1082                           parm->hostname, port_str, gai_strerror(gai_err));
1083                 fd_write_all(parm->pipe_fds[1], &len,
1084                      sizeof(len));
1085                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1086                              sizeof(ai_member));
1087                 close(parm->pipe_fds[1]);
1088                 parm->pipe_fds[1] = -1;
1089 #ifdef G_OS_WIN32
1090                 _endthread();
1091 #else
1092                 _exit(1);
1093 #endif
1094         }
1095
1096         if (res != NULL) {
1097                 if (res->ai_canonname && strlen(res->ai_canonname) < 255) {
1098                         gchar len = strlen(res->ai_canonname);
1099                         fd_write_all(parm->pipe_fds[1], &len,
1100                              sizeof(len));
1101                         fd_write_all(parm->pipe_fds[1], res->ai_canonname,
1102                              len);                       
1103                 } else {
1104                         gchar len = 0;
1105                         fd_write_all(parm->pipe_fds[1], &len,
1106                              sizeof(len));
1107                 }
1108         } else {
1109                 gchar len = 0;
1110                 fd_write_all(parm->pipe_fds[1], &len,
1111                      sizeof(len));
1112         }
1113
1114         for (ai = res; ai != NULL; ai = ai->ai_next) {
1115                 ai_member[0] = ai->ai_family;
1116                 ai_member[1] = ai->ai_socktype;
1117                 ai_member[2] = ai->ai_protocol;
1118                 ai_member[3] = ai->ai_addrlen;
1119
1120                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1121                              sizeof(ai_member));
1122                 fd_write_all(parm->pipe_fds[1], (gchar *)ai->ai_addr,
1123                              ai->ai_addrlen);
1124         }
1125
1126         if (res != NULL)
1127                 freeaddrinfo(res);
1128 #else /* !INET6 */
1129         hp = my_gethostbyname(parm->hostname);
1130         if (hp == NULL || hp->h_addrtype != AF_INET) {
1131                 gchar len = 0;
1132                 fd_write_all(parm->pipe_fds[1], &len,
1133                      sizeof(len));
1134                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1135                              sizeof(ai_member));
1136                close(parm->pipe_fds[1]);
1137                 parm->pipe_fds[1] = -1;
1138 #ifdef G_OS_WIN32
1139                 _endthread();
1140 #else
1141                 _exit(1);
1142 #endif
1143         }
1144
1145         ai_member[0] = AF_INET;
1146         ai_member[1] = SOCK_STREAM;
1147         ai_member[2] = IPPROTO_TCP;
1148         ai_member[3] = sizeof(ad);
1149
1150         memset(&ad, 0, sizeof(ad));
1151         ad.sin_family = AF_INET;
1152         ad.sin_port = htons(parm->port);
1153
1154         if (hp->h_name && strlen(hp->h_name) < 255) {
1155                 gchar len = strlen(hp->h_name);
1156                 fd_write_all(parm->pipe_fds[1], &len,
1157                      sizeof(len));
1158                 fd_write_all(parm->pipe_fds[1], hp->h_name,
1159                      len);                       
1160         } else {
1161                 gchar len = 0;
1162                 fd_write_all(parm->pipe_fds[1], &len,
1163                      sizeof(len));
1164         }
1165         for (addr_list_p = hp->h_addr_list; *addr_list_p != NULL;
1166              addr_list_p++) {
1167                 memcpy(&ad.sin_addr, *addr_list_p, hp->h_length);
1168                 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1169                              sizeof(ai_member));
1170                 fd_write_all(parm->pipe_fds[1], (gchar *)&ad, sizeof(ad));
1171         }
1172 #endif /* INET6 */
1173
1174         close(parm->pipe_fds[1]);
1175         parm->pipe_fds[1] = -1;
1176
1177 #ifdef G_OS_WIN32
1178         _endthread();
1179 #else
1180         _exit(0);
1181 #endif
1182 }
1183
1184 static SockLookupData *sock_get_address_info_async(const gchar *hostname,
1185                                                    gushort port,
1186                                                    SockAddrFunc func,
1187                                                    gpointer data)
1188 {
1189         SockLookupData *lookup_data = NULL;
1190         
1191         refresh_resolvers();
1192
1193         lookup_data = g_new0(SockLookupData, 1);
1194         lookup_data->hostname = g_strdup(hostname);
1195         lookup_data->func = func;
1196         lookup_data->data = data;
1197         lookup_data->port = port;
1198         lookup_data->child_pid = (pid_t)(-1);
1199         lookup_data->pipe_fds[0] = -1;
1200         lookup_data->pipe_fds[1] = -1;
1201
1202         if (pipe(lookup_data->pipe_fds) < 0) {
1203                 perror("pipe");
1204                 func(NULL, data);
1205                 g_free (lookup_data->hostname);
1206                 g_free (lookup_data);
1207                 return NULL;
1208         }
1209
1210 #ifndef G_OS_WIN32
1211         if ((lookup_data->child_pid = fork()) < 0) {
1212                 perror("fork");
1213                 func(NULL, data);
1214                 g_free (lookup_data->hostname);
1215                 g_free (lookup_data);
1216                 return NULL;
1217         }
1218
1219         if (lookup_data->child_pid == 0) {
1220                 /* Child process. */
1221                 address_info_async_child (lookup_data);
1222                 g_assert_not_reached ();
1223         }
1224         /* Parent process. */
1225         close(lookup_data->pipe_fds[1]);
1226         lookup_data->pipe_fds[1] = -1;
1227 #endif  /*!G_OS_WIN32 */
1228         
1229         lookup_data->channel = g_io_channel_unix_new(lookup_data->pipe_fds[0]);
1230         lookup_data->io_tag = g_io_add_watch(lookup_data->channel, G_IO_IN,
1231                                              sock_get_address_info_async_cb,
1232                                              lookup_data);
1233 #ifdef G_OS_WIN32
1234         lookup_data->child_pid = _beginthread(
1235                 address_info_async_child, 0, lookup_data);
1236 #endif
1237
1238         return lookup_data;
1239 }
1240
1241 static gint sock_get_address_info_async_cancel(SockLookupData *lookup_data)
1242 {
1243         if (lookup_data->io_tag > 0)
1244                 g_source_remove(lookup_data->io_tag);
1245         if (lookup_data->channel) {
1246                 g_io_channel_close(lookup_data->channel);
1247                 g_io_channel_unref(lookup_data->channel);
1248         }
1249
1250         if (lookup_data->child_pid > 0) {
1251 #ifdef G_OS_WIN32
1252                 /* FIXME: Need a way to cancel the thread. */
1253 #else
1254                 kill(lookup_data->child_pid, SIGKILL);
1255                 waitpid(lookup_data->child_pid, NULL, 0);
1256 #endif
1257         }
1258
1259         g_free(lookup_data->canonical_name);
1260         g_free(lookup_data->hostname);
1261         g_free(lookup_data);
1262
1263         return 0;
1264 }
1265
1266
1267 static SockInfo *sockinfo_from_fd(const gchar *hostname,
1268                                   gushort port,
1269                                   gint sock)
1270 {
1271         SockInfo *sockinfo;
1272
1273         sockinfo = g_new0(SockInfo, 1);
1274         sockinfo->sock = sock;
1275         sockinfo->sock_ch = g_io_channel_unix_new(sock);
1276         sockinfo->hostname = g_strdup(hostname);
1277         sockinfo->port = port;
1278         sockinfo->state = CONN_ESTABLISHED;
1279
1280         return sockinfo;
1281 }
1282
1283 static gint fd_read(gint fd, gchar *buf, gint len)
1284 {
1285         if (fd_check_io(fd, G_IO_IN) < 0)
1286                 return -1;
1287
1288         if (fd_is_w32_socket(fd))
1289                 return recv(fd, buf, len, 0);
1290         return read(fd, buf, len);
1291 }
1292
1293 #if USE_OPENSSL
1294 static gint ssl_read(SSL *ssl, gchar *buf, gint len)
1295 {
1296         gint err, ret;
1297
1298         if (SSL_pending(ssl) == 0) {
1299                 if (fd_check_io(SSL_get_rfd(ssl), G_IO_IN) < 0)
1300                         return -1;
1301         }
1302
1303         ret = SSL_read(ssl, buf, len);
1304
1305         switch ((err = SSL_get_error(ssl, ret))) {
1306         case SSL_ERROR_NONE:
1307                 return ret;
1308         case SSL_ERROR_WANT_READ:
1309         case SSL_ERROR_WANT_WRITE:
1310                 errno = EAGAIN;
1311                 return -1;
1312         case SSL_ERROR_ZERO_RETURN:
1313                 return 0;
1314         default:
1315                 g_warning("SSL_read() returned error %d, ret = %d\n", err, ret);
1316                 if (ret == 0)
1317                         return 0;
1318                 return -1;
1319         }
1320 }
1321 #endif
1322
1323 gint sock_read(SockInfo *sock, gchar *buf, gint len)
1324 {
1325         gint ret;
1326
1327         g_return_val_if_fail(sock != NULL, -1);
1328
1329 #if USE_OPENSSL
1330         if (sock->ssl)
1331                 ret = ssl_read(sock->ssl, buf, len);
1332         else
1333 #endif
1334                 ret = fd_read(sock->sock, buf, len);
1335         
1336         if (ret < 0)
1337                 sock->state = CONN_DISCONNECTED;
1338         return ret;
1339 }
1340
1341 gint fd_write(gint fd, const gchar *buf, gint len)
1342 {
1343         if (fd_check_io(fd, G_IO_OUT) < 0)
1344                 return -1;
1345
1346         if (fd_is_w32_socket (fd))
1347                 return send(fd, buf, len, 0);
1348         return write(fd, buf, len);
1349 }
1350
1351 #if USE_OPENSSL
1352 static gint ssl_write(SSL *ssl, const gchar *buf, gint len)
1353 {
1354         gint ret;
1355
1356         ret = SSL_write(ssl, buf, len);
1357
1358         switch (SSL_get_error(ssl, ret)) {
1359         case SSL_ERROR_NONE:
1360                 return ret;
1361         case SSL_ERROR_WANT_READ:
1362         case SSL_ERROR_WANT_WRITE:
1363                 errno = EAGAIN;
1364                 return -1;
1365         default:
1366                 return -1;
1367         }
1368 }
1369 #endif
1370
1371 gint sock_write(SockInfo *sock, const gchar *buf, gint len)
1372 {
1373         gint ret;
1374
1375         g_return_val_if_fail(sock != NULL, -1);
1376
1377 #if USE_OPENSSL
1378         if (sock->ssl)
1379                 ret = ssl_write(sock->ssl, buf, len);
1380         else
1381 #endif
1382                 ret = fd_write(sock->sock, buf, len);
1383
1384         if (ret < 0)
1385                 sock->state = CONN_DISCONNECTED;
1386         return ret;
1387 }
1388
1389 gint fd_write_all(gint fd, const gchar *buf, gint len)
1390 {
1391         gint n, wrlen = 0;
1392
1393         while (len) {
1394                 if (fd_check_io(fd, G_IO_OUT) < 0)
1395                         return -1;
1396 #ifndef G_OS_WIN32
1397                 signal(SIGPIPE, SIG_IGN);
1398 #endif
1399                 if (fd_is_w32_socket(fd))
1400                         n = send(fd, buf, len, 0);
1401                 else
1402                         n = write(fd, buf, len);
1403
1404                 if (n <= 0) {
1405                         log_error(LOG_PROTOCOL, _("write on fd%d: %s\n"), fd, strerror(errno));
1406                         return -1;
1407                 }
1408                 len -= n;
1409                 wrlen += n;
1410                 buf += n;
1411         }
1412
1413         return wrlen;
1414 }
1415
1416 #if USE_OPENSSL
1417 static gint ssl_write_all(SSL *ssl, const gchar *buf, gint len)
1418 {
1419         gint n, wrlen = 0;
1420
1421         while (len) {
1422                 n = ssl_write(ssl, buf, len);
1423                 if (n <= 0)
1424                         return -1;
1425                 len -= n;
1426                 wrlen += n;
1427                 buf += n;
1428         }
1429
1430         return wrlen;
1431 }
1432 #endif
1433
1434 gint sock_write_all(SockInfo *sock, const gchar *buf, gint len)
1435 {
1436         gint ret;
1437
1438         g_return_val_if_fail(sock != NULL, -1);
1439
1440 #if USE_OPENSSL
1441         if (sock->ssl)
1442                 ret = ssl_write_all(sock->ssl, buf, len);
1443         else
1444 #endif
1445                 ret = fd_write_all(sock->sock, buf, len);
1446
1447         if (ret < 0)
1448                 sock->state = CONN_DISCONNECTED;
1449         return ret;
1450 }
1451
1452 static gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
1453 {
1454         if (fd_check_io(fd, G_IO_IN) < 0)
1455                 return -1;
1456
1457         return recv(fd, buf, len, flags);
1458 }
1459
1460 gint fd_gets(gint fd, gchar *buf, gint len)
1461 {
1462         gchar *newline, *bp = buf;
1463         gint n;
1464
1465         if (--len < 1)
1466                 return -1;
1467
1468 #ifdef G_OS_WIN32
1469         do {
1470 /*
1471 XXX:tm try nonblock
1472 MSKB Article ID: Q147714 
1473 Windows Sockets 2 Service Provider Interface Limitations
1474 Polling with recv(MSG_PEEK) to determine when a complete message 
1475 has arrived.
1476     Reason and Workaround not available.
1477
1478 Single-byte send() and recv(). 
1479     Reason: Couple one-byte sends with Nagle disabled.
1480     Workaround: Send modest amounts and receive as much as possible.
1481 (still unused)
1482 */
1483                 if (recv(fd, bp, 1, 0) <= 0)
1484                         return -1;
1485                 if (*bp == '\n')
1486                         break;
1487                 bp++;
1488                 len--;
1489         } while (0 < len);
1490 #else /*!G_OS_WIN32*/
1491         do {
1492                 if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
1493                         return -1;
1494                 if ((newline = memchr(bp, '\n', n)) != NULL)
1495                         n = newline - bp + 1;
1496                 if ((n = fd_read(fd, bp, n)) < 0)
1497                         return -1;
1498                 bp += n;
1499                 len -= n;
1500         } while (!newline && len);
1501 #endif /*!G_OS_WIN32*/
1502
1503         *bp = '\0';
1504         return bp - buf;
1505 }
1506
1507 #if USE_OPENSSL
1508 static gint ssl_peek            (SSL *ssl, gchar *buf, gint len);
1509
1510 static gint ssl_gets(SSL *ssl, gchar *buf, gint len)
1511 {
1512         gchar *newline, *bp = buf;
1513         gint n;
1514
1515         if (--len < 1)
1516                 return -1;
1517         do {
1518                 if ((n = ssl_peek(ssl, bp, len)) <= 0)
1519                         return -1;
1520                 if ((newline = memchr(bp, '\n', n)) != NULL)
1521                         n = newline - bp + 1;
1522                 if ((n = ssl_read(ssl, bp, n)) < 0)
1523                         return -1;
1524                 bp += n;
1525                 len -= n;
1526         } while (!newline && len);
1527
1528         *bp = '\0';
1529         return bp - buf;
1530 }
1531 #endif
1532
1533 gint sock_gets(SockInfo *sock, gchar *buf, gint len)
1534 {
1535         gint ret;
1536
1537         g_return_val_if_fail(sock != NULL, -1);
1538
1539 #if USE_OPENSSL
1540         if (sock->ssl)
1541                 return ssl_gets(sock->ssl, buf, len);
1542         else
1543 #endif
1544                 return fd_gets(sock->sock, buf, len);
1545
1546         if (ret < 0)
1547                 sock->state = CONN_DISCONNECTED;
1548         return ret;
1549 }
1550
1551 /* peek at the socket data without actually reading it */
1552 #if USE_OPENSSL
1553 static gint ssl_peek(SSL *ssl, gchar *buf, gint len)
1554 {
1555         gint err, ret;
1556
1557         if (SSL_pending(ssl) == 0) {
1558                 if (fd_check_io(SSL_get_rfd(ssl), G_IO_IN) < 0)
1559                         return -1;
1560         }
1561
1562         ret = SSL_peek(ssl, buf, len);
1563
1564         switch ((err = SSL_get_error(ssl, ret))) {
1565         case SSL_ERROR_NONE:
1566                 return ret;
1567         case SSL_ERROR_WANT_READ:
1568         case SSL_ERROR_WANT_WRITE:
1569                 errno = EAGAIN;
1570                 return -1;
1571         case SSL_ERROR_ZERO_RETURN:
1572                 return 0;
1573         case SSL_ERROR_SYSCALL:
1574                 g_warning("SSL_peek() returned syscall error. errno=%d\n", errno);
1575                 return -1;
1576         default:
1577                 g_warning("SSL_peek() returned error %d, ret = %d\n", err, ret);
1578                 if (ret == 0)
1579                         return 0;
1580                 return -1;
1581         }
1582 }
1583 #endif
1584
1585 gint sock_close(SockInfo *sock)
1586 {
1587         gint ret;
1588
1589         if (!sock)
1590                 return 0;
1591
1592         if (sock->sock_ch)
1593                 g_io_channel_unref(sock->sock_ch);
1594
1595 #if USE_OPENSSL
1596         if (sock->ssl)
1597                 ssl_done_socket(sock);
1598         if (sock->g_source != 0)
1599                 g_source_remove(sock->g_source);
1600         sock->g_source = 0;
1601 #endif
1602 #ifdef G_OS_WIN32
1603         shutdown(sock->sock, 1); /* complete transfer before close */
1604         ret = closesocket(sock->sock);
1605 #else
1606         ret = fd_close(sock->sock); 
1607 #endif
1608
1609         g_free(sock->canonical_name);
1610         g_free(sock->hostname);
1611         g_free(sock);
1612
1613         return ret;
1614 }
1615
1616 gint fd_close(gint fd)
1617 {
1618         return close(fd);
1619 }