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