2 This file is part of GNUnet.
3 Copyright (C) 2009-2013 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your 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 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * @file util/connection.c
21 * @brief TCP connection management
22 * @author Christian Grothoff
24 * This code is rather complex. Only modify it if you
25 * 1) Have a NEW testcase showing that the new code
26 * is needed and correct
27 * 2) All EXISTING testcases pass with the new code
28 * These rules should apply in general, but for this
29 * module they are VERY, VERY important.
32 #include "gnunet_util_lib.h"
33 #include "gnunet_resolver_service.h"
37 * Timeout we use on TCP connect before trying another
38 * result from the DNS resolver. Actual value used
39 * is this value divided by the number of address families.
42 #define CONNECT_RETRY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
46 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-connection", syscall)
50 * Transmission handle. There can only be one for each connection.
52 struct GNUNET_CONNECTION_TransmitHandle
56 * Function to call if the send buffer has notify_size
59 GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
62 * Closure for notify_ready.
64 void *notify_ready_cls;
67 * Our connection handle.
69 struct GNUNET_CONNECTION_Handle *connection;
72 * Timeout for receiving (in absolute time).
74 struct GNUNET_TIME_Absolute transmit_timeout;
77 * Task called on timeout.
79 struct GNUNET_SCHEDULER_Task * timeout_task;
82 * At what number of bytes available in the
83 * write buffer should the notify method be called?
91 * During connect, we try multiple possible IP addresses
92 * to find out which one might work.
98 * This is a linked list.
100 struct AddressProbe *next;
103 * This is a doubly-linked list.
105 struct AddressProbe *prev;
108 * The address; do not free (allocated at the end of this struct).
110 const struct sockaddr *addr;
113 * Underlying OS's socket.
115 struct GNUNET_NETWORK_Handle *sock;
118 * Connection for which we are probing.
120 struct GNUNET_CONNECTION_Handle *connection;
128 * Task waiting for the connection to finish connecting.
130 struct GNUNET_SCHEDULER_Task * task;
135 * @brief handle for a network connection
137 struct GNUNET_CONNECTION_Handle
141 * Configuration to use.
143 const struct GNUNET_CONFIGURATION_Handle *cfg;
146 * Linked list of sockets we are currently trying out
149 struct AddressProbe *ap_head;
152 * Linked list of sockets we are currently trying out
155 struct AddressProbe *ap_tail;
158 * Network address of the other end-point, may be NULL.
160 struct sockaddr *addr;
163 * Pointer to the hostname if connection was
164 * created using DNS lookup, otherwise NULL.
169 * Underlying OS's socket, set to NULL after fatal errors.
171 struct GNUNET_NETWORK_Handle *sock;
174 * Function to call on data received, NULL if no receive is pending.
176 GNUNET_CONNECTION_Receiver receiver;
179 * Closure for @e receiver.
184 * Pointer to our write buffer.
189 * Current size of our @e write_buffer.
191 size_t write_buffer_size;
194 * Current write-offset in @e write_buffer (where
195 * would we write next).
197 size_t write_buffer_off;
200 * Current read-offset in @e write_buffer (how many
201 * bytes have already been sent).
203 size_t write_buffer_pos;
211 * Read task that we may need to wait for.
213 struct GNUNET_SCHEDULER_Task *read_task;
216 * Write task that we may need to wait for.
218 struct GNUNET_SCHEDULER_Task *write_task;
221 * Handle to a pending DNS lookup request.
223 struct GNUNET_RESOLVER_RequestHandle *dns_active;
226 * The handle we return for #GNUNET_CONNECTION_notify_transmit_ready().
228 struct GNUNET_CONNECTION_TransmitHandle nth;
231 * Timeout for receiving (in absolute time).
233 struct GNUNET_TIME_Absolute receive_timeout;
236 * Maximum number of bytes to read (for receiving).
241 * Port to connect to.
246 * When shutdown, do not ever actually close the socket, but
247 * free resources. Only should ever be set if using program
248 * termination as a signal (because only then will the leaked
254 * Usually 0. Set to 1 if this handle is in use, and should
255 * #GNUNET_CONNECTION_destroy() be called right now, the action needs
256 * to be deferred by setting it to -1.
258 int8_t destroy_later;
261 * Handle to subsequent connection after proxy handshake completes,
263 struct GNUNET_CONNECTION_Handle *proxy_handshake;
269 * Set the persist option on this connection handle. Indicates
270 * that the underlying socket or fd should never really be closed.
271 * Used for indicating process death.
273 * @param connection the connection to set persistent
276 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
278 connection->persist = GNUNET_YES;
283 * Disable the "CORK" feature for communication with the given connection,
284 * forcing the OS to immediately flush the buffer on transmission
285 * instead of potentially buffering multiple messages. Essentially
286 * reduces the OS send buffers to zero.
287 * Used to make sure that the last messages sent through the connection
288 * reach the other side before the process is terminated.
290 * @param connection the connection to make flushing and blocking
291 * @return #GNUNET_OK on success
294 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
296 return GNUNET_NETWORK_socket_disable_corking (connection->sock);
301 * Create a connection handle by boxing an existing OS socket. The OS
302 * socket should henceforth be no longer used directly.
303 * #GNUNET_connection_destroy() will close it.
305 * @param osSocket existing socket to box
306 * @return the boxed connection handle
308 struct GNUNET_CONNECTION_Handle *
309 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
311 struct GNUNET_CONNECTION_Handle *connection;
313 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
314 connection->write_buffer_size = GNUNET_MIN_MESSAGE_SIZE;
315 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
316 connection->sock = osSocket;
322 * Create a connection handle by accepting on a listen socket. This
323 * function may block if the listen socket has no connection ready.
325 * @param access_cb function to use to check if access is allowed
326 * @param access_cb_cls closure for @a access_cb
327 * @param lsock listen socket
328 * @return the connection handle, NULL on error
330 struct GNUNET_CONNECTION_Handle *
331 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access_cb,
333 struct GNUNET_NETWORK_Handle *lsock)
335 struct GNUNET_CONNECTION_Handle *connection;
338 struct GNUNET_NETWORK_Handle *sock;
340 struct sockaddr_in *v4;
341 struct sockaddr_in6 *v6;
348 struct GNUNET_CONNECTION_Credentials *gcp;
349 #if HAVE_GETPEEREID || defined(SO_PEERCRED) || HAVE_GETPEERUCRED
350 struct GNUNET_CONNECTION_Credentials gc;
356 addrlen = sizeof (addr);
358 GNUNET_NETWORK_socket_accept (lsock,
359 (struct sockaddr *) &addr,
364 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
367 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
370 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
374 sa = (struct sockaddr *) addr;
375 v6 = (struct sockaddr_in6 *) addr;
376 if ( (AF_INET6 == sa->sa_family) &&
377 (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)) )
379 /* convert to V4 address */
380 v4 = GNUNET_new (struct sockaddr_in);
381 memset (v4, 0, sizeof (struct sockaddr_in));
382 v4->sin_family = AF_INET;
383 #if HAVE_SOCKADDR_IN_SIN_LEN
384 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
386 GNUNET_memcpy (&v4->sin_addr,
387 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
388 sizeof (struct in_addr)],
389 sizeof (struct in_addr));
390 v4->sin_port = v6->sin6_port;
392 addrlen = sizeof (struct sockaddr_in);
396 uaddr = GNUNET_malloc (addrlen);
397 GNUNET_memcpy (uaddr, addr, addrlen);
400 if (AF_UNIX == sa->sa_family)
404 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock),
410 /* largely traditional GNU/Linux */
413 getsockopt (GNUNET_NETWORK_get_fd (sock),
418 (olen == sizeof (uc)) )
425 #if HAVE_GETPEERUCRED
426 /* this is for Solaris 10 */
430 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
432 gc.uid = ucred_geteuid (uc);
433 gc.gid = ucred_getegid (uc);
442 if ( (NULL != access_cb) &&
443 (GNUNET_YES != (aret = access_cb (access_cb_cls,
448 if (GNUNET_NO == aret)
449 LOG (GNUNET_ERROR_TYPE_INFO,
450 _("Access denied to `%s'\n"),
453 GNUNET_break (GNUNET_OK ==
454 GNUNET_NETWORK_socket_shutdown (sock,
456 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
460 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
461 connection->write_buffer_size = GNUNET_MIN_MESSAGE_SIZE;
462 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
463 connection->addr = uaddr;
464 connection->addrlen = addrlen;
465 connection->sock = sock;
466 LOG (GNUNET_ERROR_TYPE_INFO,
467 _("Accepting connection from `%s': %p\n"),
476 * Obtain the network address of the other party.
478 * @param connection the client to get the address for
479 * @param addr where to store the address
480 * @param addrlen where to store the length of the @a addr
481 * @return #GNUNET_OK on success
484 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
488 if ((NULL == connection->addr) || (0 == connection->addrlen))
490 *addr = GNUNET_malloc (connection->addrlen);
491 GNUNET_memcpy (*addr, connection->addr, connection->addrlen);
492 *addrlen = connection->addrlen;
498 * Tell the receiver callback that we had an IO error.
500 * @param connection connection to signal error
501 * @param errcode error code to send
504 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection,
507 GNUNET_CONNECTION_Receiver receiver;
509 LOG (GNUNET_ERROR_TYPE_DEBUG,
510 "Receive encounters error (%s), connection closed (%p)\n",
513 GNUNET_assert (NULL != (receiver = connection->receiver));
514 connection->receiver = NULL;
515 receiver (connection->receiver_cls,
525 * Tell the receiver callback that a timeout was reached.
527 * @param connection connection to signal for
530 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
532 GNUNET_CONNECTION_Receiver receiver;
534 LOG (GNUNET_ERROR_TYPE_DEBUG,
535 "Connection signals timeout to receiver (%p)!\n",
537 GNUNET_assert (NULL != (receiver = connection->receiver));
538 connection->receiver = NULL;
539 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
544 * We failed to transmit data to the service, signal the error.
546 * @param connection handle that had trouble
547 * @param ecode error code (errno)
550 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
553 GNUNET_CONNECTION_TransmitReadyNotify notify;
555 LOG (GNUNET_ERROR_TYPE_DEBUG,
556 "Transmission encounterd error (%s), connection closed (%p)\n",
559 if (NULL != connection->sock)
561 (void) GNUNET_NETWORK_socket_shutdown (connection->sock,
563 GNUNET_break (GNUNET_OK ==
564 GNUNET_NETWORK_socket_close (connection->sock));
565 connection->sock = NULL;
566 GNUNET_assert (NULL == connection->write_task);
568 if (NULL != connection->read_task)
570 /* send errors trigger read errors... */
571 GNUNET_SCHEDULER_cancel (connection->read_task);
572 connection->read_task = NULL;
573 signal_receive_timeout (connection);
576 if (NULL == connection->nth.notify_ready)
577 return; /* nobody to tell about it */
578 notify = connection->nth.notify_ready;
579 connection->nth.notify_ready = NULL;
580 notify (connection->nth.notify_ready_cls,
587 * We've failed for good to establish a connection (timeout or
588 * no more addresses to try).
590 * @param connection the connection we tried to establish
593 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
595 LOG (GNUNET_ERROR_TYPE_INFO,
596 "Failed to establish TCP connection to `%s:%u', no further addresses to try.\n",
597 connection->hostname,
599 GNUNET_break (NULL == connection->ap_head);
600 GNUNET_break (NULL == connection->ap_tail);
601 GNUNET_break (GNUNET_NO == connection->dns_active);
602 GNUNET_break (NULL == connection->sock);
603 GNUNET_assert (NULL == connection->write_task);
604 GNUNET_assert (NULL == connection->proxy_handshake);
606 /* signal errors for jobs that used to wait on the connection */
607 connection->destroy_later = 1;
608 if (NULL != connection->receiver)
609 signal_receive_error (connection,
611 if (NULL != connection->nth.notify_ready)
613 GNUNET_assert (NULL != connection->nth.timeout_task);
614 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
615 connection->nth.timeout_task = NULL;
616 signal_transmit_error (connection,
619 if (-1 == connection->destroy_later)
622 connection->destroy_later = 0;
623 GNUNET_CONNECTION_destroy (connection);
626 connection->destroy_later = 0;
631 * We are ready to transmit (or got a timeout).
633 * @param cls our connection handle
636 transmit_ready (void *cls);
640 * This function is called once we either timeout or have data ready
643 * @param cls connection to read from
646 receive_ready (void *cls);
650 * We've succeeded in establishing a connection.
652 * @param connection the connection we tried to establish
655 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
657 LOG (GNUNET_ERROR_TYPE_DEBUG,
658 "Connection to `%s' succeeded! (%p)\n",
659 GNUNET_a2s (connection->addr,
660 connection->addrlen),
662 /* trigger jobs that waited for the connection */
663 if (NULL != connection->receiver)
665 LOG (GNUNET_ERROR_TYPE_DEBUG,
666 "Connection succeeded, starting with receiving data (%p)\n",
668 GNUNET_assert (NULL == connection->read_task);
669 connection->read_task =
670 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
671 (connection->receive_timeout),
673 &receive_ready, connection);
675 if (NULL != connection->nth.notify_ready)
677 LOG (GNUNET_ERROR_TYPE_DEBUG,
678 "Connection succeeded, starting with sending data (%p)\n",
680 GNUNET_assert (connection->nth.timeout_task != NULL);
681 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
682 connection->nth.timeout_task = NULL;
683 GNUNET_assert (connection->write_task == NULL);
684 connection->write_task =
685 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
686 (connection->nth.transmit_timeout), connection->sock,
687 &transmit_ready, connection);
693 * Scheduler let us know that we're either ready to write on the
694 * socket OR connect timed out. Do the right thing.
696 * @param cls the `struct AddressProbe *` with the address that we are probing
699 connect_probe_continuation (void *cls)
701 struct AddressProbe *ap = cls;
702 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
703 const struct GNUNET_SCHEDULER_TaskContext *tc;
704 struct AddressProbe *pos;
708 GNUNET_assert (NULL != ap->sock);
709 GNUNET_CONTAINER_DLL_remove (connection->ap_head,
712 len = sizeof (error);
715 tc = GNUNET_SCHEDULER_get_task_context ();
716 if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
718 GNUNET_NETWORK_socket_getsockopt (ap->sock,
725 GNUNET_break (GNUNET_OK ==
726 GNUNET_NETWORK_socket_close (ap->sock));
728 if ( (NULL == connection->ap_head) &&
729 (GNUNET_NO == connection->dns_active) &&
730 (NULL == connection->proxy_handshake) )
731 connect_fail_continuation (connection);
734 GNUNET_assert (NULL == connection->sock);
735 connection->sock = ap->sock;
736 GNUNET_assert (NULL == connection->addr);
737 connection->addr = GNUNET_malloc (ap->addrlen);
738 GNUNET_memcpy (connection->addr, ap->addr, ap->addrlen);
739 connection->addrlen = ap->addrlen;
741 /* cancel all other attempts */
742 while (NULL != (pos = connection->ap_head))
744 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
745 GNUNET_SCHEDULER_cancel (pos->task);
746 GNUNET_CONTAINER_DLL_remove (connection->ap_head,
751 connect_success_continuation (connection);
756 * Try to establish a connection given the specified address.
757 * This function is called by the resolver once we have a DNS reply.
759 * @param cls our `struct GNUNET_CONNECTION_Handle *`
760 * @param addr address to try, NULL for "last call"
761 * @param addrlen length of @a addr
764 try_connect_using_address (void *cls,
765 const struct sockaddr *addr,
768 struct GNUNET_CONNECTION_Handle *connection = cls;
769 struct AddressProbe *ap;
770 struct GNUNET_TIME_Relative delay;
774 connection->dns_active = NULL;
775 if ((NULL == connection->ap_head) &&
776 (NULL == connection->sock) &&
777 (NULL == connection->proxy_handshake))
778 connect_fail_continuation (connection);
781 if (NULL != connection->sock)
782 return; /* already connected */
783 GNUNET_assert (NULL == connection->addr);
785 LOG (GNUNET_ERROR_TYPE_DEBUG,
786 "Trying to connect using address `%s:%u/%s:%u'\n",
787 connection->hostname,
789 GNUNET_a2s (addr, addrlen),
791 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
792 ap->addr = (const struct sockaddr *) &ap[1];
793 GNUNET_memcpy (&ap[1], addr, addrlen);
794 ap->addrlen = addrlen;
795 ap->connection = connection;
797 switch (ap->addr->sa_family)
800 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
803 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
808 return; /* not supported by us */
810 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family,
812 if (NULL == ap->sock)
815 return; /* not supported by OS */
817 LOG (GNUNET_ERROR_TYPE_INFO,
818 "Trying to connect to `%s' (%p)\n",
819 GNUNET_a2s (ap->addr, ap->addrlen),
822 GNUNET_NETWORK_socket_connect (ap->sock,
825 (EINPROGRESS != errno))
827 /* maybe refused / unsupported address, try next */
828 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
829 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
833 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
834 delay = CONNECT_RETRY_TIMEOUT;
835 if (NULL != connection->nth.notify_ready)
836 delay = GNUNET_TIME_relative_min (delay,
837 GNUNET_TIME_absolute_get_remaining (connection->nth.transmit_timeout));
838 if (NULL != connection->receiver)
839 delay = GNUNET_TIME_relative_min (delay,
840 GNUNET_TIME_absolute_get_remaining (connection->receive_timeout));
841 ap->task = GNUNET_SCHEDULER_add_write_net (delay,
843 &connect_probe_continuation,
849 * Create a connection handle by (asynchronously) connecting to a host.
850 * This function returns immediately, even if the connection has not
851 * yet been established. This function only creates TCP connections.
853 * @param cfg configuration to use
854 * @param hostname name of the host to connect to
855 * @param port port to connect to
856 * @return the connection handle
858 struct GNUNET_CONNECTION_Handle *
859 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
860 const char *hostname,
863 struct GNUNET_CONNECTION_Handle *connection;
865 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
866 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
867 connection->cfg = cfg;
868 connection->write_buffer_size = GNUNET_MIN_MESSAGE_SIZE;
869 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
870 connection->port = port;
871 connection->hostname = GNUNET_strdup (hostname);
872 connection->dns_active =
873 GNUNET_RESOLVER_ip_get (connection->hostname,
875 CONNECT_RETRY_TIMEOUT,
876 &try_connect_using_address,
883 * Create a connection handle by connecting to a UNIX domain service.
884 * This function returns immediately, even if the connection has not
885 * yet been established. This function only creates UNIX connections.
887 * @param cfg configuration to use
888 * @param unixpath path to connect to
889 * @return the connection handle, NULL on systems without UNIX support
891 struct GNUNET_CONNECTION_Handle *
892 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct GNUNET_CONFIGURATION_Handle *cfg,
893 const char *unixpath)
896 struct GNUNET_CONNECTION_Handle *connection;
897 struct sockaddr_un *un;
899 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
900 un = GNUNET_new (struct sockaddr_un);
901 un->sun_family = AF_UNIX;
902 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
907 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
909 "USE_ABSTRACT_SOCKETS");
910 if (GNUNET_YES == abstract)
911 un->sun_path[0] = '\0';
914 #if HAVE_SOCKADDR_UN_SUN_LEN
915 un->sun_len = (u_char) sizeof (struct sockaddr_un);
917 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
918 connection->cfg = cfg;
919 connection->write_buffer_size = GNUNET_MIN_MESSAGE_SIZE;
920 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
921 connection->port = 0;
922 connection->hostname = NULL;
923 connection->addr = (struct sockaddr *) un;
924 connection->addrlen = sizeof (struct sockaddr_un);
925 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX,
928 if (NULL == connection->sock)
930 GNUNET_free (connection->addr);
931 GNUNET_free (connection->write_buffer);
932 GNUNET_free (connection);
936 GNUNET_NETWORK_socket_connect (connection->sock,
938 connection->addrlen)) &&
939 (EINPROGRESS != errno) )
941 /* Just return; we expect everything to work eventually so don't fail HARD */
942 GNUNET_break (GNUNET_OK ==
943 GNUNET_NETWORK_socket_close (connection->sock));
944 connection->sock = NULL;
947 connect_success_continuation (connection);
956 * Create a connection handle by (asynchronously) connecting to a host.
957 * This function returns immediately, even if the connection has not
958 * yet been established. This function only creates TCP connections.
960 * @param s socket to connect
961 * @param serv_addr server address
962 * @param addrlen length of @a serv_addr
963 * @return the connection handle
965 struct GNUNET_CONNECTION_Handle *
966 GNUNET_CONNECTION_connect_socket (struct GNUNET_NETWORK_Handle *s,
967 const struct sockaddr *serv_addr,
970 struct GNUNET_CONNECTION_Handle *connection;
973 GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
974 (EINPROGRESS != errno) )
976 /* maybe refused / unsupported address, try next */
977 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
979 LOG (GNUNET_ERROR_TYPE_DEBUG,
980 "Attempt to connect to `%s' failed\n",
981 GNUNET_a2s (serv_addr,
983 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
986 connection = GNUNET_CONNECTION_create_from_existing (s);
987 connection->addr = GNUNET_malloc (addrlen);
988 GNUNET_memcpy (connection->addr, serv_addr, addrlen);
989 connection->addrlen = addrlen;
990 LOG (GNUNET_ERROR_TYPE_INFO,
991 "Trying to connect to `%s' (%p)\n",
992 GNUNET_a2s (serv_addr, addrlen),
999 * Create a connection handle by creating a socket and
1000 * (asynchronously) connecting to a host. This function returns
1001 * immediately, even if the connection has not yet been established.
1002 * This function only creates TCP connections.
1004 * @param af_family address family to use
1005 * @param serv_addr server address
1006 * @param addrlen length of @a serv_addr
1007 * @return the connection handle
1009 struct GNUNET_CONNECTION_Handle *
1010 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
1011 const struct sockaddr *serv_addr,
1014 struct GNUNET_NETWORK_Handle *s;
1016 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
1019 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
1023 return GNUNET_CONNECTION_connect_socket (s,
1030 * Check if connection is valid (no fatal errors have happened so far).
1031 * Note that a connection that is still trying to connect is considered
1034 * @param connection connection to check
1035 * @return #GNUNET_YES if valid, #GNUNET_NO otherwise
1038 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
1040 if ((NULL != connection->ap_head) ||
1041 (NULL != connection->dns_active) ||
1042 (NULL != connection->proxy_handshake))
1043 return GNUNET_YES; /* still trying to connect */
1044 if ( (0 != connection->destroy_later) ||
1045 (NULL == connection->sock) )
1052 * Close the connection and free associated resources. There must
1053 * not be any pending requests for reading or writing to the
1054 * connection at this time.
1056 * @param connection connection to destroy
1059 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
1061 struct AddressProbe *pos;
1063 if (0 != connection->destroy_later)
1065 connection->destroy_later = -1;
1068 LOG (GNUNET_ERROR_TYPE_DEBUG,
1069 "Shutting down connection (%p)\n",
1071 GNUNET_assert (NULL == connection->nth.notify_ready);
1072 GNUNET_assert (NULL == connection->receiver);
1073 if (NULL != connection->write_task)
1075 GNUNET_SCHEDULER_cancel (connection->write_task);
1076 connection->write_task = NULL;
1077 connection->write_buffer_off = 0;
1079 if (NULL != connection->read_task)
1081 GNUNET_SCHEDULER_cancel (connection->read_task);
1082 connection->read_task = NULL;
1084 if (NULL != connection->nth.timeout_task)
1086 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1087 connection->nth.timeout_task = NULL;
1089 connection->nth.notify_ready = NULL;
1090 if (NULL != connection->dns_active)
1092 GNUNET_RESOLVER_request_cancel (connection->dns_active);
1093 connection->dns_active = NULL;
1095 if (NULL != connection->proxy_handshake)
1097 /* GNUNET_CONNECTION_destroy (connection->proxy_handshake); */
1098 connection->proxy_handshake->destroy_later = -1;
1099 connection->proxy_handshake = NULL; /* Not leaked ??? */
1101 while (NULL != (pos = connection->ap_head))
1103 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1104 GNUNET_SCHEDULER_cancel (pos->task);
1105 GNUNET_CONTAINER_DLL_remove (connection->ap_head,
1106 connection->ap_tail,
1110 if ( (NULL != connection->sock) &&
1111 (GNUNET_YES != connection->persist) )
1114 GNUNET_NETWORK_socket_shutdown (connection->sock,
1116 (ENOTCONN != errno) &&
1117 (ECONNRESET != errno) )
1118 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1121 if (NULL != connection->sock)
1123 if (GNUNET_YES != connection->persist)
1125 GNUNET_break (GNUNET_OK ==
1126 GNUNET_NETWORK_socket_close (connection->sock));
1130 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1131 * leak the socket in this special case) ... */
1134 GNUNET_free_non_null (connection->addr);
1135 GNUNET_free_non_null (connection->hostname);
1136 GNUNET_free (connection->write_buffer);
1137 GNUNET_free (connection);
1142 * This function is called once we either timeout
1143 * or have data ready to read.
1145 * @param cls connection to read from
1148 receive_ready (void *cls)
1150 struct GNUNET_CONNECTION_Handle *connection = cls;
1151 const struct GNUNET_SCHEDULER_TaskContext *tc;
1152 char buffer[connection->max];
1154 GNUNET_CONNECTION_Receiver receiver;
1156 connection->read_task = NULL;
1157 tc = GNUNET_SCHEDULER_get_task_context ();
1158 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1160 LOG (GNUNET_ERROR_TYPE_DEBUG,
1161 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1162 GNUNET_a2s (connection->addr,
1163 connection->addrlen),
1164 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout),
1167 signal_receive_timeout (connection);
1170 if (NULL == connection->sock)
1172 /* connect failed for good */
1173 signal_receive_error (connection, ECONNREFUSED);
1176 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready,
1179 ret = GNUNET_NETWORK_socket_recv (connection->sock,
1186 signal_receive_error (connection, errno);
1189 LOG (GNUNET_ERROR_TYPE_DEBUG,
1190 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1193 GNUNET_a2s (connection->addr,
1194 connection->addrlen),
1196 GNUNET_assert (NULL != (receiver = connection->receiver));
1197 connection->receiver = NULL;
1198 receiver (connection->receiver_cls,
1202 connection->addrlen,
1208 * Receive data from the given connection. Note that this function
1209 * will call @a receiver asynchronously using the scheduler. It will
1210 * "immediately" return. Note that there MUST only be one active
1211 * receive call per connection at any given point in time (so do not
1212 * call receive again until the receiver callback has been invoked).
1214 * @param connection connection handle
1215 * @param max maximum number of bytes to read
1216 * @param timeout maximum amount of time to wait
1217 * @param receiver function to call with received data
1218 * @param receiver_cls closure for @a receiver
1219 * @return #GNUNET_SYSERR if @a connection died (receiver was
1220 * called with error)
1223 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection,
1225 struct GNUNET_TIME_Relative timeout,
1226 GNUNET_CONNECTION_Receiver receiver,
1229 GNUNET_assert ((NULL == connection->read_task) &&
1230 (NULL == connection->receiver));
1231 GNUNET_assert (NULL != receiver);
1232 connection->receiver = receiver;
1233 connection->receiver_cls = receiver_cls;
1234 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1235 connection->max = max;
1236 if (NULL != connection->sock)
1238 connection->read_task =
1239 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1240 (connection->receive_timeout),
1246 if ((NULL == connection->dns_active) &&
1247 (NULL == connection->ap_head) &&
1248 (NULL == connection->proxy_handshake))
1250 connection->receiver = NULL;
1251 receiver (receiver_cls,
1255 return GNUNET_SYSERR;
1262 * Cancel receive job on the given connection. Note that the
1263 * receiver callback must not have been called yet in order
1264 * for the cancellation to be valid.
1266 * @param connection connection handle
1267 * @return closure of the original receiver callback closure
1270 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1272 if (NULL != connection->read_task)
1274 GNUNET_assert (connection ==
1275 GNUNET_SCHEDULER_cancel (connection->read_task));
1276 connection->read_task = NULL;
1278 connection->receiver = NULL;
1279 return connection->receiver_cls;
1284 * Try to call the transmit notify method (check if we do
1285 * have enough space available first)!
1287 * @param connection connection for which we should do this processing
1288 * @return #GNUNET_YES if we were able to call notify
1291 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1296 GNUNET_CONNECTION_TransmitReadyNotify notify;
1298 LOG (GNUNET_ERROR_TYPE_DEBUG,
1299 "process_notify is running\n");
1300 GNUNET_assert (NULL == connection->write_task);
1301 if (NULL == (notify = connection->nth.notify_ready))
1303 LOG (GNUNET_ERROR_TYPE_DEBUG,
1304 "No one to notify\n");
1307 used = connection->write_buffer_off - connection->write_buffer_pos;
1308 avail = connection->write_buffer_size - used;
1309 size = connection->nth.notify_size;
1312 LOG (GNUNET_ERROR_TYPE_DEBUG,
1313 "Not enough buffer\n");
1316 connection->nth.notify_ready = NULL;
1317 if (connection->write_buffer_size - connection->write_buffer_off < size)
1319 /* need to compact */
1320 memmove (connection->write_buffer,
1321 &connection->write_buffer[connection->write_buffer_pos],
1323 connection->write_buffer_off -= connection->write_buffer_pos;
1324 connection->write_buffer_pos = 0;
1326 avail = connection->write_buffer_size - connection->write_buffer_off;
1327 GNUNET_assert (avail >= size);
1329 notify (connection->nth.notify_ready_cls, avail,
1330 &connection->write_buffer[connection->write_buffer_off]);
1331 GNUNET_assert (size <= avail);
1333 connection->write_buffer_off += size;
1339 * Task invoked by the scheduler when a call to transmit
1340 * is timing out (we never got enough buffer space to call
1341 * the callback function before the specified timeout
1344 * This task notifies the client about the timeout.
1346 * @param cls the `struct GNUNET_CONNECTION_Handle`
1349 transmit_timeout (void *cls)
1351 struct GNUNET_CONNECTION_Handle *connection = cls;
1352 GNUNET_CONNECTION_TransmitReadyNotify notify;
1354 connection->nth.timeout_task = NULL;
1355 LOG (GNUNET_ERROR_TYPE_DEBUG,
1356 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1357 connection->hostname,
1359 GNUNET_a2s (connection->addr,
1360 connection->addrlen),
1362 notify = connection->nth.notify_ready;
1363 GNUNET_assert (NULL != notify);
1364 connection->nth.notify_ready = NULL;
1365 notify (connection->nth.notify_ready_cls,
1372 * Task invoked by the scheduler when we failed to connect
1373 * at the time of being asked to transmit.
1375 * This task notifies the client about the error.
1377 * @param cls the `struct GNUNET_CONNECTION_Handle`
1380 connect_error (void *cls)
1382 struct GNUNET_CONNECTION_Handle *connection = cls;
1383 GNUNET_CONNECTION_TransmitReadyNotify notify;
1385 LOG (GNUNET_ERROR_TYPE_DEBUG,
1386 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1387 connection->nth.notify_size,
1388 connection->hostname,
1391 connection->write_task = NULL;
1392 notify = connection->nth.notify_ready;
1393 connection->nth.notify_ready = NULL;
1394 notify (connection->nth.notify_ready_cls,
1401 * We are ready to transmit (or got a timeout).
1403 * @param cls our connection handle
1406 transmit_ready (void *cls)
1408 struct GNUNET_CONNECTION_Handle *connection = cls;
1409 GNUNET_CONNECTION_TransmitReadyNotify notify;
1410 const struct GNUNET_SCHEDULER_TaskContext *tc;
1414 LOG (GNUNET_ERROR_TYPE_DEBUG,
1415 "transmit_ready running (%p).\n",
1417 GNUNET_assert (NULL != connection->write_task);
1418 connection->write_task = NULL;
1419 GNUNET_assert (NULL == connection->nth.timeout_task);
1420 tc = GNUNET_SCHEDULER_get_task_context ();
1421 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1423 LOG (GNUNET_ERROR_TYPE_DEBUG,
1424 "Transmit to `%s' fails, time out reached (%p).\n",
1425 GNUNET_a2s (connection->addr,
1426 connection->addrlen),
1428 notify = connection->nth.notify_ready;
1429 GNUNET_assert (NULL != notify);
1430 connection->nth.notify_ready = NULL;
1431 notify (connection->nth.notify_ready_cls, 0, NULL);
1434 GNUNET_assert (NULL != connection->sock);
1435 if (NULL == tc->write_ready)
1437 /* special circumstances (in particular, PREREQ_DONE after
1438 * connect): not yet ready to write, but no "fatal" error either.
1440 goto SCHEDULE_WRITE;
1442 if (! GNUNET_NETWORK_fdset_isset (tc->write_ready,
1445 GNUNET_assert (NULL == connection->write_task);
1446 /* special circumstances (in particular, shutdown): not yet ready
1447 * to write, but no "fatal" error either. Hence retry. */
1448 goto SCHEDULE_WRITE;
1450 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1451 if ((NULL != connection->nth.notify_ready) &&
1452 (connection->write_buffer_size < connection->nth.notify_size))
1454 connection->write_buffer =
1455 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1456 connection->write_buffer_size = connection->nth.notify_size;
1458 process_notify (connection);
1459 have = connection->write_buffer_off - connection->write_buffer_pos;
1462 /* no data ready for writing, terminate write loop */
1465 GNUNET_assert (have <= connection->write_buffer_size);
1466 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1467 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1470 GNUNET_NETWORK_socket_send (connection->sock,
1471 &connection->write_buffer[connection->write_buffer_pos],
1477 if (NULL != connection->write_task)
1479 GNUNET_SCHEDULER_cancel (connection->write_task);
1480 connection->write_task = NULL;
1482 signal_transmit_error (connection, errno);
1485 LOG (GNUNET_ERROR_TYPE_DEBUG,
1486 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1489 GNUNET_a2s (connection->addr,
1490 connection->addrlen),
1492 connection->write_buffer_pos += ret;
1493 if (connection->write_buffer_pos == connection->write_buffer_off)
1495 /* transmitted all pending data */
1496 connection->write_buffer_pos = 0;
1497 connection->write_buffer_off = 0;
1499 if ( (0 == connection->write_buffer_off) &&
1500 (NULL == connection->nth.notify_ready) )
1501 return; /* all data sent! */
1502 /* not done writing, schedule more */
1504 LOG (GNUNET_ERROR_TYPE_DEBUG,
1505 "Re-scheduling transmit_ready (more to do) (%p).\n",
1507 have = connection->write_buffer_off - connection->write_buffer_pos;
1508 GNUNET_assert ( (NULL != connection->nth.notify_ready) ||
1510 if (NULL == connection->write_task)
1511 connection->write_task =
1512 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1513 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1514 GNUNET_TIME_absolute_get_remaining
1515 (connection->nth.transmit_timeout),
1517 &transmit_ready, connection);
1522 * Ask the connection to call us once the specified number of bytes
1523 * are free in the transmission buffer. Will never call the @a notify
1524 * callback in this task, but always first go into the scheduler.
1526 * @param connection connection
1527 * @param size number of bytes to send
1528 * @param timeout after how long should we give up (and call
1529 * @a notify with buf NULL and size 0)?
1530 * @param notify function to call
1531 * @param notify_cls closure for @a notify
1532 * @return non-NULL if the notify callback was queued,
1533 * NULL if we are already going to notify someone else (busy)
1535 struct GNUNET_CONNECTION_TransmitHandle *
1536 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1538 struct GNUNET_TIME_Relative timeout,
1539 GNUNET_CONNECTION_TransmitReadyNotify notify,
1542 if (NULL != connection->nth.notify_ready)
1547 GNUNET_assert (NULL != notify);
1548 GNUNET_assert (size < GNUNET_MAX_MESSAGE_SIZE);
1549 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1550 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1551 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1552 connection->nth.notify_ready = notify;
1553 connection->nth.notify_ready_cls = notify_cls;
1554 connection->nth.connection = connection;
1555 connection->nth.notify_size = size;
1556 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1557 GNUNET_assert (NULL == connection->nth.timeout_task);
1558 if ((NULL == connection->sock) &&
1559 (NULL == connection->ap_head) &&
1560 (NULL == connection->dns_active) &&
1561 (NULL == connection->proxy_handshake))
1563 if (NULL != connection->write_task)
1564 GNUNET_SCHEDULER_cancel (connection->write_task);
1565 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error,
1567 return &connection->nth;
1569 if (NULL != connection->write_task)
1570 return &connection->nth; /* previous transmission still in progress */
1571 if (NULL != connection->sock)
1573 /* connected, try to transmit now */
1574 LOG (GNUNET_ERROR_TYPE_DEBUG,
1575 "Scheduling transmission (%p).\n",
1577 connection->write_task =
1578 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1579 (connection->nth.transmit_timeout),
1581 &transmit_ready, connection);
1582 return &connection->nth;
1584 /* not yet connected, wait for connection */
1585 LOG (GNUNET_ERROR_TYPE_DEBUG,
1586 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n",
1588 connection->nth.timeout_task =
1589 GNUNET_SCHEDULER_add_delayed (timeout,
1592 return &connection->nth;
1597 * Cancel the specified transmission-ready notification.
1599 * @param th notification to cancel
1602 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct GNUNET_CONNECTION_TransmitHandle *th)
1604 GNUNET_assert (NULL != th->notify_ready);
1605 th->notify_ready = NULL;
1606 if (NULL != th->timeout_task)
1608 GNUNET_SCHEDULER_cancel (th->timeout_task);
1609 th->timeout_task = NULL;
1611 if (NULL != th->connection->write_task)
1613 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1614 th->connection->write_task = NULL;
1620 * Create a connection to be proxied using a given connection.
1622 * @param cph connection to proxy server
1623 * @return connection to be proxied
1625 struct GNUNET_CONNECTION_Handle *
1626 GNUNET_CONNECTION_create_proxied_from_handshake (struct GNUNET_CONNECTION_Handle *cph)
1628 struct GNUNET_CONNECTION_Handle *proxied = GNUNET_CONNECTION_create_from_existing (NULL);
1630 proxied->proxy_handshake = cph;
1636 * Activate proxied connection and destroy initial proxy handshake connection.
1637 * There must not be any pending requests for reading or writing to the
1638 * proxy hadshake connection at this time.
1640 * @param proxied connection connection to proxy server
1643 GNUNET_CONNECTION_acivate_proxied (struct GNUNET_CONNECTION_Handle *proxied)
1645 struct GNUNET_CONNECTION_Handle *cph = proxied->proxy_handshake;
1647 GNUNET_assert (NULL != cph);
1648 GNUNET_assert (NULL == proxied->sock);
1649 GNUNET_assert (NULL != cph->sock);
1650 proxied->sock = cph->sock;
1652 GNUNET_CONNECTION_destroy (cph);
1653 connect_success_continuation (proxied);
1657 /* end of connection.c */