2 This file is part of GNUnet.
3 (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 GNUNET_SCHEDULER_TaskIdentifier 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 GNUNET_SCHEDULER_TaskIdentifier 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 GNUNET_SCHEDULER_TaskIdentifier read_task;
210 * Write task that we may need to wait for.
212 GNUNET_SCHEDULER_TaskIdentifier 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 function to use to check if access is allowed
315 * @param access_cls closure for access
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,
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) &&
419 (GNUNET_YES != (aret = access (access_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, int errcode)
474 GNUNET_CONNECTION_Receiver receiver;
476 LOG (GNUNET_ERROR_TYPE_DEBUG,
477 "Receive encounters error (%s), connection closed (%p)\n",
480 GNUNET_assert (NULL != (receiver = connection->receiver));
481 connection->receiver = NULL;
482 receiver (connection->receiver_cls, NULL, 0, connection->addr, connection->addrlen, errcode);
487 * Tell the receiver callback that a timeout was reached.
489 * @param connection connection to signal for
492 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
494 GNUNET_CONNECTION_Receiver receiver;
496 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection signals timeout to receiver (%p)!\n",
498 GNUNET_assert (NULL != (receiver = connection->receiver));
499 connection->receiver = NULL;
500 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
505 * We failed to transmit data to the service, signal the error.
507 * @param connection handle that had trouble
508 * @param ecode error code (errno)
511 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
514 GNUNET_CONNECTION_TransmitReadyNotify notify;
516 LOG (GNUNET_ERROR_TYPE_DEBUG,
517 "Transmission encounterd error (%s), connection closed (%p)\n",
520 if (NULL != connection->sock)
522 GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR);
523 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
524 connection->sock = NULL;
525 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
527 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
529 /* send errors trigger read errors... */
530 GNUNET_SCHEDULER_cancel (connection->read_task);
531 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
532 signal_receive_timeout (connection);
535 if (NULL == connection->nth.notify_ready)
536 return; /* nobody to tell about it */
537 notify = connection->nth.notify_ready;
538 connection->nth.notify_ready = NULL;
539 notify (connection->nth.notify_ready_cls, 0, NULL);
544 * We've failed for good to establish a connection (timeout or
545 * no more addresses to try).
547 * @param connection the connection we tried to establish
550 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
552 LOG (GNUNET_ERROR_TYPE_INFO,
553 _("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
554 connection->hostname, connection->port);
555 GNUNET_break (NULL == connection->ap_head);
556 GNUNET_break (NULL == connection->ap_tail);
557 GNUNET_break (GNUNET_NO == connection->dns_active);
558 GNUNET_break (NULL == connection->sock);
559 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
561 /* signal errors for jobs that used to wait on the connection */
562 connection->destroy_later = 1;
563 if (NULL != connection->receiver)
564 signal_receive_error (connection, ECONNREFUSED);
565 if (NULL != connection->nth.notify_ready)
567 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
568 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
569 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
570 signal_transmit_error (connection, ECONNREFUSED);
572 if (-1 == connection->destroy_later)
575 connection->destroy_later = 0;
576 GNUNET_CONNECTION_destroy (connection);
579 connection->destroy_later = 0;
584 * We are ready to transmit (or got a timeout).
586 * @param cls our connection handle
587 * @param tc task context describing why we are here
590 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
594 * This function is called once we either timeout or have data ready
597 * @param cls connection to read from
598 * @param tc scheduler context
601 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
605 * We've succeeded in establishing a connection.
607 * @param connection the connection we tried to establish
610 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
612 LOG (GNUNET_ERROR_TYPE_DEBUG,
613 "Connection to `%s' succeeded! (%p)\n",
614 GNUNET_a2s (connection->addr, connection->addrlen), connection);
615 /* trigger jobs that waited for the connection */
616 if (NULL != connection->receiver)
618 LOG (GNUNET_ERROR_TYPE_DEBUG,
619 "Connection succeeded, starting with receiving data (%p)\n",
621 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->read_task);
622 connection->read_task =
623 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
624 (connection->receive_timeout), connection->sock,
625 &receive_ready, connection);
627 if (NULL != connection->nth.notify_ready)
629 LOG (GNUNET_ERROR_TYPE_DEBUG,
630 "Connection succeeded, starting with sending data (%p)\n",
632 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
633 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
634 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
635 GNUNET_assert (connection->write_task == GNUNET_SCHEDULER_NO_TASK);
636 connection->write_task =
637 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
638 (connection->nth.transmit_timeout), connection->sock,
639 &transmit_ready, connection);
645 * Scheduler let us know that we're either ready to write on the
646 * socket OR connect timed out. Do the right thing.
648 * @param cls the "struct AddressProbe*" with the address that we are probing
649 * @param tc success or failure info about the connect attempt.
652 connect_probe_continuation (void *cls,
653 const struct GNUNET_SCHEDULER_TaskContext *tc)
655 struct AddressProbe *ap = cls;
656 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
657 struct AddressProbe *pos;
661 GNUNET_assert (NULL != ap->sock);
662 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
663 len = sizeof (error);
666 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
668 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
669 &len)) || (0 != error))
671 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
673 if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
674 connect_fail_continuation (connection);
677 GNUNET_assert (NULL == connection->sock);
678 connection->sock = ap->sock;
679 GNUNET_assert (NULL == connection->addr);
680 connection->addr = GNUNET_malloc (ap->addrlen);
681 memcpy (connection->addr, ap->addr, ap->addrlen);
682 connection->addrlen = ap->addrlen;
684 /* cancel all other attempts */
685 while (NULL != (pos = connection->ap_head))
687 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
688 GNUNET_SCHEDULER_cancel (pos->task);
689 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
692 connect_success_continuation (connection);
697 * Try to establish a connection given the specified address.
698 * This function is called by the resolver once we have a DNS reply.
700 * @param cls our "struct GNUNET_CONNECTION_Handle *"
701 * @param addr address to try, NULL for "last call"
702 * @param addrlen length of addr
705 try_connect_using_address (void *cls, const struct sockaddr *addr,
708 struct GNUNET_CONNECTION_Handle *connection = cls;
709 struct AddressProbe *ap;
710 struct GNUNET_TIME_Relative delay;
714 connection->dns_active = NULL;
715 if ((NULL == connection->ap_head) && (NULL == connection->sock))
716 connect_fail_continuation (connection);
719 if (NULL != connection->sock)
720 return; /* already connected */
721 GNUNET_assert (NULL == connection->addr);
723 LOG (GNUNET_ERROR_TYPE_DEBUG,
724 "Trying to connect using address `%s:%u/%s:%u'\n", connection->hostname, connection->port,
725 GNUNET_a2s (addr, addrlen), connection->port);
726 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
727 ap->addr = (const struct sockaddr *) &ap[1];
728 memcpy (&ap[1], addr, addrlen);
729 ap->addrlen = addrlen;
730 ap->connection = connection;
732 switch (ap->addr->sa_family)
735 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
738 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
743 return; /* not supported by us */
745 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
746 if (NULL == ap->sock)
749 return; /* not supported by OS */
751 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
752 GNUNET_a2s (ap->addr, ap->addrlen), connection);
754 GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
755 (EINPROGRESS != errno))
757 /* maybe refused / unsupported address, try next */
758 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
759 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
763 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
764 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
765 if (NULL != connection->nth.notify_ready)
767 GNUNET_TIME_relative_min (delay,
768 GNUNET_TIME_absolute_get_remaining (connection->
769 nth.transmit_timeout));
770 if (NULL != connection->receiver)
772 GNUNET_TIME_relative_min (delay,
773 GNUNET_TIME_absolute_get_remaining
774 (connection->receive_timeout));
776 GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
777 &connect_probe_continuation, ap);
782 * Create a connection handle by (asynchronously) connecting to a host.
783 * This function returns immediately, even if the connection has not
784 * yet been established. This function only creates TCP connections.
786 * @param cfg configuration to use
787 * @param hostname name of the host to connect to
788 * @param port port to connect to
789 * @return the connection handle
791 struct GNUNET_CONNECTION_Handle *
792 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle
793 *cfg, const char *hostname,
796 struct GNUNET_CONNECTION_Handle *connection;
798 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
799 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
800 connection->cfg = cfg;
801 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
802 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
803 connection->port = port;
804 connection->hostname = GNUNET_strdup (hostname);
805 connection->dns_active =
806 GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
807 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
808 &try_connect_using_address, connection);
814 * Create a connection handle by connecting to a UNIX domain service.
815 * This function returns immediately, even if the connection has not
816 * yet been established. This function only creates UNIX connections.
818 * @param cfg configuration to use
819 * @param unixpath path to connect to
820 * @return the connection handle, NULL on systems without UNIX support
822 struct GNUNET_CONNECTION_Handle *
823 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
824 GNUNET_CONFIGURATION_Handle
825 *cfg, const char *unixpath)
828 struct GNUNET_CONNECTION_Handle *connection;
829 struct sockaddr_un *un;
831 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
832 un = GNUNET_new (struct sockaddr_un);
833 un->sun_family = AF_UNIX;
834 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
835 #if HAVE_SOCKADDR_IN_SIN_LEN
836 un->sun_len = (u_char) sizeof (struct sockaddr_un);
838 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
839 connection->cfg = cfg;
840 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
841 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
842 connection->port = 0;
843 connection->hostname = NULL;
844 connection->addr = (struct sockaddr *) un;
845 connection->addrlen = sizeof (struct sockaddr_un);
846 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
847 if (NULL == connection->sock)
849 GNUNET_free (connection->addr);
850 GNUNET_free (connection->write_buffer);
851 GNUNET_free (connection);
855 GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
856 (EINPROGRESS != errno) )
858 /* Just return; we expect everything to work eventually so don't fail HARD */
859 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
860 connection->sock = NULL;
863 connect_success_continuation (connection);
872 * Create a connection handle by (asynchronously) connecting to a host.
873 * This function returns immediately, even if the connection has not
874 * yet been established. This function only creates TCP connections.
876 * @param af_family address family to use
877 * @param serv_addr server address
878 * @param addrlen length of server address
879 * @return the connection handle
881 struct GNUNET_CONNECTION_Handle *
882 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
883 const struct sockaddr *serv_addr,
886 struct GNUNET_NETWORK_Handle *s;
887 struct GNUNET_CONNECTION_Handle *connection;
889 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
892 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
895 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
896 (EINPROGRESS != errno))
898 /* maybe refused / unsupported address, try next */
899 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
900 LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
901 GNUNET_a2s (serv_addr, addrlen));
902 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
905 connection = GNUNET_CONNECTION_create_from_existing (s);
906 connection->addr = GNUNET_malloc (addrlen);
907 memcpy (connection->addr, serv_addr, addrlen);
908 connection->addrlen = addrlen;
909 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
910 GNUNET_a2s (serv_addr, addrlen), connection);
916 * Check if connection is valid (no fatal errors have happened so far).
917 * Note that a connection that is still trying to connect is considered
920 * @param connection connection to check
921 * @return GNUNET_YES if valid, GNUNET_NO otherwise
924 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
926 if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
927 return GNUNET_YES; /* still trying to connect */
928 return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
933 * Close the connection and free associated resources. There must
934 * not be any pending requests for reading or writing to the
935 * connection at this time.
937 * @param connection connection to destroy
940 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
942 struct AddressProbe *pos;
944 if (0 != connection->destroy_later)
946 connection->destroy_later = -1;
949 LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
950 GNUNET_assert (NULL == connection->nth.notify_ready);
951 GNUNET_assert (NULL == connection->receiver);
952 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
954 GNUNET_SCHEDULER_cancel (connection->write_task);
955 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
956 connection->write_buffer_off = 0;
958 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
960 GNUNET_SCHEDULER_cancel (connection->read_task);
961 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
963 if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
965 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
966 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
968 connection->nth.notify_ready = NULL;
969 if (NULL != connection->dns_active)
971 GNUNET_RESOLVER_request_cancel (connection->dns_active);
972 connection->dns_active = NULL;
974 while (NULL != (pos = connection->ap_head))
976 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
977 GNUNET_SCHEDULER_cancel (pos->task);
978 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
981 if ( (NULL != connection->sock) &&
982 (GNUNET_YES != connection->persist) )
984 if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
985 (ENOTCONN != errno) &&
986 (ECONNRESET != errno) )
987 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
989 if (NULL != connection->sock)
991 if (GNUNET_YES != connection->persist)
992 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
995 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
996 * leak the socket in this special case) ... */
999 GNUNET_free_non_null (connection->addr);
1000 GNUNET_free_non_null (connection->hostname);
1001 GNUNET_free (connection->write_buffer);
1002 GNUNET_free (connection);
1007 * This function is called once we either timeout
1008 * or have data ready to read.
1010 * @param cls connection to read from
1011 * @param tc scheduler context
1014 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1016 struct GNUNET_CONNECTION_Handle *connection = cls;
1017 char buffer[connection->max];
1019 GNUNET_CONNECTION_Receiver receiver;
1021 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1022 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1024 /* ignore shutdown request, go again immediately */
1025 connection->read_task =
1026 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1027 (connection->receive_timeout), connection->sock,
1028 &receive_ready, connection);
1031 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1033 LOG (GNUNET_ERROR_TYPE_DEBUG,
1034 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1035 GNUNET_a2s (connection->addr, connection->addrlen),
1036 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1038 signal_receive_timeout (connection);
1041 if (NULL == connection->sock)
1043 /* connect failed for good */
1044 signal_receive_error (connection, ECONNREFUSED);
1047 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1049 ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1054 signal_receive_error (connection, errno);
1057 LOG (GNUNET_ERROR_TYPE_DEBUG,
1058 "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1059 connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1060 GNUNET_assert (NULL != (receiver = connection->receiver));
1061 connection->receiver = NULL;
1062 receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1067 * Receive data from the given connection. Note that this function will
1068 * call "receiver" asynchronously using the scheduler. It will
1069 * "immediately" return. Note that there MUST only be one active
1070 * receive call per connection at any given point in time (so do not
1071 * call receive again until the receiver callback has been invoked).
1073 * @param connection connection handle
1074 * @param max maximum number of bytes to read
1075 * @param timeout maximum amount of time to wait
1076 * @param receiver function to call with received data
1077 * @param receiver_cls closure for receiver
1080 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1081 struct GNUNET_TIME_Relative timeout,
1082 GNUNET_CONNECTION_Receiver receiver,
1085 GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1086 (NULL == connection->receiver));
1087 GNUNET_assert (NULL != receiver);
1088 connection->receiver = receiver;
1089 connection->receiver_cls = receiver_cls;
1090 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1091 connection->max = max;
1092 if (NULL != connection->sock)
1094 connection->read_task =
1095 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1096 (connection->receive_timeout), connection->sock,
1097 &receive_ready, connection);
1100 if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1102 connection->receiver = NULL;
1103 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1110 * Cancel receive job on the given connection. Note that the
1111 * receiver callback must not have been called yet in order
1112 * for the cancellation to be valid.
1114 * @param connection connection handle
1115 * @return closure of the original receiver callback closure
1118 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1120 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1122 GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1123 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1125 connection->receiver = NULL;
1126 return connection->receiver_cls;
1131 * Try to call the transmit notify method (check if we do
1132 * have enough space available first)!
1134 * @param connection connection for which we should do this processing
1135 * @return GNUNET_YES if we were able to call notify
1138 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1143 GNUNET_CONNECTION_TransmitReadyNotify notify;
1145 LOG (GNUNET_ERROR_TYPE_DEBUG, "process_notify is running\n");
1147 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1148 if (NULL == (notify = connection->nth.notify_ready))
1150 LOG (GNUNET_ERROR_TYPE_DEBUG, "Noone to notify\n");
1153 used = connection->write_buffer_off - connection->write_buffer_pos;
1154 avail = connection->write_buffer_size - used;
1155 size = connection->nth.notify_size;
1158 LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough buffer\n");
1161 connection->nth.notify_ready = NULL;
1162 if (connection->write_buffer_size - connection->write_buffer_off < size)
1164 /* need to compact */
1165 memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1167 connection->write_buffer_off -= connection->write_buffer_pos;
1168 connection->write_buffer_pos = 0;
1170 avail = connection->write_buffer_size - connection->write_buffer_off;
1171 GNUNET_assert (avail >= size);
1173 notify (connection->nth.notify_ready_cls, avail,
1174 &connection->write_buffer[connection->write_buffer_off]);
1175 GNUNET_assert (size <= avail);
1177 connection->write_buffer_off += size;
1183 * Task invoked by the scheduler when a call to transmit
1184 * is timing out (we never got enough buffer space to call
1185 * the callback function before the specified timeout
1188 * This task notifies the client about the timeout.
1190 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1191 * @param tc scheduler context
1194 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1196 struct GNUNET_CONNECTION_Handle *connection = cls;
1197 GNUNET_CONNECTION_TransmitReadyNotify notify;
1199 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1200 LOG (GNUNET_ERROR_TYPE_DEBUG,
1201 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1202 connection->hostname,
1203 connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1204 notify = connection->nth.notify_ready;
1205 GNUNET_assert (NULL != notify);
1206 connection->nth.notify_ready = NULL;
1207 notify (connection->nth.notify_ready_cls, 0, NULL);
1212 * Task invoked by the scheduler when we failed to connect
1213 * at the time of being asked to transmit.
1215 * This task notifies the client about the error.
1217 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1218 * @param tc scheduler context
1221 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1223 struct GNUNET_CONNECTION_Handle *connection = cls;
1224 GNUNET_CONNECTION_TransmitReadyNotify notify;
1226 LOG (GNUNET_ERROR_TYPE_DEBUG,
1227 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1228 connection->nth.notify_size, connection->hostname, connection->port, connection);
1229 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1230 notify = connection->nth.notify_ready;
1231 connection->nth.notify_ready = NULL;
1232 notify (connection->nth.notify_ready_cls, 0, NULL);
1237 * We are ready to transmit (or got a timeout).
1239 * @param cls our connection handle
1240 * @param tc task context describing why we are here
1243 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1245 struct GNUNET_CONNECTION_Handle *connection = cls;
1246 GNUNET_CONNECTION_TransmitReadyNotify notify;
1250 LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1251 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1252 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1253 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1254 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1256 if (NULL != connection->sock)
1257 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1258 LOG (GNUNET_ERROR_TYPE_DEBUG,
1259 "Transmit to `%s' fails, shutdown happened (%p).\n",
1260 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1261 notify = connection->nth.notify_ready;
1264 connection->nth.notify_ready = NULL;
1265 notify (connection->nth.notify_ready_cls, 0, NULL);
1269 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1271 LOG (GNUNET_ERROR_TYPE_DEBUG,
1272 "Transmit to `%s' fails, time out reached (%p).\n",
1273 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1274 notify = connection->nth.notify_ready;
1275 GNUNET_assert (NULL != notify);
1276 connection->nth.notify_ready = NULL;
1277 notify (connection->nth.notify_ready_cls, 0, NULL);
1280 GNUNET_assert (NULL != connection->sock);
1281 if (NULL == tc->write_ready)
1283 /* special circumstances (in particular, PREREQ_DONE after
1284 * connect): not yet ready to write, but no "fatal" error either.
1286 goto SCHEDULE_WRITE;
1288 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1290 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1291 /* special circumstances (in particular, shutdown): not yet ready
1292 * to write, but no "fatal" error either. Hence retry. */
1293 goto SCHEDULE_WRITE;
1295 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1296 if ((NULL != connection->nth.notify_ready) &&
1297 (connection->write_buffer_size < connection->nth.notify_size))
1299 connection->write_buffer =
1300 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1301 connection->write_buffer_size = connection->nth.notify_size;
1303 process_notify (connection);
1304 have = connection->write_buffer_off - connection->write_buffer_pos;
1307 /* no data ready for writing, terminate write loop */
1310 GNUNET_assert (have <= connection->write_buffer_size);
1311 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1312 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1315 GNUNET_NETWORK_socket_send (connection->sock,
1316 &connection->write_buffer[connection->write_buffer_pos],
1322 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1324 GNUNET_SCHEDULER_cancel (connection->write_task);
1325 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1327 signal_transmit_error (connection, errno);
1330 LOG (GNUNET_ERROR_TYPE_DEBUG,
1331 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1332 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1333 connection->write_buffer_pos += ret;
1334 if (connection->write_buffer_pos == connection->write_buffer_off)
1336 /* transmitted all pending data */
1337 connection->write_buffer_pos = 0;
1338 connection->write_buffer_off = 0;
1340 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1341 return; /* all data sent! */
1342 /* not done writing, schedule more */
1344 LOG (GNUNET_ERROR_TYPE_DEBUG,
1345 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1346 have = connection->write_buffer_off - connection->write_buffer_pos;
1347 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1348 if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1349 connection->write_task =
1350 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1351 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1352 GNUNET_TIME_absolute_get_remaining
1353 (connection->nth.transmit_timeout),
1354 connection->sock, &transmit_ready, connection);
1359 * Ask the connection to call us once the specified number of bytes
1360 * are free in the transmission buffer. May call the notify
1361 * method immediately if enough space is available.
1363 * @param connection connection
1364 * @param size number of bytes to send
1365 * @param timeout after how long should we give up (and call
1366 * notify with buf NULL and size 0)?
1367 * @param notify function to call
1368 * @param notify_cls closure for notify
1369 * @return non-NULL if the notify callback was queued,
1370 * NULL if we are already going to notify someone else (busy)
1372 struct GNUNET_CONNECTION_TransmitHandle *
1373 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1375 struct GNUNET_TIME_Relative timeout,
1376 GNUNET_CONNECTION_TransmitReadyNotify
1377 notify, void *notify_cls)
1379 if (NULL != connection->nth.notify_ready)
1384 GNUNET_assert (NULL != notify);
1385 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1386 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1387 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1388 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1389 connection->nth.notify_ready = notify;
1390 connection->nth.notify_ready_cls = notify_cls;
1391 connection->nth.connection = connection;
1392 connection->nth.notify_size = size;
1393 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1394 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1395 if ((NULL == connection->sock) &&
1396 (NULL == connection->ap_head) &&
1397 (NULL == connection->dns_active))
1399 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1400 GNUNET_SCHEDULER_cancel (connection->write_task);
1401 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1402 return &connection->nth;
1404 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1405 return &connection->nth; /* previous transmission still in progress */
1406 if (NULL != connection->sock)
1408 /* connected, try to transmit now */
1409 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1410 connection->write_task =
1411 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1412 (connection->nth.transmit_timeout),
1413 connection->sock, &transmit_ready, connection);
1414 return &connection->nth;
1416 /* not yet connected, wait for connection */
1417 LOG (GNUNET_ERROR_TYPE_DEBUG,
1418 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1419 connection->nth.timeout_task =
1420 GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1421 return &connection->nth;
1426 * Cancel the specified transmission-ready notification.
1428 * @param th notification to cancel
1431 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1432 GNUNET_CONNECTION_TransmitHandle
1435 GNUNET_assert (NULL != th->notify_ready);
1436 th->notify_ready = NULL;
1437 if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1439 GNUNET_SCHEDULER_cancel (th->timeout_task);
1440 th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1442 if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1444 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1445 th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1449 /* end of connection.c */