add support for Ayatana indicator to Notification plugin
[claws.git] / src / common / socket.c
blobda3eb8feb65b3847bfe7965eb1c500cc6e12be57
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2022 the Claws Mail team and 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 3 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, see <http://www.gnu.org/licenses/>.
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #include "claws-features.h"
22 #endif
24 #include <glib.h>
25 #include <glib/gi18n.h>
27 #include <sys/time.h>
28 #include <sys/types.h>
29 #ifdef G_OS_WIN32
30 # include <ws2tcpip.h>
31 # ifndef EINPROGRESS
32 # define EINPROGRESS WSAEINPROGRESS
33 # endif
34 #else
35 # if HAVE_SYS_WAIT_H
36 # include <sys/wait.h>
37 # endif
38 # include <sys/socket.h>
39 # include <sys/stat.h>
40 # include <sys/un.h>
41 # include <netinet/in.h>
42 # include <arpa/inet.h>
43 # include <resolv.h>
44 # ifndef _PATH_RESCONF
45 # define _PATH_RESCONF "/etc/resolv.conf"
46 # endif
47 # include <netdb.h>
48 #endif /* G_OS_WIN32 */
49 #include <unistd.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <stdarg.h>
53 #include <fcntl.h>
54 #include <errno.h>
55 #include <signal.h>
56 #include <setjmp.h>
57 #if HAVE_SYS_SELECT_H
58 # include <sys/select.h>
59 #endif
61 #include "socket.h"
62 #include "utils.h"
63 #include "log.h"
64 #ifdef USE_GNUTLS
65 # include "ssl.h"
66 #endif
68 #if USE_GIO
69 #error USE_GIO is currently not supported
70 #endif
72 #if G_IO_WIN32
73 #define BUFFSIZE 8191
74 #else
75 #define BUFFSIZE 8192
76 #endif
79 typedef gint (*SockAddrFunc) (GList *addr_list,
80 gpointer data);
82 typedef struct _SockConnectData SockConnectData;
83 typedef struct _SockLookupData SockLookupData;
84 typedef struct _SockAddrData SockAddrData;
85 typedef struct _SockSource SockSource;
87 struct _SockConnectData {
88 gint id;
89 gchar *hostname;
90 gushort port;
91 GList *addr_list;
92 GList *cur_addr;
93 SockLookupData *lookup_data;
94 GIOChannel *channel;
95 guint io_tag;
96 SockConnectFunc func;
97 gpointer data;
98 gchar *canonical_name;
101 struct _SockLookupData {
102 gchar *hostname;
103 pid_t child_pid;
104 GIOChannel *channel;
105 guint io_tag;
106 SockAddrFunc func;
107 gpointer data;
108 gushort port;
109 gint pipe_fds[2];
110 gchar *canonical_name;
113 struct _SockAddrData {
114 gint family;
115 gint socktype;
116 gint protocol;
117 gint addr_len;
118 struct sockaddr *addr;
121 struct _SockSource {
122 GSource parent;
123 SockInfo *sock;
126 static guint io_timeout = 60;
128 static GList *sock_connect_data_list = NULL;
130 #ifdef USE_GNUTLS
131 static gboolean ssl_sock_prepare (GSource *source,
132 gint *timeout);
133 static gboolean ssl_sock_check (GSource *source);
134 static gboolean ssl_sock_dispatch (GSource *source,
135 GSourceFunc callback,
136 gpointer user_data);
137 GSourceFuncs ssl_watch_funcs = {
138 ssl_sock_prepare,
139 ssl_sock_check,
140 ssl_sock_dispatch,
141 NULL,
142 NULL,
143 NULL
145 #endif
147 static gint sock_connect_with_timeout (gint sock,
148 const struct sockaddr *serv_addr,
149 gint addrlen,
150 guint timeout_secs);
152 static gint sock_connect_by_getaddrinfo (const gchar *hostname,
153 gushort port);
155 static SockInfo *sockinfo_from_fd(const gchar *hostname,
156 gushort port,
157 gint sock);
158 static void sock_address_list_free (GList *addr_list);
160 static gboolean sock_connect_async_cb (GIOChannel *source,
161 GIOCondition condition,
162 gpointer data);
163 static gint sock_connect_async_get_address_info_cb
164 (GList *addr_list,
165 gpointer data);
167 static gint sock_connect_address_list_async (SockConnectData *conn_data);
169 static gboolean sock_get_address_info_async_cb (GIOChannel *source,
170 GIOCondition condition,
171 gpointer data);
172 static SockLookupData *sock_get_address_info_async
173 (const gchar *hostname,
174 gushort port,
175 SockAddrFunc func,
176 gpointer data);
177 static gint sock_get_address_info_async_cancel (SockLookupData *lookup_data);
180 gint sock_init(void)
182 #ifdef G_OS_WIN32
183 WSADATA wsadata;
184 gint result;
186 result = WSAStartup(MAKEWORD(2, 2), &wsadata);
187 if (result != NO_ERROR) {
188 g_warning("WSAStartup() failed");
189 return -1;
191 #endif
192 return 0;
195 gint sock_cleanup(void)
197 #ifdef G_OS_WIN32
198 WSACleanup();
199 #endif
200 return 0;
203 gint sock_set_io_timeout(guint sec)
205 io_timeout = sec;
206 return 0;
209 void refresh_resolvers(void)
211 #ifdef G_OS_UNIX
212 static time_t resolv_conf_changed = (time_t)NULL;
213 GStatBuf s;
215 /* This makes the glibc re-read resolv.conf, if it changed
216 * since our startup. Maybe that should be #ifdef'ed, I don't
217 * know if it'd work on BSDs.
218 * Why doesn't the glibc do it by itself?
220 if (g_stat(_PATH_RESCONF, &s) == 0) {
221 if (s.st_mtime > resolv_conf_changed) {
222 resolv_conf_changed = s.st_mtime;
223 res_init();
225 } /* else
226 we'll have bigger problems. */
227 #endif /*G_OS_UNIX*/
230 #ifdef G_OS_WIN32
231 #define SOCKET_IS_VALID(s) ((s) != INVALID_SOCKET)
232 #else
233 #define SOCKET_IS_VALID(s) (s != -1)
234 #endif
236 #ifdef G_OS_WIN32
237 /* Due to the fact that socket under Windows are not represented by
238 standard file descriptors, we sometimes need to check whether a
239 given file descriptor is actually a socket. This is done by
240 testing for an error. Returns true under W32 if FD is a socket. */
241 static int fd_is_w32_socket(gint fd)
243 gint optval;
244 gint retval = sizeof(optval);
246 return !getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*)&optval, &retval);
248 #endif
250 gint fd_connect_inet(gushort port)
252 gint sock;
253 struct sockaddr_in addr;
255 sock = socket(AF_INET, SOCK_STREAM, 0);
256 if (!SOCKET_IS_VALID(sock)) {
257 #ifdef G_OS_WIN32
258 debug_print("fd_connect_inet(): socket() failed: %d\n",
259 WSAGetLastError());
260 #else
261 perror("fd_connect_inet(): socket");
262 #endif
263 return -1;
266 memset(&addr, 0, sizeof(addr));
267 addr.sin_family = AF_INET;
268 addr.sin_port = htons(port);
269 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
271 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
272 fd_close(sock);
273 return -1;
276 return sock;
278 gint fd_open_inet(gushort port)
280 gint sock;
281 struct sockaddr_in addr;
282 gint val;
284 sock = socket(AF_INET, SOCK_STREAM, 0);
285 if (!SOCKET_IS_VALID(sock)) {
286 #ifdef G_OS_WIN32
287 g_warning("fd_open_inet(): socket() failed: %d",
288 WSAGetLastError());
289 #else
290 perror("fd_open_inet(): socket");
291 #endif
292 return -1;
295 val = 1;
296 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val,
297 sizeof(val)) < 0) {
298 perror("setsockopt");
299 fd_close(sock);
300 return -1;
303 memset(&addr, 0, sizeof(addr));
304 addr.sin_family = AF_INET;
305 addr.sin_port = htons(port);
306 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
308 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
309 perror("bind");
310 fd_close(sock);
311 return -1;
314 if (listen(sock, 1) < 0) {
315 perror("listen");
316 fd_close(sock);
317 return -1;
320 return sock;
323 gint fd_connect_unix(const gchar *path)
325 #ifdef G_OS_UNIX
326 gint sock;
327 struct sockaddr_un addr;
329 sock = socket(PF_UNIX, SOCK_STREAM, 0);
330 if (sock < 0) {
331 perror("sock_connect_unix(): socket");
332 return -1;
335 memset(&addr, 0, sizeof(addr));
336 addr.sun_family = AF_UNIX;
337 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
339 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
340 close(sock);
341 return -1;
344 return sock;
345 #else
346 return -1;
347 #endif
350 gint fd_open_unix(const gchar *path)
352 #ifdef G_OS_UNIX
353 gint sock;
354 struct sockaddr_un addr;
356 sock = socket(PF_UNIX, SOCK_STREAM, 0);
358 if (sock < 0) {
359 perror("sock_open_unix(): socket");
360 return -1;
363 memset(&addr, 0, sizeof(addr));
364 addr.sun_family = AF_UNIX;
365 strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
367 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
368 gchar *buf = g_strdup_printf("can't bind to %s", path);
369 perror(buf);
370 g_free(buf);
371 close(sock);
372 return -1;
375 if (listen(sock, 1) < 0) {
376 gchar *buf = g_strdup_printf("can't listen on %s", path);
377 perror(buf);
378 g_free(buf);
379 close(sock);
380 return -1;
383 return sock;
384 #else
385 return -1;
386 #endif
389 gint fd_accept(gint sock)
391 struct sockaddr_in caddr;
392 guint caddr_len;
394 caddr_len = sizeof(caddr);
395 return accept(sock, (struct sockaddr *)&caddr, &caddr_len);
399 static gint set_nonblocking_mode(gint fd, gboolean nonblock)
401 #ifdef G_OS_UNIX
402 gint flags;
404 flags = fcntl(fd, F_GETFL, 0);
405 if (flags < 0) {
406 perror("fcntl");
407 return -1;
410 if (nonblock)
411 flags |= O_NONBLOCK;
412 else
413 flags &= ~O_NONBLOCK;
415 return fcntl(fd, F_SETFL, flags);
416 #else
417 return -1;
418 #endif
421 gint sock_set_nonblocking_mode(SockInfo *sock, gboolean nonblock)
423 cm_return_val_if_fail(sock != NULL, -1);
425 return set_nonblocking_mode(sock->sock, nonblock);
428 static gboolean is_nonblocking_mode(gint fd)
430 #ifdef G_OS_UNIX
431 gint flags;
433 flags = fcntl(fd, F_GETFL, 0);
434 if (flags < 0) {
435 perror("fcntl");
436 return FALSE;
439 return ((flags & O_NONBLOCK) != 0);
440 #else
441 return FALSE;
442 #endif
445 gboolean sock_is_nonblocking_mode(SockInfo *sock)
447 cm_return_val_if_fail(sock != NULL, FALSE);
449 return is_nonblocking_mode(sock->sock);
453 #ifdef USE_GNUTLS
454 static gboolean ssl_sock_prepare(GSource *source, gint *timeout)
456 *timeout = 1;
457 return FALSE;
460 static gboolean ssl_sock_check(GSource *source)
462 SockInfo *sock = ((SockSource *)source)->sock;
463 struct timeval timeout = {0, 0};
464 fd_set fds;
465 GIOCondition condition = 0;
467 if (!sock || !sock->sock)
468 return FALSE;
470 condition = sock->condition;
472 if ((condition & G_IO_IN) == G_IO_IN &&
473 gnutls_record_check_pending(sock->ssl) != 0)
474 return TRUE;
476 FD_ZERO(&fds);
477 FD_SET(sock->sock, &fds);
479 select(sock->sock + 1,
480 (condition & G_IO_IN) ? &fds : NULL,
481 (condition & G_IO_OUT) ? &fds : NULL,
482 NULL, &timeout);
484 return FD_ISSET(sock->sock, &fds) != 0;
487 static gboolean ssl_sock_dispatch(GSource *source, GSourceFunc callback,
488 gpointer user_data)
490 SockInfo *sock = ((SockSource *)source)->sock;
492 if (!sock || !sock->callback || !sock->data)
493 return FALSE;
495 return sock->callback(sock, sock->condition, sock->data);
497 #endif
499 static gboolean sock_watch_cb(GIOChannel *source, GIOCondition condition,
500 gpointer data)
502 SockInfo *sock = (SockInfo *)data;
504 if ((condition & sock->condition) == 0)
505 return TRUE;
507 return sock->callback(sock, sock->condition, sock->data);
510 guint sock_add_watch(SockInfo *sock, GIOCondition condition, SockFunc func,
511 gpointer data)
513 if (!sock)
514 return FALSE;
516 sock->callback = func;
517 sock->condition = condition;
518 sock->data = data;
520 #ifdef USE_GNUTLS
521 if (sock->ssl)
523 GSource *source = g_source_new(&ssl_watch_funcs,
524 sizeof(SockSource));
525 ((SockSource *) source)->sock = sock;
526 g_source_set_priority(source, G_PRIORITY_DEFAULT);
527 g_source_set_can_recurse(source, FALSE);
528 sock->g_source = g_source_attach(source, NULL);
529 g_source_unref (source); /* Refcount back down to 1 */
530 return sock->g_source;
532 #endif
534 return g_io_add_watch(sock->sock_ch, condition, sock_watch_cb, sock);
537 static gint fd_check_io(gint fd, GIOCondition cond)
539 struct timeval timeout;
540 fd_set fds;
542 if (is_nonblocking_mode(fd))
543 return 0;
545 timeout.tv_sec = io_timeout;
546 timeout.tv_usec = 0;
548 FD_ZERO(&fds);
549 FD_SET(fd, &fds);
551 if (cond == G_IO_IN) {
552 select(fd + 1, &fds, NULL, NULL,
553 io_timeout > 0 ? &timeout : NULL);
554 } else {
555 select(fd + 1, NULL, &fds, NULL,
556 io_timeout > 0 ? &timeout : NULL);
559 if (FD_ISSET(fd, &fds)) {
560 return 0;
561 } else {
562 g_warning("socket IO timeout");
563 log_error(LOG_PROTOCOL, _("Socket IO timeout.\n"));
564 return -1;
568 #ifdef G_OS_UNIX
569 static sigjmp_buf jmpenv;
571 static void timeout_handler(gint sig)
573 siglongjmp(jmpenv, 1);
575 #endif /*G_OS_UNIX*/
577 static gint sock_connect_with_timeout(gint sock,
578 const struct sockaddr *serv_addr,
579 gint addrlen,
580 guint timeout_secs)
582 gint ret, saved_errno;
583 #ifdef G_OS_UNIX
584 void (*prev_handler)(gint);
586 alarm(0);
587 prev_handler = signal(SIGALRM, timeout_handler);
588 if (sigsetjmp(jmpenv, 1)) {
589 alarm(0);
590 signal(SIGALRM, prev_handler);
591 errno = ETIMEDOUT;
592 log_error(LOG_PROTOCOL, _("Connection timed out.\n"));
593 return -1;
595 alarm(timeout_secs);
596 #endif
598 ret = connect(sock, serv_addr, addrlen);
599 saved_errno = errno;
601 if (ret == -1) {
602 debug_print("connect() failed: %d (%s)\n",
603 saved_errno, g_strerror(saved_errno));
606 #ifdef G_OS_UNIX
607 alarm(0);
608 signal(SIGALRM, prev_handler);
609 #endif
611 return ret;
614 static gint sock_connect_by_getaddrinfo(const gchar *hostname, gushort port)
616 gint sock = -1, gai_error;
617 struct addrinfo hints, *res, *ai;
618 gchar port_str[6];
620 refresh_resolvers();
622 memset(&hints, 0, sizeof(hints));
623 hints.ai_flags = AI_ADDRCONFIG;
625 #ifdef INET6
626 hints.ai_family = AF_UNSPEC;
627 #else
628 hints.ai_family = AF_INET;
629 #endif
631 hints.ai_socktype = SOCK_STREAM;
632 hints.ai_protocol = IPPROTO_TCP;
634 /* convert port from integer to string. */
635 g_snprintf(port_str, sizeof(port_str), "%d", port);
637 if ((gai_error = getaddrinfo(hostname, port_str, &hints, &res)) != 0) {
638 g_printerr("getaddrinfo for %s:%s failed: %s\n",
639 hostname, port_str, gai_strerror(gai_error));
640 return -1;
643 for (ai = res; ai != NULL; ai = ai->ai_next) {
644 #ifndef INET6
645 if (ai->ai_family == AF_INET6)
646 continue;
647 #endif
649 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
650 if (sock < 0 )
651 continue;
652 #ifdef G_OS_WIN32
653 if (sock == INVALID_SOCKET)
654 continue;
655 #endif
657 if (sock_connect_with_timeout
658 (sock, ai->ai_addr, ai->ai_addrlen, io_timeout) == 0)
659 break;
661 close(sock);
664 if (res != NULL)
665 freeaddrinfo(res);
667 if (ai == NULL)
668 return -1;
670 return sock;
673 SockInfo *sock_connect(const gchar *hostname, gushort port)
675 #ifdef G_OS_WIN32
676 SOCKET sock;
677 #else
678 gint sock;
679 #endif
681 if ((sock = sock_connect_by_getaddrinfo(hostname, port)) < 0) {
682 return NULL;
685 return sockinfo_from_fd(hostname, port, sock);
689 static void sock_address_list_free(GList *addr_list)
691 GList *cur;
693 for (cur = addr_list; cur != NULL; cur = cur->next) {
694 SockAddrData *addr_data = (SockAddrData *)cur->data;
695 g_free(addr_data->addr);
696 g_free(addr_data);
699 g_list_free(addr_list);
702 /* asynchronous TCP connection */
704 static gboolean sock_connect_async_cb(GIOChannel *source,
705 GIOCondition condition, gpointer data)
707 SockConnectData *conn_data = (SockConnectData *)data;
708 gint fd;
709 gint val;
710 socklen_t len;
711 SockInfo *sockinfo;
713 if (conn_data->io_tag == 0 && conn_data->channel == NULL)
714 return FALSE;
716 fd = g_io_channel_unix_get_fd(source);
718 conn_data->io_tag = 0;
719 conn_data->channel = NULL;
720 g_io_channel_unref(source);
722 len = sizeof(val);
723 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &len) < 0) {
724 perror("getsockopt");
725 close(fd);
726 sock_connect_address_list_async(conn_data);
727 return FALSE;
730 if (val != 0) {
731 close(fd);
732 log_error(LOG_PROTOCOL, _("%s:%d: connection failed (%s).\n"),
733 conn_data->hostname, conn_data->port,
734 g_strerror(val));
735 sock_connect_address_list_async(conn_data);
736 return FALSE;
739 sockinfo = g_new0(SockInfo, 1);
740 sockinfo->sock = fd;
741 #ifndef G_OS_WIN32
742 sockinfo->sock_ch = g_io_channel_unix_new(fd);
743 #else
744 sockinfo->sock_ch = g_io_channel_win32_new_socket(fd);
745 #endif
746 sockinfo->hostname = g_strdup(conn_data->hostname);
747 sockinfo->port = conn_data->port;
748 sockinfo->state = CONN_ESTABLISHED;
749 sockinfo->canonical_name = g_strdup(conn_data->canonical_name);
751 conn_data->func(sockinfo, conn_data->data);
753 sock_connect_async_cancel(conn_data->id);
755 return FALSE;
758 static gint sock_connect_async_get_address_info_cb(GList *addr_list,
759 gpointer data)
761 SockConnectData *conn_data = (SockConnectData *)data;
763 conn_data->addr_list = addr_list;
764 conn_data->cur_addr = addr_list;
765 if (conn_data->lookup_data) {
766 conn_data->canonical_name = conn_data->lookup_data->canonical_name;
767 conn_data->lookup_data->canonical_name = NULL;
768 conn_data->lookup_data = NULL;
770 return sock_connect_address_list_async(conn_data);
773 gint sock_connect_async(const gchar *hostname, gushort port,
774 SockConnectFunc func, gpointer data)
776 static gint id = 1;
777 SockConnectData *conn_data;
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;
789 conn_data->lookup_data = sock_get_address_info_async
790 (hostname, port, sock_connect_async_get_address_info_cb,
791 conn_data);
793 if (conn_data->lookup_data == NULL) {
794 g_free(conn_data->hostname);
795 g_free(conn_data);
796 return -1;
799 sock_connect_data_list = g_list_append(sock_connect_data_list,
800 conn_data);
802 return conn_data->id;
805 gint sock_connect_async_cancel(gint id)
807 SockConnectData *conn_data = NULL;
808 GList *cur;
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;
817 if (conn_data) {
818 sock_connect_data_list = g_list_remove(sock_connect_data_list,
819 conn_data);
821 if (conn_data->lookup_data)
822 sock_get_address_info_async_cancel
823 (conn_data->lookup_data);
825 if (conn_data->io_tag > 0)
826 g_source_remove(conn_data->io_tag);
827 if (conn_data->channel) {
828 GError *err = NULL;
829 g_io_channel_shutdown(conn_data->channel, TRUE, &err);
830 if (err)
831 g_error_free(err);
832 g_io_channel_unref(conn_data->channel);
835 sock_address_list_free(conn_data->addr_list);
836 g_free(conn_data->canonical_name);
837 g_free(conn_data->hostname);
838 g_free(conn_data);
839 } else {
840 g_warning("sock_connect_async_cancel: id %d not found", id);
841 return -1;
844 return 0;
847 static gint sock_connect_address_list_async(SockConnectData *conn_data)
849 SockAddrData *addr_data;
850 gint sock = -1;
852 for (; conn_data->cur_addr != NULL;
853 conn_data->cur_addr = conn_data->cur_addr->next) {
854 addr_data = (SockAddrData *)conn_data->cur_addr->data;
856 if ((sock = socket(addr_data->family, addr_data->socktype,
857 addr_data->protocol)) < 0) {
858 perror("socket");
860 continue;
863 set_nonblocking_mode(sock, TRUE);
865 if (connect(sock, addr_data->addr, addr_data->addr_len) < 0) {
866 if (EINPROGRESS == errno) {
867 break;
868 } else {
869 perror("connect");
870 close(sock);
872 } else {
873 break;
877 if (conn_data->cur_addr == NULL) {
878 conn_data->func(NULL, conn_data->data);
879 sock_connect_async_cancel(conn_data->id);
880 return -1;
883 conn_data->cur_addr = conn_data->cur_addr->next;
885 #ifndef G_OS_WIN32
886 conn_data->channel = g_io_channel_unix_new(sock);
887 #else
888 conn_data->channel = g_io_channel_win32_new_socket(sock);
889 #endif
890 conn_data->io_tag = g_io_add_watch(conn_data->channel, G_IO_IN|G_IO_OUT,
891 sock_connect_async_cb, conn_data);
893 return 0;
896 /* asynchronous DNS lookup */
898 static gboolean sock_get_address_info_async_cb(GIOChannel *source,
899 GIOCondition condition,
900 gpointer data)
902 SockLookupData *lookup_data = (SockLookupData *)data;
903 GList *addr_list = NULL;
904 SockAddrData *addr_data;
905 gsize bytes_read;
906 gint ai_member[4];
907 struct sockaddr *addr;
908 gchar *canonical_name = NULL;
909 gchar len = 0;
910 GError *err = NULL;
912 g_io_channel_set_encoding(source, NULL, &err);
913 if (err) {
914 g_warning("can't unset encoding: %s", err->message);
915 g_error_free(err);
916 return FALSE;
918 g_io_channel_set_buffered(source, FALSE);
919 if (g_io_channel_read_chars(source, &len, sizeof(len),
920 &bytes_read, &err) == G_IO_STATUS_NORMAL) {
921 if (err != NULL) {
922 g_warning("g_io_channel_read_chars: %s", err->message);
923 g_error_free(err);
924 return FALSE;
926 if (bytes_read == sizeof(len) && len > 0) {
927 gchar *cur = NULL;
928 gint todo = len;
929 canonical_name = g_malloc0(len + 1);
930 cur = canonical_name;
931 while (todo > 0) {
932 if (g_io_channel_read_chars(source, cur, todo,
933 &bytes_read, &err) != G_IO_STATUS_NORMAL) {
934 if (err) {
935 g_warning("canonical name not read %s", err->message);
936 g_free(canonical_name);
937 canonical_name = NULL;
938 g_error_free(err);
939 err = NULL;
940 break;
942 } else {
943 cur += bytes_read;
944 todo -= bytes_read;
946 if (bytes_read == 0) {
947 g_warning("canonical name not read");
948 g_free(canonical_name);
949 canonical_name = NULL;
950 break;
955 for (;;) {
956 if (g_io_channel_read_chars(source, (gchar *)ai_member,
957 sizeof(ai_member), &bytes_read, &err)
958 != G_IO_STATUS_NORMAL) {
959 if (err != NULL) {
960 g_warning("g_io_channel_read_chars: addr len %s", err->message);
961 g_error_free(err);
962 err = NULL;
963 break;
967 if (bytes_read == 0 || bytes_read != sizeof(ai_member))
968 break;
970 if (ai_member[0] == AF_UNSPEC) {
971 g_warning("DNS lookup failed");
972 log_error(LOG_PROTOCOL, _("%s:%d: unknown host.\n"),
973 lookup_data->hostname, lookup_data->port);
974 break;
977 addr = g_malloc(ai_member[3]);
978 if (g_io_channel_read_chars(source, (gchar *)addr, ai_member[3],
979 &bytes_read, &err)
980 != G_IO_STATUS_NORMAL) {
981 if (err != NULL) {
982 g_warning("g_io_channel_read_chars: addr data read %s", err->message);
983 g_error_free(err);
984 err = NULL;
985 g_free(addr);
986 break;
990 if (bytes_read != ai_member[3]) {
991 g_warning("sock_get_address_info_async_cb: "
992 "incomplete address data");
993 g_free(addr);
994 break;
997 addr_data = g_new0(SockAddrData, 1);
998 addr_data->family = ai_member[0];
999 addr_data->socktype = ai_member[1];
1000 addr_data->protocol = ai_member[2];
1001 addr_data->addr_len = ai_member[3];
1002 addr_data->addr = addr;
1004 addr_list = g_list_append(addr_list, addr_data);
1007 g_io_channel_shutdown(source, TRUE, &err);
1008 if (err)
1009 g_error_free(err);
1010 g_io_channel_unref(source);
1012 #ifdef G_OS_WIN32
1013 /* FIXME: We would need to cancel the thread. */
1014 #else
1015 kill(lookup_data->child_pid, SIGKILL);
1016 waitpid(lookup_data->child_pid, NULL, 0);
1017 #endif
1018 lookup_data->canonical_name = canonical_name;
1020 lookup_data->func(addr_list, lookup_data->data);
1022 g_free(lookup_data->canonical_name);
1023 g_free(lookup_data->hostname);
1024 g_free(lookup_data);
1026 return FALSE;
1030 /* For better readability we use a separate function to implement the
1031 child code of sock_get_address_info_async. Note, that under W32
1032 this is actually not a child but a thread and this is the reason
1033 why we pass only a void pointer. */
1034 static void address_info_async_child(void *opaque)
1036 SockLookupData *parm = opaque;
1037 gint gai_err;
1038 struct addrinfo hints, *res, *ai;
1039 gchar port_str[6];
1040 gint ai_member[4] = {AF_UNSPEC, 0, 0, 0};
1042 #ifndef G_OS_WIN32
1043 close(parm->pipe_fds[0]);
1044 parm->pipe_fds[0] = -1;
1045 #endif
1047 memset(&hints, 0, sizeof(hints));
1048 hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
1049 #ifdef INET6
1050 hints.ai_family = AF_UNSPEC;
1051 #else
1052 hints.ai_family = AF_INET;
1053 #endif
1054 hints.ai_socktype = SOCK_STREAM;
1055 hints.ai_protocol = IPPROTO_TCP;
1057 g_snprintf(port_str, sizeof(port_str), "%d", parm->port);
1059 gai_err = getaddrinfo(parm->hostname, port_str, &hints, &res);
1060 if (gai_err != 0) {
1061 gchar len = 0;
1062 g_warning("getaddrinfo for %s:%s failed: %s",
1063 parm->hostname, port_str, gai_strerror(gai_err));
1064 log_error(LOG_PROTOCOL, _("%s:%s: host lookup failed (%s).\n"),
1065 parm->hostname, port_str, gai_strerror(gai_err));
1066 fd_write_all(parm->pipe_fds[1], &len,
1067 sizeof(len));
1068 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1069 sizeof(ai_member));
1070 close(parm->pipe_fds[1]);
1071 parm->pipe_fds[1] = -1;
1072 #ifdef G_OS_WIN32
1073 _endthread();
1074 #else
1075 _exit(1);
1076 #endif
1079 if (res != NULL) {
1080 if (res->ai_canonname && strlen(res->ai_canonname) < 255) {
1081 gchar len = strlen(res->ai_canonname);
1082 fd_write_all(parm->pipe_fds[1], &len,
1083 sizeof(len));
1084 fd_write_all(parm->pipe_fds[1], res->ai_canonname,
1085 len);
1086 } else {
1087 gchar len = 0;
1088 fd_write_all(parm->pipe_fds[1], &len,
1089 sizeof(len));
1091 } else {
1092 gchar len = 0;
1093 fd_write_all(parm->pipe_fds[1], &len,
1094 sizeof(len));
1097 for (ai = res; ai != NULL; ai = ai->ai_next) {
1098 ai_member[0] = ai->ai_family;
1099 ai_member[1] = ai->ai_socktype;
1100 ai_member[2] = ai->ai_protocol;
1101 ai_member[3] = ai->ai_addrlen;
1103 fd_write_all(parm->pipe_fds[1], (gchar *)ai_member,
1104 sizeof(ai_member));
1105 fd_write_all(parm->pipe_fds[1], (gchar *)ai->ai_addr,
1106 ai->ai_addrlen);
1109 if (res != NULL)
1110 freeaddrinfo(res);
1112 close(parm->pipe_fds[1]);
1113 parm->pipe_fds[1] = -1;
1115 #ifdef G_OS_WIN32
1116 _endthread();
1117 #else
1118 _exit(0);
1119 #endif
1122 static SockLookupData *sock_get_address_info_async(const gchar *hostname,
1123 gushort port,
1124 SockAddrFunc func,
1125 gpointer data)
1127 SockLookupData *lookup_data = NULL;
1129 refresh_resolvers();
1131 lookup_data = g_new0(SockLookupData, 1);
1132 lookup_data->hostname = g_strdup(hostname);
1133 lookup_data->func = func;
1134 lookup_data->data = data;
1135 lookup_data->port = port;
1136 lookup_data->child_pid = (pid_t)(-1);
1137 lookup_data->pipe_fds[0] = -1;
1138 lookup_data->pipe_fds[1] = -1;
1140 if (pipe(lookup_data->pipe_fds) < 0) {
1141 perror("pipe");
1142 func(NULL, data);
1143 g_free (lookup_data->hostname);
1144 g_free (lookup_data);
1145 return NULL;
1148 #ifndef G_OS_WIN32
1149 if ((lookup_data->child_pid = fork()) < 0) {
1150 perror("fork");
1151 func(NULL, data);
1152 g_free (lookup_data->hostname);
1153 g_free (lookup_data);
1154 return NULL;
1157 if (lookup_data->child_pid == 0) {
1158 /* Child process. */
1159 address_info_async_child (lookup_data);
1160 g_assert_not_reached ();
1162 /* Parent process. */
1163 close(lookup_data->pipe_fds[1]);
1164 lookup_data->pipe_fds[1] = -1;
1165 #endif /*!G_OS_WIN32 */
1167 #ifndef G_OS_WIN32
1168 lookup_data->channel = g_io_channel_unix_new(lookup_data->pipe_fds[0]);
1169 #else
1170 lookup_data->channel = g_io_channel_win32_new_fd(lookup_data->pipe_fds[0]);
1171 #endif
1172 lookup_data->io_tag = g_io_add_watch(lookup_data->channel, G_IO_IN,
1173 sock_get_address_info_async_cb,
1174 lookup_data);
1175 #ifdef G_OS_WIN32
1176 lookup_data->child_pid = _beginthread(
1177 address_info_async_child, 0, lookup_data);
1178 #endif
1180 return lookup_data;
1183 static gint sock_get_address_info_async_cancel(SockLookupData *lookup_data)
1185 if (lookup_data->io_tag > 0)
1186 g_source_remove(lookup_data->io_tag);
1187 if (lookup_data->channel) {
1188 GError *err = NULL;
1189 g_io_channel_shutdown(lookup_data->channel, TRUE, &err);
1190 if (err)
1191 g_error_free(err);
1193 g_io_channel_unref(lookup_data->channel);
1196 if (lookup_data->child_pid > 0) {
1197 #ifdef G_OS_WIN32
1198 /* FIXME: Need a way to cancel the thread. */
1199 #else
1200 kill(lookup_data->child_pid, SIGKILL);
1201 waitpid(lookup_data->child_pid, NULL, 0);
1202 #endif
1205 g_free(lookup_data->canonical_name);
1206 g_free(lookup_data->hostname);
1207 g_free(lookup_data);
1209 return 0;
1213 static SockInfo *sockinfo_from_fd(const gchar *hostname,
1214 gushort port,
1215 gint sock)
1217 SockInfo *sockinfo;
1219 sockinfo = g_new0(SockInfo, 1);
1220 sockinfo->sock = sock;
1221 #ifndef G_OS_WIN32
1222 sockinfo->sock_ch = g_io_channel_unix_new(sock);
1223 #else
1224 sockinfo->sock_ch = g_io_channel_win32_new_socket(sock);
1225 #endif
1226 sockinfo->hostname = g_strdup(hostname);
1227 sockinfo->port = port;
1228 sockinfo->state = CONN_ESTABLISHED;
1230 return sockinfo;
1233 static gint fd_read(gint fd, gchar *buf, gint len)
1235 if (fd_check_io(fd, G_IO_IN) < 0)
1236 return -1;
1238 #ifdef G_OS_WIN32
1239 if (fd_is_w32_socket(fd))
1240 return recv(fd, buf, len, 0);
1241 #endif
1243 return read(fd, buf, len);
1246 #if USE_GNUTLS
1247 static gint ssl_read(gnutls_session_t ssl, gchar *buf, gint len)
1249 gint r;
1251 if (gnutls_record_check_pending(ssl) == 0) {
1252 if (fd_check_io(GPOINTER_TO_INT(gnutls_transport_get_ptr(ssl)), G_IO_IN) < 0)
1253 return -1;
1256 while (1) {
1257 errno = 0;
1258 r = gnutls_record_recv(ssl, buf, len);
1259 if (r > 0)
1260 return r;
1262 switch (r) {
1263 case 0: /* closed connection */
1264 return -1;
1266 case GNUTLS_E_REHANDSHAKE:
1267 do {
1268 r = gnutls_handshake(ssl);
1269 } while (r == GNUTLS_E_AGAIN || r == GNUTLS_E_INTERRUPTED);
1270 break; /* re-receive */
1271 case GNUTLS_E_AGAIN:
1272 case GNUTLS_E_INTERRUPTED:
1273 errno = EAGAIN;
1274 return -1;
1275 case GNUTLS_E_PREMATURE_TERMINATION:
1276 if (errno == 0)
1277 return 0;
1278 /* fall through */
1279 default:
1280 debug_print("Unexpected TLS read result %d\n", r);
1281 errno = EIO;
1282 return -1;
1287 #endif
1289 gint sock_read(SockInfo *sock, gchar *buf, gint len)
1291 gint ret;
1293 cm_return_val_if_fail(sock != NULL, -1);
1295 #ifdef USE_GNUTLS
1296 if (sock->ssl)
1297 ret = ssl_read(sock->ssl, buf, len);
1298 else
1299 #endif
1300 ret = fd_read(sock->sock, buf, len);
1302 if (ret < 0)
1303 sock->state = CONN_DISCONNECTED;
1304 return ret;
1307 gint fd_write(gint fd, const gchar *buf, gint len)
1309 if (fd_check_io(fd, G_IO_OUT) < 0)
1310 return -1;
1312 #ifdef G_OS_WIN32
1313 if (fd_is_w32_socket (fd))
1314 return send(fd, buf, len, 0);
1315 #endif
1317 return write(fd, buf, len);
1320 #if USE_GNUTLS
1321 static gint ssl_write(gnutls_session_t ssl, const gchar *buf, gint len)
1323 gint ret;
1325 if (fd_check_io(GPOINTER_TO_INT(gnutls_transport_get_ptr(ssl)), G_IO_OUT) < 0)
1326 return -1;
1328 ret = gnutls_record_send(ssl, buf, len);
1330 switch (ret) {
1331 case 0:
1332 return -1;
1333 case GNUTLS_E_AGAIN:
1334 case GNUTLS_E_INTERRUPTED:
1335 return 0;
1337 default:
1338 return ret;
1342 #endif
1344 gint sock_write(SockInfo *sock, const gchar *buf, gint len)
1346 gint ret;
1348 cm_return_val_if_fail(sock != NULL, -1);
1350 #ifdef USE_GNUTLS
1351 if (sock->ssl)
1352 ret = ssl_write(sock->ssl, buf, len);
1353 else
1354 #endif
1355 ret = fd_write(sock->sock, buf, len);
1357 if (ret < 0)
1358 sock->state = CONN_DISCONNECTED;
1359 return ret;
1362 gint fd_write_all(gint fd, const gchar *buf, gint len)
1364 gint n, wrlen = 0;
1366 while (len) {
1367 if (fd_check_io(fd, G_IO_OUT) < 0)
1368 return -1;
1369 #ifndef G_OS_WIN32
1370 signal(SIGPIPE, SIG_IGN);
1371 #endif
1373 #ifdef G_OS_WIN32
1374 if (fd_is_w32_socket(fd))
1375 n = send(fd, buf, len, 0);
1376 else
1377 #endif
1378 n = write(fd, buf, len);
1380 if (n <= 0) {
1381 log_error(LOG_PROTOCOL, _("write on fd%d: %s\n"), fd, g_strerror(errno));
1382 return -1;
1384 len -= n;
1385 wrlen += n;
1386 buf += n;
1389 return wrlen;
1392 #ifdef USE_GNUTLS
1393 static gint ssl_write_all(gnutls_session_t ssl, const gchar *buf, gint len)
1395 gint n, wrlen = 0;
1397 while (len) {
1398 n = ssl_write(ssl, buf, len);
1399 if (n <= 0)
1400 return -1;
1401 len -= n;
1402 wrlen += n;
1403 buf += n;
1406 return wrlen;
1408 #endif
1410 gint sock_write_all(SockInfo *sock, const gchar *buf, gint len)
1412 gint ret;
1414 cm_return_val_if_fail(sock != NULL, -1);
1416 #ifdef USE_GNUTLS
1417 if (sock->ssl)
1418 ret = ssl_write_all(sock->ssl, buf, len);
1419 else
1420 #endif
1421 ret = fd_write_all(sock->sock, buf, len);
1423 if (ret < 0)
1424 sock->state = CONN_DISCONNECTED;
1425 return ret;
1428 #ifndef G_OS_WIN32
1429 static gint fd_recv(gint fd, gchar *buf, gint len, gint flags)
1431 if (fd_check_io(fd, G_IO_IN) < 0)
1432 return -1;
1434 return recv(fd, buf, len, flags);
1436 #endif
1438 gint fd_gets(gint fd, gchar *buf, gint len)
1440 gchar *bp = buf;
1442 if (--len < 1)
1443 return -1;
1445 #ifdef G_OS_WIN32
1446 fd_check_io(fd, G_IO_IN);
1447 do {
1449 XXX:tm try nonblock
1450 MSKB Article ID: Q147714
1451 Windows Sockets 2 Service Provider Interface Limitations
1452 Polling with recv(MSG_PEEK) to determine when a complete message
1453 has arrived.
1454 Reason and Workaround not available.
1456 Single-byte send() and recv().
1457 Reason: Couple one-byte sends with Nagle disabled.
1458 Workaround: Send modest amounts and receive as much as possible.
1459 (still unused)
1461 if (recv(fd, bp, 1, 0) <= 0)
1462 return -1;
1463 if (*bp == '\n')
1464 break;
1465 bp++;
1466 len--;
1467 } while (0 < len);
1468 #else /*!G_OS_WIN32*/
1469 gchar *newline;
1470 gint n;
1471 do {
1472 if ((n = fd_recv(fd, bp, len, MSG_PEEK)) <= 0)
1473 return -1;
1474 if ((newline = memchr(bp, '\n', n)) != NULL)
1475 n = newline - bp + 1;
1476 if ((n = fd_read(fd, bp, n)) < 0)
1477 return -1;
1478 bp += n;
1479 len -= n;
1480 } while (!newline && len);
1481 #endif /*!G_OS_WIN32*/
1483 *bp = '\0';
1484 return bp - buf;
1487 gint sock_close(SockInfo *sock, gboolean close_fd)
1489 gint ret = 0;
1491 if (!sock)
1492 return 0;
1494 if (sock->sock_ch)
1495 g_io_channel_unref(sock->sock_ch);
1497 #ifdef USE_GNUTLS
1498 if (sock->ssl)
1499 ssl_done_socket(sock);
1500 if (sock->g_source != 0 && g_main_context_find_source_by_id(NULL, sock->g_source) != NULL)
1501 g_source_remove(sock->g_source);
1502 sock->g_source = 0;
1503 #endif
1504 if (close_fd) {
1505 #ifdef G_OS_WIN32
1506 shutdown(sock->sock, 1); /* complete transfer before close */
1507 ret = closesocket(sock->sock);
1508 #else
1509 ret = fd_close(sock->sock);
1510 #endif
1513 g_free(sock->canonical_name);
1514 g_free(sock->hostname);
1515 g_free(sock);
1517 return ret;
1520 gint fd_close(gint fd)
1522 return close(fd);