2005-10-19 [colin] 1.9.15cvs76
[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                 return sock->g_source;
428         }
429 #endif
430
431         return g_io_add_watch(sock->sock_ch, condition, sock_watch_cb, sock);
432 }
433
434 static gint fd_check_io(gint fd, GIOCondition cond)
435 {
436         struct timeval timeout;
437         fd_set fds;
438
439         if (is_nonblocking_mode(fd))
440                 return 0;
441
442         timeout.tv_sec  = io_timeout;
443         timeout.tv_usec = 0;
444
445         FD_ZERO(&fds);
446         FD_SET(fd, &fds);
447
448         if (cond == G_IO_IN) {
449                 select(fd + 1, &fds, NULL, NULL,
450                        io_timeout > 0 ? &timeout : NULL);
451         } else {
452                 select(fd + 1, NULL, &fds, NULL,
453                        io_timeout > 0 ? &timeout : NULL);
454         }
455
456         if (FD_ISSET(fd, &fds)) {
457                 return 0;
458         } else {
459                 g_warning("Socket IO timeout\n");
460                 return -1;
461         }
462 }
463
464 #ifdef G_OS_UNIX
465 static sigjmp_buf jmpenv;
466
467 static void timeout_handler(gint sig)
468 {
469         siglongjmp(jmpenv, 1);
470 }
471 #endif
472
473 static gint sock_connect_with_timeout(gint sock,
474                                       const struct sockaddr *serv_addr,
475                                       gint addrlen,
476                                       guint timeout_secs)
477 {
478         gint ret;
479 #ifdef G_OS_UNIX
480         void (*prev_handler)(gint);
481         
482         alarm(0);
483         prev_handler = signal(SIGALRM, timeout_handler);
484         if (sigsetjmp(jmpenv, 1)) {
485                 alarm(0);
486                 signal(SIGALRM, prev_handler);
487                 errno = ETIMEDOUT;
488                 return -1;
489         }
490         alarm(timeout_secs);
491 #endif
492
493         ret = connect(sock, serv_addr, addrlen);
494
495 #ifdef G_OS_UNIX
496         alarm(0);
497         signal(SIGALRM, prev_handler);
498 #endif
499
500         return ret;
501 }
502
503 struct hostent *my_gethostbyname(const gchar *hostname)
504 {
505         struct hostent *hp;
506 #ifdef G_OS_UNIX
507         void (*prev_handler)(gint);
508         
509         alarm(0);
510         prev_handler = signal(SIGALRM, timeout_handler);
511         if (sigsetjmp(jmpenv, 1)) {
512                 alarm(0);
513                 signal(SIGALRM, prev_handler);
514                 fprintf(stderr, "%s: host lookup timed out.\n", hostname);
515                 errno = 0;
516                 return NULL;
517         }
518         alarm(io_timeout);
519 #endif
520
521         if ((hp = gethostbyname(hostname)) == NULL) {
522 #ifdef G_OS_UNIX
523                 alarm(0);
524                 signal(SIGALRM, prev_handler);
525 #endif
526                 fprintf(stderr, "%s: unknown host.\n", hostname);
527                 errno = 0;
528                 return NULL;
529         }
530
531 #ifdef G_OS_UNIX
532         alarm(0);
533         signal(SIGALRM, prev_handler);
534 #endif
535
536         return hp;
537 }
538
539 #ifndef INET6
540 static gint my_inet_aton(const gchar *hostname, struct in_addr *inp)
541 {
542 #if HAVE_INET_ATON
543         return inet_aton(hostname, inp);
544 #else
545 #if HAVE_INET_ADDR
546         guint32 inaddr;
547
548         inaddr = inet_addr(hostname);
549         if (inaddr != -1) {
550                 memcpy(inp, &inaddr, sizeof(inaddr));
551                 return 1;
552         } else
553                 return 0;
554 #else
555         return 0;
556 #endif
557 #endif /* HAVE_INET_ATON */
558 }
559
560 static gint sock_connect_by_hostname(gint sock, const gchar *hostname,
561                                      gushort port)
562 {
563         struct hostent *hp;
564         struct sockaddr_in ad;
565
566         memset(&ad, 0, sizeof(ad));
567         ad.sin_family = AF_INET;
568         ad.sin_port = htons(port);
569
570         refresh_resolvers();
571
572         if (!my_inet_aton(hostname, &ad.sin_addr)) {
573                 if ((hp = my_gethostbyname(hostname)) == NULL) {
574                         fprintf(stderr, "%s: unknown host.\n", hostname);
575                         errno = 0;
576                         return -1;
577                 }
578
579                 if (hp->h_length != 4 && hp->h_length != 8) {
580                         fprintf(stderr, "illegal address length received for host %s\n", hostname);
581                         errno = 0;
582                         return -1;
583                 }
584
585                 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
586         }
587
588         return sock_connect_with_timeout(sock, (struct sockaddr *)&ad,
589                                          sizeof(ad), io_timeout);
590 }
591
592 #else /* INET6 */
593 static gint sock_connect_by_getaddrinfo(const gchar *hostname, gushort  port)
594 {
595         gint sock = -1, gai_error;
596         struct addrinfo hints, *res, *ai;
597         gchar port_str[6];
598
599         refresh_resolvers();
600
601         memset(&hints, 0, sizeof(hints));
602         /* hints.ai_flags = AI_CANONNAME; */
603         hints.ai_family = AF_UNSPEC;
604         hints.ai_socktype = SOCK_STREAM;
605         hints.ai_protocol = IPPROTO_TCP;
606
607         /* convert port from integer to string. */
608         g_snprintf(port_str, sizeof(port_str), "%d", port);
609
610         if ((gai_error = getaddrinfo(hostname, port_str, &hints, &res)) != 0) {
611                 fprintf(stderr, "getaddrinfo for %s:%s failed: %s\n",
612                         hostname, port_str, gai_strerror(gai_error));
613                 return -1;
614         }
615
616         for (ai = res; ai != NULL; ai = ai->ai_next) {
617                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
618                 if (sock < 0)
619                         continue;
620
621                 if (sock_connect_with_timeout
622                         (sock, ai->ai_addr, ai->ai_addrlen, io_timeout) == 0)
623                         break;
624
625                 close(sock);
626         }
627
628         if (res != NULL)
629                 freeaddrinfo(res);
630
631         if (ai == NULL)
632                 return -1;
633
634         return sock;
635 }
636 #endif /* !INET6 */
637
638
639 /* Open a connection using an external program.  May be useful when
640  * you need to tunnel through a SOCKS or other firewall, or to
641  * establish an IMAP-over-SSH connection. */
642 /* TODO: Recreate this for sock_connect_thread() */
643 SockInfo *sock_connect_cmd(const gchar *hostname, const gchar *tunnelcmd)
644 {
645         gint fd[2];
646         int r;
647                      
648         if ((r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) == -1) {
649                 perror("socketpair");
650                 return NULL;
651         }
652         log_message("launching tunnel command \"%s\"\n", tunnelcmd);
653         if (fork() == 0) {
654                 close(fd[0]);
655                 close(0);
656                 close(1);
657                 dup(fd[1]);     /* set onto stdin */
658                 dup(fd[1]);
659                 execlp("/bin/sh", "/bin/sh", "-c", tunnelcmd, NULL);
660         }
661
662         close(fd[1]);
663         return sockinfo_from_fd(hostname, 0, fd[0]);
664 }
665
666
667 SockInfo *sock_connect(const gchar *hostname, gushort port)
668 {
669 #ifdef G_OS_WIN32
670         SOCKET sock;
671 #else
672         gint sock;
673 #endif
674
675 #ifdef INET6
676         if ((sock = sock_connect_by_getaddrinfo(hostname, port)) < 0)
677                 return NULL;
678 #else
679 #ifdef G_OS_WIN32
680         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
681                 g_warning("socket() failed: %ld\n", WSAGetLastError());
682 #else
683         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
684                 perror("socket");
685 #endif /* G_OS_WIN32 */
686                 return NULL;
687         }
688
689         if (sock_connect_by_hostname(sock, hostname, port) < 0) {
690                 if (errno != 0) perror("connect");
691                 close(sock);
692                 return NULL;
693         }
694 #endif /* INET6 */
695
696         return sockinfo_from_fd(hostname, port, sock);
697 }
698
699 #ifdef G_OS_UNIX
700 static void sock_address_list_free(GList *addr_list)
701 {
702         GList *cur;
703
704         for (cur = addr_list; cur != NULL; cur = cur->next) {
705                 SockAddrData *addr_data = (SockAddrData *)cur->data;
706                 g_free(addr_data->addr);
707                 g_free(addr_data);
708         }
709
710         g_list_free(addr_list);
711 }
712
713 /* asynchronous TCP connection */
714
715 static gboolean sock_connect_async_cb(GIOChannel *source,
716                                       GIOCondition condition, gpointer data)
717 {
718         SockConnectData *conn_data = (SockConnectData *)data;
719         gint fd;
720         gint val;
721         guint len;
722         SockInfo *sockinfo;
723
724         if (conn_data->io_tag == 0 && conn_data->channel == NULL)
725                 return FALSE;
726
727         fd = g_io_channel_unix_get_fd(source);
728
729         conn_data->io_tag = 0;
730         conn_data->channel = NULL;
731         g_io_channel_unref(source);
732
733         len = sizeof(val);
734         if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &len) < 0) {
735                 perror("getsockopt");
736                 close(fd);
737                 sock_connect_address_list_async(conn_data);
738                 return FALSE;
739         }
740
741         if (val != 0) {
742                 close(fd);
743                 sock_connect_address_list_async(conn_data);
744                 return FALSE;
745         }
746
747         sockinfo = g_new0(SockInfo, 1);
748         sockinfo->sock = fd;
749         sockinfo->sock_ch = g_io_channel_unix_new(fd);
750         sockinfo->hostname = g_strdup(conn_data->hostname);
751         sockinfo->port = conn_data->port;
752         sockinfo->state = CONN_ESTABLISHED;
753
754         conn_data->func(sockinfo, conn_data->data);
755
756         sock_connect_async_cancel(conn_data->id);
757
758         return FALSE;
759 }
760
761 static gint sock_connect_async_get_address_info_cb(GList *addr_list,
762                                                    gpointer data)
763 {
764         SockConnectData *conn_data = (SockConnectData *)data;
765
766         conn_data->addr_list = addr_list;
767         conn_data->cur_addr = addr_list;
768         conn_data->lookup_data = NULL;
769
770         return sock_connect_address_list_async(conn_data);
771 }
772
773 gint sock_connect_async(const gchar *hostname, gushort port,
774                         SockConnectFunc func, gpointer data)
775 {
776         static gint id = 1;
777         SockConnectData *conn_data;
778
779         conn_data = g_new0(SockConnectData, 1);
780         conn_data->id = id++;
781         conn_data->hostname = g_strdup(hostname);
782         conn_data->port = port;
783         conn_data->addr_list = NULL;
784         conn_data->cur_addr = NULL;
785         conn_data->io_tag = 0;
786         conn_data->func = func;
787         conn_data->data = data;
788
789         conn_data->lookup_data = sock_get_address_info_async
790                 (hostname, port, sock_connect_async_get_address_info_cb,
791                  conn_data);
792
793         if (conn_data->lookup_data == NULL) {
794                 g_free(conn_data->hostname);
795                 g_free(conn_data);
796                 return -1;
797         }
798
799         sock_connect_data_list = g_list_append(sock_connect_data_list,
800                                                conn_data);
801
802         return conn_data->id;
803 }
804
805 gint sock_connect_async_cancel(gint id)
806 {
807         SockConnectData *conn_data = NULL;
808         GList *cur;
809
810         for (cur = sock_connect_data_list; cur != NULL; cur = cur->next) {
811                 if (((SockConnectData *)cur->data)->id == id) {
812                         conn_data = (SockConnectData *)cur->data;
813                         break;
814                 }
815         }
816
817         if (conn_data) {
818                 sock_connect_data_list = g_list_remove(sock_connect_data_list,
819                                                        conn_data);
820
821                 if (conn_data->lookup_data)
822                         sock_get_address_info_async_cancel
823                                 (conn_data->lookup_data);
824
825                 if (conn_data->io_tag > 0)
826                         g_source_remove(conn_data->io_tag);
827                 if (conn_data->channel) {
828                         g_io_channel_close(conn_data->channel);
829                         g_io_channel_unref(conn_data->channel);
830                 }
831
832                 sock_address_list_free(conn_data->addr_list);
833                 g_free(conn_data->hostname);
834                 g_free(conn_data);
835         } else {
836                 g_warning("sock_connect_async_cancel: id %d not found.\n", id);
837                 return -1;
838         }
839
840         return 0;
841 }
842
843 static gint sock_connect_address_list_async(SockConnectData *conn_data)
844 {
845         SockAddrData *addr_data;
846         gint sock = -1;
847
848         for (; conn_data->cur_addr != NULL;
849              conn_data->cur_addr = conn_data->cur_addr->next) {
850                 addr_data = (SockAddrData *)conn_data->cur_addr->data;
851
852                 if ((sock = socket(addr_data->family, addr_data->socktype,
853                                    addr_data->protocol)) < 0) {
854                         perror("socket");
855                         continue;
856                 }
857
858                 set_nonblocking_mode(sock, TRUE);
859
860                 if (connect(sock, addr_data->addr, addr_data->addr_len) < 0) {
861                         if (EINPROGRESS == errno) {
862                                 break;
863                         } else {
864                                 perror("connect");
865                                 close(sock);
866                         }
867                 } else
868                         break;
869         }
870
871         if (conn_data->cur_addr == NULL) {
872                 g_warning("sock_connect_address_list_async: "
873                           "connection to %s:%d failed\n",
874                           conn_data->hostname, conn_data->port);
875                 conn_data->func(NULL, conn_data->data);
876                 sock_connect_async_cancel(conn_data->id);
877                 return -1;
878         }
879
880         conn_data->cur_addr = conn_data->cur_addr->next;
881
882         conn_data->channel = g_io_channel_unix_new(sock);
883         conn_data->io_tag = g_io_add_watch(conn_data->channel, G_IO_IN|G_IO_OUT,
884                                            sock_connect_async_cb, conn_data);
885
886         return 0;
887 }
888
889 /* asynchronous DNS lookup */
890
891 static gboolean sock_get_address_info_async_cb(GIOChannel *source,
892                                                GIOCondition condition,
893                                                gpointer data)
894 {
895         SockLookupData *lookup_data = (SockLookupData *)data;
896         GList *addr_list = NULL;
897         SockAddrData *addr_data;
898         gsize bytes_read;
899         gint ai_member[4];
900         struct sockaddr *addr;
901
902         for (;;) {
903                 if (g_io_channel_read(source, (gchar *)ai_member,
904                                       sizeof(ai_member), &bytes_read)
905                     != G_IO_ERROR_NONE) {
906                         g_warning("sock_get_address_info_async_cb: "
907                                   "address length read error\n");
908                         break;
909                 }
910
911                 if (bytes_read == 0 || bytes_read != sizeof(ai_member))
912                         break;
913
914                 if (ai_member[0] == AF_UNSPEC) {
915                         g_warning("DNS lookup failed\n");
916                         break;
917                 }
918
919                 addr = g_malloc(ai_member[3]);
920                 if (g_io_channel_read(source, (gchar *)addr, ai_member[3],
921                                       &bytes_read)
922                     != G_IO_ERROR_NONE) {
923                         g_warning("sock_get_address_info_async_cb: "
924                                   "address data read error\n");
925                         g_free(addr);
926                         break;
927                 }
928
929                 if (bytes_read != ai_member[3]) {
930                         g_warning("sock_get_address_info_async_cb: "
931                                   "incomplete address data\n");
932                         g_free(addr);
933                         break;
934                 }
935
936                 addr_data = g_new0(SockAddrData, 1);
937                 addr_data->family = ai_member[0];
938                 addr_data->socktype = ai_member[1];
939                 addr_data->protocol = ai_member[2];
940                 addr_data->addr_len = ai_member[3];
941                 addr_data->addr = addr;
942
943                 addr_list = g_list_append(addr_list, addr_data);
944         }
945
946         g_io_channel_close(source);
947         g_io_channel_unref(source);
948
949         kill(lookup_data->child_pid, SIGKILL);
950         waitpid(lookup_data->child_pid, NULL, 0);
951
952         lookup_data->func(addr_list, lookup_data->data);
953
954         g_free(lookup_data->hostname);
955         g_free(lookup_data);
956
957         return FALSE;
958 }
959
960 static SockLookupData *sock_get_address_info_async(const gchar *hostname,
961                                                    gushort port,
962                                                    SockAddrFunc func,
963                                                    gpointer data)
964 {
965         SockLookupData *lookup_data = NULL;
966         gint pipe_fds[2];
967         pid_t pid;
968         
969         refresh_resolvers();
970
971         if (pipe(pipe_fds) < 0) {
972                 perror("pipe");
973                 func(NULL, data);
974                 return NULL;
975         }
976
977         if ((pid = fork()) < 0) {
978                 perror("fork");
979                 func(NULL, data);
980                 return NULL;
981         }
982
983         /* child process */
984         if (pid == 0) {
985 #ifdef INET6
986                 gint gai_err;
987                 struct addrinfo hints, *res, *ai;
988                 gchar port_str[6];
989 #else /* !INET6 */
990                 struct hostent *hp;
991                 gchar **addr_list_p;
992                 struct sockaddr_in ad;
993 #endif /* INET6 */
994                 gint ai_member[4] = {AF_UNSPEC, 0, 0, 0};
995
996                 close(pipe_fds[0]);
997
998 #ifdef INET6
999                 memset(&hints, 0, sizeof(hints));
1000                 /* hints.ai_flags = AI_CANONNAME; */
1001                 hints.ai_family = AF_UNSPEC;
1002                 hints.ai_socktype = SOCK_STREAM;
1003                 hints.ai_protocol = IPPROTO_TCP;
1004
1005                 g_snprintf(port_str, sizeof(port_str), "%d", port);
1006
1007                 gai_err = getaddrinfo(hostname, port_str, &hints, &res);
1008                 if (gai_err != 0) {
1009                         g_warning("getaddrinfo for %s:%s failed: %s\n",
1010                                   hostname, port_str, gai_strerror(gai_err));
1011                         fd_write_all(pipe_fds[1], (gchar *)ai_member,
1012                                      sizeof(ai_member));
1013                         close(pipe_fds[1]);
1014                         _exit(1);
1015                 }
1016
1017                 for (ai = res; ai != NULL; ai = ai->ai_next) {
1018                         ai_member[0] = ai->ai_family;
1019                         ai_member[1] = ai->ai_socktype;
1020                         ai_member[2] = ai->ai_protocol;
1021                         ai_member[3] = ai->ai_addrlen;
1022
1023                         fd_write_all(pipe_fds[1], (gchar *)ai_member,
1024                                      sizeof(ai_member));
1025                         fd_write_all(pipe_fds[1], (gchar *)ai->ai_addr,
1026                                      ai->ai_addrlen);
1027                 }
1028
1029                 if (res != NULL)
1030                         freeaddrinfo(res);
1031 #else /* !INET6 */
1032                 hp = my_gethostbyname(hostname);
1033                 if (hp == NULL || hp->h_addrtype != AF_INET) {
1034                         fd_write_all(pipe_fds[1], (gchar *)ai_member,
1035                                      sizeof(ai_member));
1036                         close(pipe_fds[1]);
1037                         _exit(1);
1038                 }
1039
1040                 ai_member[0] = AF_INET;
1041                 ai_member[1] = SOCK_STREAM;
1042                 ai_member[2] = IPPROTO_TCP;
1043                 ai_member[3] = sizeof(ad);
1044
1045                 memset(&ad, 0, sizeof(ad));
1046                 ad.sin_family = AF_INET;
1047                 ad.sin_port = htons(port);
1048
1049                 for (addr_list_p = hp->h_addr_list; *addr_list_p != NULL;
1050                      addr_list_p++) {
1051                         memcpy(&ad.sin_addr, *addr_list_p, hp->h_length);
1052                         fd_write_all(pipe_fds[1], (gchar *)ai_member,
1053                                      sizeof(ai_member));
1054                         fd_write_all(pipe_fds[1], (gchar *)&ad, sizeof(ad));
1055                 }
1056 #endif /* INET6 */
1057
1058                 close(pipe_fds[1]);
1059
1060                 _exit(0);
1061         } else {
1062                 close(pipe_fds[1]);
1063
1064                 lookup_data = g_new0(SockLookupData, 1);
1065                 lookup_data->hostname = g_strdup(hostname);
1066                 lookup_data->child_pid = pid;
1067                 lookup_data->func = func;
1068                 lookup_data->data = data;
1069
1070                 lookup_data->channel = g_io_channel_unix_new(pipe_fds[0]);
1071                 lookup_data->io_tag = g_io_add_watch
1072                         (lookup_data->channel, G_IO_IN,
1073                          sock_get_address_info_async_cb, lookup_data);
1074         }
1075
1076         return lookup_data;
1077 }
1078
1079 static gint sock_get_address_info_async_cancel(SockLookupData *lookup_data)
1080 {
1081         if (lookup_data->io_tag > 0)
1082                 g_source_remove(lookup_data->io_tag);
1083         if (lookup_data->channel) {
1084                 g_io_channel_close(lookup_data->channel);
1085                 g_io_channel_unref(lookup_data->channel);
1086         }
1087
1088         if (lookup_data->child_pid > 0) {
1089                 kill(lookup_data->child_pid, SIGKILL);
1090                 waitpid(lookup_data->child_pid, NULL, 0);
1091         }
1092
1093         g_free(lookup_data->hostname);
1094         g_free(lookup_data);
1095
1096         return 0;
1097 }
1098 #endif /* G_OS_UNIX */
1099
1100
1101 static SockInfo *sockinfo_from_fd(const gchar *hostname,
1102                                   gushort port,
1103                                   gint sock)
1104 {
1105         SockInfo *sockinfo;
1106
1107         sockinfo = g_new0(SockInfo, 1);
1108         sockinfo->sock = sock;
1109         sockinfo->sock_ch = g_io_channel_unix_new(sock);
1110         sockinfo->hostname = g_strdup(hostname);
1111         sockinfo->port = port;
1112         sockinfo->state = CONN_ESTABLISHED;
1113
1114         return sockinfo;
1115 }
1116
1117 gint sock_printf(SockInfo *sock, const gchar *format, ...)
1118 {
1119         va_list args;
1120         gchar buf[BUFFSIZE];
1121
1122         va_start(args, format);
1123         g_vsnprintf(buf, sizeof(buf), format, args);
1124         va_end(args);
1125
1126         return sock_write_all(sock, buf, strlen(buf));
1127 }
1128
1129 gint fd_read(gint fd, gchar *buf, gint len)
1130 {
1131         if (fd_check_io(fd, G_IO_IN) < 0)
1132                 return -1;
1133
1134 #ifdef G_OS_WIN32
1135         return recv(fd, buf, len, 0);
1136 #else
1137         return read(fd, buf, len);
1138 #endif
1139 }
1140
1141 #if USE_OPENSSL
1142 gint ssl_read(SSL *ssl, gchar *buf, gint len)
1143 {
1144         gint err, ret;
1145
1146         if (SSL_pending(ssl) == 0) {
1147                 if (fd_check_io(SSL_get_rfd(ssl), G_IO_IN) < 0)
1148                         return -1;
1149         }
1150
1151         ret = SSL_read(ssl, buf, len);
1152
1153         switch ((err = SSL_get_error(ssl, ret))) {
1154         case SSL_ERROR_NONE:
1155                 return ret;
1156         case SSL_ERROR_WANT_READ:
1157         case SSL_ERROR_WANT_WRITE:
1158                 errno = EAGAIN;
1159                 return -1;
1160         case SSL_ERROR_ZERO_RETURN:
1161                 return 0;
1162         default:
1163                 g_warning("SSL_read() returned error %d, ret = %d\n", err, ret);
1164                 if (ret == 0)
1165                         return 0;
1166                 return -1;
1167         }
1168 }
1169 #endif
1170
1171 gint sock_read(SockInfo *sock, gchar *buf, gint len)
1172 {
1173         gint ret;
1174
1175         g_return_val_if_fail(sock != NULL, -1);
1176
1177 #if USE_OPENSSL
1178         if (sock->ssl)
1179                 ret = ssl_read(sock->ssl, buf, len);
1180         else
1181 #endif
1182                 ret = fd_read(sock->sock, buf, len);
1183         
1184         if (ret < 0)
1185                 sock->state = CONN_DISCONNECTED;
1186         return ret;
1187 }
1188
1189 gint fd_write(gint fd, const gchar *buf, gint len)
1190 {
1191         if (fd_check_io(fd, G_IO_OUT) < 0)
1192                 return -1;
1193
1194 #ifdef G_OS_WIN32
1195         return send(fd, buf, len, 0);
1196 #else
1197         return write(fd, buf, len);
1198 #endif
1199 }
1200
1201 #if USE_OPENSSL
1202 gint ssl_write(SSL *ssl, const gchar *buf, gint len)
1203 {
1204         gint ret;
1205
1206         ret = SSL_write(ssl, buf, len);
1207
1208         switch (SSL_get_error(ssl, ret)) {
1209         case SSL_ERROR_NONE:
1210                 return ret;
1211         case SSL_ERROR_WANT_READ:
1212         case SSL_ERROR_WANT_WRITE:
1213                 errno = EAGAIN;
1214                 return -1;
1215         default:
1216                 return -1;
1217         }
1218 }
1219 #endif
1220
1221 gint sock_write(SockInfo *sock, const gchar *buf, gint len)
1222 {
1223         gint ret;
1224
1225         g_return_val_if_fail(sock != NULL, -1);
1226
1227 #if USE_OPENSSL
1228         if (sock->ssl)
1229                 ret = ssl_write(sock->ssl, buf, len);
1230         else
1231 #endif
1232                 ret = fd_write(sock->sock, buf, len);
1233
1234         if (ret < 0)
1235                 sock->state = CONN_DISCONNECTED;
1236         return ret;
1237 }
1238
1239 gint fd_write_all(gint fd, const gchar *buf, gint len)
1240 {
1241         gint n, wrlen = 0;
1242
1243         while (len) {
1244                 if (fd_check_io(fd, G_IO_OUT) < 0)
1245                         return -1;
1246                 signal(SIGPIPE, SIG_IGN);
1247                 n = write(fd, buf, len);
1248                 if (n <= 0) {
1249                         log_error("write on fd%d: %s\n", fd, strerror(errno));
1250                         return -1;
1251                 }
1252                 len -= n;
1253                 wrlen += n;
1254                 buf += n;
1255         }
1256
1257         return wrlen;
1258 }
1259
1260 #if USE_OPENSSL
1261 gint ssl_write_all(SSL *ssl, const gchar *buf, gint len)
1262 {
1263         gint n, wrlen = 0;
1264
1265         while (len) {
1266                 n = ssl_write(ssl, buf, len);
1267                 if (n <= 0)
1268                         return -1;
1269                 len -= n;
1270                 wrlen += n;
1271                 buf += n;
1272         }
1273
1274         return wrlen;
1275 }
1276 #endif
1277
1278 gint sock_write_all(SockInfo *sock, const gchar *buf, gint len)
1279 {
1280         gint ret;
1281
1282         g_return_val_if_fail(sock != NULL, -1);
1283
1284 #if USE_OPENSSL
1285         if (sock->ssl)
1286                 ret = ssl_write_all(sock->ssl, buf, len);
1287         else
1288 #endif
1289                 ret = fd_write_all(sock->sock, buf, len);
1290
1291         if (ret < 0)
1292                 sock->state = CONN_DISCONNECTED;
1293         return ret;
1294 }
1295
1296 gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
1297 {
1298         if (fd_check_io(fd, G_IO_IN) < 0)
1299                 return -1;
1300
1301         return recv(fd, buf, len, flags);
1302 }
1303
1304 gint fd_gets(gint fd, gchar *buf, gint len)
1305 {
1306         gchar *newline, *bp = buf;
1307         gint n;
1308
1309         if (--len < 1)
1310                 return -1;
1311         do {
1312                 if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
1313                         return -1;
1314                 if ((newline = memchr(bp, '\n', n)) != NULL)
1315                         n = newline - bp + 1;
1316                 if ((n = fd_read(fd, bp, n)) < 0)
1317                         return -1;
1318                 bp += n;
1319                 len -= n;
1320         } while (!newline && len);
1321
1322         *bp = '\0';
1323         return bp - buf;
1324 }
1325
1326 #if USE_OPENSSL
1327 gint ssl_gets(SSL *ssl, gchar *buf, gint len)
1328 {
1329         gchar *newline, *bp = buf;
1330         gint n;
1331
1332         if (--len < 1)
1333                 return -1;
1334         do {
1335                 if ((n = ssl_peek(ssl, bp, len)) <= 0)
1336                         return -1;
1337                 if ((newline = memchr(bp, '\n', n)) != NULL)
1338                         n = newline - bp + 1;
1339                 if ((n = ssl_read(ssl, bp, n)) < 0)
1340                         return -1;
1341                 bp += n;
1342                 len -= n;
1343         } while (!newline && len);
1344
1345         *bp = '\0';
1346         return bp - buf;
1347 }
1348 #endif
1349
1350 gint sock_gets(SockInfo *sock, gchar *buf, gint len)
1351 {
1352         gint ret;
1353
1354         g_return_val_if_fail(sock != NULL, -1);
1355
1356 #if USE_OPENSSL
1357         if (sock->ssl)
1358                 return ssl_gets(sock->ssl, buf, len);
1359         else
1360 #endif
1361                 return fd_gets(sock->sock, buf, len);
1362
1363         if (ret < 0)
1364                 sock->state = CONN_DISCONNECTED;
1365         return ret;
1366 }
1367
1368 gint fd_getline(gint fd, gchar **str)
1369 {
1370         gchar buf[BUFFSIZE];
1371         gint len;
1372         gulong size = 1;
1373
1374         while ((len = fd_gets(fd, buf, sizeof(buf))) > 0) {
1375                 size += len;
1376                 if (!*str)
1377                         *str = g_strdup(buf);
1378                 else {
1379                         *str = g_realloc(*str, size);
1380                         strcat(*str, buf);
1381                 }
1382                 if (buf[len - 1] == '\n')
1383                         break;
1384         }
1385         if (len == -1 && *str)
1386                 g_free(*str);
1387
1388         return len;
1389 }
1390
1391 #if USE_OPENSSL
1392 gint ssl_getline(SSL *ssl, gchar **str)
1393 {
1394         gchar buf[BUFFSIZE];
1395         gint len;
1396         gulong size = 1;
1397
1398         while ((len = ssl_gets(ssl, buf, sizeof(buf))) > 0) {
1399                 size += len;
1400                 if (!*str)
1401                         *str = g_strdup(buf);
1402                 else {
1403                         *str = g_realloc(*str, size);
1404                         strcat(*str, buf);
1405                 }
1406                 if (buf[len - 1] == '\n')
1407                         break;
1408         }
1409         if (len == -1 && *str)
1410                 g_free(*str);
1411
1412         return len;
1413 }
1414 #endif
1415
1416 gchar *sock_getline(SockInfo *sock)
1417 {
1418         gint ret;
1419         gchar *str = NULL;
1420
1421         g_return_val_if_fail(sock != NULL, NULL);
1422
1423 #if USE_OPENSSL
1424         if (sock->ssl)
1425                 ret = ssl_getline(sock->ssl, &str);
1426         else
1427 #endif
1428                 ret = fd_getline(sock->sock, &str);
1429
1430         if (ret < 0)
1431                 sock->state = CONN_DISCONNECTED;
1432         return str;
1433 }
1434
1435 gint sock_puts(SockInfo *sock, const gchar *buf)
1436 {
1437         gint ret;
1438
1439         if ((ret = sock_write_all(sock, buf, strlen(buf))) < 0)
1440                 return ret;
1441         return sock_write_all(sock, "\r\n", 2);
1442 }
1443
1444 /* peek at the socket data without actually reading it */
1445 #if USE_OPENSSL
1446 gint ssl_peek(SSL *ssl, gchar *buf, gint len)
1447 {
1448         gint err, ret;
1449
1450         if (SSL_pending(ssl) == 0) {
1451                 if (fd_check_io(SSL_get_rfd(ssl), G_IO_IN) < 0)
1452                         return -1;
1453         }
1454
1455         ret = SSL_peek(ssl, buf, len);
1456
1457         switch ((err = SSL_get_error(ssl, ret))) {
1458         case SSL_ERROR_NONE:
1459                 return ret;
1460         case SSL_ERROR_WANT_READ:
1461         case SSL_ERROR_WANT_WRITE:
1462                 errno = EAGAIN;
1463                 return -1;
1464         case SSL_ERROR_ZERO_RETURN:
1465                 return 0;
1466         case SSL_ERROR_SYSCALL:
1467                 g_warning("SSL_peek() returned syscall error. errno=%d\n", errno);
1468                 return -1;
1469         default:
1470                 g_warning("SSL_peek() returned error %d, ret = %d\n", err, ret);
1471                 if (ret == 0)
1472                         return 0;
1473                 return -1;
1474         }
1475 }
1476 #endif
1477
1478 gint sock_peek(SockInfo *sock, gchar *buf, gint len)
1479 {
1480         g_return_val_if_fail(sock != NULL, -1);
1481
1482 #if USE_OPENSSL
1483         if (sock->ssl)
1484                 return ssl_peek(sock->ssl, buf, len);
1485 #endif
1486         return fd_recv(sock->sock, buf, len, MSG_PEEK);
1487 }
1488
1489 gint sock_close(SockInfo *sock)
1490 {
1491         gint ret;
1492
1493         if (!sock)
1494                 return 0;
1495
1496         if (sock->sock_ch)
1497                 g_io_channel_unref(sock->sock_ch);
1498
1499 #if USE_OPENSSL
1500         if (sock->ssl)
1501                 ssl_done_socket(sock);
1502         if (sock->g_source != 0)
1503                 g_source_remove(sock->g_source);
1504         sock->g_source = 0;
1505 #endif
1506         ret = fd_close(sock->sock); 
1507         g_free(sock->hostname);
1508         g_free(sock);
1509
1510         return ret;
1511 }
1512
1513 gint fd_close(gint fd)
1514 {
1515         return close(fd);
1516 }