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 @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 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);
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 return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
992 * Close the connection and free associated resources. There must
993 * not be any pending requests for reading or writing to the
994 * connection at this time.
996 * @param connection connection to destroy
999 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
1001 struct AddressProbe *pos;
1003 if (0 != connection->destroy_later)
1005 connection->destroy_later = -1;
1008 LOG (GNUNET_ERROR_TYPE_DEBUG,
1009 "Shutting down connection (%p)\n",
1011 GNUNET_assert (NULL == connection->nth.notify_ready);
1012 GNUNET_assert (NULL == connection->receiver);
1013 if (NULL != connection->write_task)
1015 GNUNET_SCHEDULER_cancel (connection->write_task);
1016 connection->write_task = NULL;
1017 connection->write_buffer_off = 0;
1019 if (NULL != connection->read_task)
1021 GNUNET_SCHEDULER_cancel (connection->read_task);
1022 connection->read_task = NULL;
1024 if (NULL != connection->nth.timeout_task)
1026 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1027 connection->nth.timeout_task = NULL;
1029 connection->nth.notify_ready = NULL;
1030 if (NULL != connection->dns_active)
1032 GNUNET_RESOLVER_request_cancel (connection->dns_active);
1033 connection->dns_active = NULL;
1035 while (NULL != (pos = connection->ap_head))
1037 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1038 GNUNET_SCHEDULER_cancel (pos->task);
1039 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
1042 if ( (NULL != connection->sock) &&
1043 (GNUNET_YES != connection->persist) )
1046 GNUNET_NETWORK_socket_shutdown (connection->sock,
1048 (ENOTCONN != errno) &&
1049 (ECONNRESET != errno) )
1050 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1053 if (NULL != connection->sock)
1055 if (GNUNET_YES != connection->persist)
1057 GNUNET_break (GNUNET_OK ==
1058 GNUNET_NETWORK_socket_close (connection->sock));
1062 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1063 * leak the socket in this special case) ... */
1066 GNUNET_free_non_null (connection->addr);
1067 GNUNET_free_non_null (connection->hostname);
1068 GNUNET_free (connection->write_buffer);
1069 GNUNET_free (connection);
1074 * This function is called once we either timeout
1075 * or have data ready to read.
1077 * @param cls connection to read from
1078 * @param tc scheduler context
1081 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1083 struct GNUNET_CONNECTION_Handle *connection = cls;
1084 char buffer[connection->max];
1086 GNUNET_CONNECTION_Receiver receiver;
1088 connection->read_task = NULL;
1089 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1091 /* ignore shutdown request, go again immediately */
1092 connection->read_task =
1093 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1094 (connection->receive_timeout), connection->sock,
1095 &receive_ready, connection);
1098 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1100 LOG (GNUNET_ERROR_TYPE_DEBUG,
1101 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1102 GNUNET_a2s (connection->addr, connection->addrlen),
1103 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1105 signal_receive_timeout (connection);
1108 if (NULL == connection->sock)
1110 /* connect failed for good */
1111 signal_receive_error (connection, ECONNREFUSED);
1114 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1116 ret = GNUNET_NETWORK_socket_recv (connection->sock,
1123 signal_receive_error (connection, errno);
1126 LOG (GNUNET_ERROR_TYPE_DEBUG,
1127 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1130 GNUNET_a2s (connection->addr,
1131 connection->addrlen),
1133 GNUNET_assert (NULL != (receiver = connection->receiver));
1134 connection->receiver = NULL;
1135 receiver (connection->receiver_cls,
1139 connection->addrlen,
1145 * Receive data from the given connection. Note that this function will
1146 * call @a receiver asynchronously using the scheduler. It will
1147 * "immediately" return. Note that there MUST only be one active
1148 * receive call per connection at any given point in time (so do not
1149 * call receive again until the receiver callback has been invoked).
1151 * @param connection connection handle
1152 * @param max maximum number of bytes to read
1153 * @param timeout maximum amount of time to wait
1154 * @param receiver function to call with received data
1155 * @param receiver_cls closure for @a receiver
1158 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection,
1160 struct GNUNET_TIME_Relative timeout,
1161 GNUNET_CONNECTION_Receiver receiver,
1164 GNUNET_assert ((NULL == connection->read_task) &&
1165 (NULL == connection->receiver));
1166 GNUNET_assert (NULL != receiver);
1167 connection->receiver = receiver;
1168 connection->receiver_cls = receiver_cls;
1169 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1170 connection->max = max;
1171 if (NULL != connection->sock)
1173 connection->read_task =
1174 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1175 (connection->receive_timeout), connection->sock,
1176 &receive_ready, connection);
1179 if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1181 connection->receiver = NULL;
1182 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1189 * Cancel receive job on the given connection. Note that the
1190 * receiver callback must not have been called yet in order
1191 * for the cancellation to be valid.
1193 * @param connection connection handle
1194 * @return closure of the original receiver callback closure
1197 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1199 if (NULL != connection->read_task)
1201 GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1202 connection->read_task = NULL;
1204 connection->receiver = NULL;
1205 return connection->receiver_cls;
1210 * Try to call the transmit notify method (check if we do
1211 * have enough space available first)!
1213 * @param connection connection for which we should do this processing
1214 * @return #GNUNET_YES if we were able to call notify
1217 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1222 GNUNET_CONNECTION_TransmitReadyNotify notify;
1224 LOG (GNUNET_ERROR_TYPE_DEBUG,
1225 "process_notify is running\n");
1226 GNUNET_assert (NULL == connection->write_task);
1227 if (NULL == (notify = connection->nth.notify_ready))
1229 LOG (GNUNET_ERROR_TYPE_DEBUG,
1230 "No one to notify\n");
1233 used = connection->write_buffer_off - connection->write_buffer_pos;
1234 avail = connection->write_buffer_size - used;
1235 size = connection->nth.notify_size;
1238 LOG (GNUNET_ERROR_TYPE_DEBUG,
1239 "Not enough buffer\n");
1242 connection->nth.notify_ready = NULL;
1243 if (connection->write_buffer_size - connection->write_buffer_off < size)
1245 /* need to compact */
1246 memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1248 connection->write_buffer_off -= connection->write_buffer_pos;
1249 connection->write_buffer_pos = 0;
1251 avail = connection->write_buffer_size - connection->write_buffer_off;
1252 GNUNET_assert (avail >= size);
1254 notify (connection->nth.notify_ready_cls, avail,
1255 &connection->write_buffer[connection->write_buffer_off]);
1256 GNUNET_assert (size <= avail);
1258 connection->write_buffer_off += size;
1264 * Task invoked by the scheduler when a call to transmit
1265 * is timing out (we never got enough buffer space to call
1266 * the callback function before the specified timeout
1269 * This task notifies the client about the timeout.
1271 * @param cls the `struct GNUNET_CONNECTION_Handle`
1272 * @param tc scheduler context
1275 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1277 struct GNUNET_CONNECTION_Handle *connection = cls;
1278 GNUNET_CONNECTION_TransmitReadyNotify notify;
1280 connection->nth.timeout_task = NULL;
1281 LOG (GNUNET_ERROR_TYPE_DEBUG,
1282 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1283 connection->hostname,
1284 connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1285 notify = connection->nth.notify_ready;
1286 GNUNET_assert (NULL != notify);
1287 connection->nth.notify_ready = NULL;
1288 notify (connection->nth.notify_ready_cls, 0, NULL);
1293 * Task invoked by the scheduler when we failed to connect
1294 * at the time of being asked to transmit.
1296 * This task notifies the client about the error.
1298 * @param cls the `struct GNUNET_CONNECTION_Handle`
1299 * @param tc scheduler context
1302 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1304 struct GNUNET_CONNECTION_Handle *connection = cls;
1305 GNUNET_CONNECTION_TransmitReadyNotify notify;
1307 LOG (GNUNET_ERROR_TYPE_DEBUG,
1308 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1309 connection->nth.notify_size, connection->hostname, connection->port, connection);
1310 connection->write_task = NULL;
1311 notify = connection->nth.notify_ready;
1312 connection->nth.notify_ready = NULL;
1313 notify (connection->nth.notify_ready_cls, 0, NULL);
1318 * We are ready to transmit (or got a timeout).
1320 * @param cls our connection handle
1321 * @param tc task context describing why we are here
1324 transmit_ready (void *cls,
1325 const struct GNUNET_SCHEDULER_TaskContext *tc)
1327 struct GNUNET_CONNECTION_Handle *connection = cls;
1328 GNUNET_CONNECTION_TransmitReadyNotify notify;
1332 LOG (GNUNET_ERROR_TYPE_DEBUG,
1333 "transmit_ready running (%p).\n",
1335 GNUNET_assert (NULL != connection->write_task);
1336 connection->write_task = NULL;
1337 GNUNET_assert (NULL == connection->nth.timeout_task);
1338 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1340 if (NULL != connection->sock)
1341 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1342 LOG (GNUNET_ERROR_TYPE_DEBUG,
1343 "Transmit to `%s' fails, shutdown happened (%p).\n",
1344 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1345 notify = connection->nth.notify_ready;
1348 connection->nth.notify_ready = NULL;
1349 notify (connection->nth.notify_ready_cls, 0, NULL);
1353 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1355 LOG (GNUNET_ERROR_TYPE_DEBUG,
1356 "Transmit to `%s' fails, time out reached (%p).\n",
1357 GNUNET_a2s (connection->addr,
1358 connection->addrlen),
1360 notify = connection->nth.notify_ready;
1361 GNUNET_assert (NULL != notify);
1362 connection->nth.notify_ready = NULL;
1363 notify (connection->nth.notify_ready_cls, 0, NULL);
1366 GNUNET_assert (NULL != connection->sock);
1367 if (NULL == tc->write_ready)
1369 /* special circumstances (in particular, PREREQ_DONE after
1370 * connect): not yet ready to write, but no "fatal" error either.
1372 goto SCHEDULE_WRITE;
1374 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1376 GNUNET_assert (NULL == connection->write_task);
1377 /* special circumstances (in particular, shutdown): not yet ready
1378 * to write, but no "fatal" error either. Hence retry. */
1379 goto SCHEDULE_WRITE;
1381 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1382 if ((NULL != connection->nth.notify_ready) &&
1383 (connection->write_buffer_size < connection->nth.notify_size))
1385 connection->write_buffer =
1386 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1387 connection->write_buffer_size = connection->nth.notify_size;
1389 process_notify (connection);
1390 have = connection->write_buffer_off - connection->write_buffer_pos;
1393 /* no data ready for writing, terminate write loop */
1396 GNUNET_assert (have <= connection->write_buffer_size);
1397 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1398 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1401 GNUNET_NETWORK_socket_send (connection->sock,
1402 &connection->write_buffer[connection->write_buffer_pos],
1408 if (NULL != connection->write_task)
1410 GNUNET_SCHEDULER_cancel (connection->write_task);
1411 connection->write_task = NULL;
1413 signal_transmit_error (connection, errno);
1416 LOG (GNUNET_ERROR_TYPE_DEBUG,
1417 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1418 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1419 connection->write_buffer_pos += ret;
1420 if (connection->write_buffer_pos == connection->write_buffer_off)
1422 /* transmitted all pending data */
1423 connection->write_buffer_pos = 0;
1424 connection->write_buffer_off = 0;
1426 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1427 return; /* all data sent! */
1428 /* not done writing, schedule more */
1430 LOG (GNUNET_ERROR_TYPE_DEBUG,
1431 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1432 have = connection->write_buffer_off - connection->write_buffer_pos;
1433 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1434 if (NULL == connection->write_task)
1435 connection->write_task =
1436 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1437 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1438 GNUNET_TIME_absolute_get_remaining
1439 (connection->nth.transmit_timeout),
1440 connection->sock, &transmit_ready, connection);
1445 * Ask the connection to call us once the specified number of bytes
1446 * are free in the transmission buffer. Will never call the @a notify
1447 * callback in this task, but always first go into the scheduler.
1449 * @param connection connection
1450 * @param size number of bytes to send
1451 * @param timeout after how long should we give up (and call
1452 * @a notify with buf NULL and size 0)?
1453 * @param notify function to call
1454 * @param notify_cls closure for @a notify
1455 * @return non-NULL if the notify callback was queued,
1456 * NULL if we are already going to notify someone else (busy)
1458 struct GNUNET_CONNECTION_TransmitHandle *
1459 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1461 struct GNUNET_TIME_Relative timeout,
1462 GNUNET_CONNECTION_TransmitReadyNotify
1463 notify, void *notify_cls)
1465 if (NULL != connection->nth.notify_ready)
1470 GNUNET_assert (NULL != notify);
1471 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1472 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1473 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1474 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1475 connection->nth.notify_ready = notify;
1476 connection->nth.notify_ready_cls = notify_cls;
1477 connection->nth.connection = connection;
1478 connection->nth.notify_size = size;
1479 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1480 GNUNET_assert (NULL == connection->nth.timeout_task);
1481 if ((NULL == connection->sock) &&
1482 (NULL == connection->ap_head) &&
1483 (NULL == connection->dns_active))
1485 if (NULL != connection->write_task)
1486 GNUNET_SCHEDULER_cancel (connection->write_task);
1487 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error,
1489 return &connection->nth;
1491 if (NULL != connection->write_task)
1492 return &connection->nth; /* previous transmission still in progress */
1493 if (NULL != connection->sock)
1495 /* connected, try to transmit now */
1496 LOG (GNUNET_ERROR_TYPE_DEBUG,
1497 "Scheduling transmission (%p).\n",
1499 connection->write_task =
1500 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1501 (connection->nth.transmit_timeout),
1502 connection->sock, &transmit_ready, connection);
1503 return &connection->nth;
1505 /* not yet connected, wait for connection */
1506 LOG (GNUNET_ERROR_TYPE_DEBUG,
1507 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n",
1509 connection->nth.timeout_task =
1510 GNUNET_SCHEDULER_add_delayed (timeout,
1511 &transmit_timeout, connection);
1512 return &connection->nth;
1517 * Cancel the specified transmission-ready notification.
1519 * @param th notification to cancel
1522 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1523 GNUNET_CONNECTION_TransmitHandle
1526 GNUNET_assert (NULL != th->notify_ready);
1527 th->notify_ready = NULL;
1528 if (NULL != th->timeout_task)
1530 GNUNET_SCHEDULER_cancel (th->timeout_task);
1531 th->timeout_task = NULL;
1533 if (NULL != th->connection->write_task)
1535 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1536 th->connection->write_task = NULL;
1540 /* end of connection.c */