2 This file is part of GNUnet.
3 (C) 2009, 2012 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file util/connection.c
23 * @brief TCP connection management
24 * @author Christian Grothoff
26 * This code is rather complex. Only modify it if you
27 * 1) Have a NEW testcase showing that the new code
28 * is needed and correct
29 * 2) All EXISTING testcases pass with the new code
30 * These rules should apply in general, but for this
31 * module they are VERY, VERY important.
35 #include "gnunet_common.h"
36 #include "gnunet_connection_lib.h"
37 #include "gnunet_container_lib.h"
38 #include "gnunet_resolver_service.h"
39 #include "gnunet_scheduler_lib.h"
40 #include "gnunet_server_lib.h"
43 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
45 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
49 * Transmission handle. There can only be one for each connection.
51 struct GNUNET_CONNECTION_TransmitHandle
55 * Function to call if the send buffer has notify_size
58 GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
61 * Closure for notify_ready.
63 void *notify_ready_cls;
66 * Our connection handle.
68 struct GNUNET_CONNECTION_Handle *connection;
71 * Timeout for receiving (in absolute time).
73 struct GNUNET_TIME_Absolute transmit_timeout;
76 * Task called on timeout.
78 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
81 * At what number of bytes available in the
82 * write buffer should the notify method be called?
90 * During connect, we try multiple possible IP addresses
91 * to find out which one might work.
97 * This is a linked list.
99 struct AddressProbe *next;
102 * This is a doubly-linked list.
104 struct AddressProbe *prev;
107 * The address; do not free (allocated at the end of this struct).
109 const struct sockaddr *addr;
112 * Underlying OS's socket.
114 struct GNUNET_NETWORK_Handle *sock;
117 * Connection for which we are probing.
119 struct GNUNET_CONNECTION_Handle *connection;
127 * Task waiting for the connection to finish connecting.
129 GNUNET_SCHEDULER_TaskIdentifier task;
134 * @brief handle for a network connection
136 struct GNUNET_CONNECTION_Handle
140 * Configuration to use.
142 const struct GNUNET_CONFIGURATION_Handle *cfg;
145 * Linked list of sockets we are currently trying out
148 struct AddressProbe *ap_head;
151 * Linked list of sockets we are currently trying out
154 struct AddressProbe *ap_tail;
157 * Network address of the other end-point, may be NULL.
159 struct sockaddr *addr;
162 * Pointer to the hostname if connection was
163 * created using DNS lookup, otherwise NULL.
168 * Underlying OS's socket, set to NULL after fatal errors.
170 struct GNUNET_NETWORK_Handle *sock;
173 * Function to call on data received, NULL if no receive is pending.
175 GNUNET_CONNECTION_Receiver receiver;
178 * Closure for receiver.
183 * Pointer to our write buffer.
188 * Current size of our write buffer.
190 size_t write_buffer_size;
193 * Current write-offset in write buffer (where
194 * would we write next).
196 size_t write_buffer_off;
199 * Current read-offset in write buffer (how many
200 * bytes have already been sent).
202 size_t write_buffer_pos;
210 * Read task that we may need to wait for.
212 GNUNET_SCHEDULER_TaskIdentifier read_task;
215 * Write task that we may need to wait for.
217 GNUNET_SCHEDULER_TaskIdentifier write_task;
220 * Handle to a pending DNS lookup request.
222 struct GNUNET_RESOLVER_RequestHandle *dns_active;
225 * The handle we return for GNUNET_CONNECTION_notify_transmit_ready.
227 struct GNUNET_CONNECTION_TransmitHandle nth;
230 * Timeout for receiving (in absolute time).
232 struct GNUNET_TIME_Absolute receive_timeout;
235 * Maximum number of bytes to read (for receiving).
240 * Port to connect to.
245 * When shutdown, do not ever actually close the socket, but
246 * free resources. Only should ever be set if using program
247 * termination as a signal (because only then will the leaked
256 * Set the persist option on this connection handle. Indicates
257 * that the underlying socket or fd should never really be closed.
258 * Used for indicating process death.
260 * @param connection the connection to set persistent
263 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
265 connection->persist = GNUNET_YES;
270 * Disable the "CORK" feature for communication with the given connection,
271 * forcing the OS to immediately flush the buffer on transmission
272 * instead of potentially buffering multiple messages. Essentially
273 * reduces the OS send buffers to zero.
274 * Used to make sure that the last messages sent through the connection
275 * reach the other side before the process is terminated.
277 * @param connection the connection to make flushing and blocking
278 * @return GNUNET_OK on success
281 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
283 return GNUNET_NETWORK_socket_disable_corking (connection->sock);
288 * Create a connection handle by boxing an existing OS socket. The OS
289 * socket should henceforth be no longer used directly.
290 * GNUNET_connection_destroy will close it.
292 * @param osSocket existing socket to box
293 * @return the boxed connection handle
295 struct GNUNET_CONNECTION_Handle *
296 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
298 struct GNUNET_CONNECTION_Handle *connection;
300 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
301 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
302 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
303 connection->sock = osSocket;
309 * Create a connection handle by accepting on a listen socket. This
310 * function may block if the listen socket has no connection ready.
312 * @param access function to use to check if access is allowed
313 * @param access_cls closure for access
314 * @param lsock listen socket
315 * @return the connection handle, NULL on error
317 struct GNUNET_CONNECTION_Handle *
318 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access,
320 struct GNUNET_NETWORK_Handle *lsock)
322 struct GNUNET_CONNECTION_Handle *connection;
325 struct GNUNET_NETWORK_Handle *sock;
327 struct sockaddr_in *v4;
328 struct sockaddr_in6 *v6;
331 struct GNUNET_CONNECTION_Credentials *gcp;
332 struct GNUNET_CONNECTION_Credentials gc;
338 addrlen = sizeof (addr);
340 GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
343 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
346 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
349 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
353 sa = (struct sockaddr *) addr;
354 v6 = (struct sockaddr_in6 *) addr;
355 if ((AF_INET6 == sa->sa_family) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
357 /* convert to V4 address */
358 v4 = GNUNET_malloc (sizeof (struct sockaddr_in));
359 memset (v4, 0, sizeof (struct sockaddr_in));
360 v4->sin_family = AF_INET;
361 #if HAVE_SOCKADDR_IN_SIN_LEN
362 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
364 memcpy (&v4->sin_addr,
365 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
366 sizeof (struct in_addr)],
367 sizeof (struct in_addr));
368 v4->sin_port = v6->sin6_port;
370 addrlen = sizeof (struct sockaddr_in);
374 uaddr = GNUNET_malloc (addrlen);
375 memcpy (uaddr, addr, addrlen);
380 if (AF_UNIX == sa->sa_family)
384 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock), &gc.uid, &gc.gid))
388 /* largely traditional GNU/Linux */
391 getsockopt (GNUNET_NETWORK_get_fd (sock), SOL_SOCKET, SO_PEERCRED, &uc,
392 &olen)) && (olen == sizeof (uc)))
399 #if HAVE_GETPEERUCRED
400 /* this is for Solaris 10 */
404 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
406 gc.uid = ucred_geteuid (uc);
407 gc.gid = ucred_getegid (uc);
416 if ((NULL != access) &&
417 (GNUNET_YES != (aret = access (access_cls, gcp, uaddr, addrlen))))
419 if (GNUNET_NO == aret)
420 LOG (GNUNET_ERROR_TYPE_INFO, _("Access denied to `%s'\n"),
421 GNUNET_a2s (uaddr, addrlen));
422 GNUNET_break (GNUNET_OK ==
423 GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
424 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
428 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
429 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
430 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
431 connection->addr = uaddr;
432 connection->addrlen = addrlen;
433 connection->sock = sock;
434 LOG (GNUNET_ERROR_TYPE_INFO,
435 _("Accepting connection from `%s': %p\n"),
436 GNUNET_a2s (uaddr, addrlen), connection);
442 * Obtain the network address of the other party.
444 * @param connection the client to get the address for
445 * @param addr where to store the address
446 * @param addrlen where to store the length of the address
447 * @return GNUNET_OK on success
450 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
451 void **addr, size_t * addrlen)
453 if ((NULL == connection->addr) || (0 == connection->addrlen))
455 *addr = GNUNET_malloc (connection->addrlen);
456 memcpy (*addr, connection->addr, connection->addrlen);
457 *addrlen = connection->addrlen;
463 * Tell the receiver callback that we had an IO error.
465 * @param connection connection to signal error
466 * @param errcode error code to send
469 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection, int errcode)
471 GNUNET_CONNECTION_Receiver receiver;
473 LOG (GNUNET_ERROR_TYPE_DEBUG,
474 "Receive encounters error (%s), connection closed (%p)\n",
477 GNUNET_assert (NULL != (receiver = connection->receiver));
478 connection->receiver = NULL;
479 receiver (connection->receiver_cls, NULL, 0, connection->addr, connection->addrlen, errcode);
484 * Tell the receiver callback that a timeout was reached.
486 * @param connection connection to signal for
489 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
491 GNUNET_CONNECTION_Receiver receiver;
493 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection signals timeout to receiver (%p)!\n",
495 GNUNET_assert (NULL != (receiver = connection->receiver));
496 connection->receiver = NULL;
497 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
502 * We failed to transmit data to the service, signal the error.
504 * @param connection handle that had trouble
505 * @param ecode error code (errno)
508 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
511 GNUNET_CONNECTION_TransmitReadyNotify notify;
513 LOG (GNUNET_ERROR_TYPE_DEBUG,
514 "Transmission encounterd error (%s), connection closed (%p)\n",
517 if (NULL != connection->sock)
519 GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR);
520 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
521 connection->sock = NULL;
522 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
524 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
526 /* send errors trigger read errors... */
527 GNUNET_SCHEDULER_cancel (connection->read_task);
528 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
529 signal_receive_timeout (connection);
532 if (NULL == connection->nth.notify_ready)
533 return; /* nobody to tell about it */
534 notify = connection->nth.notify_ready;
535 connection->nth.notify_ready = NULL;
536 notify (connection->nth.notify_ready_cls, 0, NULL);
541 * We've failed for good to establish a connection (timeout or
542 * no more addresses to try).
544 * @param connection the connection we tried to establish
547 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
549 LOG (GNUNET_ERROR_TYPE_INFO,
550 _("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
551 connection->hostname, connection->port);
552 GNUNET_break (NULL == connection->ap_head);
553 GNUNET_break (NULL == connection->ap_tail);
554 GNUNET_break (GNUNET_NO == connection->dns_active);
555 GNUNET_break (NULL == connection->sock);
556 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
558 /* signal errors for jobs that used to wait on the connection */
559 if (NULL != connection->receiver)
560 signal_receive_error (connection, ECONNREFUSED);
561 if (NULL != connection->nth.notify_ready)
563 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
564 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
565 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
566 signal_transmit_error (connection, ECONNREFUSED);
572 * We are ready to transmit (or got a timeout).
574 * @param cls our connection handle
575 * @param tc task context describing why we are here
578 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
582 * This function is called once we either timeout or have data ready
585 * @param cls connection to read from
586 * @param tc scheduler context
589 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
593 * We've succeeded in establishing a connection.
595 * @param connection the connection we tried to establish
598 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
600 LOG (GNUNET_ERROR_TYPE_DEBUG,
601 "Connection to `%s' succeeded! (%p)\n",
602 GNUNET_a2s (connection->addr, connection->addrlen), connection);
603 /* trigger jobs that waited for the connection */
604 if (NULL != connection->receiver)
606 LOG (GNUNET_ERROR_TYPE_DEBUG,
607 "Connection succeeded, starting with receiving data (%p)\n",
609 connection->read_task =
610 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
611 (connection->receive_timeout), connection->sock,
612 &receive_ready, connection);
614 if (NULL != connection->nth.notify_ready)
616 LOG (GNUNET_ERROR_TYPE_DEBUG,
617 "Connection succeeded, starting with sending data (%p)\n",
619 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
620 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
621 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
622 GNUNET_assert (connection->write_task == GNUNET_SCHEDULER_NO_TASK);
623 connection->write_task =
624 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
625 (connection->nth.transmit_timeout), connection->sock,
626 &transmit_ready, connection);
632 * Scheduler let us know that we're either ready to write on the
633 * socket OR connect timed out. Do the right thing.
635 * @param cls the "struct AddressProbe*" with the address that we are probing
636 * @param tc success or failure info about the connect attempt.
639 connect_probe_continuation (void *cls,
640 const struct GNUNET_SCHEDULER_TaskContext *tc)
642 struct AddressProbe *ap = cls;
643 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
644 struct AddressProbe *pos;
648 GNUNET_assert (NULL != ap->sock);
649 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
650 len = sizeof (error);
653 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
655 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
656 &len)) || (0 != error))
658 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
660 if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
661 connect_fail_continuation (connection);
664 GNUNET_assert (NULL == connection->sock);
665 connection->sock = ap->sock;
666 GNUNET_assert (NULL == connection->addr);
667 connection->addr = GNUNET_malloc (ap->addrlen);
668 memcpy (connection->addr, ap->addr, ap->addrlen);
669 connection->addrlen = ap->addrlen;
671 /* cancel all other attempts */
672 while (NULL != (pos = connection->ap_head))
674 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
675 GNUNET_SCHEDULER_cancel (pos->task);
676 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
679 connect_success_continuation (connection);
684 * Try to establish a connection given the specified address.
685 * This function is called by the resolver once we have a DNS reply.
687 * @param cls our "struct GNUNET_CONNECTION_Handle *"
688 * @param addr address to try, NULL for "last call"
689 * @param addrlen length of addr
692 try_connect_using_address (void *cls, const struct sockaddr *addr,
695 struct GNUNET_CONNECTION_Handle *connection = cls;
696 struct AddressProbe *ap;
697 struct GNUNET_TIME_Relative delay;
701 connection->dns_active = NULL;
702 if ((NULL == connection->ap_head) && (NULL == connection->sock))
703 connect_fail_continuation (connection);
706 if (NULL != connection->sock)
707 return; /* already connected */
708 GNUNET_assert (NULL == connection->addr);
710 LOG (GNUNET_ERROR_TYPE_DEBUG,
711 "Trying to connect using address `%s:%u/%s:%u'\n", connection->hostname, connection->port,
712 GNUNET_a2s (addr, addrlen), connection->port);
713 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
714 ap->addr = (const struct sockaddr *) &ap[1];
715 memcpy (&ap[1], addr, addrlen);
716 ap->addrlen = addrlen;
717 ap->connection = connection;
719 switch (ap->addr->sa_family)
722 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
725 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
730 return; /* not supported by us */
732 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
733 if (NULL == ap->sock)
736 return; /* not supported by OS */
738 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
739 GNUNET_a2s (ap->addr, ap->addrlen), connection);
741 GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
742 (EINPROGRESS != errno))
744 /* maybe refused / unsupported address, try next */
745 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
747 LOG (GNUNET_ERROR_TYPE_INFO, _("Failed to connect to `%s' (%p)\n"),
748 GNUNET_a2s (ap->addr, ap->addrlen), connection);
750 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
754 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
755 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
756 if (NULL != connection->nth.notify_ready)
758 GNUNET_TIME_relative_min (delay,
759 GNUNET_TIME_absolute_get_remaining (connection->
760 nth.transmit_timeout));
761 if (NULL != connection->receiver)
763 GNUNET_TIME_relative_min (delay,
764 GNUNET_TIME_absolute_get_remaining
765 (connection->receive_timeout));
767 GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
768 &connect_probe_continuation, ap);
773 * Create a connection handle by (asynchronously) connecting to a host.
774 * This function returns immediately, even if the connection has not
775 * yet been established. This function only creates TCP connections.
777 * @param cfg configuration to use
778 * @param hostname name of the host to connect to
779 * @param port port to connect to
780 * @return the connection handle
782 struct GNUNET_CONNECTION_Handle *
783 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle
784 *cfg, const char *hostname,
787 struct GNUNET_CONNECTION_Handle *connection;
789 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
790 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
791 connection->cfg = cfg;
792 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
793 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
794 connection->port = port;
795 connection->hostname = GNUNET_strdup (hostname);
796 connection->dns_active =
797 GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
798 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
799 &try_connect_using_address, connection);
805 * Create a connection handle by connecting to a UNIX domain service.
806 * This function returns immediately, even if the connection has not
807 * yet been established. This function only creates UNIX connections.
809 * @param cfg configuration to use
810 * @param unixpath path to connect to
811 * @return the connection handle, NULL on systems without UNIX support
813 struct GNUNET_CONNECTION_Handle *
814 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
815 GNUNET_CONFIGURATION_Handle
816 *cfg, const char *unixpath)
819 struct GNUNET_CONNECTION_Handle *connection;
820 struct sockaddr_un *un;
823 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
824 un = GNUNET_malloc (sizeof (struct sockaddr_un));
825 un->sun_family = AF_UNIX;
826 slen = strlen (unixpath);
827 if (slen >= sizeof (un->sun_path))
828 slen = sizeof (un->sun_path) - 1;
829 memcpy (un->sun_path, unixpath, slen);
830 un->sun_path[slen] = '\0';
831 slen = sizeof (struct sockaddr_un);
832 #if HAVE_SOCKADDR_IN_SIN_LEN
833 un->sun_len = (u_char) slen;
836 un->sun_path[0] = '\0';
838 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
839 connection->cfg = cfg;
840 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
841 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
842 connection->port = 0;
843 connection->hostname = NULL;
844 connection->addr = (struct sockaddr *) un;
845 connection->addrlen = slen;
846 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
847 if (NULL == connection->sock)
849 GNUNET_free (connection->addr);
850 GNUNET_free (connection->write_buffer);
851 GNUNET_free (connection);
855 GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen))
857 /* Just return; we expect everything to work eventually so don't fail HARD */
858 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
859 connection->sock = NULL;
862 connect_success_continuation (connection);
871 * Create a connection handle by (asynchronously) connecting to a host.
872 * This function returns immediately, even if the connection has not
873 * yet been established. This function only creates TCP connections.
875 * @param af_family address family to use
876 * @param serv_addr server address
877 * @param addrlen length of server address
878 * @return the connection handle
880 struct GNUNET_CONNECTION_Handle *
881 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
882 const struct sockaddr *serv_addr,
885 struct GNUNET_NETWORK_Handle *s;
886 struct GNUNET_CONNECTION_Handle *connection;
888 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
891 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
894 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
895 (EINPROGRESS != errno))
897 /* maybe refused / unsupported address, try next */
898 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
899 LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
900 GNUNET_a2s (serv_addr, addrlen));
901 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
904 connection = GNUNET_CONNECTION_create_from_existing (s);
905 connection->addr = GNUNET_malloc (addrlen);
906 memcpy (connection->addr, serv_addr, addrlen);
907 connection->addrlen = addrlen;
908 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
909 GNUNET_a2s (serv_addr, addrlen), connection);
915 * Check if connection is valid (no fatal errors have happened so far).
916 * Note that a connection that is still trying to connect is considered
919 * @param connection connection to check
920 * @return GNUNET_YES if valid, GNUNET_NO otherwise
923 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
925 if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
926 return GNUNET_YES; /* still trying to connect */
927 return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
932 * Close the connection and free associated resources. There must
933 * not be any pending requests for reading or writing to the
934 * connection at this time.
936 * @param connection connection to destroy
939 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
941 struct AddressProbe *pos;
943 LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
944 GNUNET_assert (NULL == connection->nth.notify_ready);
945 GNUNET_assert (NULL == connection->receiver);
946 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
948 GNUNET_SCHEDULER_cancel (connection->write_task);
949 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
950 connection->write_buffer_off = 0;
952 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
954 GNUNET_SCHEDULER_cancel (connection->read_task);
955 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
957 if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
959 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
960 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
962 connection->nth.notify_ready = NULL;
963 if (NULL != connection->dns_active)
965 GNUNET_RESOLVER_request_cancel (connection->dns_active);
966 connection->dns_active = NULL;
968 while (NULL != (pos = connection->ap_head))
970 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
971 GNUNET_SCHEDULER_cancel (pos->task);
972 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
975 if ( (NULL != connection->sock) &&
976 (GNUNET_YES != connection->persist) )
978 if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
979 (ENOTCONN != errno) &&
980 (ECONNRESET != errno) )
981 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
983 if (NULL != connection->sock)
985 if (GNUNET_YES != connection->persist)
986 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
988 GNUNET_free (connection->sock); /* at least no memory leak (we deliberately
989 * leak the socket in this special case) ... */
991 GNUNET_free_non_null (connection->addr);
992 GNUNET_free_non_null (connection->hostname);
993 GNUNET_free (connection->write_buffer);
994 GNUNET_free (connection);
999 * This function is called once we either timeout
1000 * or have data ready to read.
1002 * @param cls connection to read from
1003 * @param tc scheduler context
1006 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1008 struct GNUNET_CONNECTION_Handle *connection = cls;
1009 char buffer[connection->max];
1011 GNUNET_CONNECTION_Receiver receiver;
1013 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1014 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1016 /* ignore shutdown request, go again immediately */
1017 connection->read_task =
1018 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1019 (connection->receive_timeout), connection->sock,
1020 &receive_ready, connection);
1023 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1025 LOG (GNUNET_ERROR_TYPE_DEBUG,
1026 "Receive from `%s' encounters error: timeout (%p)\n",
1027 GNUNET_a2s (connection->addr, connection->addrlen),
1028 GNUNET_TIME_absolute_get_duration (connection->receive_timeout).rel_value,
1030 signal_receive_timeout (connection);
1033 if (NULL == connection->sock)
1035 /* connect failed for good */
1036 signal_receive_error (connection, ECONNREFUSED);
1039 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1041 ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1046 signal_receive_error (connection, errno);
1049 LOG (GNUNET_ERROR_TYPE_DEBUG,
1050 "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1051 connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1052 GNUNET_assert (NULL != (receiver = connection->receiver));
1053 connection->receiver = NULL;
1054 receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1059 * Receive data from the given connection. Note that this function will
1060 * call "receiver" asynchronously using the scheduler. It will
1061 * "immediately" return. Note that there MUST only be one active
1062 * receive call per connection at any given point in time (so do not
1063 * call receive again until the receiver callback has been invoked).
1065 * @param connection connection handle
1066 * @param max maximum number of bytes to read
1067 * @param timeout maximum amount of time to wait (use -1 for "forever")
1068 * @param receiver function to call with received data
1069 * @param receiver_cls closure for receiver
1072 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1073 struct GNUNET_TIME_Relative timeout,
1074 GNUNET_CONNECTION_Receiver receiver,
1077 GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1078 (NULL == connection->receiver));
1079 connection->receiver = receiver;
1080 connection->receiver_cls = receiver_cls;
1081 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1082 connection->max = max;
1083 if (NULL != connection->sock)
1085 connection->read_task =
1086 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1087 (connection->receive_timeout), connection->sock,
1088 &receive_ready, connection);
1091 if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1093 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1100 * Cancel receive job on the given connection. Note that the
1101 * receiver callback must not have been called yet in order
1102 * for the cancellation to be valid.
1104 * @param connection connection handle
1105 * @return closure of the original receiver callback closure
1108 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1110 if (GNUNET_SCHEDULER_NO_TASK == connection->read_task)
1112 GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1113 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1115 connection->receiver = NULL;
1116 return connection->receiver_cls;
1121 * Try to call the transmit notify method (check if we do
1122 * have enough space available first)!
1124 * @param connection connection for which we should do this processing
1125 * @return GNUNET_YES if we were able to call notify
1128 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1133 GNUNET_CONNECTION_TransmitReadyNotify notify;
1135 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1136 if (NULL == (notify = connection->nth.notify_ready))
1138 used = connection->write_buffer_off - connection->write_buffer_pos;
1139 avail = connection->write_buffer_size - used;
1140 size = connection->nth.notify_size;
1143 connection->nth.notify_ready = NULL;
1144 if (connection->write_buffer_size - connection->write_buffer_off < size)
1146 /* need to compact */
1147 memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1149 connection->write_buffer_off -= connection->write_buffer_pos;
1150 connection->write_buffer_pos = 0;
1152 avail = connection->write_buffer_size - connection->write_buffer_off;
1153 GNUNET_assert (avail >= size);
1155 notify (connection->nth.notify_ready_cls, avail,
1156 &connection->write_buffer[connection->write_buffer_off]);
1157 GNUNET_assert (size <= avail);
1159 connection->write_buffer_off += size;
1165 * Task invoked by the scheduler when a call to transmit
1166 * is timing out (we never got enough buffer space to call
1167 * the callback function before the specified timeout
1170 * This task notifies the client about the timeout.
1172 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1173 * @param tc scheduler context
1176 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1178 struct GNUNET_CONNECTION_Handle *connection = cls;
1179 GNUNET_CONNECTION_TransmitReadyNotify notify;
1181 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1182 LOG (GNUNET_ERROR_TYPE_DEBUG,
1183 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1184 connection->hostname,
1185 connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1186 notify = connection->nth.notify_ready;
1187 GNUNET_assert (NULL != notify);
1188 connection->nth.notify_ready = NULL;
1189 notify (connection->nth.notify_ready_cls, 0, NULL);
1194 * Task invoked by the scheduler when we failed to connect
1195 * at the time of being asked to transmit.
1197 * This task notifies the client about the error.
1199 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1200 * @param tc scheduler context
1203 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1205 struct GNUNET_CONNECTION_Handle *connection = cls;
1206 GNUNET_CONNECTION_TransmitReadyNotify notify;
1208 LOG (GNUNET_ERROR_TYPE_DEBUG,
1209 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1210 connection->nth.notify_size, connection->hostname, connection->port, connection);
1211 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1212 notify = connection->nth.notify_ready;
1213 connection->nth.notify_ready = NULL;
1214 notify (connection->nth.notify_ready_cls, 0, NULL);
1219 * We are ready to transmit (or got a timeout).
1221 * @param cls our connection handle
1222 * @param tc task context describing why we are here
1225 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1227 struct GNUNET_CONNECTION_Handle *connection = cls;
1228 GNUNET_CONNECTION_TransmitReadyNotify notify;
1232 LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1233 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1234 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1235 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1236 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1238 if (NULL != connection->sock)
1239 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1240 LOG (GNUNET_ERROR_TYPE_DEBUG,
1241 "Transmit to `%s' fails, shutdown happened (%p).\n",
1242 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1243 notify = connection->nth.notify_ready;
1246 connection->nth.notify_ready = NULL;
1247 notify (connection->nth.notify_ready_cls, 0, NULL);
1251 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1253 LOG (GNUNET_ERROR_TYPE_DEBUG,
1254 "Transmit to `%s' fails, time out reached (%p).\n",
1255 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1256 notify = connection->nth.notify_ready;
1257 GNUNET_assert (NULL != notify);
1258 connection->nth.notify_ready = NULL;
1259 notify (connection->nth.notify_ready_cls, 0, NULL);
1262 GNUNET_assert (NULL != connection->sock);
1263 if (NULL == tc->write_ready)
1265 /* special circumstances (in particular, PREREQ_DONE after
1266 * connect): not yet ready to write, but no "fatal" error either.
1268 goto SCHEDULE_WRITE;
1270 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1272 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1273 /* special circumstances (in particular, shutdown): not yet ready
1274 * to write, but no "fatal" error either. Hence retry. */
1275 goto SCHEDULE_WRITE;
1277 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1278 if ((NULL != connection->nth.notify_ready) &&
1279 (connection->write_buffer_size < connection->nth.notify_size))
1281 connection->write_buffer =
1282 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1283 connection->write_buffer_size = connection->nth.notify_size;
1285 process_notify (connection);
1286 have = connection->write_buffer_off - connection->write_buffer_pos;
1289 /* no data ready for writing, terminate write loop */
1292 GNUNET_assert (have <= connection->write_buffer_size);
1293 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1294 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1297 GNUNET_NETWORK_socket_send (connection->sock,
1298 &connection->write_buffer[connection->write_buffer_pos],
1304 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1306 GNUNET_SCHEDULER_cancel (connection->write_task);
1307 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1309 signal_transmit_error (connection, errno);
1312 LOG (GNUNET_ERROR_TYPE_DEBUG,
1313 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1314 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1315 connection->write_buffer_pos += ret;
1316 if (connection->write_buffer_pos == connection->write_buffer_off)
1318 /* transmitted all pending data */
1319 connection->write_buffer_pos = 0;
1320 connection->write_buffer_off = 0;
1322 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1323 return; /* all data sent! */
1324 /* not done writing, schedule more */
1326 LOG (GNUNET_ERROR_TYPE_DEBUG,
1327 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1328 have = connection->write_buffer_off - connection->write_buffer_pos;
1329 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1330 if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1331 connection->write_task =
1332 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1333 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1334 GNUNET_TIME_absolute_get_remaining
1335 (connection->nth.transmit_timeout),
1336 connection->sock, &transmit_ready, connection);
1341 * Ask the connection to call us once the specified number of bytes
1342 * are free in the transmission buffer. May call the notify
1343 * method immediately if enough space is available.
1345 * @param connection connection
1346 * @param size number of bytes to send
1347 * @param timeout after how long should we give up (and call
1348 * notify with buf NULL and size 0)?
1349 * @param notify function to call
1350 * @param notify_cls closure for notify
1351 * @return non-NULL if the notify callback was queued,
1352 * NULL if we are already going to notify someone else (busy)
1354 struct GNUNET_CONNECTION_TransmitHandle *
1355 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1357 struct GNUNET_TIME_Relative timeout,
1358 GNUNET_CONNECTION_TransmitReadyNotify
1359 notify, void *notify_cls)
1361 if (NULL != connection->nth.notify_ready)
1366 GNUNET_assert (NULL != notify);
1367 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1368 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1369 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1370 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1371 connection->nth.notify_ready = notify;
1372 connection->nth.notify_ready_cls = notify_cls;
1373 connection->nth.connection = connection;
1374 connection->nth.notify_size = size;
1375 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1376 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1377 if ((NULL == connection->sock) &&
1378 (NULL == connection->ap_head) &&
1379 (NULL == connection->dns_active))
1381 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1382 GNUNET_SCHEDULER_cancel (connection->write_task);
1383 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1384 return &connection->nth;
1386 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1387 return &connection->nth; /* previous transmission still in progress */
1388 if (NULL != connection->sock)
1390 /* connected, try to transmit now */
1391 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1392 connection->write_task =
1393 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1394 (connection->nth.transmit_timeout),
1395 connection->sock, &transmit_ready, connection);
1396 return &connection->nth;
1398 /* not yet connected, wait for connection */
1399 LOG (GNUNET_ERROR_TYPE_DEBUG,
1400 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1401 connection->nth.timeout_task =
1402 GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1403 return &connection->nth;
1408 * Cancel the specified transmission-ready notification.
1410 * @param th notification to cancel
1413 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1414 GNUNET_CONNECTION_TransmitHandle
1417 GNUNET_assert (NULL != th->notify_ready);
1418 th->notify_ready = NULL;
1419 if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1421 GNUNET_SCHEDULER_cancel (th->timeout_task);
1422 th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1424 if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1426 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1427 th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1431 /* end of connection.c */