2 This file is part of GNUnet.
3 Copyright (C) 2009-2013 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 3, 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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, 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.
34 #include "gnunet_util_lib.h"
35 #include "gnunet_resolver_service.h"
38 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
40 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
44 * Transmission handle. There can only be one for each connection.
46 struct GNUNET_CONNECTION_TransmitHandle
50 * Function to call if the send buffer has notify_size
53 GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
56 * Closure for notify_ready.
58 void *notify_ready_cls;
61 * Our connection handle.
63 struct GNUNET_CONNECTION_Handle *connection;
66 * Timeout for receiving (in absolute time).
68 struct GNUNET_TIME_Absolute transmit_timeout;
71 * Task called on timeout.
73 struct GNUNET_SCHEDULER_Task * timeout_task;
76 * At what number of bytes available in the
77 * write buffer should the notify method be called?
85 * During connect, we try multiple possible IP addresses
86 * to find out which one might work.
92 * This is a linked list.
94 struct AddressProbe *next;
97 * This is a doubly-linked list.
99 struct AddressProbe *prev;
102 * The address; do not free (allocated at the end of this struct).
104 const struct sockaddr *addr;
107 * Underlying OS's socket.
109 struct GNUNET_NETWORK_Handle *sock;
112 * Connection for which we are probing.
114 struct GNUNET_CONNECTION_Handle *connection;
122 * Task waiting for the connection to finish connecting.
124 struct GNUNET_SCHEDULER_Task * task;
129 * @brief handle for a network connection
131 struct GNUNET_CONNECTION_Handle
135 * Configuration to use.
137 const struct GNUNET_CONFIGURATION_Handle *cfg;
140 * Linked list of sockets we are currently trying out
143 struct AddressProbe *ap_head;
146 * Linked list of sockets we are currently trying out
149 struct AddressProbe *ap_tail;
152 * Network address of the other end-point, may be NULL.
154 struct sockaddr *addr;
157 * Pointer to the hostname if connection was
158 * created using DNS lookup, otherwise NULL.
163 * Underlying OS's socket, set to NULL after fatal errors.
165 struct GNUNET_NETWORK_Handle *sock;
168 * Function to call on data received, NULL if no receive is pending.
170 GNUNET_CONNECTION_Receiver receiver;
173 * Closure for @e receiver.
178 * Pointer to our write buffer.
183 * Current size of our @e write_buffer.
185 size_t write_buffer_size;
188 * Current write-offset in @e write_buffer (where
189 * would we write next).
191 size_t write_buffer_off;
194 * Current read-offset in @e write_buffer (how many
195 * bytes have already been sent).
197 size_t write_buffer_pos;
205 * Read task that we may need to wait for.
207 struct GNUNET_SCHEDULER_Task *read_task;
210 * Write task that we may need to wait for.
212 struct GNUNET_SCHEDULER_Task *write_task;
215 * Handle to a pending DNS lookup request.
217 struct GNUNET_RESOLVER_RequestHandle *dns_active;
220 * The handle we return for GNUNET_CONNECTION_notify_transmit_ready.
222 struct GNUNET_CONNECTION_TransmitHandle nth;
225 * Timeout for receiving (in absolute time).
227 struct GNUNET_TIME_Absolute receive_timeout;
230 * Maximum number of bytes to read (for receiving).
235 * Port to connect to.
240 * When shutdown, do not ever actually close the socket, but
241 * free resources. Only should ever be set if using program
242 * termination as a signal (because only then will the leaked
248 * Usually 0. Set to 1 if this handle is in use, and should
249 * #GNUNET_CONNECTION_destroy() be called right now, the action needs
250 * to be deferred by setting it to -1.
252 int8_t destroy_later;
255 * Handle to subsequent connection after proxy handshake completes,
257 struct GNUNET_CONNECTION_Handle *proxy_handshake;
263 * Set the persist option on this connection handle. Indicates
264 * that the underlying socket or fd should never really be closed.
265 * Used for indicating process death.
267 * @param connection the connection to set persistent
270 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
272 connection->persist = GNUNET_YES;
277 * Disable the "CORK" feature for communication with the given connection,
278 * forcing the OS to immediately flush the buffer on transmission
279 * instead of potentially buffering multiple messages. Essentially
280 * reduces the OS send buffers to zero.
281 * Used to make sure that the last messages sent through the connection
282 * reach the other side before the process is terminated.
284 * @param connection the connection to make flushing and blocking
285 * @return #GNUNET_OK on success
288 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
290 return GNUNET_NETWORK_socket_disable_corking (connection->sock);
295 * Create a connection handle by boxing an existing OS socket. The OS
296 * socket should henceforth be no longer used directly.
297 * #GNUNET_connection_destroy() will close it.
299 * @param osSocket existing socket to box
300 * @return the boxed connection handle
302 struct GNUNET_CONNECTION_Handle *
303 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
305 struct GNUNET_CONNECTION_Handle *connection;
307 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
308 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
309 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
310 connection->sock = osSocket;
316 * Create a connection handle by accepting on a listen socket. This
317 * function may block if the listen socket has no connection ready.
319 * @param access_cb function to use to check if access is allowed
320 * @param access_cb_cls closure for @a access_cb
321 * @param lsock listen socket
322 * @return the connection handle, NULL on error
324 struct GNUNET_CONNECTION_Handle *
325 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access_cb,
327 struct GNUNET_NETWORK_Handle *lsock)
329 struct GNUNET_CONNECTION_Handle *connection;
332 struct GNUNET_NETWORK_Handle *sock;
334 struct sockaddr_in *v4;
335 struct sockaddr_in6 *v6;
338 struct GNUNET_CONNECTION_Credentials *gcp;
339 struct GNUNET_CONNECTION_Credentials gc;
345 addrlen = sizeof (addr);
347 GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
351 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
354 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
357 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
361 sa = (struct sockaddr *) addr;
362 v6 = (struct sockaddr_in6 *) addr;
363 if ((AF_INET6 == sa->sa_family) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
365 /* convert to V4 address */
366 v4 = GNUNET_new (struct sockaddr_in);
367 memset (v4, 0, sizeof (struct sockaddr_in));
368 v4->sin_family = AF_INET;
369 #if HAVE_SOCKADDR_IN_SIN_LEN
370 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
372 memcpy (&v4->sin_addr,
373 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
374 sizeof (struct in_addr)],
375 sizeof (struct in_addr));
376 v4->sin_port = v6->sin6_port;
378 addrlen = sizeof (struct sockaddr_in);
382 uaddr = GNUNET_malloc (addrlen);
383 memcpy (uaddr, addr, addrlen);
388 if (AF_UNIX == sa->sa_family)
392 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock), &gc.uid, &gc.gid))
396 /* largely traditional GNU/Linux */
399 getsockopt (GNUNET_NETWORK_get_fd (sock), SOL_SOCKET, SO_PEERCRED, &uc,
400 &olen)) && (olen == sizeof (uc)))
407 #if HAVE_GETPEERUCRED
408 /* this is for Solaris 10 */
412 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
414 gc.uid = ucred_geteuid (uc);
415 gc.gid = ucred_getegid (uc);
424 if ((NULL != access_cb) &&
425 (GNUNET_YES != (aret = access_cb (access_cb_cls, gcp, uaddr, addrlen))))
427 if (GNUNET_NO == aret)
428 LOG (GNUNET_ERROR_TYPE_INFO,
429 _("Access denied to `%s'\n"),
432 GNUNET_break (GNUNET_OK ==
433 GNUNET_NETWORK_socket_shutdown (sock,
435 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
439 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
440 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
441 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
442 connection->addr = uaddr;
443 connection->addrlen = addrlen;
444 connection->sock = sock;
445 LOG (GNUNET_ERROR_TYPE_INFO,
446 _("Accepting connection from `%s': %p\n"),
447 GNUNET_a2s (uaddr, addrlen), connection);
453 * Obtain the network address of the other party.
455 * @param connection the client to get the address for
456 * @param addr where to store the address
457 * @param addrlen where to store the length of the @a addr
458 * @return #GNUNET_OK on success
461 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
465 if ((NULL == connection->addr) || (0 == connection->addrlen))
467 *addr = GNUNET_malloc (connection->addrlen);
468 memcpy (*addr, connection->addr, connection->addrlen);
469 *addrlen = connection->addrlen;
475 * Tell the receiver callback that we had an IO error.
477 * @param connection connection to signal error
478 * @param errcode error code to send
481 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection,
484 GNUNET_CONNECTION_Receiver receiver;
486 LOG (GNUNET_ERROR_TYPE_DEBUG,
487 "Receive encounters error (%s), connection closed (%p)\n",
490 GNUNET_assert (NULL != (receiver = connection->receiver));
491 connection->receiver = NULL;
492 receiver (connection->receiver_cls,
502 * Tell the receiver callback that a timeout was reached.
504 * @param connection connection to signal for
507 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
509 GNUNET_CONNECTION_Receiver receiver;
511 LOG (GNUNET_ERROR_TYPE_DEBUG,
512 "Connection signals timeout to receiver (%p)!\n",
514 GNUNET_assert (NULL != (receiver = connection->receiver));
515 connection->receiver = NULL;
516 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
521 * We failed to transmit data to the service, signal the error.
523 * @param connection handle that had trouble
524 * @param ecode error code (errno)
527 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
530 GNUNET_CONNECTION_TransmitReadyNotify notify;
532 LOG (GNUNET_ERROR_TYPE_DEBUG,
533 "Transmission encounterd error (%s), connection closed (%p)\n",
536 if (NULL != connection->sock)
538 (void) GNUNET_NETWORK_socket_shutdown (connection->sock,
540 GNUNET_break (GNUNET_OK ==
541 GNUNET_NETWORK_socket_close (connection->sock));
542 connection->sock = NULL;
543 GNUNET_assert (NULL == connection->write_task);
545 if (NULL != connection->read_task)
547 /* send errors trigger read errors... */
548 GNUNET_SCHEDULER_cancel (connection->read_task);
549 connection->read_task = NULL;
550 signal_receive_timeout (connection);
553 if (NULL == connection->nth.notify_ready)
554 return; /* nobody to tell about it */
555 notify = connection->nth.notify_ready;
556 connection->nth.notify_ready = NULL;
557 notify (connection->nth.notify_ready_cls, 0, NULL);
562 * We've failed for good to establish a connection (timeout or
563 * no more addresses to try).
565 * @param connection the connection we tried to establish
568 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
570 LOG (GNUNET_ERROR_TYPE_INFO,
571 "Failed to establish TCP connection to `%s:%u', no further addresses to try.\n",
572 connection->hostname,
574 GNUNET_break (NULL == connection->ap_head);
575 GNUNET_break (NULL == connection->ap_tail);
576 GNUNET_break (GNUNET_NO == connection->dns_active);
577 GNUNET_break (NULL == connection->sock);
578 GNUNET_assert (NULL == connection->write_task);
579 GNUNET_assert (NULL == connection->proxy_handshake);
581 /* signal errors for jobs that used to wait on the connection */
582 connection->destroy_later = 1;
583 if (NULL != connection->receiver)
584 signal_receive_error (connection,
586 if (NULL != connection->nth.notify_ready)
588 GNUNET_assert (NULL != connection->nth.timeout_task);
589 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
590 connection->nth.timeout_task = NULL;
591 signal_transmit_error (connection,
594 if (-1 == connection->destroy_later)
597 connection->destroy_later = 0;
598 GNUNET_CONNECTION_destroy (connection);
601 connection->destroy_later = 0;
606 * We are ready to transmit (or got a timeout).
608 * @param cls our connection handle
609 * @param tc task context describing why we are here
612 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
616 * This function is called once we either timeout or have data ready
619 * @param cls connection to read from
620 * @param tc scheduler context
623 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
627 * We've succeeded in establishing a connection.
629 * @param connection the connection we tried to establish
632 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
634 LOG (GNUNET_ERROR_TYPE_DEBUG,
635 "Connection to `%s' succeeded! (%p)\n",
636 GNUNET_a2s (connection->addr, connection->addrlen),
638 /* trigger jobs that waited for the connection */
639 if (NULL != connection->receiver)
641 LOG (GNUNET_ERROR_TYPE_DEBUG,
642 "Connection succeeded, starting with receiving data (%p)\n",
644 GNUNET_assert (NULL == connection->read_task);
645 connection->read_task =
646 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
647 (connection->receive_timeout), connection->sock,
648 &receive_ready, connection);
650 if (NULL != connection->nth.notify_ready)
652 LOG (GNUNET_ERROR_TYPE_DEBUG,
653 "Connection succeeded, starting with sending data (%p)\n",
655 GNUNET_assert (connection->nth.timeout_task != NULL);
656 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
657 connection->nth.timeout_task = NULL;
658 GNUNET_assert (connection->write_task == NULL);
659 connection->write_task =
660 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
661 (connection->nth.transmit_timeout), connection->sock,
662 &transmit_ready, connection);
668 * Scheduler let us know that we're either ready to write on the
669 * socket OR connect timed out. Do the right thing.
671 * @param cls the "struct AddressProbe*" with the address that we are probing
672 * @param tc success or failure info about the connect attempt.
675 connect_probe_continuation (void *cls,
676 const struct GNUNET_SCHEDULER_TaskContext *tc)
678 struct AddressProbe *ap = cls;
679 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
680 struct AddressProbe *pos;
684 GNUNET_assert (NULL != ap->sock);
685 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
686 len = sizeof (error);
689 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
691 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
692 &len)) || (0 != error))
694 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
696 if ((NULL == connection->ap_head) &&
697 (GNUNET_NO == connection->dns_active) &&
698 (NULL == connection->proxy_handshake))
699 connect_fail_continuation (connection);
702 GNUNET_assert (NULL == connection->sock);
703 connection->sock = ap->sock;
704 GNUNET_assert (NULL == connection->addr);
705 connection->addr = GNUNET_malloc (ap->addrlen);
706 memcpy (connection->addr, ap->addr, ap->addrlen);
707 connection->addrlen = ap->addrlen;
709 /* cancel all other attempts */
710 while (NULL != (pos = connection->ap_head))
712 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
713 GNUNET_SCHEDULER_cancel (pos->task);
714 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
717 connect_success_continuation (connection);
722 * Try to establish a connection given the specified address.
723 * This function is called by the resolver once we have a DNS reply.
725 * @param cls our `struct GNUNET_CONNECTION_Handle *`
726 * @param addr address to try, NULL for "last call"
727 * @param addrlen length of @a addr
730 try_connect_using_address (void *cls,
731 const struct sockaddr *addr,
734 struct GNUNET_CONNECTION_Handle *connection = cls;
735 struct AddressProbe *ap;
736 struct GNUNET_TIME_Relative delay;
740 connection->dns_active = NULL;
741 if ((NULL == connection->ap_head) &&
742 (NULL == connection->sock) &&
743 (NULL == connection->proxy_handshake))
744 connect_fail_continuation (connection);
747 if (NULL != connection->sock)
748 return; /* already connected */
749 GNUNET_assert (NULL == connection->addr);
751 LOG (GNUNET_ERROR_TYPE_DEBUG,
752 "Trying to connect using address `%s:%u/%s:%u'\n",
753 connection->hostname,
755 GNUNET_a2s (addr, addrlen),
757 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
758 ap->addr = (const struct sockaddr *) &ap[1];
759 memcpy (&ap[1], addr, addrlen);
760 ap->addrlen = addrlen;
761 ap->connection = connection;
763 switch (ap->addr->sa_family)
766 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
769 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
774 return; /* not supported by us */
776 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
777 if (NULL == ap->sock)
780 return; /* not supported by OS */
782 LOG (GNUNET_ERROR_TYPE_INFO,
783 "Trying to connect to `%s' (%p)\n",
784 GNUNET_a2s (ap->addr, ap->addrlen),
787 GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
788 (EINPROGRESS != errno))
790 /* maybe refused / unsupported address, try next */
791 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
792 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
796 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
797 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
798 if (NULL != connection->nth.notify_ready)
800 GNUNET_TIME_relative_min (delay,
801 GNUNET_TIME_absolute_get_remaining (connection->nth.transmit_timeout));
802 if (NULL != connection->receiver)
804 GNUNET_TIME_relative_min (delay,
805 GNUNET_TIME_absolute_get_remaining
806 (connection->receive_timeout));
808 GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
809 &connect_probe_continuation, ap);
814 * Create a connection handle by (asynchronously) connecting to a host.
815 * This function returns immediately, even if the connection has not
816 * yet been established. This function only creates TCP connections.
818 * @param cfg configuration to use
819 * @param hostname name of the host to connect to
820 * @param port port to connect to
821 * @return the connection handle
823 struct GNUNET_CONNECTION_Handle *
824 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
825 const char *hostname,
828 struct GNUNET_CONNECTION_Handle *connection;
830 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
831 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
832 connection->cfg = cfg;
833 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
834 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
835 connection->port = port;
836 connection->hostname = GNUNET_strdup (hostname);
837 connection->dns_active =
838 GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
839 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
840 &try_connect_using_address, connection);
846 * Create a connection handle by connecting to a UNIX domain service.
847 * This function returns immediately, even if the connection has not
848 * yet been established. This function only creates UNIX connections.
850 * @param cfg configuration to use
851 * @param unixpath path to connect to
852 * @return the connection handle, NULL on systems without UNIX support
854 struct GNUNET_CONNECTION_Handle *
855 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct GNUNET_CONFIGURATION_Handle *cfg,
856 const char *unixpath)
859 struct GNUNET_CONNECTION_Handle *connection;
860 struct sockaddr_un *un;
862 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
863 un = GNUNET_new (struct sockaddr_un);
864 un->sun_family = AF_UNIX;
865 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
870 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg, "TESTING",
871 "USE_ABSTRACT_SOCKETS");
872 if (GNUNET_YES == abstract)
873 un->sun_path[0] = '\0';
876 #if HAVE_SOCKADDR_IN_SIN_LEN
877 un->sun_len = (u_char) sizeof (struct sockaddr_un);
879 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
880 connection->cfg = cfg;
881 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
882 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
883 connection->port = 0;
884 connection->hostname = NULL;
885 connection->addr = (struct sockaddr *) un;
886 connection->addrlen = sizeof (struct sockaddr_un);
887 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
888 if (NULL == connection->sock)
890 GNUNET_free (connection->addr);
891 GNUNET_free (connection->write_buffer);
892 GNUNET_free (connection);
896 GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
897 (EINPROGRESS != errno) )
899 /* Just return; we expect everything to work eventually so don't fail HARD */
900 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
901 connection->sock = NULL;
904 connect_success_continuation (connection);
913 * Create a connection handle by (asynchronously) connecting to a host.
914 * This function returns immediately, even if the connection has not
915 * yet been established. This function only creates TCP connections.
917 * @param s socket to connect
918 * @param serv_addr server address
919 * @param addrlen length of @a serv_addr
920 * @return the connection handle
922 struct GNUNET_CONNECTION_Handle *
923 GNUNET_CONNECTION_connect_socket (struct GNUNET_NETWORK_Handle *s,
924 const struct sockaddr *serv_addr,
927 struct GNUNET_CONNECTION_Handle *connection;
930 GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
931 (EINPROGRESS != errno) )
933 /* maybe refused / unsupported address, try next */
934 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
936 LOG (GNUNET_ERROR_TYPE_DEBUG,
937 "Attempt to connect to `%s' failed\n",
938 GNUNET_a2s (serv_addr,
940 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
943 connection = GNUNET_CONNECTION_create_from_existing (s);
944 connection->addr = GNUNET_malloc (addrlen);
945 memcpy (connection->addr, serv_addr, addrlen);
946 connection->addrlen = addrlen;
947 LOG (GNUNET_ERROR_TYPE_INFO,
948 "Trying to connect to `%s' (%p)\n",
949 GNUNET_a2s (serv_addr, addrlen),
956 * Create a connection handle by creating a socket and
957 * (asynchronously) connecting to a host. This function returns
958 * immediately, even if the connection has not yet been established.
959 * This function only creates TCP connections.
961 * @param af_family address family to use
962 * @param serv_addr server address
963 * @param addrlen length of @a serv_addr
964 * @return the connection handle
966 struct GNUNET_CONNECTION_Handle *
967 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
968 const struct sockaddr *serv_addr,
971 struct GNUNET_NETWORK_Handle *s;
973 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
976 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
979 return GNUNET_CONNECTION_connect_socket (s, serv_addr, addrlen);
984 * Check if connection is valid (no fatal errors have happened so far).
985 * Note that a connection that is still trying to connect is considered
988 * @param connection connection to check
989 * @return #GNUNET_YES if valid, #GNUNET_NO otherwise
992 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
994 if ((NULL != connection->ap_head) ||
995 (NULL != connection->dns_active) ||
996 (NULL != connection->proxy_handshake))
997 return GNUNET_YES; /* still trying to connect */
998 if ( (0 != connection->destroy_later) ||
999 (NULL == connection->sock) )
1006 * Close the connection and free associated resources. There must
1007 * not be any pending requests for reading or writing to the
1008 * connection at this time.
1010 * @param connection connection to destroy
1013 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
1015 struct AddressProbe *pos;
1017 if (0 != connection->destroy_later)
1019 connection->destroy_later = -1;
1022 LOG (GNUNET_ERROR_TYPE_DEBUG,
1023 "Shutting down connection (%p)\n",
1025 GNUNET_assert (NULL == connection->nth.notify_ready);
1026 GNUNET_assert (NULL == connection->receiver);
1027 if (NULL != connection->write_task)
1029 GNUNET_SCHEDULER_cancel (connection->write_task);
1030 connection->write_task = NULL;
1031 connection->write_buffer_off = 0;
1033 if (NULL != connection->read_task)
1035 GNUNET_SCHEDULER_cancel (connection->read_task);
1036 connection->read_task = NULL;
1038 if (NULL != connection->nth.timeout_task)
1040 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1041 connection->nth.timeout_task = NULL;
1043 connection->nth.notify_ready = NULL;
1044 if (NULL != connection->dns_active)
1046 GNUNET_RESOLVER_request_cancel (connection->dns_active);
1047 connection->dns_active = NULL;
1049 if (NULL != connection->proxy_handshake)
1051 /* GNUNET_CONNECTION_destroy (connection->proxy_handshake); */
1052 connection->proxy_handshake->destroy_later = -1;
1053 connection->proxy_handshake = NULL; /* Not leaked ??? */
1055 while (NULL != (pos = connection->ap_head))
1057 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1058 GNUNET_SCHEDULER_cancel (pos->task);
1059 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
1062 if ( (NULL != connection->sock) &&
1063 (GNUNET_YES != connection->persist) )
1066 GNUNET_NETWORK_socket_shutdown (connection->sock,
1068 (ENOTCONN != errno) &&
1069 (ECONNRESET != errno) )
1070 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1073 if (NULL != connection->sock)
1075 if (GNUNET_YES != connection->persist)
1077 GNUNET_break (GNUNET_OK ==
1078 GNUNET_NETWORK_socket_close (connection->sock));
1082 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1083 * leak the socket in this special case) ... */
1086 GNUNET_free_non_null (connection->addr);
1087 GNUNET_free_non_null (connection->hostname);
1088 GNUNET_free (connection->write_buffer);
1089 GNUNET_free (connection);
1094 * This function is called once we either timeout
1095 * or have data ready to read.
1097 * @param cls connection to read from
1098 * @param tc scheduler context
1101 receive_ready (void *cls,
1102 const struct GNUNET_SCHEDULER_TaskContext *tc)
1104 struct GNUNET_CONNECTION_Handle *connection = cls;
1105 char buffer[connection->max];
1107 GNUNET_CONNECTION_Receiver receiver;
1109 connection->read_task = NULL;
1110 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1112 /* ignore shutdown request, go again immediately */
1113 connection->read_task =
1114 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1115 (connection->receive_timeout), connection->sock,
1116 &receive_ready, connection);
1119 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1121 LOG (GNUNET_ERROR_TYPE_DEBUG,
1122 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1123 GNUNET_a2s (connection->addr, connection->addrlen),
1124 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1126 signal_receive_timeout (connection);
1129 if (NULL == connection->sock)
1131 /* connect failed for good */
1132 signal_receive_error (connection, ECONNREFUSED);
1135 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1137 ret = GNUNET_NETWORK_socket_recv (connection->sock,
1144 signal_receive_error (connection, errno);
1147 LOG (GNUNET_ERROR_TYPE_DEBUG,
1148 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1151 GNUNET_a2s (connection->addr,
1152 connection->addrlen),
1154 GNUNET_assert (NULL != (receiver = connection->receiver));
1155 connection->receiver = NULL;
1156 receiver (connection->receiver_cls,
1160 connection->addrlen,
1166 * Receive data from the given connection. Note that this function will
1167 * call @a receiver asynchronously using the scheduler. It will
1168 * "immediately" return. Note that there MUST only be one active
1169 * receive call per connection at any given point in time (so do not
1170 * call receive again until the receiver callback has been invoked).
1172 * @param connection connection handle
1173 * @param max maximum number of bytes to read
1174 * @param timeout maximum amount of time to wait
1175 * @param receiver function to call with received data
1176 * @param receiver_cls closure for @a receiver
1179 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection,
1181 struct GNUNET_TIME_Relative timeout,
1182 GNUNET_CONNECTION_Receiver receiver,
1185 GNUNET_assert ((NULL == connection->read_task) &&
1186 (NULL == connection->receiver));
1187 GNUNET_assert (NULL != receiver);
1188 connection->receiver = receiver;
1189 connection->receiver_cls = receiver_cls;
1190 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1191 connection->max = max;
1192 if (NULL != connection->sock)
1194 connection->read_task =
1195 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1196 (connection->receive_timeout),
1202 if ((NULL == connection->dns_active) &&
1203 (NULL == connection->ap_head) &&
1204 (NULL == connection->proxy_handshake))
1206 connection->receiver = NULL;
1207 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1214 * Cancel receive job on the given connection. Note that the
1215 * receiver callback must not have been called yet in order
1216 * for the cancellation to be valid.
1218 * @param connection connection handle
1219 * @return closure of the original receiver callback closure
1222 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1224 if (NULL != connection->read_task)
1226 GNUNET_assert (connection ==
1227 GNUNET_SCHEDULER_cancel (connection->read_task));
1228 connection->read_task = NULL;
1230 connection->receiver = NULL;
1231 return connection->receiver_cls;
1236 * Try to call the transmit notify method (check if we do
1237 * have enough space available first)!
1239 * @param connection connection for which we should do this processing
1240 * @return #GNUNET_YES if we were able to call notify
1243 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1248 GNUNET_CONNECTION_TransmitReadyNotify notify;
1250 LOG (GNUNET_ERROR_TYPE_DEBUG,
1251 "process_notify is running\n");
1252 GNUNET_assert (NULL == connection->write_task);
1253 if (NULL == (notify = connection->nth.notify_ready))
1255 LOG (GNUNET_ERROR_TYPE_DEBUG,
1256 "No one to notify\n");
1259 used = connection->write_buffer_off - connection->write_buffer_pos;
1260 avail = connection->write_buffer_size - used;
1261 size = connection->nth.notify_size;
1264 LOG (GNUNET_ERROR_TYPE_DEBUG,
1265 "Not enough buffer\n");
1268 connection->nth.notify_ready = NULL;
1269 if (connection->write_buffer_size - connection->write_buffer_off < size)
1271 /* need to compact */
1272 memmove (connection->write_buffer,
1273 &connection->write_buffer[connection->write_buffer_pos],
1275 connection->write_buffer_off -= connection->write_buffer_pos;
1276 connection->write_buffer_pos = 0;
1278 avail = connection->write_buffer_size - connection->write_buffer_off;
1279 GNUNET_assert (avail >= size);
1281 notify (connection->nth.notify_ready_cls, avail,
1282 &connection->write_buffer[connection->write_buffer_off]);
1283 GNUNET_assert (size <= avail);
1285 connection->write_buffer_off += size;
1291 * Task invoked by the scheduler when a call to transmit
1292 * is timing out (we never got enough buffer space to call
1293 * the callback function before the specified timeout
1296 * This task notifies the client about the timeout.
1298 * @param cls the `struct GNUNET_CONNECTION_Handle`
1299 * @param tc scheduler context
1302 transmit_timeout (void *cls,
1303 const struct GNUNET_SCHEDULER_TaskContext *tc)
1305 struct GNUNET_CONNECTION_Handle *connection = cls;
1306 GNUNET_CONNECTION_TransmitReadyNotify notify;
1308 connection->nth.timeout_task = NULL;
1309 LOG (GNUNET_ERROR_TYPE_DEBUG,
1310 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1311 connection->hostname,
1313 GNUNET_a2s (connection->addr,
1314 connection->addrlen),
1316 notify = connection->nth.notify_ready;
1317 GNUNET_assert (NULL != notify);
1318 connection->nth.notify_ready = NULL;
1319 notify (connection->nth.notify_ready_cls, 0, NULL);
1324 * Task invoked by the scheduler when we failed to connect
1325 * at the time of being asked to transmit.
1327 * This task notifies the client about the error.
1329 * @param cls the `struct GNUNET_CONNECTION_Handle`
1330 * @param tc scheduler context
1333 connect_error (void *cls,
1334 const struct GNUNET_SCHEDULER_TaskContext *tc)
1336 struct GNUNET_CONNECTION_Handle *connection = cls;
1337 GNUNET_CONNECTION_TransmitReadyNotify notify;
1339 LOG (GNUNET_ERROR_TYPE_DEBUG,
1340 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1341 connection->nth.notify_size,
1342 connection->hostname,
1345 connection->write_task = NULL;
1346 notify = connection->nth.notify_ready;
1347 connection->nth.notify_ready = NULL;
1348 notify (connection->nth.notify_ready_cls, 0, NULL);
1353 * We are ready to transmit (or got a timeout).
1355 * @param cls our connection handle
1356 * @param tc task context describing why we are here
1359 transmit_ready (void *cls,
1360 const struct GNUNET_SCHEDULER_TaskContext *tc)
1362 struct GNUNET_CONNECTION_Handle *connection = cls;
1363 GNUNET_CONNECTION_TransmitReadyNotify notify;
1367 LOG (GNUNET_ERROR_TYPE_DEBUG,
1368 "transmit_ready running (%p).\n",
1370 GNUNET_assert (NULL != connection->write_task);
1371 connection->write_task = NULL;
1372 GNUNET_assert (NULL == connection->nth.timeout_task);
1373 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1375 if (NULL != connection->sock)
1376 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1377 LOG (GNUNET_ERROR_TYPE_DEBUG,
1378 "Transmit to `%s' fails, shutdown happened (%p).\n",
1379 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1380 notify = connection->nth.notify_ready;
1383 connection->nth.notify_ready = NULL;
1384 notify (connection->nth.notify_ready_cls, 0, NULL);
1388 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1390 LOG (GNUNET_ERROR_TYPE_DEBUG,
1391 "Transmit to `%s' fails, time out reached (%p).\n",
1392 GNUNET_a2s (connection->addr,
1393 connection->addrlen),
1395 notify = connection->nth.notify_ready;
1396 GNUNET_assert (NULL != notify);
1397 connection->nth.notify_ready = NULL;
1398 notify (connection->nth.notify_ready_cls, 0, NULL);
1401 GNUNET_assert (NULL != connection->sock);
1402 if (NULL == tc->write_ready)
1404 /* special circumstances (in particular, PREREQ_DONE after
1405 * connect): not yet ready to write, but no "fatal" error either.
1407 goto SCHEDULE_WRITE;
1409 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1411 GNUNET_assert (NULL == connection->write_task);
1412 /* special circumstances (in particular, shutdown): not yet ready
1413 * to write, but no "fatal" error either. Hence retry. */
1414 goto SCHEDULE_WRITE;
1416 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1417 if ((NULL != connection->nth.notify_ready) &&
1418 (connection->write_buffer_size < connection->nth.notify_size))
1420 connection->write_buffer =
1421 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1422 connection->write_buffer_size = connection->nth.notify_size;
1424 process_notify (connection);
1425 have = connection->write_buffer_off - connection->write_buffer_pos;
1428 /* no data ready for writing, terminate write loop */
1431 GNUNET_assert (have <= connection->write_buffer_size);
1432 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1433 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1436 GNUNET_NETWORK_socket_send (connection->sock,
1437 &connection->write_buffer[connection->write_buffer_pos],
1443 if (NULL != connection->write_task)
1445 GNUNET_SCHEDULER_cancel (connection->write_task);
1446 connection->write_task = NULL;
1448 signal_transmit_error (connection, errno);
1451 LOG (GNUNET_ERROR_TYPE_DEBUG,
1452 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1453 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1454 connection->write_buffer_pos += ret;
1455 if (connection->write_buffer_pos == connection->write_buffer_off)
1457 /* transmitted all pending data */
1458 connection->write_buffer_pos = 0;
1459 connection->write_buffer_off = 0;
1461 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1462 return; /* all data sent! */
1463 /* not done writing, schedule more */
1465 LOG (GNUNET_ERROR_TYPE_DEBUG,
1466 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1467 have = connection->write_buffer_off - connection->write_buffer_pos;
1468 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1469 if (NULL == connection->write_task)
1470 connection->write_task =
1471 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1472 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1473 GNUNET_TIME_absolute_get_remaining
1474 (connection->nth.transmit_timeout),
1475 connection->sock, &transmit_ready, connection);
1480 * Ask the connection to call us once the specified number of bytes
1481 * are free in the transmission buffer. Will never call the @a notify
1482 * callback in this task, but always first go into the scheduler.
1484 * @param connection connection
1485 * @param size number of bytes to send
1486 * @param timeout after how long should we give up (and call
1487 * @a notify with buf NULL and size 0)?
1488 * @param notify function to call
1489 * @param notify_cls closure for @a notify
1490 * @return non-NULL if the notify callback was queued,
1491 * NULL if we are already going to notify someone else (busy)
1493 struct GNUNET_CONNECTION_TransmitHandle *
1494 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1496 struct GNUNET_TIME_Relative timeout,
1497 GNUNET_CONNECTION_TransmitReadyNotify
1498 notify, void *notify_cls)
1500 if (NULL != connection->nth.notify_ready)
1505 GNUNET_assert (NULL != notify);
1506 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1507 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1508 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1509 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1510 connection->nth.notify_ready = notify;
1511 connection->nth.notify_ready_cls = notify_cls;
1512 connection->nth.connection = connection;
1513 connection->nth.notify_size = size;
1514 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1515 GNUNET_assert (NULL == connection->nth.timeout_task);
1516 if ((NULL == connection->sock) &&
1517 (NULL == connection->ap_head) &&
1518 (NULL == connection->dns_active) &&
1519 (NULL == connection->proxy_handshake))
1521 if (NULL != connection->write_task)
1522 GNUNET_SCHEDULER_cancel (connection->write_task);
1523 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error,
1525 return &connection->nth;
1527 if (NULL != connection->write_task)
1528 return &connection->nth; /* previous transmission still in progress */
1529 if (NULL != connection->sock)
1531 /* connected, try to transmit now */
1532 LOG (GNUNET_ERROR_TYPE_DEBUG,
1533 "Scheduling transmission (%p).\n",
1535 connection->write_task =
1536 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1537 (connection->nth.transmit_timeout),
1538 connection->sock, &transmit_ready, connection);
1539 return &connection->nth;
1541 /* not yet connected, wait for connection */
1542 LOG (GNUNET_ERROR_TYPE_DEBUG,
1543 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n",
1545 connection->nth.timeout_task =
1546 GNUNET_SCHEDULER_add_delayed (timeout,
1547 &transmit_timeout, connection);
1548 return &connection->nth;
1553 * Cancel the specified transmission-ready notification.
1555 * @param th notification to cancel
1558 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct GNUNET_CONNECTION_TransmitHandle *th)
1560 GNUNET_assert (NULL != th->notify_ready);
1561 th->notify_ready = NULL;
1562 if (NULL != th->timeout_task)
1564 GNUNET_SCHEDULER_cancel (th->timeout_task);
1565 th->timeout_task = NULL;
1567 if (NULL != th->connection->write_task)
1569 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1570 th->connection->write_task = NULL;
1576 * Create a connection to be proxied using a given connection.
1578 * @param cph connection to proxy server
1579 * @return connection to be proxied
1581 struct GNUNET_CONNECTION_Handle *
1582 GNUNET_CONNECTION_create_proxied_from_handshake (struct GNUNET_CONNECTION_Handle *cph)
1584 struct GNUNET_CONNECTION_Handle * proxied = GNUNET_CONNECTION_create_from_existing(NULL);
1585 proxied->proxy_handshake = cph;
1591 * Activate proxied connection and destroy initial proxy handshake connection.
1592 * There must not be any pending requests for reading or writing to the
1593 * proxy hadshake connection at this time.
1595 * @param proxied connection connection to proxy server
1598 GNUNET_CONNECTION_acivate_proxied (struct GNUNET_CONNECTION_Handle *proxied)
1600 struct GNUNET_CONNECTION_Handle *cph = proxied->proxy_handshake;
1601 GNUNET_assert (NULL != cph);
1602 GNUNET_assert (NULL == proxied->sock);
1603 GNUNET_assert (NULL != cph->sock);
1604 proxied->sock=cph->sock;
1606 GNUNET_CONNECTION_destroy (cph);
1607 connect_success_continuation (proxied);
1611 /* end of connection.c */