2 This file is part of GNUnet.
3 (C) 2009, 2012 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 2, 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_connection_lib.h"
37 #include "gnunet_container_lib.h"
38 #include "gnunet_resolver_service.h"
39 #include "gnunet_scheduler_lib.h"
40 #include "gnunet_server_lib.h"
43 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
45 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
49 * Transmission handle. There can only be one for each connection.
51 struct GNUNET_CONNECTION_TransmitHandle
55 * Function to call if the send buffer has notify_size
58 GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
61 * Closure for notify_ready.
63 void *notify_ready_cls;
66 * Our connection handle.
68 struct GNUNET_CONNECTION_Handle *connection;
71 * Timeout for receiving (in absolute time).
73 struct GNUNET_TIME_Absolute transmit_timeout;
76 * Task called on timeout.
78 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
81 * At what number of bytes available in the
82 * write buffer should the notify method be called?
90 * During connect, we try multiple possible IP addresses
91 * to find out which one might work.
97 * This is a linked list.
99 struct AddressProbe *next;
102 * This is a doubly-linked list.
104 struct AddressProbe *prev;
107 * The address; do not free (allocated at the end of this struct).
109 const struct sockaddr *addr;
112 * Underlying OS's socket.
114 struct GNUNET_NETWORK_Handle *sock;
117 * Connection for which we are probing.
119 struct GNUNET_CONNECTION_Handle *connection;
127 * Task waiting for the connection to finish connecting.
129 GNUNET_SCHEDULER_TaskIdentifier task;
134 * @brief handle for a network connection
136 struct GNUNET_CONNECTION_Handle
140 * Configuration to use.
142 const struct GNUNET_CONFIGURATION_Handle *cfg;
145 * Linked list of sockets we are currently trying out
148 struct AddressProbe *ap_head;
151 * Linked list of sockets we are currently trying out
154 struct AddressProbe *ap_tail;
157 * Network address of the other end-point, may be NULL.
159 struct sockaddr *addr;
162 * Pointer to the hostname if connection was
163 * created using DNS lookup, otherwise NULL.
168 * Underlying OS's socket, set to NULL after fatal errors.
170 struct GNUNET_NETWORK_Handle *sock;
173 * Function to call on data received, NULL if no receive is pending.
175 GNUNET_CONNECTION_Receiver receiver;
178 * Closure for receiver.
183 * Pointer to our write buffer.
188 * Current size of our write buffer.
190 size_t write_buffer_size;
193 * Current write-offset in write buffer (where
194 * would we write next).
196 size_t write_buffer_off;
199 * Current read-offset in write buffer (how many
200 * bytes have already been sent).
202 size_t write_buffer_pos;
210 * Read task that we may need to wait for.
212 GNUNET_SCHEDULER_TaskIdentifier read_task;
215 * Write task that we may need to wait for.
217 GNUNET_SCHEDULER_TaskIdentifier write_task;
220 * Handle to a pending DNS lookup request.
222 struct GNUNET_RESOLVER_RequestHandle *dns_active;
225 * The handle we return for GNUNET_CONNECTION_notify_transmit_ready.
227 struct GNUNET_CONNECTION_TransmitHandle nth;
230 * Timeout for receiving (in absolute time).
232 struct GNUNET_TIME_Absolute receive_timeout;
235 * Maximum number of bytes to read (for receiving).
240 * Port to connect to.
245 * When shutdown, do not ever actually close the socket, but
246 * free resources. Only should ever be set if using program
247 * termination as a signal (because only then will the leaked
253 * Usually 0. Set to 1 if this handle is in used and should
254 * 'GNUNET_CONNECTION_destroy' be called right now, the action needs
255 * to be deferred by setting it to -1.
257 int8_t destroy_later;
263 * Set the persist option on this connection handle. Indicates
264 * that the underlying socket or fd should never really be closed.
265 * Used for indicating process death.
267 * @param connection the connection to set persistent
270 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
272 connection->persist = GNUNET_YES;
277 * Disable the "CORK" feature for communication with the given connection,
278 * forcing the OS to immediately flush the buffer on transmission
279 * instead of potentially buffering multiple messages. Essentially
280 * reduces the OS send buffers to zero.
281 * Used to make sure that the last messages sent through the connection
282 * reach the other side before the process is terminated.
284 * @param connection the connection to make flushing and blocking
285 * @return GNUNET_OK on success
288 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
290 return GNUNET_NETWORK_socket_disable_corking (connection->sock);
295 * Create a connection handle by boxing an existing OS socket. The OS
296 * socket should henceforth be no longer used directly.
297 * GNUNET_connection_destroy will close it.
299 * @param osSocket existing socket to box
300 * @return the boxed connection handle
302 struct GNUNET_CONNECTION_Handle *
303 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
305 struct GNUNET_CONNECTION_Handle *connection;
307 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
308 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
309 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
310 connection->sock = osSocket;
316 * Create a connection handle by accepting on a listen socket. This
317 * function may block if the listen socket has no connection ready.
319 * @param access function to use to check if access is allowed
320 * @param access_cls closure for access
321 * @param lsock listen socket
322 * @return the connection handle, NULL on error
324 struct GNUNET_CONNECTION_Handle *
325 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access,
327 struct GNUNET_NETWORK_Handle *lsock)
329 struct GNUNET_CONNECTION_Handle *connection;
332 struct GNUNET_NETWORK_Handle *sock;
334 struct sockaddr_in *v4;
335 struct sockaddr_in6 *v6;
338 struct GNUNET_CONNECTION_Credentials *gcp;
339 struct GNUNET_CONNECTION_Credentials gc;
345 addrlen = sizeof (addr);
347 GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
350 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
353 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
356 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
360 sa = (struct sockaddr *) addr;
361 v6 = (struct sockaddr_in6 *) addr;
362 if ((AF_INET6 == sa->sa_family) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
364 /* convert to V4 address */
365 v4 = GNUNET_malloc (sizeof (struct sockaddr_in));
366 memset (v4, 0, sizeof (struct sockaddr_in));
367 v4->sin_family = AF_INET;
368 #if HAVE_SOCKADDR_IN_SIN_LEN
369 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
371 memcpy (&v4->sin_addr,
372 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
373 sizeof (struct in_addr)],
374 sizeof (struct in_addr));
375 v4->sin_port = v6->sin6_port;
377 addrlen = sizeof (struct sockaddr_in);
381 uaddr = GNUNET_malloc (addrlen);
382 memcpy (uaddr, addr, addrlen);
387 if (AF_UNIX == sa->sa_family)
391 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock), &gc.uid, &gc.gid))
395 /* largely traditional GNU/Linux */
398 getsockopt (GNUNET_NETWORK_get_fd (sock), SOL_SOCKET, SO_PEERCRED, &uc,
399 &olen)) && (olen == sizeof (uc)))
406 #if HAVE_GETPEERUCRED
407 /* this is for Solaris 10 */
411 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
413 gc.uid = ucred_geteuid (uc);
414 gc.gid = ucred_getegid (uc);
423 if ((NULL != access) &&
424 (GNUNET_YES != (aret = access (access_cls, gcp, uaddr, addrlen))))
426 if (GNUNET_NO == aret)
427 LOG (GNUNET_ERROR_TYPE_INFO, _("Access denied to `%s'\n"),
428 GNUNET_a2s (uaddr, addrlen));
429 GNUNET_break (GNUNET_OK ==
430 GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
431 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
435 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
436 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
437 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
438 connection->addr = uaddr;
439 connection->addrlen = addrlen;
440 connection->sock = sock;
441 LOG (GNUNET_ERROR_TYPE_INFO,
442 _("Accepting connection from `%s': %p\n"),
443 GNUNET_a2s (uaddr, addrlen), connection);
449 * Obtain the network address of the other party.
451 * @param connection the client to get the address for
452 * @param addr where to store the address
453 * @param addrlen where to store the length of the address
454 * @return GNUNET_OK on success
457 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
458 void **addr, size_t * addrlen)
460 if ((NULL == connection->addr) || (0 == connection->addrlen))
462 *addr = GNUNET_malloc (connection->addrlen);
463 memcpy (*addr, connection->addr, connection->addrlen);
464 *addrlen = connection->addrlen;
470 * Tell the receiver callback that we had an IO error.
472 * @param connection connection to signal error
473 * @param errcode error code to send
476 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection, int errcode)
478 GNUNET_CONNECTION_Receiver receiver;
480 LOG (GNUNET_ERROR_TYPE_DEBUG,
481 "Receive encounters error (%s), connection closed (%p)\n",
484 GNUNET_assert (NULL != (receiver = connection->receiver));
485 connection->receiver = NULL;
486 receiver (connection->receiver_cls, NULL, 0, connection->addr, connection->addrlen, errcode);
491 * Tell the receiver callback that a timeout was reached.
493 * @param connection connection to signal for
496 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
498 GNUNET_CONNECTION_Receiver receiver;
500 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection signals timeout to receiver (%p)!\n",
502 GNUNET_assert (NULL != (receiver = connection->receiver));
503 connection->receiver = NULL;
504 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
509 * We failed to transmit data to the service, signal the error.
511 * @param connection handle that had trouble
512 * @param ecode error code (errno)
515 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
518 GNUNET_CONNECTION_TransmitReadyNotify notify;
520 LOG (GNUNET_ERROR_TYPE_DEBUG,
521 "Transmission encounterd error (%s), connection closed (%p)\n",
524 if (NULL != connection->sock)
526 GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR);
527 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
528 connection->sock = NULL;
529 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
531 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
533 /* send errors trigger read errors... */
534 GNUNET_SCHEDULER_cancel (connection->read_task);
535 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
536 signal_receive_timeout (connection);
539 if (NULL == connection->nth.notify_ready)
540 return; /* nobody to tell about it */
541 notify = connection->nth.notify_ready;
542 connection->nth.notify_ready = NULL;
543 notify (connection->nth.notify_ready_cls, 0, NULL);
548 * We've failed for good to establish a connection (timeout or
549 * no more addresses to try).
551 * @param connection the connection we tried to establish
554 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
556 LOG (GNUNET_ERROR_TYPE_INFO,
557 _("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
558 connection->hostname, connection->port);
559 GNUNET_break (NULL == connection->ap_head);
560 GNUNET_break (NULL == connection->ap_tail);
561 GNUNET_break (GNUNET_NO == connection->dns_active);
562 GNUNET_break (NULL == connection->sock);
563 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
565 /* signal errors for jobs that used to wait on the connection */
566 connection->destroy_later = 1;
567 if (NULL != connection->receiver)
568 signal_receive_error (connection, ECONNREFUSED);
569 if (NULL != connection->nth.notify_ready)
571 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
572 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
573 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
574 signal_transmit_error (connection, ECONNREFUSED);
576 if (-1 == connection->destroy_later)
579 connection->destroy_later = 0;
580 GNUNET_CONNECTION_destroy (connection);
583 connection->destroy_later = 0;
588 * We are ready to transmit (or got a timeout).
590 * @param cls our connection handle
591 * @param tc task context describing why we are here
594 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
598 * This function is called once we either timeout or have data ready
601 * @param cls connection to read from
602 * @param tc scheduler context
605 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
609 * We've succeeded in establishing a connection.
611 * @param connection the connection we tried to establish
614 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
616 LOG (GNUNET_ERROR_TYPE_DEBUG,
617 "Connection to `%s' succeeded! (%p)\n",
618 GNUNET_a2s (connection->addr, connection->addrlen), connection);
619 /* trigger jobs that waited for the connection */
620 if (NULL != connection->receiver)
622 LOG (GNUNET_ERROR_TYPE_DEBUG,
623 "Connection succeeded, starting with receiving data (%p)\n",
625 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->read_task);
626 connection->read_task =
627 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
628 (connection->receive_timeout), connection->sock,
629 &receive_ready, connection);
631 if (NULL != connection->nth.notify_ready)
633 LOG (GNUNET_ERROR_TYPE_DEBUG,
634 "Connection succeeded, starting with sending data (%p)\n",
636 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
637 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
638 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
639 GNUNET_assert (connection->write_task == GNUNET_SCHEDULER_NO_TASK);
640 connection->write_task =
641 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
642 (connection->nth.transmit_timeout), connection->sock,
643 &transmit_ready, connection);
649 * Scheduler let us know that we're either ready to write on the
650 * socket OR connect timed out. Do the right thing.
652 * @param cls the "struct AddressProbe*" with the address that we are probing
653 * @param tc success or failure info about the connect attempt.
656 connect_probe_continuation (void *cls,
657 const struct GNUNET_SCHEDULER_TaskContext *tc)
659 struct AddressProbe *ap = cls;
660 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
661 struct AddressProbe *pos;
665 GNUNET_assert (NULL != ap->sock);
666 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
667 len = sizeof (error);
670 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
672 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
673 &len)) || (0 != error))
675 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
677 if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
678 connect_fail_continuation (connection);
681 GNUNET_assert (NULL == connection->sock);
682 connection->sock = ap->sock;
683 GNUNET_assert (NULL == connection->addr);
684 connection->addr = GNUNET_malloc (ap->addrlen);
685 memcpy (connection->addr, ap->addr, ap->addrlen);
686 connection->addrlen = ap->addrlen;
688 /* cancel all other attempts */
689 while (NULL != (pos = connection->ap_head))
691 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
692 GNUNET_SCHEDULER_cancel (pos->task);
693 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
696 connect_success_continuation (connection);
701 * Try to establish a connection given the specified address.
702 * This function is called by the resolver once we have a DNS reply.
704 * @param cls our "struct GNUNET_CONNECTION_Handle *"
705 * @param addr address to try, NULL for "last call"
706 * @param addrlen length of addr
709 try_connect_using_address (void *cls, const struct sockaddr *addr,
712 struct GNUNET_CONNECTION_Handle *connection = cls;
713 struct AddressProbe *ap;
714 struct GNUNET_TIME_Relative delay;
718 connection->dns_active = NULL;
719 if ((NULL == connection->ap_head) && (NULL == connection->sock))
720 connect_fail_continuation (connection);
723 if (NULL != connection->sock)
724 return; /* already connected */
725 GNUNET_assert (NULL == connection->addr);
727 LOG (GNUNET_ERROR_TYPE_DEBUG,
728 "Trying to connect using address `%s:%u/%s:%u'\n", connection->hostname, connection->port,
729 GNUNET_a2s (addr, addrlen), connection->port);
730 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
731 ap->addr = (const struct sockaddr *) &ap[1];
732 memcpy (&ap[1], addr, addrlen);
733 ap->addrlen = addrlen;
734 ap->connection = connection;
736 switch (ap->addr->sa_family)
739 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
742 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
747 return; /* not supported by us */
749 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
750 if (NULL == ap->sock)
753 return; /* not supported by OS */
755 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
756 GNUNET_a2s (ap->addr, ap->addrlen), connection);
758 GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
759 (EINPROGRESS != errno))
761 /* maybe refused / unsupported address, try next */
762 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
763 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
767 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
768 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
769 if (NULL != connection->nth.notify_ready)
771 GNUNET_TIME_relative_min (delay,
772 GNUNET_TIME_absolute_get_remaining (connection->
773 nth.transmit_timeout));
774 if (NULL != connection->receiver)
776 GNUNET_TIME_relative_min (delay,
777 GNUNET_TIME_absolute_get_remaining
778 (connection->receive_timeout));
780 GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
781 &connect_probe_continuation, ap);
786 * Create a connection handle by (asynchronously) connecting to a host.
787 * This function returns immediately, even if the connection has not
788 * yet been established. This function only creates TCP connections.
790 * @param cfg configuration to use
791 * @param hostname name of the host to connect to
792 * @param port port to connect to
793 * @return the connection handle
795 struct GNUNET_CONNECTION_Handle *
796 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle
797 *cfg, const char *hostname,
800 struct GNUNET_CONNECTION_Handle *connection;
802 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
803 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
804 connection->cfg = cfg;
805 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
806 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
807 connection->port = port;
808 connection->hostname = GNUNET_strdup (hostname);
809 connection->dns_active =
810 GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
811 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
812 &try_connect_using_address, connection);
818 * Create a connection handle by connecting to a UNIX domain service.
819 * This function returns immediately, even if the connection has not
820 * yet been established. This function only creates UNIX connections.
822 * @param cfg configuration to use
823 * @param unixpath path to connect to
824 * @return the connection handle, NULL on systems without UNIX support
826 struct GNUNET_CONNECTION_Handle *
827 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
828 GNUNET_CONFIGURATION_Handle
829 *cfg, const char *unixpath)
832 struct GNUNET_CONNECTION_Handle *connection;
833 struct sockaddr_un *un;
836 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
837 un = GNUNET_malloc (sizeof (struct sockaddr_un));
838 un->sun_family = AF_UNIX;
839 slen = strlen (unixpath);
840 if (slen >= sizeof (un->sun_path))
841 slen = sizeof (un->sun_path) - 1;
842 memcpy (un->sun_path, unixpath, slen);
843 un->sun_path[slen] = '\0';
844 slen = sizeof (struct sockaddr_un);
845 #if HAVE_SOCKADDR_IN_SIN_LEN
846 un->sun_len = (u_char) slen;
849 un->sun_path[0] = '\0';
851 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
852 connection->cfg = cfg;
853 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
854 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
855 connection->port = 0;
856 connection->hostname = NULL;
857 connection->addr = (struct sockaddr *) un;
858 connection->addrlen = slen;
859 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
860 if (NULL == connection->sock)
862 GNUNET_free (connection->addr);
863 GNUNET_free (connection->write_buffer);
864 GNUNET_free (connection);
868 GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
869 (EINPROGRESS != errno) )
871 /* Just return; we expect everything to work eventually so don't fail HARD */
872 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
873 connection->sock = NULL;
876 connect_success_continuation (connection);
885 * Create a connection handle by (asynchronously) connecting to a host.
886 * This function returns immediately, even if the connection has not
887 * yet been established. This function only creates TCP connections.
889 * @param af_family address family to use
890 * @param serv_addr server address
891 * @param addrlen length of server address
892 * @return the connection handle
894 struct GNUNET_CONNECTION_Handle *
895 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
896 const struct sockaddr *serv_addr,
899 struct GNUNET_NETWORK_Handle *s;
900 struct GNUNET_CONNECTION_Handle *connection;
902 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
905 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
908 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
909 (EINPROGRESS != errno))
911 /* maybe refused / unsupported address, try next */
912 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
913 LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
914 GNUNET_a2s (serv_addr, addrlen));
915 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
918 connection = GNUNET_CONNECTION_create_from_existing (s);
919 connection->addr = GNUNET_malloc (addrlen);
920 memcpy (connection->addr, serv_addr, addrlen);
921 connection->addrlen = addrlen;
922 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
923 GNUNET_a2s (serv_addr, addrlen), connection);
929 * Check if connection is valid (no fatal errors have happened so far).
930 * Note that a connection that is still trying to connect is considered
933 * @param connection connection to check
934 * @return GNUNET_YES if valid, GNUNET_NO otherwise
937 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
939 if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
940 return GNUNET_YES; /* still trying to connect */
941 return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
946 * Close the connection and free associated resources. There must
947 * not be any pending requests for reading or writing to the
948 * connection at this time.
950 * @param connection connection to destroy
953 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
955 struct AddressProbe *pos;
957 if (0 != connection->destroy_later)
959 connection->destroy_later = -1;
962 LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
963 GNUNET_assert (NULL == connection->nth.notify_ready);
964 GNUNET_assert (NULL == connection->receiver);
965 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
967 GNUNET_SCHEDULER_cancel (connection->write_task);
968 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
969 connection->write_buffer_off = 0;
971 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
973 GNUNET_SCHEDULER_cancel (connection->read_task);
974 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
976 if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
978 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
979 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
981 connection->nth.notify_ready = NULL;
982 if (NULL != connection->dns_active)
984 GNUNET_RESOLVER_request_cancel (connection->dns_active);
985 connection->dns_active = NULL;
987 while (NULL != (pos = connection->ap_head))
989 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
990 GNUNET_SCHEDULER_cancel (pos->task);
991 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
994 if ( (NULL != connection->sock) &&
995 (GNUNET_YES != connection->persist) )
997 if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
998 (ENOTCONN != errno) &&
999 (ECONNRESET != errno) )
1000 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
1002 if (NULL != connection->sock)
1004 if (GNUNET_YES != connection->persist)
1005 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
1007 GNUNET_free (connection->sock); /* at least no memory leak (we deliberately
1008 * leak the socket in this special case) ... */
1010 GNUNET_free_non_null (connection->addr);
1011 GNUNET_free_non_null (connection->hostname);
1012 GNUNET_free (connection->write_buffer);
1013 GNUNET_free (connection);
1018 * This function is called once we either timeout
1019 * or have data ready to read.
1021 * @param cls connection to read from
1022 * @param tc scheduler context
1025 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1027 struct GNUNET_CONNECTION_Handle *connection = cls;
1028 char buffer[connection->max];
1030 GNUNET_CONNECTION_Receiver receiver;
1032 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1033 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1035 /* ignore shutdown request, go again immediately */
1036 connection->read_task =
1037 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1038 (connection->receive_timeout), connection->sock,
1039 &receive_ready, connection);
1042 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1044 LOG (GNUNET_ERROR_TYPE_DEBUG,
1045 "Receive from `%s' encounters error: timeout (%p)\n",
1046 GNUNET_a2s (connection->addr, connection->addrlen),
1047 GNUNET_TIME_absolute_get_duration (connection->receive_timeout).rel_value,
1049 signal_receive_timeout (connection);
1052 if (NULL == connection->sock)
1054 /* connect failed for good */
1055 signal_receive_error (connection, ECONNREFUSED);
1058 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1060 ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1065 signal_receive_error (connection, errno);
1068 LOG (GNUNET_ERROR_TYPE_DEBUG,
1069 "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1070 connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1071 GNUNET_assert (NULL != (receiver = connection->receiver));
1072 connection->receiver = NULL;
1073 receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1078 * Receive data from the given connection. Note that this function will
1079 * call "receiver" asynchronously using the scheduler. It will
1080 * "immediately" return. Note that there MUST only be one active
1081 * receive call per connection at any given point in time (so do not
1082 * call receive again until the receiver callback has been invoked).
1084 * @param connection connection handle
1085 * @param max maximum number of bytes to read
1086 * @param timeout maximum amount of time to wait
1087 * @param receiver function to call with received data
1088 * @param receiver_cls closure for receiver
1091 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1092 struct GNUNET_TIME_Relative timeout,
1093 GNUNET_CONNECTION_Receiver receiver,
1096 GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1097 (NULL == connection->receiver));
1098 GNUNET_assert (NULL != receiver);
1099 connection->receiver = receiver;
1100 connection->receiver_cls = receiver_cls;
1101 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1102 connection->max = max;
1103 if (NULL != connection->sock)
1105 connection->read_task =
1106 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1107 (connection->receive_timeout), connection->sock,
1108 &receive_ready, connection);
1111 if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1113 connection->receiver = NULL;
1114 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1121 * Cancel receive job on the given connection. Note that the
1122 * receiver callback must not have been called yet in order
1123 * for the cancellation to be valid.
1125 * @param connection connection handle
1126 * @return closure of the original receiver callback closure
1129 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1131 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1133 GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1134 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1136 connection->receiver = NULL;
1137 return connection->receiver_cls;
1142 * Try to call the transmit notify method (check if we do
1143 * have enough space available first)!
1145 * @param connection connection for which we should do this processing
1146 * @return GNUNET_YES if we were able to call notify
1149 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1154 GNUNET_CONNECTION_TransmitReadyNotify notify;
1156 LOG (GNUNET_ERROR_TYPE_DEBUG, "process_notify is running\n");
1158 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1159 if (NULL == (notify = connection->nth.notify_ready))
1161 LOG (GNUNET_ERROR_TYPE_DEBUG, "Noone to notify\n");
1164 used = connection->write_buffer_off - connection->write_buffer_pos;
1165 avail = connection->write_buffer_size - used;
1166 size = connection->nth.notify_size;
1169 LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough buffer\n");
1172 connection->nth.notify_ready = NULL;
1173 if (connection->write_buffer_size - connection->write_buffer_off < size)
1175 /* need to compact */
1176 memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1178 connection->write_buffer_off -= connection->write_buffer_pos;
1179 connection->write_buffer_pos = 0;
1181 avail = connection->write_buffer_size - connection->write_buffer_off;
1182 GNUNET_assert (avail >= size);
1184 notify (connection->nth.notify_ready_cls, avail,
1185 &connection->write_buffer[connection->write_buffer_off]);
1186 GNUNET_assert (size <= avail);
1188 connection->write_buffer_off += size;
1194 * Task invoked by the scheduler when a call to transmit
1195 * is timing out (we never got enough buffer space to call
1196 * the callback function before the specified timeout
1199 * This task notifies the client about the timeout.
1201 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1202 * @param tc scheduler context
1205 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1207 struct GNUNET_CONNECTION_Handle *connection = cls;
1208 GNUNET_CONNECTION_TransmitReadyNotify notify;
1210 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1211 LOG (GNUNET_ERROR_TYPE_DEBUG,
1212 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1213 connection->hostname,
1214 connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1215 notify = connection->nth.notify_ready;
1216 GNUNET_assert (NULL != notify);
1217 connection->nth.notify_ready = NULL;
1218 notify (connection->nth.notify_ready_cls, 0, NULL);
1223 * Task invoked by the scheduler when we failed to connect
1224 * at the time of being asked to transmit.
1226 * This task notifies the client about the error.
1228 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1229 * @param tc scheduler context
1232 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1234 struct GNUNET_CONNECTION_Handle *connection = cls;
1235 GNUNET_CONNECTION_TransmitReadyNotify notify;
1237 LOG (GNUNET_ERROR_TYPE_DEBUG,
1238 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1239 connection->nth.notify_size, connection->hostname, connection->port, connection);
1240 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1241 notify = connection->nth.notify_ready;
1242 connection->nth.notify_ready = NULL;
1243 notify (connection->nth.notify_ready_cls, 0, NULL);
1248 * We are ready to transmit (or got a timeout).
1250 * @param cls our connection handle
1251 * @param tc task context describing why we are here
1254 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1256 struct GNUNET_CONNECTION_Handle *connection = cls;
1257 GNUNET_CONNECTION_TransmitReadyNotify notify;
1261 LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1262 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1263 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1264 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1265 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1267 if (NULL != connection->sock)
1268 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1269 LOG (GNUNET_ERROR_TYPE_DEBUG,
1270 "Transmit to `%s' fails, shutdown happened (%p).\n",
1271 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1272 notify = connection->nth.notify_ready;
1275 connection->nth.notify_ready = NULL;
1276 notify (connection->nth.notify_ready_cls, 0, NULL);
1280 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1282 LOG (GNUNET_ERROR_TYPE_DEBUG,
1283 "Transmit to `%s' fails, time out reached (%p).\n",
1284 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1285 notify = connection->nth.notify_ready;
1286 GNUNET_assert (NULL != notify);
1287 connection->nth.notify_ready = NULL;
1288 notify (connection->nth.notify_ready_cls, 0, NULL);
1291 GNUNET_assert (NULL != connection->sock);
1292 if (NULL == tc->write_ready)
1294 /* special circumstances (in particular, PREREQ_DONE after
1295 * connect): not yet ready to write, but no "fatal" error either.
1297 goto SCHEDULE_WRITE;
1299 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1301 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1302 /* special circumstances (in particular, shutdown): not yet ready
1303 * to write, but no "fatal" error either. Hence retry. */
1304 goto SCHEDULE_WRITE;
1306 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1307 if ((NULL != connection->nth.notify_ready) &&
1308 (connection->write_buffer_size < connection->nth.notify_size))
1310 connection->write_buffer =
1311 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1312 connection->write_buffer_size = connection->nth.notify_size;
1314 process_notify (connection);
1315 have = connection->write_buffer_off - connection->write_buffer_pos;
1318 /* no data ready for writing, terminate write loop */
1321 GNUNET_assert (have <= connection->write_buffer_size);
1322 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1323 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1326 GNUNET_NETWORK_socket_send (connection->sock,
1327 &connection->write_buffer[connection->write_buffer_pos],
1333 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1335 GNUNET_SCHEDULER_cancel (connection->write_task);
1336 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1338 signal_transmit_error (connection, errno);
1341 LOG (GNUNET_ERROR_TYPE_DEBUG,
1342 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1343 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1344 connection->write_buffer_pos += ret;
1345 if (connection->write_buffer_pos == connection->write_buffer_off)
1347 /* transmitted all pending data */
1348 connection->write_buffer_pos = 0;
1349 connection->write_buffer_off = 0;
1351 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1352 return; /* all data sent! */
1353 /* not done writing, schedule more */
1355 LOG (GNUNET_ERROR_TYPE_DEBUG,
1356 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1357 have = connection->write_buffer_off - connection->write_buffer_pos;
1358 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1359 if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1360 connection->write_task =
1361 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1362 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1363 GNUNET_TIME_absolute_get_remaining
1364 (connection->nth.transmit_timeout),
1365 connection->sock, &transmit_ready, connection);
1370 * Ask the connection to call us once the specified number of bytes
1371 * are free in the transmission buffer. May call the notify
1372 * method immediately if enough space is available.
1374 * @param connection connection
1375 * @param size number of bytes to send
1376 * @param timeout after how long should we give up (and call
1377 * notify with buf NULL and size 0)?
1378 * @param notify function to call
1379 * @param notify_cls closure for notify
1380 * @return non-NULL if the notify callback was queued,
1381 * NULL if we are already going to notify someone else (busy)
1383 struct GNUNET_CONNECTION_TransmitHandle *
1384 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1386 struct GNUNET_TIME_Relative timeout,
1387 GNUNET_CONNECTION_TransmitReadyNotify
1388 notify, void *notify_cls)
1390 if (NULL != connection->nth.notify_ready)
1395 GNUNET_assert (NULL != notify);
1396 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1397 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1398 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1399 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1400 connection->nth.notify_ready = notify;
1401 connection->nth.notify_ready_cls = notify_cls;
1402 connection->nth.connection = connection;
1403 connection->nth.notify_size = size;
1404 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1405 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1406 if ((NULL == connection->sock) &&
1407 (NULL == connection->ap_head) &&
1408 (NULL == connection->dns_active))
1410 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1411 GNUNET_SCHEDULER_cancel (connection->write_task);
1412 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1413 return &connection->nth;
1415 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1416 return &connection->nth; /* previous transmission still in progress */
1417 if (NULL != connection->sock)
1419 /* connected, try to transmit now */
1420 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1421 connection->write_task =
1422 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1423 (connection->nth.transmit_timeout),
1424 connection->sock, &transmit_ready, connection);
1425 return &connection->nth;
1427 /* not yet connected, wait for connection */
1428 LOG (GNUNET_ERROR_TYPE_DEBUG,
1429 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1430 connection->nth.timeout_task =
1431 GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1432 return &connection->nth;
1437 * Cancel the specified transmission-ready notification.
1439 * @param th notification to cancel
1442 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1443 GNUNET_CONNECTION_TransmitHandle
1446 GNUNET_assert (NULL != th->notify_ready);
1447 th->notify_ready = NULL;
1448 if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1450 GNUNET_SCHEDULER_cancel (th->timeout_task);
1451 th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1453 if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1455 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1456 th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1460 /* end of connection.c */