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.
35 #include "gnunet_common.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_resolver_service.h"
40 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
46 * Transmission handle. There can only be one for each connection.
48 struct GNUNET_CONNECTION_TransmitHandle
52 * Function to call if the send buffer has notify_size
55 GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
58 * Closure for notify_ready.
60 void *notify_ready_cls;
63 * Our connection handle.
65 struct GNUNET_CONNECTION_Handle *connection;
68 * Timeout for receiving (in absolute time).
70 struct GNUNET_TIME_Absolute transmit_timeout;
73 * Task called on timeout.
75 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
78 * At what number of bytes available in the
79 * write buffer should the notify method be called?
87 * During connect, we try multiple possible IP addresses
88 * to find out which one might work.
94 * This is a linked list.
96 struct AddressProbe *next;
99 * This is a doubly-linked list.
101 struct AddressProbe *prev;
104 * The address; do not free (allocated at the end of this struct).
106 const struct sockaddr *addr;
109 * Underlying OS's socket.
111 struct GNUNET_NETWORK_Handle *sock;
114 * Connection for which we are probing.
116 struct GNUNET_CONNECTION_Handle *connection;
124 * Task waiting for the connection to finish connecting.
126 GNUNET_SCHEDULER_TaskIdentifier task;
131 * @brief handle for a network connection
133 struct GNUNET_CONNECTION_Handle
137 * Configuration to use.
139 const struct GNUNET_CONFIGURATION_Handle *cfg;
142 * Linked list of sockets we are currently trying out
145 struct AddressProbe *ap_head;
148 * Linked list of sockets we are currently trying out
151 struct AddressProbe *ap_tail;
154 * Network address of the other end-point, may be NULL.
156 struct sockaddr *addr;
159 * Pointer to the hostname if connection was
160 * created using DNS lookup, otherwise NULL.
165 * Underlying OS's socket, set to NULL after fatal errors.
167 struct GNUNET_NETWORK_Handle *sock;
170 * Function to call on data received, NULL if no receive is pending.
172 GNUNET_CONNECTION_Receiver receiver;
175 * Closure for receiver.
180 * Pointer to our write buffer.
185 * Current size of our write buffer.
187 size_t write_buffer_size;
190 * Current write-offset in write buffer (where
191 * would we write next).
193 size_t write_buffer_off;
196 * Current read-offset in write buffer (how many
197 * bytes have already been sent).
199 size_t write_buffer_pos;
207 * Read task that we may need to wait for.
209 GNUNET_SCHEDULER_TaskIdentifier read_task;
212 * Write task that we may need to wait for.
214 GNUNET_SCHEDULER_TaskIdentifier write_task;
217 * Handle to a pending DNS lookup request.
219 struct GNUNET_RESOLVER_RequestHandle *dns_active;
222 * The handle we return for GNUNET_CONNECTION_notify_transmit_ready.
224 struct GNUNET_CONNECTION_TransmitHandle nth;
227 * Timeout for receiving (in absolute time).
229 struct GNUNET_TIME_Absolute receive_timeout;
232 * Maximum number of bytes to read (for receiving).
237 * Port to connect to.
242 * When shutdown, do not ever actually close the socket, but
243 * free resources. Only should ever be set if using program
244 * termination as a signal (because only then will the leaked
250 * Usually 0. Set to 1 if this handle is in used and should
251 * 'GNUNET_CONNECTION_destroy' be called right now, the action needs
252 * to be deferred by setting it to -1.
254 int8_t destroy_later;
260 * Set the persist option on this connection handle. Indicates
261 * that the underlying socket or fd should never really be closed.
262 * Used for indicating process death.
264 * @param connection the connection to set persistent
267 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
269 connection->persist = GNUNET_YES;
274 * Disable the "CORK" feature for communication with the given connection,
275 * forcing the OS to immediately flush the buffer on transmission
276 * instead of potentially buffering multiple messages. Essentially
277 * reduces the OS send buffers to zero.
278 * Used to make sure that the last messages sent through the connection
279 * reach the other side before the process is terminated.
281 * @param connection the connection to make flushing and blocking
282 * @return GNUNET_OK on success
285 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
287 return GNUNET_NETWORK_socket_disable_corking (connection->sock);
292 * Create a connection handle by boxing an existing OS socket. The OS
293 * socket should henceforth be no longer used directly.
294 * GNUNET_connection_destroy will close it.
296 * @param osSocket existing socket to box
297 * @return the boxed connection handle
299 struct GNUNET_CONNECTION_Handle *
300 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
302 struct GNUNET_CONNECTION_Handle *connection;
304 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
305 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
306 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
307 connection->sock = osSocket;
313 * Create a connection handle by accepting on a listen socket. This
314 * function may block if the listen socket has no connection ready.
316 * @param access function to use to check if access is allowed
317 * @param access_cls closure for access
318 * @param lsock listen socket
319 * @return the connection handle, NULL on error
321 struct GNUNET_CONNECTION_Handle *
322 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access,
324 struct GNUNET_NETWORK_Handle *lsock)
326 struct GNUNET_CONNECTION_Handle *connection;
329 struct GNUNET_NETWORK_Handle *sock;
331 struct sockaddr_in *v4;
332 struct sockaddr_in6 *v6;
335 struct GNUNET_CONNECTION_Credentials *gcp;
336 struct GNUNET_CONNECTION_Credentials gc;
342 addrlen = sizeof (addr);
344 GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
347 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
350 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
353 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
357 sa = (struct sockaddr *) addr;
358 v6 = (struct sockaddr_in6 *) addr;
359 if ((AF_INET6 == sa->sa_family) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
361 /* convert to V4 address */
362 v4 = GNUNET_new (struct sockaddr_in);
363 memset (v4, 0, sizeof (struct sockaddr_in));
364 v4->sin_family = AF_INET;
365 #if HAVE_SOCKADDR_IN_SIN_LEN
366 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
368 memcpy (&v4->sin_addr,
369 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
370 sizeof (struct in_addr)],
371 sizeof (struct in_addr));
372 v4->sin_port = v6->sin6_port;
374 addrlen = sizeof (struct sockaddr_in);
378 uaddr = GNUNET_malloc (addrlen);
379 memcpy (uaddr, addr, addrlen);
384 if (AF_UNIX == sa->sa_family)
388 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock), &gc.uid, &gc.gid))
392 /* largely traditional GNU/Linux */
395 getsockopt (GNUNET_NETWORK_get_fd (sock), SOL_SOCKET, SO_PEERCRED, &uc,
396 &olen)) && (olen == sizeof (uc)))
403 #if HAVE_GETPEERUCRED
404 /* this is for Solaris 10 */
408 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
410 gc.uid = ucred_geteuid (uc);
411 gc.gid = ucred_getegid (uc);
420 if ((NULL != access) &&
421 (GNUNET_YES != (aret = access (access_cls, gcp, uaddr, addrlen))))
423 if (GNUNET_NO == aret)
424 LOG (GNUNET_ERROR_TYPE_INFO, _("Access denied to `%s'\n"),
425 GNUNET_a2s (uaddr, addrlen));
426 GNUNET_break (GNUNET_OK ==
427 GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
428 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
432 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
433 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
434 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
435 connection->addr = uaddr;
436 connection->addrlen = addrlen;
437 connection->sock = sock;
438 LOG (GNUNET_ERROR_TYPE_INFO,
439 _("Accepting connection from `%s': %p\n"),
440 GNUNET_a2s (uaddr, addrlen), connection);
446 * Obtain the network address of the other party.
448 * @param connection the client to get the address for
449 * @param addr where to store the address
450 * @param addrlen where to store the length of the address
451 * @return GNUNET_OK on success
454 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
455 void **addr, size_t * addrlen)
457 if ((NULL == connection->addr) || (0 == connection->addrlen))
459 *addr = GNUNET_malloc (connection->addrlen);
460 memcpy (*addr, connection->addr, connection->addrlen);
461 *addrlen = connection->addrlen;
467 * Tell the receiver callback that we had an IO error.
469 * @param connection connection to signal error
470 * @param errcode error code to send
473 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection, int errcode)
475 GNUNET_CONNECTION_Receiver receiver;
477 LOG (GNUNET_ERROR_TYPE_DEBUG,
478 "Receive encounters error (%s), connection closed (%p)\n",
481 GNUNET_assert (NULL != (receiver = connection->receiver));
482 connection->receiver = NULL;
483 receiver (connection->receiver_cls, NULL, 0, connection->addr, connection->addrlen, errcode);
488 * Tell the receiver callback that a timeout was reached.
490 * @param connection connection to signal for
493 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
495 GNUNET_CONNECTION_Receiver receiver;
497 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection signals timeout to receiver (%p)!\n",
499 GNUNET_assert (NULL != (receiver = connection->receiver));
500 connection->receiver = NULL;
501 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
506 * We failed to transmit data to the service, signal the error.
508 * @param connection handle that had trouble
509 * @param ecode error code (errno)
512 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
515 GNUNET_CONNECTION_TransmitReadyNotify notify;
517 LOG (GNUNET_ERROR_TYPE_DEBUG,
518 "Transmission encounterd error (%s), connection closed (%p)\n",
521 if (NULL != connection->sock)
523 GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR);
524 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
525 connection->sock = NULL;
526 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
528 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
530 /* send errors trigger read errors... */
531 GNUNET_SCHEDULER_cancel (connection->read_task);
532 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
533 signal_receive_timeout (connection);
536 if (NULL == connection->nth.notify_ready)
537 return; /* nobody to tell about it */
538 notify = connection->nth.notify_ready;
539 connection->nth.notify_ready = NULL;
540 notify (connection->nth.notify_ready_cls, 0, NULL);
545 * We've failed for good to establish a connection (timeout or
546 * no more addresses to try).
548 * @param connection the connection we tried to establish
551 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
553 LOG (GNUNET_ERROR_TYPE_INFO,
554 _("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
555 connection->hostname, connection->port);
556 GNUNET_break (NULL == connection->ap_head);
557 GNUNET_break (NULL == connection->ap_tail);
558 GNUNET_break (GNUNET_NO == connection->dns_active);
559 GNUNET_break (NULL == connection->sock);
560 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
562 /* signal errors for jobs that used to wait on the connection */
563 connection->destroy_later = 1;
564 if (NULL != connection->receiver)
565 signal_receive_error (connection, ECONNREFUSED);
566 if (NULL != connection->nth.notify_ready)
568 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
569 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
570 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
571 signal_transmit_error (connection, ECONNREFUSED);
573 if (-1 == connection->destroy_later)
576 connection->destroy_later = 0;
577 GNUNET_CONNECTION_destroy (connection);
580 connection->destroy_later = 0;
585 * We are ready to transmit (or got a timeout).
587 * @param cls our connection handle
588 * @param tc task context describing why we are here
591 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
595 * This function is called once we either timeout or have data ready
598 * @param cls connection to read from
599 * @param tc scheduler context
602 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
606 * We've succeeded in establishing a connection.
608 * @param connection the connection we tried to establish
611 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
613 LOG (GNUNET_ERROR_TYPE_DEBUG,
614 "Connection to `%s' succeeded! (%p)\n",
615 GNUNET_a2s (connection->addr, connection->addrlen), connection);
616 /* trigger jobs that waited for the connection */
617 if (NULL != connection->receiver)
619 LOG (GNUNET_ERROR_TYPE_DEBUG,
620 "Connection succeeded, starting with receiving data (%p)\n",
622 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->read_task);
623 connection->read_task =
624 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
625 (connection->receive_timeout), connection->sock,
626 &receive_ready, connection);
628 if (NULL != connection->nth.notify_ready)
630 LOG (GNUNET_ERROR_TYPE_DEBUG,
631 "Connection succeeded, starting with sending data (%p)\n",
633 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
634 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
635 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
636 GNUNET_assert (connection->write_task == GNUNET_SCHEDULER_NO_TASK);
637 connection->write_task =
638 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
639 (connection->nth.transmit_timeout), connection->sock,
640 &transmit_ready, connection);
646 * Scheduler let us know that we're either ready to write on the
647 * socket OR connect timed out. Do the right thing.
649 * @param cls the "struct AddressProbe*" with the address that we are probing
650 * @param tc success or failure info about the connect attempt.
653 connect_probe_continuation (void *cls,
654 const struct GNUNET_SCHEDULER_TaskContext *tc)
656 struct AddressProbe *ap = cls;
657 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
658 struct AddressProbe *pos;
662 GNUNET_assert (NULL != ap->sock);
663 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
664 len = sizeof (error);
667 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
669 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
670 &len)) || (0 != error))
672 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
674 if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
675 connect_fail_continuation (connection);
678 GNUNET_assert (NULL == connection->sock);
679 connection->sock = ap->sock;
680 GNUNET_assert (NULL == connection->addr);
681 connection->addr = GNUNET_malloc (ap->addrlen);
682 memcpy (connection->addr, ap->addr, ap->addrlen);
683 connection->addrlen = ap->addrlen;
685 /* cancel all other attempts */
686 while (NULL != (pos = connection->ap_head))
688 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
689 GNUNET_SCHEDULER_cancel (pos->task);
690 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
693 connect_success_continuation (connection);
698 * Try to establish a connection given the specified address.
699 * This function is called by the resolver once we have a DNS reply.
701 * @param cls our "struct GNUNET_CONNECTION_Handle *"
702 * @param addr address to try, NULL for "last call"
703 * @param addrlen length of addr
706 try_connect_using_address (void *cls, const struct sockaddr *addr,
709 struct GNUNET_CONNECTION_Handle *connection = cls;
710 struct AddressProbe *ap;
711 struct GNUNET_TIME_Relative delay;
715 connection->dns_active = NULL;
716 if ((NULL == connection->ap_head) && (NULL == connection->sock))
717 connect_fail_continuation (connection);
720 if (NULL != connection->sock)
721 return; /* already connected */
722 GNUNET_assert (NULL == connection->addr);
724 LOG (GNUNET_ERROR_TYPE_DEBUG,
725 "Trying to connect using address `%s:%u/%s:%u'\n", connection->hostname, connection->port,
726 GNUNET_a2s (addr, addrlen), connection->port);
727 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
728 ap->addr = (const struct sockaddr *) &ap[1];
729 memcpy (&ap[1], addr, addrlen);
730 ap->addrlen = addrlen;
731 ap->connection = connection;
733 switch (ap->addr->sa_family)
736 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
739 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
744 return; /* not supported by us */
746 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
747 if (NULL == ap->sock)
750 return; /* not supported by OS */
752 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
753 GNUNET_a2s (ap->addr, ap->addrlen), connection);
755 GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
756 (EINPROGRESS != errno))
758 /* maybe refused / unsupported address, try next */
759 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
760 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
764 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
765 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
766 if (NULL != connection->nth.notify_ready)
768 GNUNET_TIME_relative_min (delay,
769 GNUNET_TIME_absolute_get_remaining (connection->
770 nth.transmit_timeout));
771 if (NULL != connection->receiver)
773 GNUNET_TIME_relative_min (delay,
774 GNUNET_TIME_absolute_get_remaining
775 (connection->receive_timeout));
777 GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
778 &connect_probe_continuation, ap);
783 * Create a connection handle by (asynchronously) connecting to a host.
784 * This function returns immediately, even if the connection has not
785 * yet been established. This function only creates TCP connections.
787 * @param cfg configuration to use
788 * @param hostname name of the host to connect to
789 * @param port port to connect to
790 * @return the connection handle
792 struct GNUNET_CONNECTION_Handle *
793 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle
794 *cfg, const char *hostname,
797 struct GNUNET_CONNECTION_Handle *connection;
799 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
800 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
801 connection->cfg = cfg;
802 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
803 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
804 connection->port = port;
805 connection->hostname = GNUNET_strdup (hostname);
806 connection->dns_active =
807 GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
808 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
809 &try_connect_using_address, connection);
815 * Create a connection handle by connecting to a UNIX domain service.
816 * This function returns immediately, even if the connection has not
817 * yet been established. This function only creates UNIX connections.
819 * @param cfg configuration to use
820 * @param unixpath path to connect to
821 * @return the connection handle, NULL on systems without UNIX support
823 struct GNUNET_CONNECTION_Handle *
824 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
825 GNUNET_CONFIGURATION_Handle
826 *cfg, const char *unixpath)
829 struct GNUNET_CONNECTION_Handle *connection;
830 struct sockaddr_un *un;
832 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
833 un = GNUNET_new (struct sockaddr_un);
834 un->sun_family = AF_UNIX;
835 strncpy(un->sun_path, unixpath, sizeof(un->sun_path) - 1);
836 #if HAVE_SOCKADDR_IN_SIN_LEN
837 un->sun_len = (u_char) sizeof (struct sockaddr_un);
839 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
840 connection->cfg = cfg;
841 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
842 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
843 connection->port = 0;
844 connection->hostname = NULL;
845 connection->addr = (struct sockaddr *) un;
846 connection->addrlen = sizeof (struct sockaddr_un);
847 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
848 if (NULL == connection->sock)
850 GNUNET_free (connection->addr);
851 GNUNET_free (connection->write_buffer);
852 GNUNET_free (connection);
856 GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
857 (EINPROGRESS != errno) )
859 /* Just return; we expect everything to work eventually so don't fail HARD */
860 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
861 connection->sock = NULL;
864 connect_success_continuation (connection);
873 * Create a connection handle by (asynchronously) connecting to a host.
874 * This function returns immediately, even if the connection has not
875 * yet been established. This function only creates TCP connections.
877 * @param af_family address family to use
878 * @param serv_addr server address
879 * @param addrlen length of server address
880 * @return the connection handle
882 struct GNUNET_CONNECTION_Handle *
883 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
884 const struct sockaddr *serv_addr,
887 struct GNUNET_NETWORK_Handle *s;
888 struct GNUNET_CONNECTION_Handle *connection;
890 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
893 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
896 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
897 (EINPROGRESS != errno))
899 /* maybe refused / unsupported address, try next */
900 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
901 LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
902 GNUNET_a2s (serv_addr, addrlen));
903 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
906 connection = GNUNET_CONNECTION_create_from_existing (s);
907 connection->addr = GNUNET_malloc (addrlen);
908 memcpy (connection->addr, serv_addr, addrlen);
909 connection->addrlen = addrlen;
910 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
911 GNUNET_a2s (serv_addr, addrlen), connection);
917 * Check if connection is valid (no fatal errors have happened so far).
918 * Note that a connection that is still trying to connect is considered
921 * @param connection connection to check
922 * @return GNUNET_YES if valid, GNUNET_NO otherwise
925 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
927 if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
928 return GNUNET_YES; /* still trying to connect */
929 return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
934 * Close the connection and free associated resources. There must
935 * not be any pending requests for reading or writing to the
936 * connection at this time.
938 * @param connection connection to destroy
941 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
943 struct AddressProbe *pos;
945 if (0 != connection->destroy_later)
947 connection->destroy_later = -1;
950 LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
951 GNUNET_assert (NULL == connection->nth.notify_ready);
952 GNUNET_assert (NULL == connection->receiver);
953 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
955 GNUNET_SCHEDULER_cancel (connection->write_task);
956 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
957 connection->write_buffer_off = 0;
959 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
961 GNUNET_SCHEDULER_cancel (connection->read_task);
962 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
964 if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
966 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
967 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
969 connection->nth.notify_ready = NULL;
970 if (NULL != connection->dns_active)
972 GNUNET_RESOLVER_request_cancel (connection->dns_active);
973 connection->dns_active = NULL;
975 while (NULL != (pos = connection->ap_head))
977 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
978 GNUNET_SCHEDULER_cancel (pos->task);
979 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
982 if ( (NULL != connection->sock) &&
983 (GNUNET_YES != connection->persist) )
985 if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
986 (ENOTCONN != errno) &&
987 (ECONNRESET != errno) )
988 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
990 if (NULL != connection->sock)
992 if (GNUNET_YES != connection->persist)
993 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
996 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
997 * leak the socket in this special case) ... */
1000 GNUNET_free_non_null (connection->addr);
1001 GNUNET_free_non_null (connection->hostname);
1002 GNUNET_free (connection->write_buffer);
1003 GNUNET_free (connection);
1008 * This function is called once we either timeout
1009 * or have data ready to read.
1011 * @param cls connection to read from
1012 * @param tc scheduler context
1015 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1017 struct GNUNET_CONNECTION_Handle *connection = cls;
1018 char buffer[connection->max];
1020 GNUNET_CONNECTION_Receiver receiver;
1022 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1023 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1025 /* ignore shutdown request, go again immediately */
1026 connection->read_task =
1027 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1028 (connection->receive_timeout), connection->sock,
1029 &receive_ready, connection);
1032 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1034 LOG (GNUNET_ERROR_TYPE_DEBUG,
1035 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1036 GNUNET_a2s (connection->addr, connection->addrlen),
1037 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1039 signal_receive_timeout (connection);
1042 if (NULL == connection->sock)
1044 /* connect failed for good */
1045 signal_receive_error (connection, ECONNREFUSED);
1048 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1050 ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1055 signal_receive_error (connection, errno);
1058 LOG (GNUNET_ERROR_TYPE_DEBUG,
1059 "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1060 connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1061 GNUNET_assert (NULL != (receiver = connection->receiver));
1062 connection->receiver = NULL;
1063 receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1068 * Receive data from the given connection. Note that this function will
1069 * call "receiver" asynchronously using the scheduler. It will
1070 * "immediately" return. Note that there MUST only be one active
1071 * receive call per connection at any given point in time (so do not
1072 * call receive again until the receiver callback has been invoked).
1074 * @param connection connection handle
1075 * @param max maximum number of bytes to read
1076 * @param timeout maximum amount of time to wait
1077 * @param receiver function to call with received data
1078 * @param receiver_cls closure for receiver
1081 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1082 struct GNUNET_TIME_Relative timeout,
1083 GNUNET_CONNECTION_Receiver receiver,
1086 GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1087 (NULL == connection->receiver));
1088 GNUNET_assert (NULL != receiver);
1089 connection->receiver = receiver;
1090 connection->receiver_cls = receiver_cls;
1091 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1092 connection->max = max;
1093 if (NULL != connection->sock)
1095 connection->read_task =
1096 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1097 (connection->receive_timeout), connection->sock,
1098 &receive_ready, connection);
1101 if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1103 connection->receiver = NULL;
1104 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1111 * Cancel receive job on the given connection. Note that the
1112 * receiver callback must not have been called yet in order
1113 * for the cancellation to be valid.
1115 * @param connection connection handle
1116 * @return closure of the original receiver callback closure
1119 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1121 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1123 GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1124 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1126 connection->receiver = NULL;
1127 return connection->receiver_cls;
1132 * Try to call the transmit notify method (check if we do
1133 * have enough space available first)!
1135 * @param connection connection for which we should do this processing
1136 * @return GNUNET_YES if we were able to call notify
1139 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1144 GNUNET_CONNECTION_TransmitReadyNotify notify;
1146 LOG (GNUNET_ERROR_TYPE_DEBUG, "process_notify is running\n");
1148 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1149 if (NULL == (notify = connection->nth.notify_ready))
1151 LOG (GNUNET_ERROR_TYPE_DEBUG, "Noone to notify\n");
1154 used = connection->write_buffer_off - connection->write_buffer_pos;
1155 avail = connection->write_buffer_size - used;
1156 size = connection->nth.notify_size;
1159 LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough buffer\n");
1162 connection->nth.notify_ready = NULL;
1163 if (connection->write_buffer_size - connection->write_buffer_off < size)
1165 /* need to compact */
1166 memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1168 connection->write_buffer_off -= connection->write_buffer_pos;
1169 connection->write_buffer_pos = 0;
1171 avail = connection->write_buffer_size - connection->write_buffer_off;
1172 GNUNET_assert (avail >= size);
1174 notify (connection->nth.notify_ready_cls, avail,
1175 &connection->write_buffer[connection->write_buffer_off]);
1176 GNUNET_assert (size <= avail);
1178 connection->write_buffer_off += size;
1184 * Task invoked by the scheduler when a call to transmit
1185 * is timing out (we never got enough buffer space to call
1186 * the callback function before the specified timeout
1189 * This task notifies the client about the timeout.
1191 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1192 * @param tc scheduler context
1195 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1197 struct GNUNET_CONNECTION_Handle *connection = cls;
1198 GNUNET_CONNECTION_TransmitReadyNotify notify;
1200 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1201 LOG (GNUNET_ERROR_TYPE_DEBUG,
1202 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1203 connection->hostname,
1204 connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1205 notify = connection->nth.notify_ready;
1206 GNUNET_assert (NULL != notify);
1207 connection->nth.notify_ready = NULL;
1208 notify (connection->nth.notify_ready_cls, 0, NULL);
1213 * Task invoked by the scheduler when we failed to connect
1214 * at the time of being asked to transmit.
1216 * This task notifies the client about the error.
1218 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1219 * @param tc scheduler context
1222 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1224 struct GNUNET_CONNECTION_Handle *connection = cls;
1225 GNUNET_CONNECTION_TransmitReadyNotify notify;
1227 LOG (GNUNET_ERROR_TYPE_DEBUG,
1228 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1229 connection->nth.notify_size, connection->hostname, connection->port, connection);
1230 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1231 notify = connection->nth.notify_ready;
1232 connection->nth.notify_ready = NULL;
1233 notify (connection->nth.notify_ready_cls, 0, NULL);
1238 * We are ready to transmit (or got a timeout).
1240 * @param cls our connection handle
1241 * @param tc task context describing why we are here
1244 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1246 struct GNUNET_CONNECTION_Handle *connection = cls;
1247 GNUNET_CONNECTION_TransmitReadyNotify notify;
1251 LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1252 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1253 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1254 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1255 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1257 if (NULL != connection->sock)
1258 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1259 LOG (GNUNET_ERROR_TYPE_DEBUG,
1260 "Transmit to `%s' fails, shutdown happened (%p).\n",
1261 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1262 notify = connection->nth.notify_ready;
1265 connection->nth.notify_ready = NULL;
1266 notify (connection->nth.notify_ready_cls, 0, NULL);
1270 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1272 LOG (GNUNET_ERROR_TYPE_DEBUG,
1273 "Transmit to `%s' fails, time out reached (%p).\n",
1274 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1275 notify = connection->nth.notify_ready;
1276 GNUNET_assert (NULL != notify);
1277 connection->nth.notify_ready = NULL;
1278 notify (connection->nth.notify_ready_cls, 0, NULL);
1281 GNUNET_assert (NULL != connection->sock);
1282 if (NULL == tc->write_ready)
1284 /* special circumstances (in particular, PREREQ_DONE after
1285 * connect): not yet ready to write, but no "fatal" error either.
1287 goto SCHEDULE_WRITE;
1289 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1291 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1292 /* special circumstances (in particular, shutdown): not yet ready
1293 * to write, but no "fatal" error either. Hence retry. */
1294 goto SCHEDULE_WRITE;
1296 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1297 if ((NULL != connection->nth.notify_ready) &&
1298 (connection->write_buffer_size < connection->nth.notify_size))
1300 connection->write_buffer =
1301 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1302 connection->write_buffer_size = connection->nth.notify_size;
1304 process_notify (connection);
1305 have = connection->write_buffer_off - connection->write_buffer_pos;
1308 /* no data ready for writing, terminate write loop */
1311 GNUNET_assert (have <= connection->write_buffer_size);
1312 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1313 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1316 GNUNET_NETWORK_socket_send (connection->sock,
1317 &connection->write_buffer[connection->write_buffer_pos],
1323 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1325 GNUNET_SCHEDULER_cancel (connection->write_task);
1326 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1328 signal_transmit_error (connection, errno);
1331 LOG (GNUNET_ERROR_TYPE_DEBUG,
1332 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1333 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1334 connection->write_buffer_pos += ret;
1335 if (connection->write_buffer_pos == connection->write_buffer_off)
1337 /* transmitted all pending data */
1338 connection->write_buffer_pos = 0;
1339 connection->write_buffer_off = 0;
1341 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1342 return; /* all data sent! */
1343 /* not done writing, schedule more */
1345 LOG (GNUNET_ERROR_TYPE_DEBUG,
1346 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1347 have = connection->write_buffer_off - connection->write_buffer_pos;
1348 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1349 if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1350 connection->write_task =
1351 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1352 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1353 GNUNET_TIME_absolute_get_remaining
1354 (connection->nth.transmit_timeout),
1355 connection->sock, &transmit_ready, connection);
1360 * Ask the connection to call us once the specified number of bytes
1361 * are free in the transmission buffer. May call the notify
1362 * method immediately if enough space is available.
1364 * @param connection connection
1365 * @param size number of bytes to send
1366 * @param timeout after how long should we give up (and call
1367 * notify with buf NULL and size 0)?
1368 * @param notify function to call
1369 * @param notify_cls closure for notify
1370 * @return non-NULL if the notify callback was queued,
1371 * NULL if we are already going to notify someone else (busy)
1373 struct GNUNET_CONNECTION_TransmitHandle *
1374 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1376 struct GNUNET_TIME_Relative timeout,
1377 GNUNET_CONNECTION_TransmitReadyNotify
1378 notify, void *notify_cls)
1380 if (NULL != connection->nth.notify_ready)
1385 GNUNET_assert (NULL != notify);
1386 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1387 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1388 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1389 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1390 connection->nth.notify_ready = notify;
1391 connection->nth.notify_ready_cls = notify_cls;
1392 connection->nth.connection = connection;
1393 connection->nth.notify_size = size;
1394 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1395 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1396 if ((NULL == connection->sock) &&
1397 (NULL == connection->ap_head) &&
1398 (NULL == connection->dns_active))
1400 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1401 GNUNET_SCHEDULER_cancel (connection->write_task);
1402 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1403 return &connection->nth;
1405 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1406 return &connection->nth; /* previous transmission still in progress */
1407 if (NULL != connection->sock)
1409 /* connected, try to transmit now */
1410 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1411 connection->write_task =
1412 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1413 (connection->nth.transmit_timeout),
1414 connection->sock, &transmit_ready, connection);
1415 return &connection->nth;
1417 /* not yet connected, wait for connection */
1418 LOG (GNUNET_ERROR_TYPE_DEBUG,
1419 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1420 connection->nth.timeout_task =
1421 GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1422 return &connection->nth;
1427 * Cancel the specified transmission-ready notification.
1429 * @param th notification to cancel
1432 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1433 GNUNET_CONNECTION_TransmitHandle
1436 GNUNET_assert (NULL != th->notify_ready);
1437 th->notify_ready = NULL;
1438 if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1440 GNUNET_SCHEDULER_cancel (th->timeout_task);
1441 th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1443 if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1445 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1446 th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1450 /* end of connection.c */