2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2003 Hiroyuki Yamamoto
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.
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.
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.
26 #include <sys/types.h>
28 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
42 # include <sys/select.h>
53 #error USE_GIO is currently not supported
58 typedef gint (*SockAddrFunc) (GList *addr_list,
61 typedef struct _SockConnectData SockConnectData;
62 typedef struct _SockLookupData SockLookupData;
63 typedef struct _SockAddrData SockAddrData;
65 struct _SockConnectData {
71 SockLookupData *lookup_data;
78 struct _SockLookupData {
87 struct _SockAddrData {
92 struct sockaddr *addr;
95 static guint io_timeout = 60;
97 static GList *sock_connect_data_list = NULL;
99 static gint sock_connect_with_timeout (gint sock,
100 const struct sockaddr *serv_addr,
105 static gint sock_connect_by_hostname (gint sock,
106 const gchar *hostname,
109 static gint sock_connect_by_getaddrinfo (const gchar *hostname,
113 static SockInfo *sockinfo_from_fd(const gchar *hostname,
116 static void sock_address_list_free (GList *addr_list);
118 static gboolean sock_connect_async_cb (GIOChannel *source,
119 GIOCondition condition,
121 static gint sock_connect_async_get_address_info_cb
125 static gint sock_connect_address_list_async (SockConnectData *conn_data);
127 static gboolean sock_get_address_info_async_cb (GIOChannel *source,
128 GIOCondition condition,
130 static SockLookupData *sock_get_address_info_async
131 (const gchar *hostname,
135 static gint sock_get_address_info_async_cancel (SockLookupData *lookup_data);
138 gint sock_set_io_timeout(guint sec)
144 gint fd_connect_unix(const gchar *path)
147 struct sockaddr_un addr;
149 sock = socket(PF_UNIX, SOCK_STREAM, 0);
151 perror("sock_connect_unix(): socket");
155 memset(&addr, 0, sizeof(addr));
156 addr.sun_family = AF_UNIX;
157 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
159 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
167 gint fd_open_unix(const gchar *path)
170 struct sockaddr_un addr;
172 sock = socket(PF_UNIX, SOCK_STREAM, 0);
175 perror("sock_open_unix(): socket");
179 memset(&addr, 0, sizeof(addr));
180 addr.sun_family = AF_UNIX;
181 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
183 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
189 if (listen(sock, 1) < 0) {
198 gint fd_accept(gint sock)
200 struct sockaddr_in caddr;
203 caddr_len = sizeof(caddr);
204 return accept(sock, (struct sockaddr *)&caddr, &caddr_len);
208 static gint set_nonblocking_mode(gint fd, gboolean nonblock)
212 flags = fcntl(fd, F_GETFL, 0);
221 flags &= ~O_NONBLOCK;
223 return fcntl(fd, F_SETFL, flags);
226 gint sock_set_nonblocking_mode(SockInfo *sock, gboolean nonblock)
228 g_return_val_if_fail(sock != NULL, -1);
230 return set_nonblocking_mode(sock->sock, nonblock);
234 static gboolean is_nonblocking_mode(gint fd)
238 flags = fcntl(fd, F_GETFL, 0);
244 return ((flags & O_NONBLOCK) != 0);
247 gboolean sock_is_nonblocking_mode(SockInfo *sock)
249 g_return_val_if_fail(sock != NULL, FALSE);
251 return is_nonblocking_mode(sock->sock);
254 static gint fd_check_io(gint fd, GIOCondition cond)
256 struct timeval timeout;
259 if (is_nonblocking_mode(fd))
262 timeout.tv_sec = io_timeout;
268 if (cond == G_IO_IN) {
269 select(fd + 1, &fds, NULL, NULL,
270 io_timeout > 0 ? &timeout : NULL);
272 select(fd + 1, NULL, &fds, NULL,
273 io_timeout > 0 ? &timeout : NULL);
276 if (FD_ISSET(fd, &fds)) {
279 g_warning("Socket IO timeout\n");
284 static sigjmp_buf jmpenv;
286 static void timeout_handler(gint sig)
288 siglongjmp(jmpenv, 1);
291 static gint sock_connect_with_timeout(gint sock,
292 const struct sockaddr *serv_addr,
297 void (*prev_handler)(gint);
300 prev_handler = signal(SIGALRM, timeout_handler);
301 if (sigsetjmp(jmpenv, 1)) {
303 signal(SIGALRM, prev_handler);
309 ret = connect(sock, serv_addr, addrlen);
312 signal(SIGALRM, prev_handler);
317 struct hostent *my_gethostbyname(const gchar *hostname)
320 void (*prev_handler)(gint);
323 prev_handler = signal(SIGALRM, timeout_handler);
324 if (sigsetjmp(jmpenv, 1)) {
326 signal(SIGALRM, prev_handler);
327 fprintf(stderr, "%s: host lookup timed out.\n", hostname);
333 if ((hp = gethostbyname(hostname)) == NULL) {
335 signal(SIGALRM, prev_handler);
336 fprintf(stderr, "%s: unknown host.\n", hostname);
342 signal(SIGALRM, prev_handler);
348 static gint my_inet_aton(const gchar *hostname, struct in_addr *inp)
351 return inet_aton(hostname, inp);
356 inaddr = inet_addr(hostname);
358 memcpy(inp, &inaddr, sizeof(inaddr));
365 #endif /* HAVE_INET_ATON */
368 static gint sock_connect_by_hostname(gint sock, const gchar *hostname,
372 struct sockaddr_in ad;
374 memset(&ad, 0, sizeof(ad));
375 ad.sin_family = AF_INET;
376 ad.sin_port = htons(port);
378 if (!my_inet_aton(hostname, &ad.sin_addr)) {
379 if ((hp = my_gethostbyname(hostname)) == NULL) {
380 fprintf(stderr, "%s: unknown host.\n", hostname);
385 if (hp->h_length != 4 && hp->h_length != 8) {
386 fprintf(stderr, "illegal address length received for host %s\n", hostname);
391 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
394 return sock_connect_with_timeout(sock, (struct sockaddr *)&ad,
395 sizeof(ad), io_timeout);
399 static gint sock_connect_by_getaddrinfo(const gchar *hostname, gushort port)
401 gint sock = -1, gai_error;
402 struct addrinfo hints, *res, *ai;
405 memset(&hints, 0, sizeof(hints));
406 /* hints.ai_flags = AI_CANONNAME; */
407 hints.ai_family = AF_UNSPEC;
408 hints.ai_socktype = SOCK_STREAM;
409 hints.ai_protocol = IPPROTO_TCP;
411 /* convert port from integer to string. */
412 g_snprintf(port_str, sizeof(port_str), "%d", port);
414 if ((gai_error = getaddrinfo(hostname, port_str, &hints, &res)) != 0) {
415 fprintf(stderr, "getaddrinfo for %s:%s failed: %s\n",
416 hostname, port_str, gai_strerror(gai_error));
420 for (ai = res; ai != NULL; ai = ai->ai_next) {
421 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
425 if (sock_connect_with_timeout
426 (sock, ai->ai_addr, ai->ai_addrlen, io_timeout) == 0)
443 /* Open a connection using an external program. May be useful when
444 * you need to tunnel through a SOCKS or other firewall, or to
445 * establish an IMAP-over-SSH connection. */
446 /* TODO: Recreate this for sock_connect_thread() */
447 SockInfo *sock_connect_cmd(const gchar *hostname, const gchar *tunnelcmd)
452 if ((r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) == -1) {
453 perror("socketpair");
456 log_message("launching tunnel command \"%s\"\n", tunnelcmd);
461 dup(fd[1]); /* set onto stdin */
463 execlp("/bin/sh", "/bin/sh", "-c", tunnelcmd, NULL);
467 return sockinfo_from_fd(hostname, 0, fd[0]);
471 SockInfo *sock_connect(const gchar *hostname, gushort port)
476 if ((sock = sock_connect_by_getaddrinfo(hostname, port)) < 0)
479 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
484 if (sock_connect_by_hostname(sock, hostname, port) < 0) {
485 if (errno != 0) perror("connect");
491 return sockinfo_from_fd(hostname, port, sock);
494 static void sock_address_list_free(GList *addr_list)
498 for (cur = addr_list; cur != NULL; cur = cur->next) {
499 SockAddrData *addr_data = (SockAddrData *)cur->data;
500 g_free(addr_data->addr);
504 g_list_free(addr_list);
507 /* asynchronous TCP connection */
509 static gboolean sock_connect_async_cb(GIOChannel *source,
510 GIOCondition condition, gpointer data)
512 SockConnectData *conn_data = (SockConnectData *)data;
518 fd = g_io_channel_unix_get_fd(source);
520 conn_data->io_tag = 0;
521 conn_data->channel = NULL;
522 g_io_channel_unref(source);
525 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &len) < 0) {
526 perror("getsockopt");
528 sock_connect_address_list_async(conn_data);
534 sock_connect_address_list_async(conn_data);
538 sockinfo = g_new0(SockInfo, 1);
540 sockinfo->hostname = g_strdup(conn_data->hostname);
541 sockinfo->port = conn_data->port;
542 sockinfo->state = CONN_ESTABLISHED;
544 conn_data->func(sockinfo, conn_data->data);
546 sock_connect_async_cancel(conn_data->id);
551 static gint sock_connect_async_get_address_info_cb(GList *addr_list,
554 SockConnectData *conn_data = (SockConnectData *)data;
556 conn_data->addr_list = addr_list;
557 conn_data->cur_addr = addr_list;
558 conn_data->lookup_data = NULL;
560 return sock_connect_address_list_async(conn_data);
563 gint sock_connect_async(const gchar *hostname, gushort port,
564 SockConnectFunc func, gpointer data)
567 SockConnectData *conn_data;
569 conn_data = g_new0(SockConnectData, 1);
570 conn_data->id = id++;
571 conn_data->hostname = g_strdup(hostname);
572 conn_data->port = port;
573 conn_data->addr_list = NULL;
574 conn_data->cur_addr = NULL;
575 conn_data->io_tag = 0;
576 conn_data->func = func;
577 conn_data->data = data;
579 conn_data->lookup_data = sock_get_address_info_async
580 (hostname, port, sock_connect_async_get_address_info_cb,
583 if (conn_data->lookup_data == NULL) {
584 g_free(conn_data->hostname);
589 sock_connect_data_list = g_list_append(sock_connect_data_list,
592 return conn_data->id;
595 gint sock_connect_async_cancel(gint id)
597 SockConnectData *conn_data = NULL;
600 for (cur = sock_connect_data_list; cur != NULL; cur = cur->next) {
601 if (((SockConnectData *)cur->data)->id == id) {
602 conn_data = (SockConnectData *)cur->data;
608 sock_connect_data_list = g_list_remove(sock_connect_data_list,
611 if (conn_data->lookup_data)
612 sock_get_address_info_async_cancel
613 (conn_data->lookup_data);
615 if (conn_data->io_tag > 0)
616 g_source_remove(conn_data->io_tag);
617 if (conn_data->channel) {
618 g_io_channel_close(conn_data->channel);
619 g_io_channel_unref(conn_data->channel);
622 sock_address_list_free(conn_data->addr_list);
623 g_free(conn_data->hostname);
626 g_warning("sock_connect_async_cancel: id %d not found.\n", id);
633 static gint sock_connect_address_list_async(SockConnectData *conn_data)
635 SockAddrData *addr_data;
638 for (; conn_data->cur_addr != NULL;
639 conn_data->cur_addr = conn_data->cur_addr->next) {
640 addr_data = (SockAddrData *)conn_data->cur_addr->data;
642 if ((sock = socket(addr_data->family, addr_data->socktype,
643 addr_data->protocol)) < 0) {
648 set_nonblocking_mode(sock, TRUE);
650 if (connect(sock, addr_data->addr, addr_data->addr_len) < 0) {
651 if (EINPROGRESS == errno) {
661 if (conn_data->cur_addr == NULL) {
662 g_warning("sock_connect_address_list_async: "
663 "connection to %s:%d failed\n",
664 conn_data->hostname, conn_data->port);
665 conn_data->func(NULL, conn_data->data);
666 sock_connect_async_cancel(conn_data->id);
670 conn_data->cur_addr = conn_data->cur_addr->next;
672 conn_data->channel = g_io_channel_unix_new(sock);
673 conn_data->io_tag = g_io_add_watch(conn_data->channel, G_IO_IN|G_IO_OUT,
674 sock_connect_async_cb, conn_data);
679 /* asynchronous DNS lookup */
681 static gboolean sock_get_address_info_async_cb(GIOChannel *source,
682 GIOCondition condition,
685 SockLookupData *lookup_data = (SockLookupData *)data;
686 GList *addr_list = NULL;
687 SockAddrData *addr_data;
690 struct sockaddr *addr;
693 if (g_io_channel_read(source, (gchar *)ai_member,
694 sizeof(ai_member), &bytes_read)
695 != G_IO_ERROR_NONE) {
696 g_warning("sock_get_address_info_async_cb: "
697 "address length read error\n");
701 if (bytes_read == 0 || bytes_read != sizeof(ai_member))
704 if (ai_member[0] == AF_UNSPEC) {
705 g_warning("DNS lookup failed\n");
709 addr = g_malloc(ai_member[3]);
710 if (g_io_channel_read(source, (gchar *)addr, ai_member[3],
712 != G_IO_ERROR_NONE) {
713 g_warning("sock_get_address_info_async_cb: "
714 "address data read error\n");
719 if (bytes_read != ai_member[3]) {
720 g_warning("sock_get_address_info_async_cb: "
721 "incomplete address data\n");
726 addr_data = g_new0(SockAddrData, 1);
727 addr_data->family = ai_member[0];
728 addr_data->socktype = ai_member[1];
729 addr_data->protocol = ai_member[2];
730 addr_data->addr_len = ai_member[3];
731 addr_data->addr = addr;
733 addr_list = g_list_append(addr_list, addr_data);
736 g_io_channel_close(source);
737 g_io_channel_unref(source);
739 kill(lookup_data->child_pid, SIGKILL);
740 waitpid(lookup_data->child_pid, NULL, 0);
742 lookup_data->func(addr_list, lookup_data->data);
744 g_free(lookup_data->hostname);
750 static SockLookupData *sock_get_address_info_async(const gchar *hostname,
755 SockLookupData *lookup_data = NULL;
759 if (pipe(pipe_fds) < 0) {
765 if ((pid = fork()) < 0) {
775 struct addrinfo hints, *res, *ai;
780 struct sockaddr_in ad;
782 gint ai_member[4] = {AF_UNSPEC, 0, 0, 0};
787 memset(&hints, 0, sizeof(hints));
788 /* hints.ai_flags = AI_CANONNAME; */
789 hints.ai_family = AF_UNSPEC;
790 hints.ai_socktype = SOCK_STREAM;
791 hints.ai_protocol = IPPROTO_TCP;
793 g_snprintf(port_str, sizeof(port_str), "%d", port);
795 gai_err = getaddrinfo(hostname, port_str, &hints, &res);
797 g_warning("getaddrinfo for %s:%s failed: %s\n",
798 hostname, port_str, gai_strerror(gai_err));
799 fd_write_all(pipe_fds[1], (gchar *)ai_member,
805 for (ai = res; ai != NULL; ai = ai->ai_next) {
806 ai_member[0] = ai->ai_family;
807 ai_member[1] = ai->ai_socktype;
808 ai_member[2] = ai->ai_protocol;
809 ai_member[3] = ai->ai_addrlen;
811 fd_write_all(pipe_fds[1], (gchar *)ai_member,
813 fd_write_all(pipe_fds[1], (gchar *)ai->ai_addr,
820 hp = my_gethostbyname(hostname);
821 if (hp == NULL || hp->h_addrtype != AF_INET) {
822 fd_write_all(pipe_fds[1], (gchar *)ai_member,
828 ai_member[0] = AF_INET;
829 ai_member[1] = SOCK_STREAM;
830 ai_member[2] = IPPROTO_TCP;
831 ai_member[3] = sizeof(ad);
833 memset(&ad, 0, sizeof(ad));
834 ad.sin_family = AF_INET;
835 ad.sin_port = htons(port);
837 for (addr_list_p = hp->h_addr_list; *addr_list_p != NULL;
839 memcpy(&ad.sin_addr, *addr_list_p, hp->h_length);
840 fd_write_all(pipe_fds[1], (gchar *)ai_member,
842 fd_write_all(pipe_fds[1], (gchar *)&ad, sizeof(ad));
852 lookup_data = g_new0(SockLookupData, 1);
853 lookup_data->hostname = g_strdup(hostname);
854 lookup_data->child_pid = pid;
855 lookup_data->func = func;
856 lookup_data->data = data;
858 lookup_data->channel = g_io_channel_unix_new(pipe_fds[0]);
859 lookup_data->io_tag = g_io_add_watch
860 (lookup_data->channel, G_IO_IN,
861 sock_get_address_info_async_cb, lookup_data);
867 static gint sock_get_address_info_async_cancel(SockLookupData *lookup_data)
869 if (lookup_data->io_tag > 0)
870 g_source_remove(lookup_data->io_tag);
871 if (lookup_data->channel) {
872 g_io_channel_close(lookup_data->channel);
873 g_io_channel_unref(lookup_data->channel);
876 if (lookup_data->child_pid > 0) {
877 kill(lookup_data->child_pid, SIGKILL);
878 waitpid(lookup_data->child_pid, NULL, 0);
881 g_free(lookup_data->hostname);
888 static SockInfo *sockinfo_from_fd(const gchar *hostname,
894 sockinfo = g_new0(SockInfo, 1);
895 sockinfo->sock = sock;
896 sockinfo->hostname = g_strdup(hostname);
897 sockinfo->port = port;
898 sockinfo->state = CONN_ESTABLISHED;
905 gint sock_printf(SockInfo *sock, const gchar *format, ...)
910 va_start(args, format);
911 g_vsnprintf(buf, sizeof(buf), format, args);
914 return sock_write_all(sock, buf, strlen(buf));
917 gint fd_read(gint fd, gchar *buf, gint len)
919 if (fd_check_io(fd, G_IO_IN) < 0)
922 return read(fd, buf, len);
926 gint ssl_read(SSL *ssl, gchar *buf, gint len)
928 return SSL_read(ssl, buf, len);
932 gint sock_read(SockInfo *sock, gchar *buf, gint len)
936 g_return_val_if_fail(sock != NULL, -1);
940 ret = ssl_read(sock->ssl, buf, len);
943 ret = fd_read(sock->sock, buf, len);
946 sock->state = CONN_DISCONNECTED;
950 gint fd_write(gint fd, const gchar *buf, gint len)
952 if (fd_check_io(fd, G_IO_OUT) < 0)
955 return write(fd, buf, len);
959 gint ssl_write(SSL *ssl, const gchar *buf, gint len)
961 return SSL_write(ssl, buf, len);
965 gint sock_write(SockInfo *sock, const gchar *buf, gint len)
969 g_return_val_if_fail(sock != NULL, -1);
973 ret = ssl_write(sock->ssl, buf, len);
976 ret = fd_write(sock->sock, buf, len);
979 sock->state = CONN_DISCONNECTED;
983 gint fd_write_all(gint fd, const gchar *buf, gint len)
988 if (fd_check_io(fd, G_IO_OUT) < 0)
990 signal(SIGPIPE, SIG_IGN);
991 n = write(fd, buf, len);
993 log_error("write on fd%d: %s\n", fd, strerror(errno));
1005 gint ssl_write_all(SSL *ssl, const gchar *buf, gint len)
1010 n = SSL_write(ssl, buf, len);
1022 gint sock_write_all(SockInfo *sock, const gchar *buf, gint len)
1026 g_return_val_if_fail(sock != NULL, -1);
1030 ret = ssl_write_all(sock->ssl, buf, len);
1033 ret = fd_write_all(sock->sock, buf, len);
1036 sock->state = CONN_DISCONNECTED;
1040 gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
1042 if (fd_check_io(fd, G_IO_IN) < 0)
1045 return recv(fd, buf, len, flags);
1048 gint fd_gets(gint fd, gchar *buf, gint len)
1050 gchar *newline, *bp = buf;
1056 if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
1058 if ((newline = memchr(bp, '\n', n)) != NULL)
1059 n = newline - bp + 1;
1060 if ((n = fd_read(fd, bp, n)) < 0)
1064 } while (!newline && len);
1071 gint ssl_gets(SSL *ssl, gchar *buf, gint len)
1073 gchar *newline, *bp = buf;
1079 if ((n = SSL_peek(ssl, bp, len)) <= 0)
1081 if ((newline = memchr(bp, '\n', n)) != NULL)
1082 n = newline - bp + 1;
1083 if ((n = SSL_read(ssl, bp, n)) < 0)
1087 } while (!newline && len);
1094 gint sock_gets(SockInfo *sock, gchar *buf, gint len)
1098 g_return_val_if_fail(sock != NULL, -1);
1102 return ssl_gets(sock->ssl, buf, len);
1105 return fd_gets(sock->sock, buf, len);
1108 sock->state = CONN_DISCONNECTED;
1112 gint fd_getline(gint fd, gchar **str)
1114 gchar buf[BUFFSIZE];
1118 while ((len = fd_gets(fd, buf, sizeof(buf))) > 0) {
1121 *str = g_strdup(buf);
1123 *str = g_realloc(*str, size);
1126 if (buf[len - 1] == '\n')
1129 if (len == -1 && *str)
1136 gint ssl_getline(SSL *ssl, gchar **str)
1138 gchar buf[BUFFSIZE];
1142 while ((len = ssl_gets(ssl, buf, sizeof(buf))) > 0) {
1145 *str = g_strdup(buf);
1147 *str = g_realloc(*str, size);
1150 if (buf[len - 1] == '\n')
1153 if (len == -1 && *str)
1160 gchar *sock_getline(SockInfo *sock)
1165 g_return_val_if_fail(sock != NULL, NULL);
1169 ret = ssl_getline(sock->ssl, &str);
1172 ret = fd_getline(sock->sock, &str);
1175 sock->state = CONN_DISCONNECTED;
1179 gint sock_puts(SockInfo *sock, const gchar *buf)
1183 if ((ret = sock_write_all(sock, buf, strlen(buf))) < 0)
1185 return sock_write_all(sock, "\r\n", 2);
1188 /* peek at the socket data without actually reading it */
1189 gint sock_peek(SockInfo *sock, gchar *buf, gint len)
1191 g_return_val_if_fail(sock != NULL, -1);
1195 return SSL_peek(sock->ssl, buf, len);
1197 return fd_recv(sock->sock, buf, len, MSG_PEEK);
1200 gint sock_close(SockInfo *sock)
1209 ssl_done_socket(sock);
1211 ret = fd_close(sock->sock);
1212 g_free(sock->hostname);
1218 gint fd_close(gint fd)