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