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;
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);
346 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
349 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
352 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
356 sa = (struct sockaddr *) addr;
357 v6 = (struct sockaddr_in6 *) addr;
358 if ((AF_INET6 == sa->sa_family) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
360 /* convert to V4 address */
361 v4 = GNUNET_new (struct sockaddr_in);
362 memset (v4, 0, sizeof (struct sockaddr_in));
363 v4->sin_family = AF_INET;
364 #if HAVE_SOCKADDR_IN_SIN_LEN
365 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
367 memcpy (&v4->sin_addr,
368 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
369 sizeof (struct in_addr)],
370 sizeof (struct in_addr));
371 v4->sin_port = v6->sin6_port;
373 addrlen = sizeof (struct sockaddr_in);
377 uaddr = GNUNET_malloc (addrlen);
378 memcpy (uaddr, addr, addrlen);
383 if (AF_UNIX == sa->sa_family)
387 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock), &gc.uid, &gc.gid))
391 /* largely traditional GNU/Linux */
394 getsockopt (GNUNET_NETWORK_get_fd (sock), SOL_SOCKET, SO_PEERCRED, &uc,
395 &olen)) && (olen == sizeof (uc)))
402 #if HAVE_GETPEERUCRED
403 /* this is for Solaris 10 */
407 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
409 gc.uid = ucred_geteuid (uc);
410 gc.gid = ucred_getegid (uc);
419 if ((NULL != access_cb) &&
420 (GNUNET_YES != (aret = access_cb (access_cb_cls, gcp, uaddr, addrlen))))
422 if (GNUNET_NO == aret)
423 LOG (GNUNET_ERROR_TYPE_INFO,
424 _("Access denied to `%s'\n"),
427 GNUNET_break (GNUNET_OK ==
428 GNUNET_NETWORK_socket_shutdown (sock,
430 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
434 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
435 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
436 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
437 connection->addr = uaddr;
438 connection->addrlen = addrlen;
439 connection->sock = sock;
440 LOG (GNUNET_ERROR_TYPE_INFO,
441 _("Accepting connection from `%s': %p\n"),
442 GNUNET_a2s (uaddr, addrlen), connection);
448 * Obtain the network address of the other party.
450 * @param connection the client to get the address for
451 * @param addr where to store the address
452 * @param addrlen where to store the length of the @a addr
453 * @return #GNUNET_OK on success
456 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
460 if ((NULL == connection->addr) || (0 == connection->addrlen))
462 *addr = GNUNET_malloc (connection->addrlen);
463 memcpy (*addr, connection->addr, connection->addrlen);
464 *addrlen = connection->addrlen;
470 * Tell the receiver callback that we had an IO error.
472 * @param connection connection to signal error
473 * @param errcode error code to send
476 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection,
479 GNUNET_CONNECTION_Receiver receiver;
481 LOG (GNUNET_ERROR_TYPE_DEBUG,
482 "Receive encounters error (%s), connection closed (%p)\n",
485 GNUNET_assert (NULL != (receiver = connection->receiver));
486 connection->receiver = NULL;
487 receiver (connection->receiver_cls,
497 * Tell the receiver callback that a timeout was reached.
499 * @param connection connection to signal for
502 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
504 GNUNET_CONNECTION_Receiver receiver;
506 LOG (GNUNET_ERROR_TYPE_DEBUG,
507 "Connection signals timeout to receiver (%p)!\n",
509 GNUNET_assert (NULL != (receiver = connection->receiver));
510 connection->receiver = NULL;
511 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
516 * We failed to transmit data to the service, signal the error.
518 * @param connection handle that had trouble
519 * @param ecode error code (errno)
522 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
525 GNUNET_CONNECTION_TransmitReadyNotify notify;
527 LOG (GNUNET_ERROR_TYPE_DEBUG,
528 "Transmission encounterd error (%s), connection closed (%p)\n",
531 if (NULL != connection->sock)
533 (void) GNUNET_NETWORK_socket_shutdown (connection->sock,
535 GNUNET_break (GNUNET_OK ==
536 GNUNET_NETWORK_socket_close (connection->sock));
537 connection->sock = NULL;
538 GNUNET_assert (NULL == connection->write_task);
540 if (NULL != connection->read_task)
542 /* send errors trigger read errors... */
543 GNUNET_SCHEDULER_cancel (connection->read_task);
544 connection->read_task = NULL;
545 signal_receive_timeout (connection);
548 if (NULL == connection->nth.notify_ready)
549 return; /* nobody to tell about it */
550 notify = connection->nth.notify_ready;
551 connection->nth.notify_ready = NULL;
552 notify (connection->nth.notify_ready_cls, 0, NULL);
557 * We've failed for good to establish a connection (timeout or
558 * no more addresses to try).
560 * @param connection the connection we tried to establish
563 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
565 LOG (GNUNET_ERROR_TYPE_INFO,
566 "Failed to establish TCP connection to `%s:%u', no further addresses to try.\n",
567 connection->hostname,
569 GNUNET_break (NULL == connection->ap_head);
570 GNUNET_break (NULL == connection->ap_tail);
571 GNUNET_break (GNUNET_NO == connection->dns_active);
572 GNUNET_break (NULL == connection->sock);
573 GNUNET_assert (NULL == connection->write_task);
575 /* signal errors for jobs that used to wait on the connection */
576 connection->destroy_later = 1;
577 if (NULL != connection->receiver)
578 signal_receive_error (connection,
580 if (NULL != connection->nth.notify_ready)
582 GNUNET_assert (NULL != connection->nth.timeout_task);
583 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
584 connection->nth.timeout_task = NULL;
585 signal_transmit_error (connection,
588 if (-1 == connection->destroy_later)
591 connection->destroy_later = 0;
592 GNUNET_CONNECTION_destroy (connection);
595 connection->destroy_later = 0;
600 * We are ready to transmit (or got a timeout).
602 * @param cls our connection handle
603 * @param tc task context describing why we are here
606 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
610 * This function is called once we either timeout or have data ready
613 * @param cls connection to read from
614 * @param tc scheduler context
617 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
621 * We've succeeded in establishing a connection.
623 * @param connection the connection we tried to establish
626 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
628 LOG (GNUNET_ERROR_TYPE_DEBUG,
629 "Connection to `%s' succeeded! (%p)\n",
630 GNUNET_a2s (connection->addr, connection->addrlen),
632 /* trigger jobs that waited for the connection */
633 if (NULL != connection->receiver)
635 LOG (GNUNET_ERROR_TYPE_DEBUG,
636 "Connection succeeded, starting with receiving data (%p)\n",
638 GNUNET_assert (NULL == connection->read_task);
639 connection->read_task =
640 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
641 (connection->receive_timeout), connection->sock,
642 &receive_ready, connection);
644 if (NULL != connection->nth.notify_ready)
646 LOG (GNUNET_ERROR_TYPE_DEBUG,
647 "Connection succeeded, starting with sending data (%p)\n",
649 GNUNET_assert (connection->nth.timeout_task != NULL);
650 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
651 connection->nth.timeout_task = NULL;
652 GNUNET_assert (connection->write_task == NULL);
653 connection->write_task =
654 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
655 (connection->nth.transmit_timeout), connection->sock,
656 &transmit_ready, connection);
662 * Scheduler let us know that we're either ready to write on the
663 * socket OR connect timed out. Do the right thing.
665 * @param cls the "struct AddressProbe*" with the address that we are probing
666 * @param tc success or failure info about the connect attempt.
669 connect_probe_continuation (void *cls,
670 const struct GNUNET_SCHEDULER_TaskContext *tc)
672 struct AddressProbe *ap = cls;
673 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
674 struct AddressProbe *pos;
678 GNUNET_assert (NULL != ap->sock);
679 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
680 len = sizeof (error);
683 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
685 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
686 &len)) || (0 != error))
688 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
690 if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
691 connect_fail_continuation (connection);
694 GNUNET_assert (NULL == connection->sock);
695 connection->sock = ap->sock;
696 GNUNET_assert (NULL == connection->addr);
697 connection->addr = GNUNET_malloc (ap->addrlen);
698 memcpy (connection->addr, ap->addr, ap->addrlen);
699 connection->addrlen = ap->addrlen;
701 /* cancel all other attempts */
702 while (NULL != (pos = connection->ap_head))
704 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
705 GNUNET_SCHEDULER_cancel (pos->task);
706 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
709 connect_success_continuation (connection);
714 * Try to establish a connection given the specified address.
715 * This function is called by the resolver once we have a DNS reply.
717 * @param cls our `struct GNUNET_CONNECTION_Handle *`
718 * @param addr address to try, NULL for "last call"
719 * @param addrlen length of @a addr
722 try_connect_using_address (void *cls,
723 const struct sockaddr *addr,
726 struct GNUNET_CONNECTION_Handle *connection = cls;
727 struct AddressProbe *ap;
728 struct GNUNET_TIME_Relative delay;
732 connection->dns_active = NULL;
733 if ((NULL == connection->ap_head) && (NULL == connection->sock))
734 connect_fail_continuation (connection);
737 if (NULL != connection->sock)
738 return; /* already connected */
739 GNUNET_assert (NULL == connection->addr);
741 LOG (GNUNET_ERROR_TYPE_DEBUG,
742 "Trying to connect using address `%s:%u/%s:%u'\n",
743 connection->hostname,
745 GNUNET_a2s (addr, addrlen),
747 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
748 ap->addr = (const struct sockaddr *) &ap[1];
749 memcpy (&ap[1], addr, addrlen);
750 ap->addrlen = addrlen;
751 ap->connection = connection;
753 switch (ap->addr->sa_family)
756 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
759 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
764 return; /* not supported by us */
766 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
767 if (NULL == ap->sock)
770 return; /* not supported by OS */
772 LOG (GNUNET_ERROR_TYPE_INFO,
773 "Trying to connect to `%s' (%p)\n",
774 GNUNET_a2s (ap->addr, ap->addrlen),
777 GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
778 (EINPROGRESS != errno))
780 /* maybe refused / unsupported address, try next */
781 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
782 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
786 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
787 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
788 if (NULL != connection->nth.notify_ready)
790 GNUNET_TIME_relative_min (delay,
791 GNUNET_TIME_absolute_get_remaining (connection->
792 nth.transmit_timeout));
793 if (NULL != connection->receiver)
795 GNUNET_TIME_relative_min (delay,
796 GNUNET_TIME_absolute_get_remaining
797 (connection->receive_timeout));
799 GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
800 &connect_probe_continuation, ap);
805 * Create a connection handle by (asynchronously) connecting to a host.
806 * This function returns immediately, even if the connection has not
807 * yet been established. This function only creates TCP connections.
809 * @param cfg configuration to use
810 * @param hostname name of the host to connect to
811 * @param port port to connect to
812 * @return the connection handle
814 struct GNUNET_CONNECTION_Handle *
815 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
816 const char *hostname,
819 struct GNUNET_CONNECTION_Handle *connection;
821 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
822 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
823 connection->cfg = cfg;
824 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
825 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
826 connection->port = port;
827 connection->hostname = GNUNET_strdup (hostname);
828 connection->dns_active =
829 GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
830 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
831 &try_connect_using_address, connection);
837 * Create a connection handle by connecting to a UNIX domain service.
838 * This function returns immediately, even if the connection has not
839 * yet been established. This function only creates UNIX connections.
841 * @param cfg configuration to use
842 * @param unixpath path to connect to
843 * @return the connection handle, NULL on systems without UNIX support
845 struct GNUNET_CONNECTION_Handle *
846 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct GNUNET_CONFIGURATION_Handle *cfg,
847 const char *unixpath)
850 struct GNUNET_CONNECTION_Handle *connection;
851 struct sockaddr_un *un;
853 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
854 un = GNUNET_new (struct sockaddr_un);
855 un->sun_family = AF_UNIX;
856 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
861 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg, "TESTING",
862 "USE_ABSTRACT_SOCKETS");
863 if (GNUNET_YES == abstract)
864 un->sun_path[0] = '\0';
867 #if HAVE_SOCKADDR_IN_SIN_LEN
868 un->sun_len = (u_char) sizeof (struct sockaddr_un);
870 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
871 connection->cfg = cfg;
872 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
873 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
874 connection->port = 0;
875 connection->hostname = NULL;
876 connection->addr = (struct sockaddr *) un;
877 connection->addrlen = sizeof (struct sockaddr_un);
878 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
879 if (NULL == connection->sock)
881 GNUNET_free (connection->addr);
882 GNUNET_free (connection->write_buffer);
883 GNUNET_free (connection);
887 GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
888 (EINPROGRESS != errno) )
890 /* Just return; we expect everything to work eventually so don't fail HARD */
891 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
892 connection->sock = NULL;
895 connect_success_continuation (connection);
904 * Create a connection handle by (asynchronously) connecting to a host.
905 * This function returns immediately, even if the connection has not
906 * yet been established. This function only creates TCP connections.
908 * @param s socket to connect
909 * @param serv_addr server address
910 * @param addrlen length of @a serv_addr
911 * @return the connection handle
913 struct GNUNET_CONNECTION_Handle *
914 GNUNET_CONNECTION_connect_socket (struct GNUNET_NETWORK_Handle *s,
915 const struct sockaddr *serv_addr,
918 struct GNUNET_CONNECTION_Handle *connection;
921 GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
922 (EINPROGRESS != errno) )
924 /* maybe refused / unsupported address, try next */
925 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
927 LOG (GNUNET_ERROR_TYPE_DEBUG,
928 "Attempt to connect to `%s' failed\n",
929 GNUNET_a2s (serv_addr,
931 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
934 connection = GNUNET_CONNECTION_create_from_existing (s);
935 connection->addr = GNUNET_malloc (addrlen);
936 memcpy (connection->addr, serv_addr, addrlen);
937 connection->addrlen = addrlen;
938 LOG (GNUNET_ERROR_TYPE_INFO,
939 "Trying to connect to `%s' (%p)\n",
940 GNUNET_a2s (serv_addr, addrlen),
947 * Create a connection handle by creating a socket and
948 * (asynchronously) connecting to a host. This function returns
949 * immediately, even if the connection has not yet been established.
950 * This function only creates TCP connections.
952 * @param af_family address family to use
953 * @param serv_addr server address
954 * @param addrlen length of @a serv_addr
955 * @return the connection handle
957 struct GNUNET_CONNECTION_Handle *
958 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
959 const struct sockaddr *serv_addr,
962 struct GNUNET_NETWORK_Handle *s;
964 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
967 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
970 return GNUNET_CONNECTION_connect_socket (s, serv_addr, addrlen);
975 * Check if connection is valid (no fatal errors have happened so far).
976 * Note that a connection that is still trying to connect is considered
979 * @param connection connection to check
980 * @return #GNUNET_YES if valid, #GNUNET_NO otherwise
983 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
985 if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
986 return GNUNET_YES; /* still trying to connect */
987 if ( (0 != connection->destroy_later) ||
988 (NULL == connection->sock) )
995 * Close the connection and free associated resources. There must
996 * not be any pending requests for reading or writing to the
997 * connection at this time.
999 * @param connection connection to destroy
1002 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
1004 struct AddressProbe *pos;
1006 if (0 != connection->destroy_later)
1008 connection->destroy_later = -1;
1011 LOG (GNUNET_ERROR_TYPE_DEBUG,
1012 "Shutting down connection (%p)\n",
1014 GNUNET_assert (NULL == connection->nth.notify_ready);
1015 GNUNET_assert (NULL == connection->receiver);
1016 if (NULL != connection->write_task)
1018 GNUNET_SCHEDULER_cancel (connection->write_task);
1019 connection->write_task = NULL;
1020 connection->write_buffer_off = 0;
1022 if (NULL != connection->read_task)
1024 GNUNET_SCHEDULER_cancel (connection->read_task);
1025 connection->read_task = NULL;
1027 if (NULL != connection->nth.timeout_task)
1029 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1030 connection->nth.timeout_task = NULL;
1032 connection->nth.notify_ready = NULL;
1033 if (NULL != connection->dns_active)
1035 GNUNET_RESOLVER_request_cancel (connection->dns_active);
1036 connection->dns_active = NULL;
1038 while (NULL != (pos = connection->ap_head))
1040 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1041 GNUNET_SCHEDULER_cancel (pos->task);
1042 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
1045 if ( (NULL != connection->sock) &&
1046 (GNUNET_YES != connection->persist) )
1049 GNUNET_NETWORK_socket_shutdown (connection->sock,
1051 (ENOTCONN != errno) &&
1052 (ECONNRESET != errno) )
1053 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1056 if (NULL != connection->sock)
1058 if (GNUNET_YES != connection->persist)
1060 GNUNET_break (GNUNET_OK ==
1061 GNUNET_NETWORK_socket_close (connection->sock));
1065 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1066 * leak the socket in this special case) ... */
1069 GNUNET_free_non_null (connection->addr);
1070 GNUNET_free_non_null (connection->hostname);
1071 GNUNET_free (connection->write_buffer);
1072 GNUNET_free (connection);
1077 * This function is called once we either timeout
1078 * or have data ready to read.
1080 * @param cls connection to read from
1081 * @param tc scheduler context
1084 receive_ready (void *cls,
1085 const struct GNUNET_SCHEDULER_TaskContext *tc)
1087 struct GNUNET_CONNECTION_Handle *connection = cls;
1088 char buffer[connection->max];
1090 GNUNET_CONNECTION_Receiver receiver;
1092 connection->read_task = NULL;
1093 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1095 /* ignore shutdown request, go again immediately */
1096 connection->read_task =
1097 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1098 (connection->receive_timeout), connection->sock,
1099 &receive_ready, connection);
1102 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1104 LOG (GNUNET_ERROR_TYPE_DEBUG,
1105 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1106 GNUNET_a2s (connection->addr, connection->addrlen),
1107 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1109 signal_receive_timeout (connection);
1112 if (NULL == connection->sock)
1114 /* connect failed for good */
1115 signal_receive_error (connection, ECONNREFUSED);
1118 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1120 ret = GNUNET_NETWORK_socket_recv (connection->sock,
1127 signal_receive_error (connection, errno);
1130 LOG (GNUNET_ERROR_TYPE_DEBUG,
1131 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1134 GNUNET_a2s (connection->addr,
1135 connection->addrlen),
1137 GNUNET_assert (NULL != (receiver = connection->receiver));
1138 connection->receiver = NULL;
1139 receiver (connection->receiver_cls,
1143 connection->addrlen,
1149 * Receive data from the given connection. Note that this function will
1150 * call @a receiver asynchronously using the scheduler. It will
1151 * "immediately" return. Note that there MUST only be one active
1152 * receive call per connection at any given point in time (so do not
1153 * call receive again until the receiver callback has been invoked).
1155 * @param connection connection handle
1156 * @param max maximum number of bytes to read
1157 * @param timeout maximum amount of time to wait
1158 * @param receiver function to call with received data
1159 * @param receiver_cls closure for @a receiver
1162 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection,
1164 struct GNUNET_TIME_Relative timeout,
1165 GNUNET_CONNECTION_Receiver receiver,
1168 GNUNET_assert ((NULL == connection->read_task) &&
1169 (NULL == connection->receiver));
1170 GNUNET_assert (NULL != receiver);
1171 connection->receiver = receiver;
1172 connection->receiver_cls = receiver_cls;
1173 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1174 connection->max = max;
1175 if (NULL != connection->sock)
1177 connection->read_task =
1178 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1179 (connection->receive_timeout),
1185 if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1187 connection->receiver = NULL;
1188 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1195 * Cancel receive job on the given connection. Note that the
1196 * receiver callback must not have been called yet in order
1197 * for the cancellation to be valid.
1199 * @param connection connection handle
1200 * @return closure of the original receiver callback closure
1203 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1205 if (NULL != connection->read_task)
1207 GNUNET_assert (connection ==
1208 GNUNET_SCHEDULER_cancel (connection->read_task));
1209 connection->read_task = NULL;
1211 connection->receiver = NULL;
1212 return connection->receiver_cls;
1217 * Try to call the transmit notify method (check if we do
1218 * have enough space available first)!
1220 * @param connection connection for which we should do this processing
1221 * @return #GNUNET_YES if we were able to call notify
1224 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1229 GNUNET_CONNECTION_TransmitReadyNotify notify;
1231 LOG (GNUNET_ERROR_TYPE_DEBUG,
1232 "process_notify is running\n");
1233 GNUNET_assert (NULL == connection->write_task);
1234 if (NULL == (notify = connection->nth.notify_ready))
1236 LOG (GNUNET_ERROR_TYPE_DEBUG,
1237 "No one to notify\n");
1240 used = connection->write_buffer_off - connection->write_buffer_pos;
1241 avail = connection->write_buffer_size - used;
1242 size = connection->nth.notify_size;
1245 LOG (GNUNET_ERROR_TYPE_DEBUG,
1246 "Not enough buffer\n");
1249 connection->nth.notify_ready = NULL;
1250 if (connection->write_buffer_size - connection->write_buffer_off < size)
1252 /* need to compact */
1253 memmove (connection->write_buffer,
1254 &connection->write_buffer[connection->write_buffer_pos],
1256 connection->write_buffer_off -= connection->write_buffer_pos;
1257 connection->write_buffer_pos = 0;
1259 avail = connection->write_buffer_size - connection->write_buffer_off;
1260 GNUNET_assert (avail >= size);
1262 notify (connection->nth.notify_ready_cls, avail,
1263 &connection->write_buffer[connection->write_buffer_off]);
1264 GNUNET_assert (size <= avail);
1266 connection->write_buffer_off += size;
1272 * Task invoked by the scheduler when a call to transmit
1273 * is timing out (we never got enough buffer space to call
1274 * the callback function before the specified timeout
1277 * This task notifies the client about the timeout.
1279 * @param cls the `struct GNUNET_CONNECTION_Handle`
1280 * @param tc scheduler context
1283 transmit_timeout (void *cls,
1284 const struct GNUNET_SCHEDULER_TaskContext *tc)
1286 struct GNUNET_CONNECTION_Handle *connection = cls;
1287 GNUNET_CONNECTION_TransmitReadyNotify notify;
1289 connection->nth.timeout_task = NULL;
1290 LOG (GNUNET_ERROR_TYPE_DEBUG,
1291 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1292 connection->hostname,
1294 GNUNET_a2s (connection->addr,
1295 connection->addrlen),
1297 notify = connection->nth.notify_ready;
1298 GNUNET_assert (NULL != notify);
1299 connection->nth.notify_ready = NULL;
1300 notify (connection->nth.notify_ready_cls, 0, NULL);
1305 * Task invoked by the scheduler when we failed to connect
1306 * at the time of being asked to transmit.
1308 * This task notifies the client about the error.
1310 * @param cls the `struct GNUNET_CONNECTION_Handle`
1311 * @param tc scheduler context
1314 connect_error (void *cls,
1315 const struct GNUNET_SCHEDULER_TaskContext *tc)
1317 struct GNUNET_CONNECTION_Handle *connection = cls;
1318 GNUNET_CONNECTION_TransmitReadyNotify notify;
1320 LOG (GNUNET_ERROR_TYPE_DEBUG,
1321 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1322 connection->nth.notify_size,
1323 connection->hostname,
1326 connection->write_task = NULL;
1327 notify = connection->nth.notify_ready;
1328 connection->nth.notify_ready = NULL;
1329 notify (connection->nth.notify_ready_cls, 0, NULL);
1334 * We are ready to transmit (or got a timeout).
1336 * @param cls our connection handle
1337 * @param tc task context describing why we are here
1340 transmit_ready (void *cls,
1341 const struct GNUNET_SCHEDULER_TaskContext *tc)
1343 struct GNUNET_CONNECTION_Handle *connection = cls;
1344 GNUNET_CONNECTION_TransmitReadyNotify notify;
1348 LOG (GNUNET_ERROR_TYPE_DEBUG,
1349 "transmit_ready running (%p).\n",
1351 GNUNET_assert (NULL != connection->write_task);
1352 connection->write_task = NULL;
1353 GNUNET_assert (NULL == connection->nth.timeout_task);
1354 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1356 if (NULL != connection->sock)
1357 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1358 LOG (GNUNET_ERROR_TYPE_DEBUG,
1359 "Transmit to `%s' fails, shutdown happened (%p).\n",
1360 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1361 notify = connection->nth.notify_ready;
1364 connection->nth.notify_ready = NULL;
1365 notify (connection->nth.notify_ready_cls, 0, NULL);
1369 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1371 LOG (GNUNET_ERROR_TYPE_DEBUG,
1372 "Transmit to `%s' fails, time out reached (%p).\n",
1373 GNUNET_a2s (connection->addr,
1374 connection->addrlen),
1376 notify = connection->nth.notify_ready;
1377 GNUNET_assert (NULL != notify);
1378 connection->nth.notify_ready = NULL;
1379 notify (connection->nth.notify_ready_cls, 0, NULL);
1382 GNUNET_assert (NULL != connection->sock);
1383 if (NULL == tc->write_ready)
1385 /* special circumstances (in particular, PREREQ_DONE after
1386 * connect): not yet ready to write, but no "fatal" error either.
1388 goto SCHEDULE_WRITE;
1390 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1392 GNUNET_assert (NULL == connection->write_task);
1393 /* special circumstances (in particular, shutdown): not yet ready
1394 * to write, but no "fatal" error either. Hence retry. */
1395 goto SCHEDULE_WRITE;
1397 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1398 if ((NULL != connection->nth.notify_ready) &&
1399 (connection->write_buffer_size < connection->nth.notify_size))
1401 connection->write_buffer =
1402 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1403 connection->write_buffer_size = connection->nth.notify_size;
1405 process_notify (connection);
1406 have = connection->write_buffer_off - connection->write_buffer_pos;
1409 /* no data ready for writing, terminate write loop */
1412 GNUNET_assert (have <= connection->write_buffer_size);
1413 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1414 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1417 GNUNET_NETWORK_socket_send (connection->sock,
1418 &connection->write_buffer[connection->write_buffer_pos],
1424 if (NULL != connection->write_task)
1426 GNUNET_SCHEDULER_cancel (connection->write_task);
1427 connection->write_task = NULL;
1429 signal_transmit_error (connection, errno);
1432 LOG (GNUNET_ERROR_TYPE_DEBUG,
1433 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1434 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1435 connection->write_buffer_pos += ret;
1436 if (connection->write_buffer_pos == connection->write_buffer_off)
1438 /* transmitted all pending data */
1439 connection->write_buffer_pos = 0;
1440 connection->write_buffer_off = 0;
1442 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1443 return; /* all data sent! */
1444 /* not done writing, schedule more */
1446 LOG (GNUNET_ERROR_TYPE_DEBUG,
1447 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1448 have = connection->write_buffer_off - connection->write_buffer_pos;
1449 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1450 if (NULL == connection->write_task)
1451 connection->write_task =
1452 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1453 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1454 GNUNET_TIME_absolute_get_remaining
1455 (connection->nth.transmit_timeout),
1456 connection->sock, &transmit_ready, connection);
1461 * Ask the connection to call us once the specified number of bytes
1462 * are free in the transmission buffer. Will never call the @a notify
1463 * callback in this task, but always first go into the scheduler.
1465 * @param connection connection
1466 * @param size number of bytes to send
1467 * @param timeout after how long should we give up (and call
1468 * @a notify with buf NULL and size 0)?
1469 * @param notify function to call
1470 * @param notify_cls closure for @a notify
1471 * @return non-NULL if the notify callback was queued,
1472 * NULL if we are already going to notify someone else (busy)
1474 struct GNUNET_CONNECTION_TransmitHandle *
1475 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1477 struct GNUNET_TIME_Relative timeout,
1478 GNUNET_CONNECTION_TransmitReadyNotify
1479 notify, void *notify_cls)
1481 if (NULL != connection->nth.notify_ready)
1486 GNUNET_assert (NULL != notify);
1487 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1488 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1489 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1490 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1491 connection->nth.notify_ready = notify;
1492 connection->nth.notify_ready_cls = notify_cls;
1493 connection->nth.connection = connection;
1494 connection->nth.notify_size = size;
1495 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1496 GNUNET_assert (NULL == connection->nth.timeout_task);
1497 if ((NULL == connection->sock) &&
1498 (NULL == connection->ap_head) &&
1499 (NULL == connection->dns_active))
1501 if (NULL != connection->write_task)
1502 GNUNET_SCHEDULER_cancel (connection->write_task);
1503 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error,
1505 return &connection->nth;
1507 if (NULL != connection->write_task)
1508 return &connection->nth; /* previous transmission still in progress */
1509 if (NULL != connection->sock)
1511 /* connected, try to transmit now */
1512 LOG (GNUNET_ERROR_TYPE_DEBUG,
1513 "Scheduling transmission (%p).\n",
1515 connection->write_task =
1516 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1517 (connection->nth.transmit_timeout),
1518 connection->sock, &transmit_ready, connection);
1519 return &connection->nth;
1521 /* not yet connected, wait for connection */
1522 LOG (GNUNET_ERROR_TYPE_DEBUG,
1523 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n",
1525 connection->nth.timeout_task =
1526 GNUNET_SCHEDULER_add_delayed (timeout,
1527 &transmit_timeout, connection);
1528 return &connection->nth;
1533 * Cancel the specified transmission-ready notification.
1535 * @param th notification to cancel
1538 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct GNUNET_CONNECTION_TransmitHandle *th)
1540 GNUNET_assert (NULL != th->notify_ready);
1541 th->notify_ready = NULL;
1542 if (NULL != th->timeout_task)
1544 GNUNET_SCHEDULER_cancel (th->timeout_task);
1545 th->timeout_task = NULL;
1547 if (NULL != th->connection->write_task)
1549 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1550 th->connection->write_task = NULL;
1554 /* end of connection.c */