e9bbef27bd7009f3f5679666fb9c775c80a97d6c
[claws.git] / src / common / socket.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 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/socket.h>
28 #include <sys/un.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 #include <netdb.h>
32 #include <unistd.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <stdarg.h>
36 #include <fcntl.h>
37 #include <errno.h>
38 #include <signal.h>
39 #include <setjmp.h>
40 #if HAVE_SYS_SELECT_H
41 #  include <sys/select.h>
42 #endif
43
44 #include "socket.h"
45 #include "utils.h"
46 #include "log.h"
47 #if USE_SSL
48 #  include "ssl.h"
49 #endif
50
51 #if USE_GIO
52 #error USE_GIO is currently not supported
53 #endif
54
55 #define BUFFSIZE        8192
56 #define IO_TIMEOUT      60
57
58 static gint sock_connect_with_timeout   (gint                    sock,
59                                          const struct sockaddr  *serv_addr,
60                                          gint                    addrlen,
61                                          guint                   timeout_secs);
62
63 #ifndef INET6
64 static gint sock_connect_by_hostname    (gint            sock,
65                                          const gchar    *hostname,
66                                          gushort         port);
67 #else
68 static gint sock_connect_by_getaddrinfo (const gchar    *hostname,
69                                          gushort         port);
70 #endif
71
72 static SockInfo *sockinfo_from_fd(const gchar *hostname,
73                                   gushort port,
74                                   gint sock);
75
76 gint fd_connect_unix(const gchar *path)
77 {
78         gint sock;
79         struct sockaddr_un addr;
80
81         sock = socket(PF_UNIX, SOCK_STREAM, 0);
82         if (sock < 0) {
83                 perror("sock_connect_unix(): socket");
84                 return -1;
85         }
86
87         memset(&addr, 0, sizeof(addr));
88         addr.sun_family = AF_UNIX;
89         strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
90
91         if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
92                 close(sock);
93                 return -1;
94         }
95
96         return sock;
97 }
98
99 gint fd_open_unix(const gchar *path)
100 {
101         gint sock;
102         struct sockaddr_un addr;
103
104         sock = socket(PF_UNIX, SOCK_STREAM, 0);
105
106         if (sock < 0) {
107                 perror("sock_open_unix(): socket");
108                 return -1;
109         }
110
111         memset(&addr, 0, sizeof(addr));
112         addr.sun_family = AF_UNIX;
113         strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
114
115         if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
116                 perror("bind");
117                 close(sock);
118                 return -1;
119         }
120
121         if (listen(sock, 1) < 0) {
122                 perror("listen");
123                 close(sock);
124                 return -1;              
125         }
126
127         return sock;
128 }
129
130 gint fd_accept(gint sock)
131 {
132         struct sockaddr_in caddr;
133         gint caddr_len;
134
135         caddr_len = sizeof(caddr);
136         return accept(sock, (struct sockaddr *)&caddr, &caddr_len);
137 }
138
139
140 static gint set_nonblocking_mode(gint fd, gboolean nonblock)
141 {
142         gint flags;
143
144         flags = fcntl(fd, F_GETFL, 0);
145         if (flags < 0) {
146                 perror("fcntl");
147                 return -1;
148         }
149
150         if (nonblock)
151                 flags |= O_NONBLOCK;
152         else
153                 flags &= ~O_NONBLOCK;
154
155         return fcntl(fd, F_SETFL, flags);
156 }
157
158 gint sock_set_nonblocking_mode(SockInfo *sock, gboolean nonblock)
159 {
160         g_return_val_if_fail(sock != NULL, -1);
161
162         return set_nonblocking_mode(sock->sock, nonblock);
163 }
164
165
166 static gboolean is_nonblocking_mode(gint fd)
167 {
168         gint flags;
169
170         flags = fcntl(fd, F_GETFL, 0);
171         if (flags < 0) {
172                 perror("fcntl");
173                 return FALSE;
174         }
175
176         return ((flags & O_NONBLOCK) != 0);
177 }
178
179 gboolean sock_is_nonblocking_mode(SockInfo *sock)
180 {
181         g_return_val_if_fail(sock != NULL, FALSE);
182
183         return is_nonblocking_mode(sock->sock);
184 }
185
186 static gint fd_check_io(gint fd, GIOCondition cond)
187 {
188         struct timeval timeout;
189         fd_set fds;
190
191         timeout.tv_sec  = IO_TIMEOUT;
192         timeout.tv_usec = 0;
193
194         FD_ZERO(&fds);
195         FD_SET(fd, &fds);
196
197         if (cond == G_IO_IN) {
198                 select(fd + 1, &fds, NULL, NULL, &timeout);
199         } else {
200                 select(fd + 1, NULL, &fds, NULL, &timeout);
201         }
202
203         if (FD_ISSET(fd, &fds)) {
204                 return 0;
205         } else {
206                 g_warning("Socket IO timeout\n");
207                 return -1;
208         }
209 }
210
211 static sigjmp_buf jmpenv;
212
213 static void timeout_handler(gint sig)
214 {
215         siglongjmp(jmpenv, 1);
216 }
217
218 static gint sock_connect_with_timeout(gint sock,
219                                       const struct sockaddr *serv_addr,
220                                       gint addrlen,
221                                       guint timeout_secs)
222 {
223         gint ret;
224         void (*prev_handler)(gint);
225
226         alarm(0);
227         prev_handler = signal(SIGALRM, timeout_handler);
228         if (sigsetjmp(jmpenv, 1)) {
229                 alarm(0);
230                 signal(SIGALRM, prev_handler);
231                 errno = ETIMEDOUT;
232                 return -1;
233         }
234         alarm(timeout_secs);
235
236         ret = connect(sock, serv_addr, addrlen);
237
238         alarm(0);
239         signal(SIGALRM, prev_handler);
240
241         return ret;
242 }
243
244 struct hostent *my_gethostbyname(const gchar *hostname)
245 {
246         struct hostent *hp;
247         void (*prev_handler)(gint);
248         guint timeout_secs = IO_TIMEOUT;
249
250         alarm(0);
251         prev_handler = signal(SIGALRM, timeout_handler);
252         if (sigsetjmp(jmpenv, 1)) {
253                 alarm(0);
254                 signal(SIGALRM, prev_handler);
255                 fprintf(stderr, "%s: host lookup timed out.\n", hostname);
256                 errno = 0;
257                 return NULL;
258         }
259         alarm(timeout_secs);
260
261         if ((hp = gethostbyname(hostname)) == NULL) {
262                 alarm(0);
263                 signal(SIGALRM, prev_handler);
264                 fprintf(stderr, "%s: unknown host.\n", hostname);
265                 errno = 0;
266                 return NULL;
267         }
268
269         alarm(0);
270         signal(SIGALRM, prev_handler);
271
272         return hp;
273 }
274
275 #ifndef INET6
276 static gint my_inet_aton(const gchar *hostname, struct in_addr *inp)
277 {
278 #if HAVE_INET_ATON
279         return inet_aton(hostname, inp);
280 #else
281 #if HAVE_INET_ADDR
282         guint32 inaddr;
283
284         inaddr = inet_addr(hostname);
285         if (inaddr != -1) {
286                 memcpy(inp, &inaddr, sizeof(inaddr));
287                 return 1;
288         } else
289                 return 0;
290 #else
291         return 0;
292 #endif
293 #endif /* HAVE_INET_ATON */
294 }
295
296 static gint sock_connect_by_hostname(gint sock, const gchar *hostname,
297                                      gushort port)
298 {
299         struct hostent *hp;
300         struct sockaddr_in ad;
301         guint timeout_secs = IO_TIMEOUT;
302
303         memset(&ad, 0, sizeof(ad));
304         ad.sin_family = AF_INET;
305         ad.sin_port = htons(port);
306
307         if (!my_inet_aton(hostname, &ad.sin_addr)) {
308                 if ((hp = my_gethostbyname(hostname)) == NULL) {
309                         fprintf(stderr, "%s: unknown host.\n", hostname);
310                         errno = 0;
311                         return -1;
312                 }
313
314                 if (hp->h_length != 4 && hp->h_length != 8) {
315                         fprintf(stderr, "illegal address length received for host %s\n", hostname);
316                         errno = 0;
317                         return -1;
318                 }
319
320                 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
321         }
322
323         return sock_connect_with_timeout(sock, (struct sockaddr *)&ad,
324                                          sizeof(ad), timeout_secs);
325 }
326
327 #else /* INET6 */
328 static gint sock_connect_by_getaddrinfo(const gchar *hostname, gushort  port)
329 {
330         gint sock = -1, gai_error;
331         struct addrinfo hints, *res, *ai;
332         guint timeout_secs = IO_TIMEOUT;
333         gchar port_str[6];
334
335         memset(&hints, 0, sizeof(hints));
336         /* hints.ai_flags = AI_CANONNAME; */
337         hints.ai_family = AF_UNSPEC;
338         hints.ai_socktype = SOCK_STREAM;
339         hints.ai_protocol = IPPROTO_TCP;
340
341         /* convert port from integer to string. */
342         g_snprintf(port_str, sizeof(port_str), "%d", port);
343
344         if ((gai_error = getaddrinfo(hostname, port_str, &hints, &res)) != 0) {
345                 fprintf(stderr, "getaddrinfo for %s:%s failed: %s\n",
346                         hostname, port_str, gai_strerror(gai_error));
347                 return -1;
348         }
349
350         for (ai = res; ai != NULL; ai = ai->ai_next) {
351                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
352                 if (sock < 0)
353                         continue;
354
355                 if (sock_connect_with_timeout
356                         (sock, ai->ai_addr, ai->ai_addrlen, timeout_secs) == 0)
357                         break;
358
359                 close(sock);
360         }
361
362         if (res != NULL)
363                 freeaddrinfo(res);
364
365         if (ai == NULL)
366                 return -1;
367
368         return sock;
369 }
370 #endif /* !INET6 */
371
372
373 /* Open a connection using an external program.  May be useful when
374  * you need to tunnel through a SOCKS or other firewall, or to
375  * establish an IMAP-over-SSH connection. */
376 /* TODO: Recreate this for sock_connect_thread() */
377 SockInfo *sock_connect_cmd(const gchar *hostname, const gchar *tunnelcmd)
378 {
379         gint fd[2];
380         int r;
381                      
382         if ((r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) == -1) {
383                 perror("socketpair");
384                 return NULL;
385         }
386         log_message("launching tunnel command \"%s\"\n", tunnelcmd);
387         if (fork() == 0) {
388                 close(fd[0]);
389                 close(0);
390                 close(1);
391                 dup(fd[1]);     /* set onto stdin */
392                 dup(fd[1]);
393                 execlp("/bin/sh", "/bin/sh", "-c", tunnelcmd, NULL);
394         }
395
396         close(fd[1]);
397         return sockinfo_from_fd(hostname, 0, fd[0]);
398 }
399
400
401 SockInfo *sock_connect(const gchar *hostname, gushort port)
402 {
403         gint sock;
404
405 #ifdef INET6
406         if ((sock = sock_connect_by_getaddrinfo(hostname, port)) < 0)
407                 return NULL;
408 #else
409         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
410                 perror("socket");
411                 return NULL;
412         }
413
414         if (sock_connect_by_hostname(sock, hostname, port) < 0) {
415                 if (errno != 0) perror("connect");
416                 close(sock);
417                 return NULL;
418         }
419 #endif /* INET6 */
420
421         return sockinfo_from_fd(hostname, port, sock);
422 }
423
424
425 static SockInfo *sockinfo_from_fd(const gchar *hostname,
426                                   gushort port,
427                                   gint sock)
428 {
429         SockInfo *sockinfo;
430         
431         sockinfo = g_new0(SockInfo, 1);
432         sockinfo->sock = sock;
433         sockinfo->hostname = g_strdup(hostname);
434         sockinfo->port = port;
435         sockinfo->state = CONN_ESTABLISHED;
436
437         usleep(100000);
438
439         return sockinfo;
440 }
441
442 gint sock_printf(SockInfo *sock, const gchar *format, ...)
443 {
444         va_list args;
445         gchar buf[BUFFSIZE];
446
447         va_start(args, format);
448         g_vsnprintf(buf, sizeof(buf), format, args);
449         va_end(args);
450
451         return sock_write(sock, buf, strlen(buf));
452 }
453
454 gint sock_read(SockInfo *sock, gchar *buf, gint len)
455 {
456         g_return_val_if_fail(sock != NULL, -1);
457
458 #if USE_SSL
459         if (sock->ssl)
460                 return ssl_read(sock->ssl, buf, len);
461 #endif
462         return fd_read(sock->sock, buf, len);
463 }
464
465 gint fd_read(gint fd, gchar *buf, gint len)
466 {
467         if (fd_check_io(fd, G_IO_IN) < 0)
468                 return -1;
469
470         return read(fd, buf, len);
471 }
472
473 #if USE_SSL
474 gint ssl_read(SSL *ssl, gchar *buf, gint len)
475 {
476         return SSL_read(ssl, buf, len);
477 }
478 #endif
479
480 gint sock_write(SockInfo *sock, const gchar *buf, gint len)
481 {
482         g_return_val_if_fail(sock != NULL, -1);
483
484 #if USE_SSL
485         if (sock->ssl)
486                 return ssl_write(sock->ssl, buf, len);
487 #endif
488         return fd_write(sock->sock, buf, len);
489 }
490
491 gint fd_write(gint fd, const gchar *buf, gint len)
492 {
493         gint n, wrlen = 0;
494
495         while (len) {
496                 if (fd_check_io(fd, G_IO_OUT) < 0)
497                         return -1;
498                 signal(SIGPIPE, SIG_IGN);
499                 n = write(fd, buf, len);
500                 if (n <= 0) {
501                         log_error("write on fd%d: %s\n", fd, strerror(errno));
502                         return -1;
503                 }
504                 len -= n;
505                 wrlen += n;
506                 buf += n;
507         }
508
509         return wrlen;
510 }
511
512 #if USE_SSL
513 gint ssl_write(SSL *ssl, const gchar *buf, gint len)
514 {
515         gint n, wrlen = 0;
516
517         while (len) {
518                 n = SSL_write(ssl, buf, len);
519                 if (n <= 0)
520                         return -1;
521                 len -= n;
522                 wrlen += n;
523                 buf += n;
524         }
525
526         return wrlen;
527 }
528 #endif
529
530 gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
531 {
532         if (fd_check_io(fd, G_IO_IN) < 0)
533                 return -1;
534
535         return recv(fd, buf, len, flags);
536 }
537
538 gint fd_gets(gint fd, gchar *buf, gint len)
539 {
540         gchar *newline, *bp = buf;
541         gint n;
542
543         if (--len < 1)
544                 return -1;
545         do {
546                 if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
547                         return -1;
548                 if ((newline = memchr(bp, '\n', n)) != NULL)
549                         n = newline - bp + 1;
550                 if ((n = fd_read(fd, bp, n)) < 0)
551                         return -1;
552                 bp += n;
553                 len -= n;
554         } while (!newline && len);
555
556         *bp = '\0';
557         return bp - buf;
558 }
559
560 #if USE_SSL
561 gint ssl_gets(SSL *ssl, gchar *buf, gint len)
562 {
563         gchar *newline, *bp = buf;
564         gint n;
565
566         if (--len < 1)
567                 return -1;
568         do {
569                 if ((n = SSL_peek(ssl, bp, len)) <= 0)
570                         return -1;
571                 if ((newline = memchr(bp, '\n', n)) != NULL)
572                         n = newline - bp + 1;
573                 if ((n = SSL_read(ssl, bp, n)) < 0)
574                         return -1;
575                 bp += n;
576                 len -= n;
577         } while (!newline && len);
578
579         *bp = '\0';
580         return bp - buf;
581 }
582 #endif
583
584 gint sock_gets(SockInfo *sock, gchar *buf, gint len)
585 {
586         g_return_val_if_fail(sock != NULL, -1);
587
588 #if USE_SSL
589         if (sock->ssl)
590                 return ssl_gets(sock->ssl, buf, len);
591 #endif
592         return fd_gets(sock->sock, buf, len);
593 }
594
595 gchar *fd_getline(gint fd)
596 {
597         gchar buf[BUFFSIZE];
598         gchar *str = NULL;
599         gint len;
600         gulong size = 1;
601
602         while ((len = fd_gets(fd, buf, sizeof(buf))) > 0) {
603                 size += len;
604                 if (!str)
605                         str = g_strdup(buf);
606                 else {
607                         str = g_realloc(str, size);
608                         strcat(str, buf);
609                 }
610                 if (buf[len - 1] == '\n')
611                         break;
612         }
613         if (len == -1) {
614                 log_error("Read from socket fd%d failed: %s\n",
615                           fd, strerror(errno));
616                 if (str)
617                         g_free(str);
618                 return NULL;
619         }
620
621         return str;
622 }
623
624 #if USE_SSL
625 gchar *ssl_getline(SSL *ssl)
626 {
627         gchar buf[BUFFSIZE];
628         gchar *str = NULL;
629         gint len;
630         gulong size = 1;
631
632         while ((len = ssl_gets(ssl, buf, sizeof(buf))) > 0) {
633                 size += len;
634                 if (!str)
635                         str = g_strdup(buf);
636                 else {
637                         str = g_realloc(str, size);
638                         strcat(str, buf);
639                 }
640                 if (buf[len - 1] == '\n')
641                         break;
642         }
643
644         return str;
645 }
646 #endif
647
648 gchar *sock_getline(SockInfo *sock)
649 {
650         g_return_val_if_fail(sock != NULL, NULL);
651
652 #if USE_SSL
653         if (sock->ssl)
654                 return ssl_getline(sock->ssl);
655 #endif
656         return fd_getline(sock->sock);
657 }
658
659 gint sock_puts(SockInfo *sock, const gchar *buf)
660 {
661         gint ret;
662
663         if ((ret = sock_write(sock, buf, strlen(buf))) < 0)
664                 return ret;
665         return sock_write(sock, "\r\n", 2);
666 }
667
668 /* peek at the next socket character without actually reading it */
669 gint sock_peek(SockInfo *sock)
670 {
671         gint n;
672         gchar ch;
673
674         g_return_val_if_fail(sock != NULL, -1);
675
676 #if USE_SSL
677         if (sock->ssl) {
678                 if ((n = SSL_peek(sock->ssl, &ch, 1)) < 0)
679                         return -1;
680                 else
681                         return ch;
682         }
683 #endif
684         if ((n = recv(sock->sock, &ch, 1, MSG_PEEK)) < 0)
685                 return -1;
686         else
687                 return ch;
688 }
689
690 gint sock_close(SockInfo *sock)
691 {
692         gint ret;
693
694         if (!sock)
695                 return 0;
696
697 #if USE_SSL
698         if (sock->ssl)
699                 ssl_done_socket(sock);
700 #endif
701         ret = fd_close(sock->sock); 
702         g_free(sock->hostname);
703         g_free(sock);
704
705         return ret;
706 }
707
708 gint fd_close(gint fd)
709 {
710         return close(fd);
711 }
712
713 gint sock_input_add(SockInfo *sock,
714                     GIOCondition condition,
715                     GIOFunc function,
716                     gpointer data)
717 {
718         GIOChannel *channel;
719         guint result;
720
721         g_return_val_if_fail(sock != NULL, -1);
722
723         channel = g_io_channel_unix_new(sock->sock);
724         /* :WK: We have to change some things here becuse most likey
725            function() does take SockInfo * and not an gint */
726         result = g_io_add_watch(channel, condition, function, data);
727         g_io_channel_unref(channel);
728
729         return result;
730 }