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., 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.
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 receiver.
178 * Pointer to our write buffer.
183 * Current size of our write buffer.
185 size_t write_buffer_size;
188 * Current write-offset in write buffer (where
189 * would we write next).
191 size_t write_buffer_off;
194 * Current read-offset in 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 used 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;
258 * Set the persist option on this connection handle. Indicates
259 * that the underlying socket or fd should never really be closed.
260 * Used for indicating process death.
262 * @param connection the connection to set persistent
265 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
267 connection->persist = GNUNET_YES;
272 * Disable the "CORK" feature for communication with the given connection,
273 * forcing the OS to immediately flush the buffer on transmission
274 * instead of potentially buffering multiple messages. Essentially
275 * reduces the OS send buffers to zero.
276 * Used to make sure that the last messages sent through the connection
277 * reach the other side before the process is terminated.
279 * @param connection the connection to make flushing and blocking
280 * @return GNUNET_OK on success
283 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
285 return GNUNET_NETWORK_socket_disable_corking (connection->sock);
290 * Create a connection handle by boxing an existing OS socket. The OS
291 * socket should henceforth be no longer used directly.
292 * GNUNET_connection_destroy will close it.
294 * @param osSocket existing socket to box
295 * @return the boxed connection handle
297 struct GNUNET_CONNECTION_Handle *
298 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
300 struct GNUNET_CONNECTION_Handle *connection;
302 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
303 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
304 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
305 connection->sock = osSocket;
311 * Create a connection handle by accepting on a listen socket. This
312 * function may block if the listen socket has no connection ready.
314 * @param access_cb function to use to check if access is allowed
315 * @param access_cb_cls closure for @a access_cb
316 * @param lsock listen socket
317 * @return the connection handle, NULL on error
319 struct GNUNET_CONNECTION_Handle *
320 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access_cb,
322 struct GNUNET_NETWORK_Handle *lsock)
324 struct GNUNET_CONNECTION_Handle *connection;
327 struct GNUNET_NETWORK_Handle *sock;
329 struct sockaddr_in *v4;
330 struct sockaddr_in6 *v6;
333 struct GNUNET_CONNECTION_Credentials *gcp;
334 struct GNUNET_CONNECTION_Credentials gc;
340 addrlen = sizeof (addr);
342 GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
345 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
348 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
351 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
355 sa = (struct sockaddr *) addr;
356 v6 = (struct sockaddr_in6 *) addr;
357 if ((AF_INET6 == sa->sa_family) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
359 /* convert to V4 address */
360 v4 = GNUNET_new (struct sockaddr_in);
361 memset (v4, 0, sizeof (struct sockaddr_in));
362 v4->sin_family = AF_INET;
363 #if HAVE_SOCKADDR_IN_SIN_LEN
364 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
366 memcpy (&v4->sin_addr,
367 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
368 sizeof (struct in_addr)],
369 sizeof (struct in_addr));
370 v4->sin_port = v6->sin6_port;
372 addrlen = sizeof (struct sockaddr_in);
376 uaddr = GNUNET_malloc (addrlen);
377 memcpy (uaddr, addr, addrlen);
382 if (AF_UNIX == sa->sa_family)
386 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock), &gc.uid, &gc.gid))
390 /* largely traditional GNU/Linux */
393 getsockopt (GNUNET_NETWORK_get_fd (sock), SOL_SOCKET, SO_PEERCRED, &uc,
394 &olen)) && (olen == sizeof (uc)))
401 #if HAVE_GETPEERUCRED
402 /* this is for Solaris 10 */
406 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
408 gc.uid = ucred_geteuid (uc);
409 gc.gid = ucred_getegid (uc);
418 if ((NULL != access_cb) &&
419 (GNUNET_YES != (aret = access_cb (access_cb_cls, gcp, uaddr, addrlen))))
421 if (GNUNET_NO == aret)
422 LOG (GNUNET_ERROR_TYPE_INFO,
423 _("Access denied to `%s'\n"),
424 GNUNET_a2s (uaddr, addrlen));
425 GNUNET_break (GNUNET_OK ==
426 GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
427 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
431 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
432 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
433 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
434 connection->addr = uaddr;
435 connection->addrlen = addrlen;
436 connection->sock = sock;
437 LOG (GNUNET_ERROR_TYPE_INFO,
438 _("Accepting connection from `%s': %p\n"),
439 GNUNET_a2s (uaddr, addrlen), connection);
445 * Obtain the network address of the other party.
447 * @param connection the client to get the address for
448 * @param addr where to store the address
449 * @param addrlen where to store the length of the address
450 * @return GNUNET_OK on success
453 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
454 void **addr, size_t * addrlen)
456 if ((NULL == connection->addr) || (0 == connection->addrlen))
458 *addr = GNUNET_malloc (connection->addrlen);
459 memcpy (*addr, connection->addr, connection->addrlen);
460 *addrlen = connection->addrlen;
466 * Tell the receiver callback that we had an IO error.
468 * @param connection connection to signal error
469 * @param errcode error code to send
472 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection,
475 GNUNET_CONNECTION_Receiver receiver;
477 LOG (GNUNET_ERROR_TYPE_DEBUG,
478 "Receive encounters error (%s), connection closed (%p)\n",
481 GNUNET_assert (NULL != (receiver = connection->receiver));
482 connection->receiver = NULL;
483 receiver (connection->receiver_cls,
493 * Tell the receiver callback that a timeout was reached.
495 * @param connection connection to signal for
498 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
500 GNUNET_CONNECTION_Receiver receiver;
502 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection signals timeout to receiver (%p)!\n",
504 GNUNET_assert (NULL != (receiver = connection->receiver));
505 connection->receiver = NULL;
506 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
511 * We failed to transmit data to the service, signal the error.
513 * @param connection handle that had trouble
514 * @param ecode error code (errno)
517 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
520 GNUNET_CONNECTION_TransmitReadyNotify notify;
522 LOG (GNUNET_ERROR_TYPE_DEBUG,
523 "Transmission encounterd error (%s), connection closed (%p)\n",
526 if (NULL != connection->sock)
528 (void) GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR);
529 GNUNET_break (GNUNET_OK ==
530 GNUNET_NETWORK_socket_close (connection->sock));
531 connection->sock = NULL;
532 GNUNET_assert (NULL == connection->write_task);
534 if (NULL != connection->read_task)
536 /* send errors trigger read errors... */
537 GNUNET_SCHEDULER_cancel (connection->read_task);
538 connection->read_task = NULL;
539 signal_receive_timeout (connection);
542 if (NULL == connection->nth.notify_ready)
543 return; /* nobody to tell about it */
544 notify = connection->nth.notify_ready;
545 connection->nth.notify_ready = NULL;
546 notify (connection->nth.notify_ready_cls, 0, NULL);
551 * We've failed for good to establish a connection (timeout or
552 * no more addresses to try).
554 * @param connection the connection we tried to establish
557 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
559 LOG (GNUNET_ERROR_TYPE_INFO,
560 _("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
561 connection->hostname, connection->port);
562 GNUNET_break (NULL == connection->ap_head);
563 GNUNET_break (NULL == connection->ap_tail);
564 GNUNET_break (GNUNET_NO == connection->dns_active);
565 GNUNET_break (NULL == connection->sock);
566 GNUNET_assert (NULL == connection->write_task);
568 /* signal errors for jobs that used to wait on the connection */
569 connection->destroy_later = 1;
570 if (NULL != connection->receiver)
571 signal_receive_error (connection,
573 if (NULL != connection->nth.notify_ready)
575 GNUNET_assert (NULL != connection->nth.timeout_task);
576 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
577 connection->nth.timeout_task = NULL;
578 signal_transmit_error (connection,
581 if (-1 == connection->destroy_later)
584 connection->destroy_later = 0;
585 GNUNET_CONNECTION_destroy (connection);
588 connection->destroy_later = 0;
593 * We are ready to transmit (or got a timeout).
595 * @param cls our connection handle
596 * @param tc task context describing why we are here
599 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
603 * This function is called once we either timeout or have data ready
606 * @param cls connection to read from
607 * @param tc scheduler context
610 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
614 * We've succeeded in establishing a connection.
616 * @param connection the connection we tried to establish
619 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
621 LOG (GNUNET_ERROR_TYPE_DEBUG,
622 "Connection to `%s' succeeded! (%p)\n",
623 GNUNET_a2s (connection->addr, connection->addrlen), connection);
624 /* trigger jobs that waited for the connection */
625 if (NULL != connection->receiver)
627 LOG (GNUNET_ERROR_TYPE_DEBUG,
628 "Connection succeeded, starting with receiving data (%p)\n",
630 GNUNET_assert (NULL == connection->read_task);
631 connection->read_task =
632 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
633 (connection->receive_timeout), connection->sock,
634 &receive_ready, connection);
636 if (NULL != connection->nth.notify_ready)
638 LOG (GNUNET_ERROR_TYPE_DEBUG,
639 "Connection succeeded, starting with sending data (%p)\n",
641 GNUNET_assert (connection->nth.timeout_task != NULL);
642 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
643 connection->nth.timeout_task = NULL;
644 GNUNET_assert (connection->write_task == NULL);
645 connection->write_task =
646 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
647 (connection->nth.transmit_timeout), connection->sock,
648 &transmit_ready, connection);
654 * Scheduler let us know that we're either ready to write on the
655 * socket OR connect timed out. Do the right thing.
657 * @param cls the "struct AddressProbe*" with the address that we are probing
658 * @param tc success or failure info about the connect attempt.
661 connect_probe_continuation (void *cls,
662 const struct GNUNET_SCHEDULER_TaskContext *tc)
664 struct AddressProbe *ap = cls;
665 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
666 struct AddressProbe *pos;
670 GNUNET_assert (NULL != ap->sock);
671 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
672 len = sizeof (error);
675 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
677 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
678 &len)) || (0 != error))
680 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
682 if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
683 connect_fail_continuation (connection);
686 GNUNET_assert (NULL == connection->sock);
687 connection->sock = ap->sock;
688 GNUNET_assert (NULL == connection->addr);
689 connection->addr = GNUNET_malloc (ap->addrlen);
690 memcpy (connection->addr, ap->addr, ap->addrlen);
691 connection->addrlen = ap->addrlen;
693 /* cancel all other attempts */
694 while (NULL != (pos = connection->ap_head))
696 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
697 GNUNET_SCHEDULER_cancel (pos->task);
698 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
701 connect_success_continuation (connection);
706 * Try to establish a connection given the specified address.
707 * This function is called by the resolver once we have a DNS reply.
709 * @param cls our "struct GNUNET_CONNECTION_Handle *"
710 * @param addr address to try, NULL for "last call"
711 * @param addrlen length of addr
714 try_connect_using_address (void *cls, const struct sockaddr *addr,
717 struct GNUNET_CONNECTION_Handle *connection = cls;
718 struct AddressProbe *ap;
719 struct GNUNET_TIME_Relative delay;
723 connection->dns_active = NULL;
724 if ((NULL == connection->ap_head) && (NULL == connection->sock))
725 connect_fail_continuation (connection);
728 if (NULL != connection->sock)
729 return; /* already connected */
730 GNUNET_assert (NULL == connection->addr);
732 LOG (GNUNET_ERROR_TYPE_DEBUG,
733 "Trying to connect using address `%s:%u/%s:%u'\n", connection->hostname, connection->port,
734 GNUNET_a2s (addr, addrlen), connection->port);
735 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
736 ap->addr = (const struct sockaddr *) &ap[1];
737 memcpy (&ap[1], addr, addrlen);
738 ap->addrlen = addrlen;
739 ap->connection = connection;
741 switch (ap->addr->sa_family)
744 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
747 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
752 return; /* not supported by us */
754 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
755 if (NULL == ap->sock)
758 return; /* not supported by OS */
760 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
761 GNUNET_a2s (ap->addr, ap->addrlen), connection);
763 GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
764 (EINPROGRESS != errno))
766 /* maybe refused / unsupported address, try next */
767 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
768 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
772 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
773 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
774 if (NULL != connection->nth.notify_ready)
776 GNUNET_TIME_relative_min (delay,
777 GNUNET_TIME_absolute_get_remaining (connection->
778 nth.transmit_timeout));
779 if (NULL != connection->receiver)
781 GNUNET_TIME_relative_min (delay,
782 GNUNET_TIME_absolute_get_remaining
783 (connection->receive_timeout));
785 GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
786 &connect_probe_continuation, ap);
791 * Create a connection handle by (asynchronously) connecting to a host.
792 * This function returns immediately, even if the connection has not
793 * yet been established. This function only creates TCP connections.
795 * @param cfg configuration to use
796 * @param hostname name of the host to connect to
797 * @param port port to connect to
798 * @return the connection handle
800 struct GNUNET_CONNECTION_Handle *
801 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
802 const char *hostname,
805 struct GNUNET_CONNECTION_Handle *connection;
807 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
808 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
809 connection->cfg = cfg;
810 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
811 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
812 connection->port = port;
813 connection->hostname = GNUNET_strdup (hostname);
814 connection->dns_active =
815 GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
816 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
817 &try_connect_using_address, connection);
823 * Create a connection handle by connecting to a UNIX domain service.
824 * This function returns immediately, even if the connection has not
825 * yet been established. This function only creates UNIX connections.
827 * @param cfg configuration to use
828 * @param unixpath path to connect to
829 * @return the connection handle, NULL on systems without UNIX support
831 struct GNUNET_CONNECTION_Handle *
832 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
833 GNUNET_CONFIGURATION_Handle
834 *cfg, const char *unixpath)
837 struct GNUNET_CONNECTION_Handle *connection;
838 struct sockaddr_un *un;
840 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
841 un = GNUNET_new (struct sockaddr_un);
842 un->sun_family = AF_UNIX;
843 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
848 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg, "TESTING",
849 "USE_ABSTRACT_SOCKETS");
850 if (GNUNET_YES == abstract)
851 un->sun_path[0] = '\0';
854 #if HAVE_SOCKADDR_IN_SIN_LEN
855 un->sun_len = (u_char) sizeof (struct sockaddr_un);
857 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
858 connection->cfg = cfg;
859 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
860 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
861 connection->port = 0;
862 connection->hostname = NULL;
863 connection->addr = (struct sockaddr *) un;
864 connection->addrlen = sizeof (struct sockaddr_un);
865 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
866 if (NULL == connection->sock)
868 GNUNET_free (connection->addr);
869 GNUNET_free (connection->write_buffer);
870 GNUNET_free (connection);
874 GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
875 (EINPROGRESS != errno) )
877 /* Just return; we expect everything to work eventually so don't fail HARD */
878 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
879 connection->sock = NULL;
882 connect_success_continuation (connection);
891 * Create a connection handle by (asynchronously) connecting to a host.
892 * This function returns immediately, even if the connection has not
893 * yet been established. This function only creates TCP connections.
895 * @param s socket to connect
896 * @param serv_addr server address
897 * @param addrlen length of server address
898 * @return the connection handle
900 struct GNUNET_CONNECTION_Handle *
901 GNUNET_CONNECTION_connect_socket (struct GNUNET_NETWORK_Handle *s,
902 const struct sockaddr *serv_addr,
905 struct GNUNET_CONNECTION_Handle *connection;
907 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
908 (EINPROGRESS != errno))
910 /* maybe refused / unsupported address, try next */
911 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
912 LOG (GNUNET_ERROR_TYPE_INFO,
913 _("Attempt to connect to `%s' failed\n"),
914 GNUNET_a2s (serv_addr, addrlen));
915 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
918 connection = GNUNET_CONNECTION_create_from_existing (s);
919 connection->addr = GNUNET_malloc (addrlen);
920 memcpy (connection->addr, serv_addr, addrlen);
921 connection->addrlen = addrlen;
922 LOG (GNUNET_ERROR_TYPE_INFO,
923 _("Trying to connect to `%s' (%p)\n"),
924 GNUNET_a2s (serv_addr, addrlen), connection);
930 * Create a connection handle by creating a socket and
931 * (asynchronously) connecting to a host. This function returns
932 * immediately, even if the connection has not yet been established.
933 * This function only creates TCP connections.
935 * @param af_family address family to use
936 * @param serv_addr server address
937 * @param addrlen length of @a serv_addr
938 * @return the connection handle
940 struct GNUNET_CONNECTION_Handle *
941 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
942 const struct sockaddr *serv_addr,
945 struct GNUNET_NETWORK_Handle *s;
947 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
950 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
953 return GNUNET_CONNECTION_connect_socket (s, serv_addr, addrlen);
958 * Check if connection is valid (no fatal errors have happened so far).
959 * Note that a connection that is still trying to connect is considered
962 * @param connection connection to check
963 * @return #GNUNET_YES if valid, #GNUNET_NO otherwise
966 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
968 if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
969 return GNUNET_YES; /* still trying to connect */
970 return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
975 * Close the connection and free associated resources. There must
976 * not be any pending requests for reading or writing to the
977 * connection at this time.
979 * @param connection connection to destroy
982 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
984 struct AddressProbe *pos;
986 if (0 != connection->destroy_later)
988 connection->destroy_later = -1;
991 LOG (GNUNET_ERROR_TYPE_DEBUG,
992 "Shutting down connection (%p)\n",
994 GNUNET_assert (NULL == connection->nth.notify_ready);
995 GNUNET_assert (NULL == connection->receiver);
996 if (NULL != connection->write_task)
998 GNUNET_SCHEDULER_cancel (connection->write_task);
999 connection->write_task = NULL;
1000 connection->write_buffer_off = 0;
1002 if (NULL != connection->read_task)
1004 GNUNET_SCHEDULER_cancel (connection->read_task);
1005 connection->read_task = NULL;
1007 if (NULL != connection->nth.timeout_task)
1009 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1010 connection->nth.timeout_task = NULL;
1012 connection->nth.notify_ready = NULL;
1013 if (NULL != connection->dns_active)
1015 GNUNET_RESOLVER_request_cancel (connection->dns_active);
1016 connection->dns_active = NULL;
1018 while (NULL != (pos = connection->ap_head))
1020 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1021 GNUNET_SCHEDULER_cancel (pos->task);
1022 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
1025 if ( (NULL != connection->sock) &&
1026 (GNUNET_YES != connection->persist) )
1029 GNUNET_NETWORK_socket_shutdown (connection->sock,
1031 (ENOTCONN != errno) &&
1032 (ECONNRESET != errno) )
1033 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1036 if (NULL != connection->sock)
1038 if (GNUNET_YES != connection->persist)
1040 GNUNET_break (GNUNET_OK ==
1041 GNUNET_NETWORK_socket_close (connection->sock));
1045 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1046 * leak the socket in this special case) ... */
1049 GNUNET_free_non_null (connection->addr);
1050 GNUNET_free_non_null (connection->hostname);
1051 GNUNET_free (connection->write_buffer);
1052 GNUNET_free (connection);
1057 * This function is called once we either timeout
1058 * or have data ready to read.
1060 * @param cls connection to read from
1061 * @param tc scheduler context
1064 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1066 struct GNUNET_CONNECTION_Handle *connection = cls;
1067 char buffer[connection->max];
1069 GNUNET_CONNECTION_Receiver receiver;
1071 connection->read_task = NULL;
1072 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1074 /* ignore shutdown request, go again immediately */
1075 connection->read_task =
1076 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1077 (connection->receive_timeout), connection->sock,
1078 &receive_ready, connection);
1081 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1083 LOG (GNUNET_ERROR_TYPE_DEBUG,
1084 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1085 GNUNET_a2s (connection->addr, connection->addrlen),
1086 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1088 signal_receive_timeout (connection);
1091 if (NULL == connection->sock)
1093 /* connect failed for good */
1094 signal_receive_error (connection, ECONNREFUSED);
1097 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1099 ret = GNUNET_NETWORK_socket_recv (connection->sock,
1106 signal_receive_error (connection, errno);
1109 LOG (GNUNET_ERROR_TYPE_DEBUG,
1110 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1113 GNUNET_a2s (connection->addr,
1114 connection->addrlen),
1116 GNUNET_assert (NULL != (receiver = connection->receiver));
1117 connection->receiver = NULL;
1118 receiver (connection->receiver_cls,
1122 connection->addrlen,
1128 * Receive data from the given connection. Note that this function will
1129 * call "receiver" asynchronously using the scheduler. It will
1130 * "immediately" return. Note that there MUST only be one active
1131 * receive call per connection at any given point in time (so do not
1132 * call receive again until the receiver callback has been invoked).
1134 * @param connection connection handle
1135 * @param max maximum number of bytes to read
1136 * @param timeout maximum amount of time to wait
1137 * @param receiver function to call with received data
1138 * @param receiver_cls closure for receiver
1141 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1142 struct GNUNET_TIME_Relative timeout,
1143 GNUNET_CONNECTION_Receiver receiver,
1146 GNUNET_assert ((NULL == connection->read_task) &&
1147 (NULL == connection->receiver));
1148 GNUNET_assert (NULL != receiver);
1149 connection->receiver = receiver;
1150 connection->receiver_cls = receiver_cls;
1151 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1152 connection->max = max;
1153 if (NULL != connection->sock)
1155 connection->read_task =
1156 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1157 (connection->receive_timeout), connection->sock,
1158 &receive_ready, connection);
1161 if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1163 connection->receiver = NULL;
1164 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1171 * Cancel receive job on the given connection. Note that the
1172 * receiver callback must not have been called yet in order
1173 * for the cancellation to be valid.
1175 * @param connection connection handle
1176 * @return closure of the original receiver callback closure
1179 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1181 if (NULL != connection->read_task)
1183 GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1184 connection->read_task = NULL;
1186 connection->receiver = NULL;
1187 return connection->receiver_cls;
1192 * Try to call the transmit notify method (check if we do
1193 * have enough space available first)!
1195 * @param connection connection for which we should do this processing
1196 * @return GNUNET_YES if we were able to call notify
1199 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1204 GNUNET_CONNECTION_TransmitReadyNotify notify;
1206 LOG (GNUNET_ERROR_TYPE_DEBUG, "process_notify is running\n");
1208 GNUNET_assert (NULL == connection->write_task);
1209 if (NULL == (notify = connection->nth.notify_ready))
1211 LOG (GNUNET_ERROR_TYPE_DEBUG, "Noone to notify\n");
1214 used = connection->write_buffer_off - connection->write_buffer_pos;
1215 avail = connection->write_buffer_size - used;
1216 size = connection->nth.notify_size;
1219 LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough buffer\n");
1222 connection->nth.notify_ready = NULL;
1223 if (connection->write_buffer_size - connection->write_buffer_off < size)
1225 /* need to compact */
1226 memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1228 connection->write_buffer_off -= connection->write_buffer_pos;
1229 connection->write_buffer_pos = 0;
1231 avail = connection->write_buffer_size - connection->write_buffer_off;
1232 GNUNET_assert (avail >= size);
1234 notify (connection->nth.notify_ready_cls, avail,
1235 &connection->write_buffer[connection->write_buffer_off]);
1236 GNUNET_assert (size <= avail);
1238 connection->write_buffer_off += size;
1244 * Task invoked by the scheduler when a call to transmit
1245 * is timing out (we never got enough buffer space to call
1246 * the callback function before the specified timeout
1249 * This task notifies the client about the timeout.
1251 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1252 * @param tc scheduler context
1255 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1257 struct GNUNET_CONNECTION_Handle *connection = cls;
1258 GNUNET_CONNECTION_TransmitReadyNotify notify;
1260 connection->nth.timeout_task = NULL;
1261 LOG (GNUNET_ERROR_TYPE_DEBUG,
1262 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1263 connection->hostname,
1264 connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1265 notify = connection->nth.notify_ready;
1266 GNUNET_assert (NULL != notify);
1267 connection->nth.notify_ready = NULL;
1268 notify (connection->nth.notify_ready_cls, 0, NULL);
1273 * Task invoked by the scheduler when we failed to connect
1274 * at the time of being asked to transmit.
1276 * This task notifies the client about the error.
1278 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1279 * @param tc scheduler context
1282 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1284 struct GNUNET_CONNECTION_Handle *connection = cls;
1285 GNUNET_CONNECTION_TransmitReadyNotify notify;
1287 LOG (GNUNET_ERROR_TYPE_DEBUG,
1288 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1289 connection->nth.notify_size, connection->hostname, connection->port, connection);
1290 connection->write_task = NULL;
1291 notify = connection->nth.notify_ready;
1292 connection->nth.notify_ready = NULL;
1293 notify (connection->nth.notify_ready_cls, 0, NULL);
1298 * We are ready to transmit (or got a timeout).
1300 * @param cls our connection handle
1301 * @param tc task context describing why we are here
1304 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1306 struct GNUNET_CONNECTION_Handle *connection = cls;
1307 GNUNET_CONNECTION_TransmitReadyNotify notify;
1311 LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1312 GNUNET_assert (NULL != connection->write_task);
1313 connection->write_task = NULL;
1314 GNUNET_assert (NULL == connection->nth.timeout_task);
1315 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1317 if (NULL != connection->sock)
1318 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1319 LOG (GNUNET_ERROR_TYPE_DEBUG,
1320 "Transmit to `%s' fails, shutdown happened (%p).\n",
1321 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1322 notify = connection->nth.notify_ready;
1325 connection->nth.notify_ready = NULL;
1326 notify (connection->nth.notify_ready_cls, 0, NULL);
1330 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1332 LOG (GNUNET_ERROR_TYPE_DEBUG,
1333 "Transmit to `%s' fails, time out reached (%p).\n",
1334 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1335 notify = connection->nth.notify_ready;
1336 GNUNET_assert (NULL != notify);
1337 connection->nth.notify_ready = NULL;
1338 notify (connection->nth.notify_ready_cls, 0, NULL);
1341 GNUNET_assert (NULL != connection->sock);
1342 if (NULL == tc->write_ready)
1344 /* special circumstances (in particular, PREREQ_DONE after
1345 * connect): not yet ready to write, but no "fatal" error either.
1347 goto SCHEDULE_WRITE;
1349 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1351 GNUNET_assert (NULL == connection->write_task);
1352 /* special circumstances (in particular, shutdown): not yet ready
1353 * to write, but no "fatal" error either. Hence retry. */
1354 goto SCHEDULE_WRITE;
1356 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1357 if ((NULL != connection->nth.notify_ready) &&
1358 (connection->write_buffer_size < connection->nth.notify_size))
1360 connection->write_buffer =
1361 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1362 connection->write_buffer_size = connection->nth.notify_size;
1364 process_notify (connection);
1365 have = connection->write_buffer_off - connection->write_buffer_pos;
1368 /* no data ready for writing, terminate write loop */
1371 GNUNET_assert (have <= connection->write_buffer_size);
1372 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1373 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1376 GNUNET_NETWORK_socket_send (connection->sock,
1377 &connection->write_buffer[connection->write_buffer_pos],
1383 if (NULL != connection->write_task)
1385 GNUNET_SCHEDULER_cancel (connection->write_task);
1386 connection->write_task = NULL;
1388 signal_transmit_error (connection, errno);
1391 LOG (GNUNET_ERROR_TYPE_DEBUG,
1392 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1393 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1394 connection->write_buffer_pos += ret;
1395 if (connection->write_buffer_pos == connection->write_buffer_off)
1397 /* transmitted all pending data */
1398 connection->write_buffer_pos = 0;
1399 connection->write_buffer_off = 0;
1401 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1402 return; /* all data sent! */
1403 /* not done writing, schedule more */
1405 LOG (GNUNET_ERROR_TYPE_DEBUG,
1406 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1407 have = connection->write_buffer_off - connection->write_buffer_pos;
1408 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1409 if (NULL == connection->write_task)
1410 connection->write_task =
1411 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1412 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1413 GNUNET_TIME_absolute_get_remaining
1414 (connection->nth.transmit_timeout),
1415 connection->sock, &transmit_ready, connection);
1420 * Ask the connection to call us once the specified number of bytes
1421 * are free in the transmission buffer. Will never call the @a notify
1422 * callback in this task, but always first go into the scheduler.
1424 * @param connection connection
1425 * @param size number of bytes to send
1426 * @param timeout after how long should we give up (and call
1427 * notify with buf NULL and size 0)?
1428 * @param notify function to call
1429 * @param notify_cls closure for @a notify
1430 * @return non-NULL if the notify callback was queued,
1431 * NULL if we are already going to notify someone else (busy)
1433 struct GNUNET_CONNECTION_TransmitHandle *
1434 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1436 struct GNUNET_TIME_Relative timeout,
1437 GNUNET_CONNECTION_TransmitReadyNotify
1438 notify, void *notify_cls)
1440 if (NULL != connection->nth.notify_ready)
1445 GNUNET_assert (NULL != notify);
1446 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1447 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1448 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1449 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1450 connection->nth.notify_ready = notify;
1451 connection->nth.notify_ready_cls = notify_cls;
1452 connection->nth.connection = connection;
1453 connection->nth.notify_size = size;
1454 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1455 GNUNET_assert (NULL == connection->nth.timeout_task);
1456 if ((NULL == connection->sock) &&
1457 (NULL == connection->ap_head) &&
1458 (NULL == connection->dns_active))
1460 if (NULL != connection->write_task)
1461 GNUNET_SCHEDULER_cancel (connection->write_task);
1462 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error,
1464 return &connection->nth;
1466 if (NULL != connection->write_task)
1467 return &connection->nth; /* previous transmission still in progress */
1468 if (NULL != connection->sock)
1470 /* connected, try to transmit now */
1471 LOG (GNUNET_ERROR_TYPE_DEBUG,
1472 "Scheduling transmission (%p).\n",
1474 connection->write_task =
1475 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1476 (connection->nth.transmit_timeout),
1477 connection->sock, &transmit_ready, connection);
1478 return &connection->nth;
1480 /* not yet connected, wait for connection */
1481 LOG (GNUNET_ERROR_TYPE_DEBUG,
1482 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n",
1484 connection->nth.timeout_task =
1485 GNUNET_SCHEDULER_add_delayed (timeout,
1486 &transmit_timeout, connection);
1487 return &connection->nth;
1492 * Cancel the specified transmission-ready notification.
1494 * @param th notification to cancel
1497 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1498 GNUNET_CONNECTION_TransmitHandle
1501 GNUNET_assert (NULL != th->notify_ready);
1502 th->notify_ready = NULL;
1503 if (NULL != th->timeout_task)
1505 GNUNET_SCHEDULER_cancel (th->timeout_task);
1506 th->timeout_task = NULL;
1508 if (NULL != th->connection->write_task)
1510 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1511 th->connection->write_task = NULL;
1515 /* end of connection.c */