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
256 * Set the persist option on this connection handle. Indicates
257 * that the underlying socket or fd should never really be closed.
258 * Used for indicating process death.
260 * @param connection the connection to set persistent
263 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
265 connection->persist = GNUNET_YES;
270 * Disable the "CORK" feature for communication with the given connection,
271 * forcing the OS to immediately flush the buffer on transmission
272 * instead of potentially buffering multiple messages. Essentially
273 * reduces the OS send buffers to zero.
274 * Used to make sure that the last messages sent through the connection
275 * reach the other side before the process is terminated.
277 * @param connection the connection to make flushing and blocking
278 * @return GNUNET_OK on success
281 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
283 return GNUNET_NETWORK_socket_disable_corking (connection->sock);
288 * Create a connection handle by boxing an existing OS socket. The OS
289 * socket should henceforth be no longer used directly.
290 * GNUNET_connection_destroy will close it.
292 * @param osSocket existing socket to box
293 * @return the boxed connection handle
295 struct GNUNET_CONNECTION_Handle *
296 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
298 struct GNUNET_CONNECTION_Handle *connection;
300 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
301 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
302 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
303 connection->sock = osSocket;
309 * Create a connection handle by accepting on a listen socket. This
310 * function may block if the listen socket has no connection ready.
312 * @param access function to use to check if access is allowed
313 * @param access_cls closure for access
314 * @param lsock listen socket
315 * @return the connection handle, NULL on error
317 struct GNUNET_CONNECTION_Handle *
318 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access,
320 struct GNUNET_NETWORK_Handle *lsock)
322 struct GNUNET_CONNECTION_Handle *connection;
325 struct GNUNET_NETWORK_Handle *sock;
327 struct sockaddr_in *v4;
328 struct sockaddr_in6 *v6;
331 struct GNUNET_CONNECTION_Credentials *gcp;
332 struct GNUNET_CONNECTION_Credentials gc;
338 addrlen = sizeof (addr);
340 GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
343 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
346 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
349 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
353 sa = (struct sockaddr *) addr;
354 v6 = (struct sockaddr_in6 *) addr;
355 if ((AF_INET6 == sa->sa_family) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
357 /* convert to V4 address */
358 v4 = GNUNET_malloc (sizeof (struct sockaddr_in));
359 memset (v4, 0, sizeof (struct sockaddr_in));
360 v4->sin_family = AF_INET;
361 #if HAVE_SOCKADDR_IN_SIN_LEN
362 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
364 memcpy (&v4->sin_addr,
365 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
366 sizeof (struct in_addr)],
367 sizeof (struct in_addr));
368 v4->sin_port = v6->sin6_port;
370 addrlen = sizeof (struct sockaddr_in);
374 uaddr = GNUNET_malloc (addrlen);
375 memcpy (uaddr, addr, addrlen);
380 if (AF_UNIX == sa->sa_family)
384 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock), &gc.uid, &gc.gid))
388 /* largely traditional GNU/Linux */
391 getsockopt (GNUNET_NETWORK_get_fd (sock), SOL_SOCKET, SO_PEERCRED, &uc,
392 &olen)) && (olen == sizeof (uc)))
399 #if HAVE_GETPEERUCRED
400 /* this is for Solaris 10 */
404 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
406 gc.uid = ucred_geteuid (uc);
407 gc.gid = ucred_getegid (uc);
416 if ((NULL != access) &&
417 (GNUNET_YES != (aret = access (access_cls, gcp, uaddr, addrlen))))
419 if (GNUNET_NO == aret)
420 LOG (GNUNET_ERROR_TYPE_INFO, _("Access denied to `%s'\n"),
421 GNUNET_a2s (uaddr, addrlen));
422 GNUNET_break (GNUNET_OK ==
423 GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
424 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
428 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
429 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
430 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
431 connection->addr = uaddr;
432 connection->addrlen = addrlen;
433 connection->sock = sock;
434 LOG (GNUNET_ERROR_TYPE_INFO,
435 _("Accepting connection from `%s': %p\n"),
436 GNUNET_a2s (uaddr, addrlen), connection);
442 * Obtain the network address of the other party.
444 * @param connection the client to get the address for
445 * @param addr where to store the address
446 * @param addrlen where to store the length of the address
447 * @return GNUNET_OK on success
450 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
451 void **addr, size_t * addrlen)
453 if ((NULL == connection->addr) || (0 == connection->addrlen))
455 *addr = GNUNET_malloc (connection->addrlen);
456 memcpy (*addr, connection->addr, connection->addrlen);
457 *addrlen = connection->addrlen;
463 * Tell the receiver callback that we had an IO error.
465 * @param connection connection to signal error
466 * @param errcode error code to send
469 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection, int errcode)
471 GNUNET_CONNECTION_Receiver receiver;
473 LOG (GNUNET_ERROR_TYPE_DEBUG,
474 "Receive encounters error (%s), connection closed (%p)\n",
477 GNUNET_assert (NULL != (receiver = connection->receiver));
478 connection->receiver = NULL;
479 receiver (connection->receiver_cls, NULL, 0, connection->addr, connection->addrlen, errcode);
484 * Tell the receiver callback that a timeout was reached.
486 * @param connection connection to signal for
489 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
491 GNUNET_CONNECTION_Receiver receiver;
493 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection signals timeout to receiver (%p)!\n",
495 GNUNET_assert (NULL != (receiver = connection->receiver));
496 connection->receiver = NULL;
497 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
502 * We failed to transmit data to the service, signal the error.
504 * @param connection handle that had trouble
505 * @param ecode error code (errno)
508 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
511 GNUNET_CONNECTION_TransmitReadyNotify notify;
513 LOG (GNUNET_ERROR_TYPE_DEBUG,
514 "Transmission encounterd error (%s), connection closed (%p)\n",
517 if (NULL != connection->sock)
519 GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR);
520 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
521 connection->sock = NULL;
522 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
524 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
526 /* send errors trigger read errors... */
527 GNUNET_SCHEDULER_cancel (connection->read_task);
528 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
529 signal_receive_timeout (connection);
532 if (NULL == connection->nth.notify_ready)
533 return; /* nobody to tell about it */
534 notify = connection->nth.notify_ready;
535 connection->nth.notify_ready = NULL;
536 notify (connection->nth.notify_ready_cls, 0, NULL);
541 * We've failed for good to establish a connection (timeout or
542 * no more addresses to try).
544 * @param connection the connection we tried to establish
547 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
549 LOG (GNUNET_ERROR_TYPE_INFO,
550 _("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
551 connection->hostname, connection->port);
552 GNUNET_break (NULL == connection->ap_head);
553 GNUNET_break (NULL == connection->ap_tail);
554 GNUNET_break (GNUNET_NO == connection->dns_active);
555 GNUNET_break (NULL == connection->sock);
556 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
558 /* signal errors for jobs that used to wait on the connection */
559 if (NULL != connection->receiver)
560 signal_receive_error (connection, ECONNREFUSED);
561 if (NULL != connection->nth.notify_ready)
563 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
564 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
565 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
566 signal_transmit_error (connection, ECONNREFUSED);
572 * We are ready to transmit (or got a timeout).
574 * @param cls our connection handle
575 * @param tc task context describing why we are here
578 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
582 * This function is called once we either timeout or have data ready
585 * @param cls connection to read from
586 * @param tc scheduler context
589 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
593 * We've succeeded in establishing a connection.
595 * @param connection the connection we tried to establish
598 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
600 LOG (GNUNET_ERROR_TYPE_DEBUG,
601 "Connection to `%s' succeeded! (%p)\n",
602 GNUNET_a2s (connection->addr, connection->addrlen), connection);
603 /* trigger jobs that waited for the connection */
604 if (NULL != connection->receiver)
606 LOG (GNUNET_ERROR_TYPE_DEBUG,
607 "Connection succeeded, starting with receiving data (%p)\n",
609 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->read_task);
610 connection->read_task =
611 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
612 (connection->receive_timeout), connection->sock,
613 &receive_ready, connection);
615 if (NULL != connection->nth.notify_ready)
617 LOG (GNUNET_ERROR_TYPE_DEBUG,
618 "Connection succeeded, starting with sending data (%p)\n",
620 GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
621 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
622 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
623 GNUNET_assert (connection->write_task == GNUNET_SCHEDULER_NO_TASK);
624 connection->write_task =
625 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
626 (connection->nth.transmit_timeout), connection->sock,
627 &transmit_ready, connection);
633 * Scheduler let us know that we're either ready to write on the
634 * socket OR connect timed out. Do the right thing.
636 * @param cls the "struct AddressProbe*" with the address that we are probing
637 * @param tc success or failure info about the connect attempt.
640 connect_probe_continuation (void *cls,
641 const struct GNUNET_SCHEDULER_TaskContext *tc)
643 struct AddressProbe *ap = cls;
644 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
645 struct AddressProbe *pos;
649 GNUNET_assert (NULL != ap->sock);
650 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
651 len = sizeof (error);
654 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
656 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
657 &len)) || (0 != error))
659 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
661 if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
662 connect_fail_continuation (connection);
665 GNUNET_assert (NULL == connection->sock);
666 connection->sock = ap->sock;
667 GNUNET_assert (NULL == connection->addr);
668 connection->addr = GNUNET_malloc (ap->addrlen);
669 memcpy (connection->addr, ap->addr, ap->addrlen);
670 connection->addrlen = ap->addrlen;
672 /* cancel all other attempts */
673 while (NULL != (pos = connection->ap_head))
675 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
676 GNUNET_SCHEDULER_cancel (pos->task);
677 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
680 connect_success_continuation (connection);
685 * Try to establish a connection given the specified address.
686 * This function is called by the resolver once we have a DNS reply.
688 * @param cls our "struct GNUNET_CONNECTION_Handle *"
689 * @param addr address to try, NULL for "last call"
690 * @param addrlen length of addr
693 try_connect_using_address (void *cls, const struct sockaddr *addr,
696 struct GNUNET_CONNECTION_Handle *connection = cls;
697 struct AddressProbe *ap;
698 struct GNUNET_TIME_Relative delay;
702 connection->dns_active = NULL;
703 if ((NULL == connection->ap_head) && (NULL == connection->sock))
704 connect_fail_continuation (connection);
707 if (NULL != connection->sock)
708 return; /* already connected */
709 GNUNET_assert (NULL == connection->addr);
711 LOG (GNUNET_ERROR_TYPE_DEBUG,
712 "Trying to connect using address `%s:%u/%s:%u'\n", connection->hostname, connection->port,
713 GNUNET_a2s (addr, addrlen), connection->port);
714 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
715 ap->addr = (const struct sockaddr *) &ap[1];
716 memcpy (&ap[1], addr, addrlen);
717 ap->addrlen = addrlen;
718 ap->connection = connection;
720 switch (ap->addr->sa_family)
723 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
726 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
731 return; /* not supported by us */
733 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
734 if (NULL == ap->sock)
737 return; /* not supported by OS */
739 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
740 GNUNET_a2s (ap->addr, ap->addrlen), connection);
742 GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
743 (EINPROGRESS != errno))
745 /* maybe refused / unsupported address, try next */
746 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
748 LOG (GNUNET_ERROR_TYPE_INFO, _("Failed to connect to `%s' (%p)\n"),
749 GNUNET_a2s (ap->addr, ap->addrlen), connection);
751 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
755 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
756 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
757 if (NULL != connection->nth.notify_ready)
759 GNUNET_TIME_relative_min (delay,
760 GNUNET_TIME_absolute_get_remaining (connection->
761 nth.transmit_timeout));
762 if (NULL != connection->receiver)
764 GNUNET_TIME_relative_min (delay,
765 GNUNET_TIME_absolute_get_remaining
766 (connection->receive_timeout));
768 GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
769 &connect_probe_continuation, ap);
774 * Create a connection handle by (asynchronously) connecting to a host.
775 * This function returns immediately, even if the connection has not
776 * yet been established. This function only creates TCP connections.
778 * @param cfg configuration to use
779 * @param hostname name of the host to connect to
780 * @param port port to connect to
781 * @return the connection handle
783 struct GNUNET_CONNECTION_Handle *
784 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle
785 *cfg, const char *hostname,
788 struct GNUNET_CONNECTION_Handle *connection;
790 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
791 connection = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle));
792 connection->cfg = cfg;
793 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
794 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
795 connection->port = port;
796 connection->hostname = GNUNET_strdup (hostname);
797 connection->dns_active =
798 GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
799 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
800 &try_connect_using_address, connection);
806 * Create a connection handle by connecting to a UNIX domain service.
807 * This function returns immediately, even if the connection has not
808 * yet been established. This function only creates UNIX connections.
810 * @param cfg configuration to use
811 * @param unixpath path to connect to
812 * @return the connection handle, NULL on systems without UNIX support
814 struct GNUNET_CONNECTION_Handle *
815 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
816 GNUNET_CONFIGURATION_Handle
817 *cfg, const char *unixpath)
820 struct GNUNET_CONNECTION_Handle *connection;
821 struct sockaddr_un *un;
824 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
825 un = GNUNET_malloc (sizeof (struct sockaddr_un));
826 un->sun_family = AF_UNIX;
827 slen = strlen (unixpath);
828 if (slen >= sizeof (un->sun_path))
829 slen = sizeof (un->sun_path) - 1;
830 memcpy (un->sun_path, unixpath, slen);
831 un->sun_path[slen] = '\0';
832 slen = sizeof (struct sockaddr_un);
833 #if HAVE_SOCKADDR_IN_SIN_LEN
834 un->sun_len = (u_char) slen;
837 un->sun_path[0] = '\0';
839 connection = GNUNET_malloc (sizeof (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 = slen;
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))
858 /* Just return; we expect everything to work eventually so don't fail HARD */
859 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
860 connection->sock = NULL;
863 connect_success_continuation (connection);
872 * Create a connection handle by (asynchronously) connecting to a host.
873 * This function returns immediately, even if the connection has not
874 * yet been established. This function only creates TCP connections.
876 * @param af_family address family to use
877 * @param serv_addr server address
878 * @param addrlen length of server address
879 * @return the connection handle
881 struct GNUNET_CONNECTION_Handle *
882 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
883 const struct sockaddr *serv_addr,
886 struct GNUNET_NETWORK_Handle *s;
887 struct GNUNET_CONNECTION_Handle *connection;
889 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
892 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
895 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
896 (EINPROGRESS != errno))
898 /* maybe refused / unsupported address, try next */
899 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
900 LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
901 GNUNET_a2s (serv_addr, addrlen));
902 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
905 connection = GNUNET_CONNECTION_create_from_existing (s);
906 connection->addr = GNUNET_malloc (addrlen);
907 memcpy (connection->addr, serv_addr, addrlen);
908 connection->addrlen = addrlen;
909 LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
910 GNUNET_a2s (serv_addr, addrlen), connection);
916 * Check if connection is valid (no fatal errors have happened so far).
917 * Note that a connection that is still trying to connect is considered
920 * @param connection connection to check
921 * @return GNUNET_YES if valid, GNUNET_NO otherwise
924 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
926 if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
927 return GNUNET_YES; /* still trying to connect */
928 return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
933 * Close the connection and free associated resources. There must
934 * not be any pending requests for reading or writing to the
935 * connection at this time.
937 * @param connection connection to destroy
940 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
942 struct AddressProbe *pos;
944 LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
945 GNUNET_assert (NULL == connection->nth.notify_ready);
946 GNUNET_assert (NULL == connection->receiver);
947 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
949 GNUNET_SCHEDULER_cancel (connection->write_task);
950 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
951 connection->write_buffer_off = 0;
953 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
955 GNUNET_SCHEDULER_cancel (connection->read_task);
956 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
958 if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
960 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
961 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
963 connection->nth.notify_ready = NULL;
964 if (NULL != connection->dns_active)
966 GNUNET_RESOLVER_request_cancel (connection->dns_active);
967 connection->dns_active = NULL;
969 while (NULL != (pos = connection->ap_head))
971 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
972 GNUNET_SCHEDULER_cancel (pos->task);
973 GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
976 if ( (NULL != connection->sock) &&
977 (GNUNET_YES != connection->persist) )
979 if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
980 (ENOTCONN != errno) &&
981 (ECONNRESET != errno) )
982 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
984 if (NULL != connection->sock)
986 if (GNUNET_YES != connection->persist)
987 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
989 GNUNET_free (connection->sock); /* at least no memory leak (we deliberately
990 * leak the socket in this special case) ... */
992 GNUNET_free_non_null (connection->addr);
993 GNUNET_free_non_null (connection->hostname);
994 GNUNET_free (connection->write_buffer);
995 GNUNET_free (connection);
1000 * This function is called once we either timeout
1001 * or have data ready to read.
1003 * @param cls connection to read from
1004 * @param tc scheduler context
1007 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1009 struct GNUNET_CONNECTION_Handle *connection = cls;
1010 char buffer[connection->max];
1012 GNUNET_CONNECTION_Receiver receiver;
1014 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1015 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1017 /* ignore shutdown request, go again immediately */
1018 connection->read_task =
1019 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1020 (connection->receive_timeout), connection->sock,
1021 &receive_ready, connection);
1024 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1026 LOG (GNUNET_ERROR_TYPE_DEBUG,
1027 "Receive from `%s' encounters error: timeout (%p)\n",
1028 GNUNET_a2s (connection->addr, connection->addrlen),
1029 GNUNET_TIME_absolute_get_duration (connection->receive_timeout).rel_value,
1031 signal_receive_timeout (connection);
1034 if (NULL == connection->sock)
1036 /* connect failed for good */
1037 signal_receive_error (connection, ECONNREFUSED);
1040 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1042 ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1047 signal_receive_error (connection, errno);
1050 LOG (GNUNET_ERROR_TYPE_DEBUG,
1051 "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1052 connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1053 GNUNET_assert (NULL != (receiver = connection->receiver));
1054 connection->receiver = NULL;
1055 receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1060 * Receive data from the given connection. Note that this function will
1061 * call "receiver" asynchronously using the scheduler. It will
1062 * "immediately" return. Note that there MUST only be one active
1063 * receive call per connection at any given point in time (so do not
1064 * call receive again until the receiver callback has been invoked).
1066 * @param connection connection handle
1067 * @param max maximum number of bytes to read
1068 * @param timeout maximum amount of time to wait
1069 * @param receiver function to call with received data
1070 * @param receiver_cls closure for receiver
1073 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1074 struct GNUNET_TIME_Relative timeout,
1075 GNUNET_CONNECTION_Receiver receiver,
1078 GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1079 (NULL == connection->receiver));
1080 GNUNET_assert (NULL != receiver);
1081 connection->receiver = receiver;
1082 connection->receiver_cls = receiver_cls;
1083 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1084 connection->max = max;
1085 if (NULL != connection->sock)
1087 connection->read_task =
1088 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1089 (connection->receive_timeout), connection->sock,
1090 &receive_ready, connection);
1093 if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1095 connection->receiver = NULL;
1096 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1103 * Cancel receive job on the given connection. Note that the
1104 * receiver callback must not have been called yet in order
1105 * for the cancellation to be valid.
1107 * @param connection connection handle
1108 * @return closure of the original receiver callback closure
1111 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1113 if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1115 GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1116 connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1118 connection->receiver = NULL;
1119 return connection->receiver_cls;
1124 * Try to call the transmit notify method (check if we do
1125 * have enough space available first)!
1127 * @param connection connection for which we should do this processing
1128 * @return GNUNET_YES if we were able to call notify
1131 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1136 GNUNET_CONNECTION_TransmitReadyNotify notify;
1138 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1139 if (NULL == (notify = connection->nth.notify_ready))
1141 used = connection->write_buffer_off - connection->write_buffer_pos;
1142 avail = connection->write_buffer_size - used;
1143 size = connection->nth.notify_size;
1146 connection->nth.notify_ready = NULL;
1147 if (connection->write_buffer_size - connection->write_buffer_off < size)
1149 /* need to compact */
1150 memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1152 connection->write_buffer_off -= connection->write_buffer_pos;
1153 connection->write_buffer_pos = 0;
1155 avail = connection->write_buffer_size - connection->write_buffer_off;
1156 GNUNET_assert (avail >= size);
1158 notify (connection->nth.notify_ready_cls, avail,
1159 &connection->write_buffer[connection->write_buffer_off]);
1160 GNUNET_assert (size <= avail);
1162 connection->write_buffer_off += size;
1168 * Task invoked by the scheduler when a call to transmit
1169 * is timing out (we never got enough buffer space to call
1170 * the callback function before the specified timeout
1173 * This task notifies the client about the timeout.
1175 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1176 * @param tc scheduler context
1179 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1181 struct GNUNET_CONNECTION_Handle *connection = cls;
1182 GNUNET_CONNECTION_TransmitReadyNotify notify;
1184 connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1185 LOG (GNUNET_ERROR_TYPE_DEBUG,
1186 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1187 connection->hostname,
1188 connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1189 notify = connection->nth.notify_ready;
1190 GNUNET_assert (NULL != notify);
1191 connection->nth.notify_ready = NULL;
1192 notify (connection->nth.notify_ready_cls, 0, NULL);
1197 * Task invoked by the scheduler when we failed to connect
1198 * at the time of being asked to transmit.
1200 * This task notifies the client about the error.
1202 * @param cls the 'struct GNUNET_CONNECTION_Handle'
1203 * @param tc scheduler context
1206 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1208 struct GNUNET_CONNECTION_Handle *connection = cls;
1209 GNUNET_CONNECTION_TransmitReadyNotify notify;
1211 LOG (GNUNET_ERROR_TYPE_DEBUG,
1212 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1213 connection->nth.notify_size, connection->hostname, connection->port, connection);
1214 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1215 notify = connection->nth.notify_ready;
1216 connection->nth.notify_ready = NULL;
1217 notify (connection->nth.notify_ready_cls, 0, NULL);
1222 * We are ready to transmit (or got a timeout).
1224 * @param cls our connection handle
1225 * @param tc task context describing why we are here
1228 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1230 struct GNUNET_CONNECTION_Handle *connection = cls;
1231 GNUNET_CONNECTION_TransmitReadyNotify notify;
1235 LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1236 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1237 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1238 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1239 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1241 if (NULL != connection->sock)
1242 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1243 LOG (GNUNET_ERROR_TYPE_DEBUG,
1244 "Transmit to `%s' fails, shutdown happened (%p).\n",
1245 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1246 notify = connection->nth.notify_ready;
1249 connection->nth.notify_ready = NULL;
1250 notify (connection->nth.notify_ready_cls, 0, NULL);
1254 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1256 LOG (GNUNET_ERROR_TYPE_DEBUG,
1257 "Transmit to `%s' fails, time out reached (%p).\n",
1258 GNUNET_a2s (connection->addr, connection->addrlen), connection);
1259 notify = connection->nth.notify_ready;
1260 GNUNET_assert (NULL != notify);
1261 connection->nth.notify_ready = NULL;
1262 notify (connection->nth.notify_ready_cls, 0, NULL);
1265 GNUNET_assert (NULL != connection->sock);
1266 if (NULL == tc->write_ready)
1268 /* special circumstances (in particular, PREREQ_DONE after
1269 * connect): not yet ready to write, but no "fatal" error either.
1271 goto SCHEDULE_WRITE;
1273 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1275 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1276 /* special circumstances (in particular, shutdown): not yet ready
1277 * to write, but no "fatal" error either. Hence retry. */
1278 goto SCHEDULE_WRITE;
1280 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1281 if ((NULL != connection->nth.notify_ready) &&
1282 (connection->write_buffer_size < connection->nth.notify_size))
1284 connection->write_buffer =
1285 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1286 connection->write_buffer_size = connection->nth.notify_size;
1288 process_notify (connection);
1289 have = connection->write_buffer_off - connection->write_buffer_pos;
1292 /* no data ready for writing, terminate write loop */
1295 GNUNET_assert (have <= connection->write_buffer_size);
1296 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1297 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1300 GNUNET_NETWORK_socket_send (connection->sock,
1301 &connection->write_buffer[connection->write_buffer_pos],
1307 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1309 GNUNET_SCHEDULER_cancel (connection->write_task);
1310 connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1312 signal_transmit_error (connection, errno);
1315 LOG (GNUNET_ERROR_TYPE_DEBUG,
1316 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1317 (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1318 connection->write_buffer_pos += ret;
1319 if (connection->write_buffer_pos == connection->write_buffer_off)
1321 /* transmitted all pending data */
1322 connection->write_buffer_pos = 0;
1323 connection->write_buffer_off = 0;
1325 if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1326 return; /* all data sent! */
1327 /* not done writing, schedule more */
1329 LOG (GNUNET_ERROR_TYPE_DEBUG,
1330 "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1331 have = connection->write_buffer_off - connection->write_buffer_pos;
1332 GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1333 if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1334 connection->write_task =
1335 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1336 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1337 GNUNET_TIME_absolute_get_remaining
1338 (connection->nth.transmit_timeout),
1339 connection->sock, &transmit_ready, connection);
1344 * Ask the connection to call us once the specified number of bytes
1345 * are free in the transmission buffer. May call the notify
1346 * method immediately if enough space is available.
1348 * @param connection connection
1349 * @param size number of bytes to send
1350 * @param timeout after how long should we give up (and call
1351 * notify with buf NULL and size 0)?
1352 * @param notify function to call
1353 * @param notify_cls closure for notify
1354 * @return non-NULL if the notify callback was queued,
1355 * NULL if we are already going to notify someone else (busy)
1357 struct GNUNET_CONNECTION_TransmitHandle *
1358 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1360 struct GNUNET_TIME_Relative timeout,
1361 GNUNET_CONNECTION_TransmitReadyNotify
1362 notify, void *notify_cls)
1364 if (NULL != connection->nth.notify_ready)
1369 GNUNET_assert (NULL != notify);
1370 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1371 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1372 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1373 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1374 connection->nth.notify_ready = notify;
1375 connection->nth.notify_ready_cls = notify_cls;
1376 connection->nth.connection = connection;
1377 connection->nth.notify_size = size;
1378 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1379 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1380 if ((NULL == connection->sock) &&
1381 (NULL == connection->ap_head) &&
1382 (NULL == connection->dns_active))
1384 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1385 GNUNET_SCHEDULER_cancel (connection->write_task);
1386 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1387 return &connection->nth;
1389 if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1390 return &connection->nth; /* previous transmission still in progress */
1391 if (NULL != connection->sock)
1393 /* connected, try to transmit now */
1394 LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1395 connection->write_task =
1396 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1397 (connection->nth.transmit_timeout),
1398 connection->sock, &transmit_ready, connection);
1399 return &connection->nth;
1401 /* not yet connected, wait for connection */
1402 LOG (GNUNET_ERROR_TYPE_DEBUG,
1403 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1404 connection->nth.timeout_task =
1405 GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1406 return &connection->nth;
1411 * Cancel the specified transmission-ready notification.
1413 * @param th notification to cancel
1416 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1417 GNUNET_CONNECTION_TransmitHandle
1420 GNUNET_assert (NULL != th->notify_ready);
1421 th->notify_ready = NULL;
1422 if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1424 GNUNET_SCHEDULER_cancel (th->timeout_task);
1425 th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1427 if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1429 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1430 th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1434 /* end of connection.c */