sync with 0.9.2cvs6
[claws.git] / src / common / socket.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 #include <sys/wait.h>
28 #include <sys/socket.h>
29 #include <sys/un.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
32 #include <netdb.h>
33 #include <unistd.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdarg.h>
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <signal.h>
40 #include <setjmp.h>
41 #if HAVE_SYS_SELECT_H
42 #  include <sys/select.h>
43 #endif
44
45 #include "socket.h"
46 #include "utils.h"
47 #include "log.h"
48 #if USE_OPENSSL
49 #  include "ssl.h"
50 #endif
51
52 #if USE_GIO
53 #error USE_GIO is currently not supported
54 #endif
55
56 #define BUFFSIZE        8192
57
58 typedef gint (*SockAddrFunc)    (GList          *addr_list,
59                                  gpointer        data);
60
61 typedef struct _SockConnectData SockConnectData;
62 typedef struct _SockLookupData  SockLookupData;
63 typedef struct _SockAddrData    SockAddrData;
64
65 struct _SockConnectData {
66         gint id;
67         gchar *hostname;
68         gushort port;
69         GList *addr_list;
70         GList *cur_addr;
71         SockLookupData *lookup_data;
72         GIOChannel *channel;
73         guint io_tag;
74         SockConnectFunc func;
75         gpointer data;
76 };
77
78 struct _SockLookupData {
79         gchar *hostname;
80         pid_t child_pid;
81         GIOChannel *channel;
82         guint io_tag;
83         SockAddrFunc func;
84         gpointer data;
85 };
86
87 struct _SockAddrData {
88         gint family;
89         gint socktype;
90         gint protocol;
91         gint addr_len;
92         struct sockaddr *addr;
93 };
94
95 static guint io_timeout = 60;
96
97 static GList *sock_connect_data_list = NULL;
98
99 static gint sock_connect_with_timeout   (gint                    sock,
100                                          const struct sockaddr  *serv_addr,
101                                          gint                    addrlen,
102                                          guint                   timeout_secs);
103
104 #ifndef INET6
105 static gint sock_connect_by_hostname    (gint            sock,
106                                          const gchar    *hostname,
107                                          gushort         port);
108 #else
109 static gint sock_connect_by_getaddrinfo (const gchar    *hostname,
110                                          gushort         port);
111 #endif
112
113 static SockInfo *sockinfo_from_fd(const gchar *hostname,
114                                   gushort port,
115                                   gint sock);
116 static void sock_address_list_free              (GList          *addr_list);
117
118 static gboolean sock_connect_async_cb           (GIOChannel     *source,
119                                                  GIOCondition    condition,
120                                                  gpointer        data);
121 static gint sock_connect_async_get_address_info_cb
122                                                 (GList          *addr_list,
123                                                  gpointer        data);
124
125 static gint sock_connect_address_list_async     (SockConnectData *conn_data);
126
127 static gboolean sock_get_address_info_async_cb  (GIOChannel     *source,
128                                                  GIOCondition    condition,
129                                                  gpointer        data);
130 static SockLookupData *sock_get_address_info_async
131                                                 (const gchar    *hostname,
132                                                  gushort         port,
133                                                  SockAddrFunc    func,
134                                                  gpointer        data);
135 static gint sock_get_address_info_async_cancel  (SockLookupData *lookup_data);
136
137
138 gint sock_set_io_timeout(guint sec)
139 {
140         io_timeout = sec;
141         return 0;
142 }
143
144 gint fd_connect_unix(const gchar *path)
145 {
146         gint sock;
147         struct sockaddr_un addr;
148
149         sock = socket(PF_UNIX, SOCK_STREAM, 0);
150         if (sock < 0) {
151                 perror("sock_connect_unix(): socket");
152                 return -1;
153         }
154
155         memset(&addr, 0, sizeof(addr));
156         addr.sun_family = AF_UNIX;
157         strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
158
159         if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
160                 close(sock);
161                 return -1;
162         }
163
164         return sock;
165 }
166
167 gint fd_open_unix(const gchar *path)
168 {
169         gint sock;
170         struct sockaddr_un addr;
171
172         sock = socket(PF_UNIX, SOCK_STREAM, 0);
173
174         if (sock < 0) {
175                 perror("sock_open_unix(): socket");
176                 return -1;
177         }
178
179         memset(&addr, 0, sizeof(addr));
180         addr.sun_family = AF_UNIX;
181         strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
182
183         if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
184                 perror("bind");
185                 close(sock);
186                 return -1;
187         }
188
189         if (listen(sock, 1) < 0) {
190                 perror("listen");
191                 close(sock);
192                 return -1;              
193         }
194
195         return sock;
196 }
197
198 gint fd_accept(gint sock)
199 {
200         struct sockaddr_in caddr;
201         gint caddr_len;
202
203         caddr_len = sizeof(caddr);
204         return accept(sock, (struct sockaddr *)&caddr, &caddr_len);
205 }
206
207
208 static gint set_nonblocking_mode(gint fd, gboolean nonblock)
209 {
210         gint flags;
211
212         flags = fcntl(fd, F_GETFL, 0);
213         if (flags < 0) {
214                 perror("fcntl");
215                 return -1;
216         }
217
218         if (nonblock)
219                 flags |= O_NONBLOCK;
220         else
221                 flags &= ~O_NONBLOCK;
222
223         return fcntl(fd, F_SETFL, flags);
224 }
225
226 gint sock_set_nonblocking_mode(SockInfo *sock, gboolean nonblock)
227 {
228         g_return_val_if_fail(sock != NULL, -1);
229
230         return set_nonblocking_mode(sock->sock, nonblock);
231 }
232
233
234 static gboolean is_nonblocking_mode(gint fd)
235 {
236         gint flags;
237
238         flags = fcntl(fd, F_GETFL, 0);
239         if (flags < 0) {
240                 perror("fcntl");
241                 return FALSE;
242         }
243
244         return ((flags & O_NONBLOCK) != 0);
245 }
246
247 gboolean sock_is_nonblocking_mode(SockInfo *sock)
248 {
249         g_return_val_if_fail(sock != NULL, FALSE);
250
251         return is_nonblocking_mode(sock->sock);
252 }
253
254 static gint fd_check_io(gint fd, GIOCondition cond)
255 {
256         struct timeval timeout;
257         fd_set fds;
258
259         if (is_nonblocking_mode(fd))
260                 return 0;
261
262         timeout.tv_sec  = io_timeout;
263         timeout.tv_usec = 0;
264
265         FD_ZERO(&fds);
266         FD_SET(fd, &fds);
267
268         if (cond == G_IO_IN) {
269                 select(fd + 1, &fds, NULL, NULL,
270                        io_timeout > 0 ? &timeout : NULL);
271         } else {
272                 select(fd + 1, NULL, &fds, NULL,
273                        io_timeout > 0 ? &timeout : NULL);
274         }
275
276         if (FD_ISSET(fd, &fds)) {
277                 return 0;
278         } else {
279                 g_warning("Socket IO timeout\n");
280                 return -1;
281         }
282 }
283
284 static sigjmp_buf jmpenv;
285
286 static void timeout_handler(gint sig)
287 {
288         siglongjmp(jmpenv, 1);
289 }
290
291 static gint sock_connect_with_timeout(gint sock,
292                                       const struct sockaddr *serv_addr,
293                                       gint addrlen,
294                                       guint timeout_secs)
295 {
296         gint ret;
297         void (*prev_handler)(gint);
298
299         alarm(0);
300         prev_handler = signal(SIGALRM, timeout_handler);
301         if (sigsetjmp(jmpenv, 1)) {
302                 alarm(0);
303                 signal(SIGALRM, prev_handler);
304                 errno = ETIMEDOUT;
305                 return -1;
306         }
307         alarm(timeout_secs);
308
309         ret = connect(sock, serv_addr, addrlen);
310
311         alarm(0);
312         signal(SIGALRM, prev_handler);
313
314         return ret;
315 }
316
317 struct hostent *my_gethostbyname(const gchar *hostname)
318 {
319         struct hostent *hp;
320         void (*prev_handler)(gint);
321
322         alarm(0);
323         prev_handler = signal(SIGALRM, timeout_handler);
324         if (sigsetjmp(jmpenv, 1)) {
325                 alarm(0);
326                 signal(SIGALRM, prev_handler);
327                 fprintf(stderr, "%s: host lookup timed out.\n", hostname);
328                 errno = 0;
329                 return NULL;
330         }
331         alarm(io_timeout);
332
333         if ((hp = gethostbyname(hostname)) == NULL) {
334                 alarm(0);
335                 signal(SIGALRM, prev_handler);
336                 fprintf(stderr, "%s: unknown host.\n", hostname);
337                 errno = 0;
338                 return NULL;
339         }
340
341         alarm(0);
342         signal(SIGALRM, prev_handler);
343
344         return hp;
345 }
346
347 #ifndef INET6
348 static gint my_inet_aton(const gchar *hostname, struct in_addr *inp)
349 {
350 #if HAVE_INET_ATON
351         return inet_aton(hostname, inp);
352 #else
353 #if HAVE_INET_ADDR
354         guint32 inaddr;
355
356         inaddr = inet_addr(hostname);
357         if (inaddr != -1) {
358                 memcpy(inp, &inaddr, sizeof(inaddr));
359                 return 1;
360         } else
361                 return 0;
362 #else
363         return 0;
364 #endif
365 #endif /* HAVE_INET_ATON */
366 }
367
368 static gint sock_connect_by_hostname(gint sock, const gchar *hostname,
369                                      gushort port)
370 {
371         struct hostent *hp;
372         struct sockaddr_in ad;
373
374         memset(&ad, 0, sizeof(ad));
375         ad.sin_family = AF_INET;
376         ad.sin_port = htons(port);
377
378         if (!my_inet_aton(hostname, &ad.sin_addr)) {
379                 if ((hp = my_gethostbyname(hostname)) == NULL) {
380                         fprintf(stderr, "%s: unknown host.\n", hostname);
381                         errno = 0;
382                         return -1;
383                 }
384
385                 if (hp->h_length != 4 && hp->h_length != 8) {
386                         fprintf(stderr, "illegal address length received for host %s\n", hostname);
387                         errno = 0;
388                         return -1;
389                 }
390
391                 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
392         }
393
394         return sock_connect_with_timeout(sock, (struct sockaddr *)&ad,
395                                          sizeof(ad), io_timeout);
396 }
397
398 #else /* INET6 */
399 static gint sock_connect_by_getaddrinfo(const gchar *hostname, gushort  port)
400 {
401         gint sock = -1, gai_error;
402         struct addrinfo hints, *res, *ai;
403         gchar port_str[6];
404
405         memset(&hints, 0, sizeof(hints));
406         /* hints.ai_flags = AI_CANONNAME; */
407         hints.ai_family = AF_UNSPEC;
408         hints.ai_socktype = SOCK_STREAM;
409         hints.ai_protocol = IPPROTO_TCP;
410
411         /* convert port from integer to string. */
412         g_snprintf(port_str, sizeof(port_str), "%d", port);
413
414         if ((gai_error = getaddrinfo(hostname, port_str, &hints, &res)) != 0) {
415                 fprintf(stderr, "getaddrinfo for %s:%s failed: %s\n",
416                         hostname, port_str, gai_strerror(gai_error));
417                 return -1;
418         }
419
420         for (ai = res; ai != NULL; ai = ai->ai_next) {
421                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
422                 if (sock < 0)
423                         continue;
424
425                 if (sock_connect_with_timeout
426                         (sock, ai->ai_addr, ai->ai_addrlen, io_timeout) == 0)
427                         break;
428
429                 close(sock);
430         }
431
432         if (res != NULL)
433                 freeaddrinfo(res);
434
435         if (ai == NULL)
436                 return -1;
437
438         return sock;
439 }
440 #endif /* !INET6 */
441
442
443 /* Open a connection using an external program.  May be useful when
444  * you need to tunnel through a SOCKS or other firewall, or to
445  * establish an IMAP-over-SSH connection. */
446 /* TODO: Recreate this for sock_connect_thread() */
447 SockInfo *sock_connect_cmd(const gchar *hostname, const gchar *tunnelcmd)
448 {
449         gint fd[2];
450         int r;
451                      
452         if ((r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) == -1) {
453                 perror("socketpair");
454                 return NULL;
455         }
456         log_message("launching tunnel command \"%s\"\n", tunnelcmd);
457         if (fork() == 0) {
458                 close(fd[0]);
459                 close(0);
460                 close(1);
461                 dup(fd[1]);     /* set onto stdin */
462                 dup(fd[1]);
463                 execlp("/bin/sh", "/bin/sh", "-c", tunnelcmd, NULL);
464         }
465
466         close(fd[1]);
467         return sockinfo_from_fd(hostname, 0, fd[0]);
468 }
469
470
471 SockInfo *sock_connect(const gchar *hostname, gushort port)
472 {
473         gint sock;
474
475 #ifdef INET6
476         if ((sock = sock_connect_by_getaddrinfo(hostname, port)) < 0)
477                 return NULL;
478 #else
479         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
480                 perror("socket");
481                 return NULL;
482         }
483
484         if (sock_connect_by_hostname(sock, hostname, port) < 0) {
485                 if (errno != 0) perror("connect");
486                 close(sock);
487                 return NULL;
488         }
489 #endif /* INET6 */
490
491         return sockinfo_from_fd(hostname, port, sock);
492 }
493
494 static void sock_address_list_free(GList *addr_list)
495 {
496         GList *cur;
497
498         for (cur = addr_list; cur != NULL; cur = cur->next) {
499                 SockAddrData *addr_data = (SockAddrData *)cur->data;
500                 g_free(addr_data->addr);
501                 g_free(addr_data);
502         }
503
504         g_list_free(addr_list);
505 }
506
507 /* asynchronous TCP connection */
508
509 static gboolean sock_connect_async_cb(GIOChannel *source,
510                                       GIOCondition condition, gpointer data)
511 {
512         SockConnectData *conn_data = (SockConnectData *)data;
513         gint fd;
514         gint val;
515         gint len;
516         SockInfo *sockinfo;
517
518         fd = g_io_channel_unix_get_fd(source);
519
520         conn_data->io_tag = 0;
521         conn_data->channel = NULL;
522         g_io_channel_unref(source);
523
524         len = sizeof(val);
525         if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &len) < 0) {
526                 perror("getsockopt");
527                 close(fd);
528                 sock_connect_address_list_async(conn_data);
529                 return FALSE;
530         }
531
532         if (val != 0) {
533                 close(fd);
534                 sock_connect_address_list_async(conn_data);
535                 return FALSE;
536         }
537
538         sockinfo = g_new0(SockInfo, 1);
539         sockinfo->sock = fd;
540         sockinfo->hostname = g_strdup(conn_data->hostname);
541         sockinfo->port = conn_data->port;
542         sockinfo->state = CONN_ESTABLISHED;
543
544         conn_data->func(sockinfo, conn_data->data);
545
546         sock_connect_async_cancel(conn_data->id);
547
548         return FALSE;
549 }
550
551 static gint sock_connect_async_get_address_info_cb(GList *addr_list,
552                                                    gpointer data)
553 {
554         SockConnectData *conn_data = (SockConnectData *)data;
555
556         conn_data->addr_list = addr_list;
557         conn_data->cur_addr = addr_list;
558         conn_data->lookup_data = NULL;
559
560         return sock_connect_address_list_async(conn_data);
561 }
562
563 gint sock_connect_async(const gchar *hostname, gushort port,
564                         SockConnectFunc func, gpointer data)
565 {
566         static gint id = 1;
567         SockConnectData *conn_data;
568
569         conn_data = g_new0(SockConnectData, 1);
570         conn_data->id = id++;
571         conn_data->hostname = g_strdup(hostname);
572         conn_data->port = port;
573         conn_data->addr_list = NULL;
574         conn_data->cur_addr = NULL;
575         conn_data->io_tag = 0;
576         conn_data->func = func;
577         conn_data->data = data;
578
579         conn_data->lookup_data = sock_get_address_info_async
580                 (hostname, port, sock_connect_async_get_address_info_cb,
581                  conn_data);
582
583         if (conn_data->lookup_data == NULL) {
584                 g_free(conn_data->hostname);
585                 g_free(conn_data);
586                 return -1;
587         }
588
589         sock_connect_data_list = g_list_append(sock_connect_data_list,
590                                                conn_data);
591
592         return conn_data->id;
593 }
594
595 gint sock_connect_async_cancel(gint id)
596 {
597         SockConnectData *conn_data = NULL;
598         GList *cur;
599
600         for (cur = sock_connect_data_list; cur != NULL; cur = cur->next) {
601                 if (((SockConnectData *)cur->data)->id == id) {
602                         conn_data = (SockConnectData *)cur->data;
603                         break;
604                 }
605         }
606
607         if (conn_data) {
608                 sock_connect_data_list = g_list_remove(sock_connect_data_list,
609                                                        conn_data);
610
611                 if (conn_data->lookup_data)
612                         sock_get_address_info_async_cancel
613                                 (conn_data->lookup_data);
614
615                 if (conn_data->io_tag > 0)
616                         g_source_remove(conn_data->io_tag);
617                 if (conn_data->channel) {
618                         g_io_channel_close(conn_data->channel);
619                         g_io_channel_unref(conn_data->channel);
620                 }
621
622                 sock_address_list_free(conn_data->addr_list);
623                 g_free(conn_data->hostname);
624                 g_free(conn_data);
625         } else {
626                 g_warning("sock_connect_async_cancel: id %d not found.\n", id);
627                 return -1;
628         }
629
630         return 0;
631 }
632
633 static gint sock_connect_address_list_async(SockConnectData *conn_data)
634 {
635         SockAddrData *addr_data;
636         gint sock = -1;
637
638         for (; conn_data->cur_addr != NULL;
639              conn_data->cur_addr = conn_data->cur_addr->next) {
640                 addr_data = (SockAddrData *)conn_data->cur_addr->data;
641
642                 if ((sock = socket(addr_data->family, addr_data->socktype,
643                                    addr_data->protocol)) < 0) {
644                         perror("socket");
645                         continue;
646                 }
647
648                 set_nonblocking_mode(sock, TRUE);
649
650                 if (connect(sock, addr_data->addr, addr_data->addr_len) < 0) {
651                         if (EINPROGRESS == errno) {
652                                 break;
653                         } else {
654                                 perror("connect");
655                                 close(sock);
656                         }
657                 } else
658                         break;
659         }
660
661         if (conn_data->cur_addr == NULL) {
662                 g_warning("sock_connect_address_list_async: "
663                           "connection to %s:%d failed\n",
664                           conn_data->hostname, conn_data->port);
665                 conn_data->func(NULL, conn_data->data);
666                 sock_connect_async_cancel(conn_data->id);
667                 return -1;
668         }
669
670         conn_data->cur_addr = conn_data->cur_addr->next;
671
672         conn_data->channel = g_io_channel_unix_new(sock);
673         conn_data->io_tag = g_io_add_watch(conn_data->channel, G_IO_IN|G_IO_OUT,
674                                            sock_connect_async_cb, conn_data);
675
676         return 0;
677 }
678
679 /* asynchronous DNS lookup */
680
681 static gboolean sock_get_address_info_async_cb(GIOChannel *source,
682                                                GIOCondition condition,
683                                                gpointer data)
684 {
685         SockLookupData *lookup_data = (SockLookupData *)data;
686         GList *addr_list = NULL;
687         SockAddrData *addr_data;
688         guint bytes_read;
689         gint ai_member[4];
690         struct sockaddr *addr;
691
692         for (;;) {
693                 if (g_io_channel_read(source, (gchar *)ai_member,
694                                       sizeof(ai_member), &bytes_read)
695                     != G_IO_ERROR_NONE) {
696                         g_warning("sock_get_address_info_async_cb: "
697                                   "address length read error\n");
698                         break;
699                 }
700
701                 if (bytes_read == 0 || bytes_read != sizeof(ai_member))
702                         break;
703
704                 if (ai_member[0] == AF_UNSPEC) {
705                         g_warning("DNS lookup failed\n");
706                         break;
707                 }
708
709                 addr = g_malloc(ai_member[3]);
710                 if (g_io_channel_read(source, (gchar *)addr, ai_member[3],
711                                       &bytes_read)
712                     != G_IO_ERROR_NONE) {
713                         g_warning("sock_get_address_info_async_cb: "
714                                   "address data read error\n");
715                         g_free(addr);
716                         break;
717                 }
718
719                 if (bytes_read != ai_member[3]) {
720                         g_warning("sock_get_address_info_async_cb: "
721                                   "incomplete address data\n");
722                         g_free(addr);
723                         break;
724                 }
725
726                 addr_data = g_new0(SockAddrData, 1);
727                 addr_data->family = ai_member[0];
728                 addr_data->socktype = ai_member[1];
729                 addr_data->protocol = ai_member[2];
730                 addr_data->addr_len = ai_member[3];
731                 addr_data->addr = addr;
732
733                 addr_list = g_list_append(addr_list, addr_data);
734         }
735
736         g_io_channel_close(source);
737         g_io_channel_unref(source);
738
739         kill(lookup_data->child_pid, SIGKILL);
740         waitpid(lookup_data->child_pid, NULL, 0);
741
742         lookup_data->func(addr_list, lookup_data->data);
743
744         g_free(lookup_data->hostname);
745         g_free(lookup_data);
746
747         return FALSE;
748 }
749
750 static SockLookupData *sock_get_address_info_async(const gchar *hostname,
751                                                    gushort port,
752                                                    SockAddrFunc func,
753                                                    gpointer data)
754 {
755         SockLookupData *lookup_data = NULL;
756         gint pipe_fds[2];
757         pid_t pid;
758
759         if (pipe(pipe_fds) < 0) {
760                 perror("pipe");
761                 func(NULL, data);
762                 return NULL;
763         }
764
765         if ((pid = fork()) < 0) {
766                 perror("fork");
767                 func(NULL, data);
768                 return NULL;
769         }
770
771         /* child process */
772         if (pid == 0) {
773 #ifdef INET6
774                 gint gai_err;
775                 struct addrinfo hints, *res, *ai;
776                 gchar port_str[6];
777 #else /* !INET6 */
778                 struct hostent *hp;
779                 gchar **addr_list_p;
780                 struct sockaddr_in ad;
781 #endif /* INET6 */
782                 gint ai_member[4] = {AF_UNSPEC, 0, 0, 0};
783
784                 close(pipe_fds[0]);
785
786 #ifdef INET6
787                 memset(&hints, 0, sizeof(hints));
788                 /* hints.ai_flags = AI_CANONNAME; */
789                 hints.ai_family = AF_UNSPEC;
790                 hints.ai_socktype = SOCK_STREAM;
791                 hints.ai_protocol = IPPROTO_TCP;
792
793                 g_snprintf(port_str, sizeof(port_str), "%d", port);
794
795                 gai_err = getaddrinfo(hostname, port_str, &hints, &res);
796                 if (gai_err != 0) {
797                         g_warning("getaddrinfo for %s:%s failed: %s\n",
798                                   hostname, port_str, gai_strerror(gai_err));
799                         fd_write_all(pipe_fds[1], (gchar *)ai_member,
800                                      sizeof(ai_member));
801                         close(pipe_fds[1]);
802                         _exit(1);
803                 }
804
805                 for (ai = res; ai != NULL; ai = ai->ai_next) {
806                         ai_member[0] = ai->ai_family;
807                         ai_member[1] = ai->ai_socktype;
808                         ai_member[2] = ai->ai_protocol;
809                         ai_member[3] = ai->ai_addrlen;
810
811                         fd_write_all(pipe_fds[1], (gchar *)ai_member,
812                                      sizeof(ai_member));
813                         fd_write_all(pipe_fds[1], (gchar *)ai->ai_addr,
814                                      ai->ai_addrlen);
815                 }
816
817                 if (res != NULL)
818                         freeaddrinfo(res);
819 #else /* !INET6 */
820                 hp = my_gethostbyname(hostname);
821                 if (hp == NULL || hp->h_addrtype != AF_INET) {
822                         fd_write_all(pipe_fds[1], (gchar *)ai_member,
823                                      sizeof(ai_member));
824                         close(pipe_fds[1]);
825                         _exit(1);
826                 }
827
828                 ai_member[0] = AF_INET;
829                 ai_member[1] = SOCK_STREAM;
830                 ai_member[2] = IPPROTO_TCP;
831                 ai_member[3] = sizeof(ad);
832
833                 memset(&ad, 0, sizeof(ad));
834                 ad.sin_family = AF_INET;
835                 ad.sin_port = htons(port);
836
837                 for (addr_list_p = hp->h_addr_list; *addr_list_p != NULL;
838                      addr_list_p++) {
839                         memcpy(&ad.sin_addr, *addr_list_p, hp->h_length);
840                         fd_write_all(pipe_fds[1], (gchar *)ai_member,
841                                      sizeof(ai_member));
842                         fd_write_all(pipe_fds[1], (gchar *)&ad, sizeof(ad));
843                 }
844 #endif /* INET6 */
845
846                 close(pipe_fds[1]);
847
848                 _exit(0);
849         } else {
850                 close(pipe_fds[1]);
851
852                 lookup_data = g_new0(SockLookupData, 1);
853                 lookup_data->hostname = g_strdup(hostname);
854                 lookup_data->child_pid = pid;
855                 lookup_data->func = func;
856                 lookup_data->data = data;
857
858                 lookup_data->channel = g_io_channel_unix_new(pipe_fds[0]);
859                 lookup_data->io_tag = g_io_add_watch
860                         (lookup_data->channel, G_IO_IN,
861                          sock_get_address_info_async_cb, lookup_data);
862         }
863
864         return lookup_data;
865 }
866
867 static gint sock_get_address_info_async_cancel(SockLookupData *lookup_data)
868 {
869         if (lookup_data->io_tag > 0)
870                 g_source_remove(lookup_data->io_tag);
871         if (lookup_data->channel) {
872                 g_io_channel_close(lookup_data->channel);
873                 g_io_channel_unref(lookup_data->channel);
874         }
875
876         if (lookup_data->child_pid > 0) {
877                 kill(lookup_data->child_pid, SIGKILL);
878                 waitpid(lookup_data->child_pid, NULL, 0);
879         }
880
881         g_free(lookup_data->hostname);
882         g_free(lookup_data);
883
884         return 0;
885 }
886
887
888 static SockInfo *sockinfo_from_fd(const gchar *hostname,
889                                   gushort port,
890                                   gint sock)
891 {
892         SockInfo *sockinfo;
893
894         sockinfo = g_new0(SockInfo, 1);
895         sockinfo->sock = sock;
896         sockinfo->hostname = g_strdup(hostname);
897         sockinfo->port = port;
898         sockinfo->state = CONN_ESTABLISHED;
899
900         usleep(100000);
901
902         return sockinfo;
903 }
904
905 gint sock_printf(SockInfo *sock, const gchar *format, ...)
906 {
907         va_list args;
908         gchar buf[BUFFSIZE];
909
910         va_start(args, format);
911         g_vsnprintf(buf, sizeof(buf), format, args);
912         va_end(args);
913
914         return sock_write_all(sock, buf, strlen(buf));
915 }
916
917 gint fd_read(gint fd, gchar *buf, gint len)
918 {
919         if (fd_check_io(fd, G_IO_IN) < 0)
920                 return -1;
921
922         return read(fd, buf, len);
923 }
924
925 #if USE_OPENSSL
926 gint ssl_read(SSL *ssl, gchar *buf, gint len)
927 {
928         return SSL_read(ssl, buf, len);
929 }
930 #endif
931
932 gint sock_read(SockInfo *sock, gchar *buf, gint len)
933 {
934         gint ret;
935
936         g_return_val_if_fail(sock != NULL, -1);
937
938 #if USE_OPENSSL
939         if (sock->ssl)
940                 ret = ssl_read(sock->ssl, buf, len);
941         else
942 #endif
943                 ret = fd_read(sock->sock, buf, len);
944         
945         if (ret < 0)
946                 sock->state = CONN_DISCONNECTED;
947         return ret;
948 }
949
950 gint fd_write(gint fd, const gchar *buf, gint len)
951 {
952         if (fd_check_io(fd, G_IO_OUT) < 0)
953                 return -1;
954
955         return write(fd, buf, len);
956 }
957
958 #if USE_OPENSSL
959 gint ssl_write(SSL *ssl, const gchar *buf, gint len)
960 {
961         return SSL_write(ssl, buf, len);
962 }
963 #endif
964
965 gint sock_write(SockInfo *sock, const gchar *buf, gint len)
966 {
967         gint ret;
968
969         g_return_val_if_fail(sock != NULL, -1);
970
971 #if USE_OPENSSL
972         if (sock->ssl)
973                 ret = ssl_write(sock->ssl, buf, len);
974         else
975 #endif
976                 ret = fd_write(sock->sock, buf, len);
977
978         if (ret < 0)
979                 sock->state = CONN_DISCONNECTED;
980         return ret;
981 }
982
983 gint fd_write_all(gint fd, const gchar *buf, gint len)
984 {
985         gint n, wrlen = 0;
986
987         while (len) {
988                 if (fd_check_io(fd, G_IO_OUT) < 0)
989                         return -1;
990                 signal(SIGPIPE, SIG_IGN);
991                 n = write(fd, buf, len);
992                 if (n <= 0) {
993                         log_error("write on fd%d: %s\n", fd, strerror(errno));
994                         return -1;
995                 }
996                 len -= n;
997                 wrlen += n;
998                 buf += n;
999         }
1000
1001         return wrlen;
1002 }
1003
1004 #if USE_OPENSSL
1005 gint ssl_write_all(SSL *ssl, const gchar *buf, gint len)
1006 {
1007         gint n, wrlen = 0;
1008
1009         while (len) {
1010                 n = SSL_write(ssl, buf, len);
1011                 if (n <= 0)
1012                         return -1;
1013                 len -= n;
1014                 wrlen += n;
1015                 buf += n;
1016         }
1017
1018         return wrlen;
1019 }
1020 #endif
1021
1022 gint sock_write_all(SockInfo *sock, const gchar *buf, gint len)
1023 {
1024         gint ret;
1025
1026         g_return_val_if_fail(sock != NULL, -1);
1027
1028 #if USE_OPENSSL
1029         if (sock->ssl)
1030                 ret = ssl_write_all(sock->ssl, buf, len);
1031         else
1032 #endif
1033                 ret = fd_write_all(sock->sock, buf, len);
1034
1035         if (ret < 0)
1036                 sock->state = CONN_DISCONNECTED;
1037         return ret;
1038 }
1039
1040 gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
1041 {
1042         if (fd_check_io(fd, G_IO_IN) < 0)
1043                 return -1;
1044
1045         return recv(fd, buf, len, flags);
1046 }
1047
1048 gint fd_gets(gint fd, gchar *buf, gint len)
1049 {
1050         gchar *newline, *bp = buf;
1051         gint n;
1052
1053         if (--len < 1)
1054                 return -1;
1055         do {
1056                 if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
1057                         return -1;
1058                 if ((newline = memchr(bp, '\n', n)) != NULL)
1059                         n = newline - bp + 1;
1060                 if ((n = fd_read(fd, bp, n)) < 0)
1061                         return -1;
1062                 bp += n;
1063                 len -= n;
1064         } while (!newline && len);
1065
1066         *bp = '\0';
1067         return bp - buf;
1068 }
1069
1070 #if USE_OPENSSL
1071 gint ssl_gets(SSL *ssl, gchar *buf, gint len)
1072 {
1073         gchar *newline, *bp = buf;
1074         gint n;
1075
1076         if (--len < 1)
1077                 return -1;
1078         do {
1079                 if ((n = SSL_peek(ssl, bp, len)) <= 0)
1080                         return -1;
1081                 if ((newline = memchr(bp, '\n', n)) != NULL)
1082                         n = newline - bp + 1;
1083                 if ((n = SSL_read(ssl, bp, n)) < 0)
1084                         return -1;
1085                 bp += n;
1086                 len -= n;
1087         } while (!newline && len);
1088
1089         *bp = '\0';
1090         return bp - buf;
1091 }
1092 #endif
1093
1094 gint sock_gets(SockInfo *sock, gchar *buf, gint len)
1095 {
1096         gint ret;
1097
1098         g_return_val_if_fail(sock != NULL, -1);
1099
1100 #if USE_OPENSSL
1101         if (sock->ssl)
1102                 return ssl_gets(sock->ssl, buf, len);
1103         else
1104 #endif
1105                 return fd_gets(sock->sock, buf, len);
1106
1107         if (ret < 0)
1108                 sock->state = CONN_DISCONNECTED;
1109         return ret;
1110 }
1111
1112 gint fd_getline(gint fd, gchar **str)
1113 {
1114         gchar buf[BUFFSIZE];
1115         gint len;
1116         gulong size = 1;
1117
1118         while ((len = fd_gets(fd, buf, sizeof(buf))) > 0) {
1119                 size += len;
1120                 if (!*str)
1121                         *str = g_strdup(buf);
1122                 else {
1123                         *str = g_realloc(*str, size);
1124                         strcat(*str, buf);
1125                 }
1126                 if (buf[len - 1] == '\n')
1127                         break;
1128         }
1129         if (len == -1 && *str)
1130                 g_free(*str);
1131
1132         return len;
1133 }
1134
1135 #if USE_OPENSSL
1136 gint ssl_getline(SSL *ssl, gchar **str)
1137 {
1138         gchar buf[BUFFSIZE];
1139         gint len;
1140         gulong size = 1;
1141
1142         while ((len = ssl_gets(ssl, buf, sizeof(buf))) > 0) {
1143                 size += len;
1144                 if (!*str)
1145                         *str = g_strdup(buf);
1146                 else {
1147                         *str = g_realloc(*str, size);
1148                         strcat(*str, buf);
1149                 }
1150                 if (buf[len - 1] == '\n')
1151                         break;
1152         }
1153         if (len == -1 && *str)
1154                 g_free(*str);
1155
1156         return len;
1157 }
1158 #endif
1159
1160 gchar *sock_getline(SockInfo *sock)
1161 {
1162         gint ret;
1163         gchar *str = NULL;
1164
1165         g_return_val_if_fail(sock != NULL, NULL);
1166
1167 #if USE_OPENSSL
1168         if (sock->ssl)
1169                 ret = ssl_getline(sock->ssl, &str);
1170         else
1171 #endif
1172                 ret = fd_getline(sock->sock, &str);
1173
1174         if (ret < 0)
1175                 sock->state = CONN_DISCONNECTED;
1176         return str;
1177 }
1178
1179 gint sock_puts(SockInfo *sock, const gchar *buf)
1180 {
1181         gint ret;
1182
1183         if ((ret = sock_write_all(sock, buf, strlen(buf))) < 0)
1184                 return ret;
1185         return sock_write_all(sock, "\r\n", 2);
1186 }
1187
1188 /* peek at the socket data without actually reading it */
1189 gint sock_peek(SockInfo *sock, gchar *buf, gint len)
1190 {
1191         g_return_val_if_fail(sock != NULL, -1);
1192
1193 #if USE_OPENSSL
1194         if (sock->ssl)
1195                 return SSL_peek(sock->ssl, buf, len);
1196 #endif
1197         return fd_recv(sock->sock, buf, len, MSG_PEEK);
1198 }
1199
1200 gint sock_close(SockInfo *sock)
1201 {
1202         gint ret;
1203
1204         if (!sock)
1205                 return 0;
1206
1207 #if USE_OPENSSL
1208         if (sock->ssl)
1209                 ssl_done_socket(sock);
1210 #endif
1211         ret = fd_close(sock->sock); 
1212         g_free(sock->hostname);
1213         g_free(sock);
1214
1215         return ret;
1216 }
1217
1218 gint fd_close(gint fd)
1219 {
1220         return close(fd);
1221 }