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