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);
839 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg, "TESTING",
840 "USE_ABSTRACT_SOCKETS");
841 if (GNUNET_YES == abstract)
842 un->sun_path[0] = '\0';
845 #if HAVE_SOCKADDR_IN_SIN_LEN
846 un->sun_len = (u_char) sizeof (struct sockaddr_un);
848 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
849 connection->cfg = cfg;
850 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
851 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
852 connection->port = 0;
853 connection->hostname = NULL;
854 connection->addr = (struct sockaddr *) un;
855 connection->addrlen = sizeof (struct sockaddr_un);
856 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
857 if (NULL == connection->sock)
859 GNUNET_free (connection->addr);
860 GNUNET_free (connection->write_buffer);
861 GNUNET_free (connection);
865 GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
866 (EINPROGRESS != errno) )
868 /* Just return; we expect everything to work eventually so don't fail HARD */
869 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
870 connection->sock = NULL;
873 connect_success_continuation (connection);
882 * Create a connection handle by (asynchronously) connecting to a host.
883 * This function returns immediately, even if the connection has not
884 * yet been established. This function only creates TCP connections.
886 * @param af_family address family to use
887 * @param serv_addr server address
888 * @param addrlen length of server address
889 * @return the connection handle
891 struct GNUNET_CONNECTION_Handle *
892 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
893 const struct sockaddr *serv_addr,
896 struct GNUNET_NETWORK_Handle *s;
897 struct GNUNET_CONNECTION_Handle *connection;
899 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
902 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
905 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
906 (EINPROGRESS != errno))
908 /* maybe refused / unsupported address, try next */
909 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
910 LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
911 GNUNET_a2s (serv_addr, addrlen));
912 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
915 connection = GNUNET_CONNECTION_create_from_existing (s);
916 connection->addr = GNUNET_malloc (addrlen);
917 memcpy (connection->addr, serv_addr, addrlen);
918 connection->addrlen = addrlen;
919 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
920 GNUNET_a2s (serv_addr, addrlen), connection);
926 * Check if connection is valid (no fatal errors have happened so far).
927 * Note that a connection that is still trying to connect is considered
930 * @param connection connection to check
931 * @return GNUNET_YES if valid, GNUNET_NO otherwise
934 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
936 if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
937 return GNUNET_YES; /* still trying to connect */
938 return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
943 * Close the connection and free associated resources. There must
944 * not be any pending requests for reading or writing to the
945 * connection at this time.
947 * @param connection connection to destroy
950 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
952 struct AddressProbe *pos;
954 if (0 != connection->destroy_later)
956 connection->destroy_later = -1;
959 LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
960 GNUNET_assert (NULL == connection->nth.notify_ready);
961 GNUNET_assert (NULL == connection->receiver);
962 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
964 GNUNET_SCHEDULER_cancel (connection->write_task);
965 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
966 connection->write_buffer_off = 0;
968 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
970 GNUNET_SCHEDULER_cancel (connection->read_task);
971 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
973 if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
975 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
976 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
978 connection->nth.notify_ready = NULL;
979 if (NULL != connection->dns_active)
981 GNUNET_RESOLVER_request_cancel (connection->dns_active);
982 connection->dns_active = NULL;
984 while (NULL != (pos = connection->ap_head))
986 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
987 GNUNET_SCHEDULER_cancel (pos->task);
988 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
991 if ( (NULL != connection->sock) &&
992 (GNUNET_YES != connection->persist) )
994 if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
995 (ENOTCONN != errno) &&
996 (ECONNRESET != errno) )
997 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
999 if (NULL != connection->sock)
1001 if (GNUNET_YES != connection->persist)
1002 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
1005 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1006 * leak the socket in this special case) ... */
1009 GNUNET_free_non_null (connection->addr);
1010 GNUNET_free_non_null (connection->hostname);
1011 GNUNET_free (connection->write_buffer);
1012 GNUNET_free (connection);
1017 * This function is called once we either timeout
1018 * or have data ready to read.
1020 * @param cls connection to read from
1021 * @param tc scheduler context
1024 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1026 struct GNUNET_CONNECTION_Handle *connection = cls;
1027 char buffer[connection->max];
1029 GNUNET_CONNECTION_Receiver receiver;
1031 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1032 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1034 /* ignore shutdown request, go again immediately */
1035 connection->read_task =
1036 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1037 (connection->receive_timeout), connection->sock,
1038 &receive_ready, connection);
1041 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1043 LOG (GNUNET_ERROR_TYPE_DEBUG,
1044 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1045 GNUNET_a2s (connection->addr, connection->addrlen),
1046 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1048 signal_receive_timeout (connection);
1051 if (NULL == connection->sock)
1053 /* connect failed for good */
1054 signal_receive_error (connection, ECONNREFUSED);
1057 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1059 ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1064 signal_receive_error (connection, errno);
1067 LOG (GNUNET_ERROR_TYPE_DEBUG,
1068 "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1069 connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1070 GNUNET_assert (NULL != (receiver = connection->receiver));
1071 connection->receiver = NULL;
1072 receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1077 * Receive data from the given connection. Note that this function will
1078 * call "receiver" asynchronously using the scheduler. It will
1079 * "immediately" return. Note that there MUST only be one active
1080 * receive call per connection at any given point in time (so do not
1081 * call receive again until the receiver callback has been invoked).
1083 * @param connection connection handle
1084 * @param max maximum number of bytes to read
1085 * @param timeout maximum amount of time to wait
1086 * @param receiver function to call with received data
1087 * @param receiver_cls closure for receiver
1090 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1091 struct GNUNET_TIME_Relative timeout,
1092 GNUNET_CONNECTION_Receiver receiver,
1095 GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1096 (NULL == connection->receiver));
1097 GNUNET_assert (NULL != receiver);
1098 connection->receiver = receiver;
1099 connection->receiver_cls = receiver_cls;
1100 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1101 connection->max = max;
1102 if (NULL != connection->sock)
1104 connection->read_task =
1105 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1106 (connection->receive_timeout), connection->sock,
1107 &receive_ready, connection);
1110 if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1112 connection->receiver = NULL;
1113 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1120 * Cancel receive job on the given connection. Note that the
1121 * receiver callback must not have been called yet in order
1122 * for the cancellation to be valid.
1124 * @param connection connection handle
1125 * @return closure of the original receiver callback closure
1128 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1130 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1132 GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1133 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1135 connection->receiver = NULL;
1136 return connection->receiver_cls;
1141 * Try to call the transmit notify method (check if we do
1142 * have enough space available first)!
1144 * @param connection connection for which we should do this processing
1145 * @return GNUNET_YES if we were able to call notify
1148 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1153 GNUNET_CONNECTION_TransmitReadyNotify notify;
1155 LOG (GNUNET_ERROR_TYPE_DEBUG, "process_notify is running\n");
1157 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1158 if (NULL == (notify = connection->nth.notify_ready))
1160 LOG (GNUNET_ERROR_TYPE_DEBUG, "Noone to notify\n");
1163 used = connection->write_buffer_off - connection->write_buffer_pos;
1164 avail = connection->write_buffer_size - used;
1165 size = connection->nth.notify_size;
1168 LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough buffer\n");
1171 connection->nth.notify_ready = NULL;
1172 if (connection->write_buffer_size - connection->write_buffer_off < size)
1174 /* need to compact */
1175 memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1177 connection->write_buffer_off -= connection->write_buffer_pos;
1178 connection->write_buffer_pos = 0;
1180 avail = connection->write_buffer_size - connection->write_buffer_off;
1181 GNUNET_assert (avail >= size);
1183 notify (connection->nth.notify_ready_cls, avail,
1184 &connection->write_buffer[connection->write_buffer_off]);
1185 GNUNET_assert (size <= avail);
1187 connection->write_buffer_off += size;
1193 * Task invoked by the scheduler when a call to transmit
1194 * is timing out (we never got enough buffer space to call
1195 * the callback function before the specified timeout
1198 * This task notifies the client about the timeout.
1200 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1201 * @param tc scheduler context
1204 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1206 struct GNUNET_CONNECTION_Handle *connection = cls;
1207 GNUNET_CONNECTION_TransmitReadyNotify notify;
1209 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1210 LOG (GNUNET_ERROR_TYPE_DEBUG,
1211 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1212 connection->hostname,
1213 connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1214 notify = connection->nth.notify_ready;
1215 GNUNET_assert (NULL != notify);
1216 connection->nth.notify_ready = NULL;
1217 notify (connection->nth.notify_ready_cls, 0, NULL);
1222 * Task invoked by the scheduler when we failed to connect
1223 * at the time of being asked to transmit.
1225 * This task notifies the client about the error.
1227 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1228 * @param tc scheduler context
1231 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1233 struct GNUNET_CONNECTION_Handle *connection = cls;
1234 GNUNET_CONNECTION_TransmitReadyNotify notify;
1236 LOG (GNUNET_ERROR_TYPE_DEBUG,
1237 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1238 connection->nth.notify_size, connection->hostname, connection->port, connection);
1239 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1240 notify = connection->nth.notify_ready;
1241 connection->nth.notify_ready = NULL;
1242 notify (connection->nth.notify_ready_cls, 0, NULL);
1247 * We are ready to transmit (or got a timeout).
1249 * @param cls our connection handle
1250 * @param tc task context describing why we are here
1253 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1255 struct GNUNET_CONNECTION_Handle *connection = cls;
1256 GNUNET_CONNECTION_TransmitReadyNotify notify;
1260 LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1261 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1262 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1263 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1264 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1266 if (NULL != connection->sock)
1267 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1268 LOG (GNUNET_ERROR_TYPE_DEBUG,
1269 "Transmit to `%s' fails, shutdown happened (%p).\n",
1270 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1271 notify = connection->nth.notify_ready;
1274 connection->nth.notify_ready = NULL;
1275 notify (connection->nth.notify_ready_cls, 0, NULL);
1279 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1281 LOG (GNUNET_ERROR_TYPE_DEBUG,
1282 "Transmit to `%s' fails, time out reached (%p).\n",
1283 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1284 notify = connection->nth.notify_ready;
1285 GNUNET_assert (NULL != notify);
1286 connection->nth.notify_ready = NULL;
1287 notify (connection->nth.notify_ready_cls, 0, NULL);
1290 GNUNET_assert (NULL != connection->sock);
1291 if (NULL == tc->write_ready)
1293 /* special circumstances (in particular, PREREQ_DONE after
1294 * connect): not yet ready to write, but no "fatal" error either.
1296 goto SCHEDULE_WRITE;
1298 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1300 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1301 /* special circumstances (in particular, shutdown): not yet ready
1302 * to write, but no "fatal" error either. Hence retry. */
1303 goto SCHEDULE_WRITE;
1305 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1306 if ((NULL != connection->nth.notify_ready) &&
1307 (connection->write_buffer_size < connection->nth.notify_size))
1309 connection->write_buffer =
1310 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1311 connection->write_buffer_size = connection->nth.notify_size;
1313 process_notify (connection);
1314 have = connection->write_buffer_off - connection->write_buffer_pos;
1317 /* no data ready for writing, terminate write loop */
1320 GNUNET_assert (have <= connection->write_buffer_size);
1321 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1322 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1325 GNUNET_NETWORK_socket_send (connection->sock,
1326 &connection->write_buffer[connection->write_buffer_pos],
1332 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1334 GNUNET_SCHEDULER_cancel (connection->write_task);
1335 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1337 signal_transmit_error (connection, errno);
1340 LOG (GNUNET_ERROR_TYPE_DEBUG,
1341 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1342 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1343 connection->write_buffer_pos += ret;
1344 if (connection->write_buffer_pos == connection->write_buffer_off)
1346 /* transmitted all pending data */
1347 connection->write_buffer_pos = 0;
1348 connection->write_buffer_off = 0;
1350 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1351 return; /* all data sent! */
1352 /* not done writing, schedule more */
1354 LOG (GNUNET_ERROR_TYPE_DEBUG,
1355 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1356 have = connection->write_buffer_off - connection->write_buffer_pos;
1357 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1358 if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1359 connection->write_task =
1360 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1361 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1362 GNUNET_TIME_absolute_get_remaining
1363 (connection->nth.transmit_timeout),
1364 connection->sock, &transmit_ready, connection);
1369 * Ask the connection to call us once the specified number of bytes
1370 * are free in the transmission buffer. May call the notify
1371 * method immediately if enough space is available.
1373 * @param connection connection
1374 * @param size number of bytes to send
1375 * @param timeout after how long should we give up (and call
1376 * notify with buf NULL and size 0)?
1377 * @param notify function to call
1378 * @param notify_cls closure for notify
1379 * @return non-NULL if the notify callback was queued,
1380 * NULL if we are already going to notify someone else (busy)
1382 struct GNUNET_CONNECTION_TransmitHandle *
1383 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1385 struct GNUNET_TIME_Relative timeout,
1386 GNUNET_CONNECTION_TransmitReadyNotify
1387 notify, void *notify_cls)
1389 if (NULL != connection->nth.notify_ready)
1394 GNUNET_assert (NULL != notify);
1395 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1396 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1397 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1398 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1399 connection->nth.notify_ready = notify;
1400 connection->nth.notify_ready_cls = notify_cls;
1401 connection->nth.connection = connection;
1402 connection->nth.notify_size = size;
1403 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1404 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1405 if ((NULL == connection->sock) &&
1406 (NULL == connection->ap_head) &&
1407 (NULL == connection->dns_active))
1409 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1410 GNUNET_SCHEDULER_cancel (connection->write_task);
1411 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1412 return &connection->nth;
1414 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1415 return &connection->nth; /* previous transmission still in progress */
1416 if (NULL != connection->sock)
1418 /* connected, try to transmit now */
1419 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1420 connection->write_task =
1421 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1422 (connection->nth.transmit_timeout),
1423 connection->sock, &transmit_ready, connection);
1424 return &connection->nth;
1426 /* not yet connected, wait for connection */
1427 LOG (GNUNET_ERROR_TYPE_DEBUG,
1428 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1429 connection->nth.timeout_task =
1430 GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1431 return &connection->nth;
1436 * Cancel the specified transmission-ready notification.
1438 * @param th notification to cancel
1441 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1442 GNUNET_CONNECTION_TransmitHandle
1445 GNUNET_assert (NULL != th->notify_ready);
1446 th->notify_ready = NULL;
1447 if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1449 GNUNET_SCHEDULER_cancel (th->timeout_task);
1450 th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1452 if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1454 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1455 th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1459 /* end of connection.c */