2 This file is part of GNUnet.
3 Copyright (C) 2009-2013 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, 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 struct GNUNET_SCHEDULER_Task * 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 struct GNUNET_SCHEDULER_Task * 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 @e receiver.
178 * Pointer to our write buffer.
183 * Current size of our @e write_buffer.
185 size_t write_buffer_size;
188 * Current write-offset in @e write_buffer (where
189 * would we write next).
191 size_t write_buffer_off;
194 * Current read-offset in @e 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 struct GNUNET_SCHEDULER_Task *read_task;
210 * Write task that we may need to wait for.
212 struct GNUNET_SCHEDULER_Task *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 use, 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;
255 * Handle to subsequent connection after proxy handshake completes,
257 struct GNUNET_CONNECTION_Handle *proxy_handshake;
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_new (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_cb function to use to check if access is allowed
320 * @param access_cb_cls closure for @a access_cb
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_cb,
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,
348 (struct sockaddr *) &addr,
353 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
356 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
359 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
363 sa = (struct sockaddr *) addr;
364 v6 = (struct sockaddr_in6 *) addr;
365 if ( (AF_INET6 == sa->sa_family) &&
366 (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)) )
368 /* convert to V4 address */
369 v4 = GNUNET_new (struct sockaddr_in);
370 memset (v4, 0, sizeof (struct sockaddr_in));
371 v4->sin_family = AF_INET;
372 #if HAVE_SOCKADDR_IN_SIN_LEN
373 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
375 GNUNET_memcpy (&v4->sin_addr,
376 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
377 sizeof (struct in_addr)],
378 sizeof (struct in_addr));
379 v4->sin_port = v6->sin6_port;
381 addrlen = sizeof (struct sockaddr_in);
385 uaddr = GNUNET_malloc (addrlen);
386 GNUNET_memcpy (uaddr, addr, addrlen);
391 if (AF_UNIX == sa->sa_family)
395 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock),
401 /* largely traditional GNU/Linux */
404 getsockopt (GNUNET_NETWORK_get_fd (sock),
409 (olen == sizeof (uc)) )
416 #if HAVE_GETPEERUCRED
417 /* this is for Solaris 10 */
421 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
423 gc.uid = ucred_geteuid (uc);
424 gc.gid = ucred_getegid (uc);
433 if ( (NULL != access_cb) &&
434 (GNUNET_YES != (aret = access_cb (access_cb_cls,
439 if (GNUNET_NO == aret)
440 LOG (GNUNET_ERROR_TYPE_INFO,
441 _("Access denied to `%s'\n"),
444 GNUNET_break (GNUNET_OK ==
445 GNUNET_NETWORK_socket_shutdown (sock,
447 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
451 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
452 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
453 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
454 connection->addr = uaddr;
455 connection->addrlen = addrlen;
456 connection->sock = sock;
457 LOG (GNUNET_ERROR_TYPE_INFO,
458 _("Accepting connection from `%s': %p\n"),
467 * Obtain the network address of the other party.
469 * @param connection the client to get the address for
470 * @param addr where to store the address
471 * @param addrlen where to store the length of the @a addr
472 * @return #GNUNET_OK on success
475 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
479 if ((NULL == connection->addr) || (0 == connection->addrlen))
481 *addr = GNUNET_malloc (connection->addrlen);
482 GNUNET_memcpy (*addr, connection->addr, connection->addrlen);
483 *addrlen = connection->addrlen;
489 * Tell the receiver callback that we had an IO error.
491 * @param connection connection to signal error
492 * @param errcode error code to send
495 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection,
498 GNUNET_CONNECTION_Receiver receiver;
500 LOG (GNUNET_ERROR_TYPE_DEBUG,
501 "Receive encounters error (%s), connection closed (%p)\n",
504 GNUNET_assert (NULL != (receiver = connection->receiver));
505 connection->receiver = NULL;
506 receiver (connection->receiver_cls,
516 * Tell the receiver callback that a timeout was reached.
518 * @param connection connection to signal for
521 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
523 GNUNET_CONNECTION_Receiver receiver;
525 LOG (GNUNET_ERROR_TYPE_DEBUG,
526 "Connection signals timeout to receiver (%p)!\n",
528 GNUNET_assert (NULL != (receiver = connection->receiver));
529 connection->receiver = NULL;
530 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
535 * We failed to transmit data to the service, signal the error.
537 * @param connection handle that had trouble
538 * @param ecode error code (errno)
541 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
544 GNUNET_CONNECTION_TransmitReadyNotify notify;
546 LOG (GNUNET_ERROR_TYPE_DEBUG,
547 "Transmission encounterd error (%s), connection closed (%p)\n",
550 if (NULL != connection->sock)
552 (void) GNUNET_NETWORK_socket_shutdown (connection->sock,
554 GNUNET_break (GNUNET_OK ==
555 GNUNET_NETWORK_socket_close (connection->sock));
556 connection->sock = NULL;
557 GNUNET_assert (NULL == connection->write_task);
559 if (NULL != connection->read_task)
561 /* send errors trigger read errors... */
562 GNUNET_SCHEDULER_cancel (connection->read_task);
563 connection->read_task = NULL;
564 signal_receive_timeout (connection);
567 if (NULL == connection->nth.notify_ready)
568 return; /* nobody to tell about it */
569 notify = connection->nth.notify_ready;
570 connection->nth.notify_ready = NULL;
571 notify (connection->nth.notify_ready_cls,
578 * We've failed for good to establish a connection (timeout or
579 * no more addresses to try).
581 * @param connection the connection we tried to establish
584 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
586 LOG (GNUNET_ERROR_TYPE_INFO,
587 "Failed to establish TCP connection to `%s:%u', no further addresses to try.\n",
588 connection->hostname,
590 GNUNET_break (NULL == connection->ap_head);
591 GNUNET_break (NULL == connection->ap_tail);
592 GNUNET_break (GNUNET_NO == connection->dns_active);
593 GNUNET_break (NULL == connection->sock);
594 GNUNET_assert (NULL == connection->write_task);
595 GNUNET_assert (NULL == connection->proxy_handshake);
597 /* signal errors for jobs that used to wait on the connection */
598 connection->destroy_later = 1;
599 if (NULL != connection->receiver)
600 signal_receive_error (connection,
602 if (NULL != connection->nth.notify_ready)
604 GNUNET_assert (NULL != connection->nth.timeout_task);
605 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
606 connection->nth.timeout_task = NULL;
607 signal_transmit_error (connection,
610 if (-1 == connection->destroy_later)
613 connection->destroy_later = 0;
614 GNUNET_CONNECTION_destroy (connection);
617 connection->destroy_later = 0;
622 * We are ready to transmit (or got a timeout).
624 * @param cls our connection handle
627 transmit_ready (void *cls);
631 * This function is called once we either timeout or have data ready
634 * @param cls connection to read from
637 receive_ready (void *cls);
641 * We've succeeded in establishing a connection.
643 * @param connection the connection we tried to establish
646 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
648 LOG (GNUNET_ERROR_TYPE_DEBUG,
649 "Connection to `%s' succeeded! (%p)\n",
650 GNUNET_a2s (connection->addr,
651 connection->addrlen),
653 /* trigger jobs that waited for the connection */
654 if (NULL != connection->receiver)
656 LOG (GNUNET_ERROR_TYPE_DEBUG,
657 "Connection succeeded, starting with receiving data (%p)\n",
659 GNUNET_assert (NULL == connection->read_task);
660 connection->read_task =
661 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
662 (connection->receive_timeout),
664 &receive_ready, connection);
666 if (NULL != connection->nth.notify_ready)
668 LOG (GNUNET_ERROR_TYPE_DEBUG,
669 "Connection succeeded, starting with sending data (%p)\n",
671 GNUNET_assert (connection->nth.timeout_task != NULL);
672 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
673 connection->nth.timeout_task = NULL;
674 GNUNET_assert (connection->write_task == NULL);
675 connection->write_task =
676 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
677 (connection->nth.transmit_timeout), connection->sock,
678 &transmit_ready, connection);
684 * Scheduler let us know that we're either ready to write on the
685 * socket OR connect timed out. Do the right thing.
687 * @param cls the `struct AddressProbe *` with the address that we are probing
690 connect_probe_continuation (void *cls)
692 struct AddressProbe *ap = cls;
693 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
694 const struct GNUNET_SCHEDULER_TaskContext *tc;
695 struct AddressProbe *pos;
699 GNUNET_assert (NULL != ap->sock);
700 GNUNET_CONTAINER_DLL_remove (connection->ap_head,
703 len = sizeof (error);
706 tc = GNUNET_SCHEDULER_get_task_context ();
707 if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
709 GNUNET_NETWORK_socket_getsockopt (ap->sock,
716 GNUNET_break (GNUNET_OK ==
717 GNUNET_NETWORK_socket_close (ap->sock));
719 if ( (NULL == connection->ap_head) &&
720 (GNUNET_NO == connection->dns_active) &&
721 (NULL == connection->proxy_handshake) )
722 connect_fail_continuation (connection);
725 GNUNET_assert (NULL == connection->sock);
726 connection->sock = ap->sock;
727 GNUNET_assert (NULL == connection->addr);
728 connection->addr = GNUNET_malloc (ap->addrlen);
729 GNUNET_memcpy (connection->addr, ap->addr, ap->addrlen);
730 connection->addrlen = ap->addrlen;
732 /* cancel all other attempts */
733 while (NULL != (pos = connection->ap_head))
735 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
736 GNUNET_SCHEDULER_cancel (pos->task);
737 GNUNET_CONTAINER_DLL_remove (connection->ap_head,
742 connect_success_continuation (connection);
747 * Try to establish a connection given the specified address.
748 * This function is called by the resolver once we have a DNS reply.
750 * @param cls our `struct GNUNET_CONNECTION_Handle *`
751 * @param addr address to try, NULL for "last call"
752 * @param addrlen length of @a addr
755 try_connect_using_address (void *cls,
756 const struct sockaddr *addr,
759 struct GNUNET_CONNECTION_Handle *connection = cls;
760 struct AddressProbe *ap;
761 struct GNUNET_TIME_Relative delay;
765 connection->dns_active = NULL;
766 if ((NULL == connection->ap_head) &&
767 (NULL == connection->sock) &&
768 (NULL == connection->proxy_handshake))
769 connect_fail_continuation (connection);
772 if (NULL != connection->sock)
773 return; /* already connected */
774 GNUNET_assert (NULL == connection->addr);
776 LOG (GNUNET_ERROR_TYPE_DEBUG,
777 "Trying to connect using address `%s:%u/%s:%u'\n",
778 connection->hostname,
780 GNUNET_a2s (addr, addrlen),
782 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
783 ap->addr = (const struct sockaddr *) &ap[1];
784 GNUNET_memcpy (&ap[1], addr, addrlen);
785 ap->addrlen = addrlen;
786 ap->connection = connection;
788 switch (ap->addr->sa_family)
791 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
794 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
799 return; /* not supported by us */
801 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family,
803 if (NULL == ap->sock)
806 return; /* not supported by OS */
808 LOG (GNUNET_ERROR_TYPE_INFO,
809 "Trying to connect to `%s' (%p)\n",
810 GNUNET_a2s (ap->addr, ap->addrlen),
813 GNUNET_NETWORK_socket_connect (ap->sock,
816 (EINPROGRESS != errno))
818 /* maybe refused / unsupported address, try next */
819 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
820 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
824 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
825 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
826 if (NULL != connection->nth.notify_ready)
827 delay = GNUNET_TIME_relative_min (delay,
828 GNUNET_TIME_absolute_get_remaining (connection->nth.transmit_timeout));
829 if (NULL != connection->receiver)
830 delay = GNUNET_TIME_relative_min (delay,
831 GNUNET_TIME_absolute_get_remaining (connection->receive_timeout));
832 ap->task = GNUNET_SCHEDULER_add_write_net (delay,
834 &connect_probe_continuation,
840 * Create a connection handle by (asynchronously) connecting to a host.
841 * This function returns immediately, even if the connection has not
842 * yet been established. This function only creates TCP connections.
844 * @param cfg configuration to use
845 * @param hostname name of the host to connect to
846 * @param port port to connect to
847 * @return the connection handle
849 struct GNUNET_CONNECTION_Handle *
850 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
851 const char *hostname,
854 struct GNUNET_CONNECTION_Handle *connection;
856 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
857 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
858 connection->cfg = cfg;
859 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
860 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
861 connection->port = port;
862 connection->hostname = GNUNET_strdup (hostname);
863 connection->dns_active =
864 GNUNET_RESOLVER_ip_get (connection->hostname,
866 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
867 &try_connect_using_address,
874 * Create a connection handle by connecting to a UNIX domain service.
875 * This function returns immediately, even if the connection has not
876 * yet been established. This function only creates UNIX connections.
878 * @param cfg configuration to use
879 * @param unixpath path to connect to
880 * @return the connection handle, NULL on systems without UNIX support
882 struct GNUNET_CONNECTION_Handle *
883 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct GNUNET_CONFIGURATION_Handle *cfg,
884 const char *unixpath)
887 struct GNUNET_CONNECTION_Handle *connection;
888 struct sockaddr_un *un;
890 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
891 un = GNUNET_new (struct sockaddr_un);
892 un->sun_family = AF_UNIX;
893 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
898 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
900 "USE_ABSTRACT_SOCKETS");
901 if (GNUNET_YES == abstract)
902 un->sun_path[0] = '\0';
905 #if HAVE_SOCKADDR_UN_SUN_LEN
906 un->sun_len = (u_char) sizeof (struct sockaddr_un);
908 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
909 connection->cfg = cfg;
910 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
911 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
912 connection->port = 0;
913 connection->hostname = NULL;
914 connection->addr = (struct sockaddr *) un;
915 connection->addrlen = sizeof (struct sockaddr_un);
916 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX,
919 if (NULL == connection->sock)
921 GNUNET_free (connection->addr);
922 GNUNET_free (connection->write_buffer);
923 GNUNET_free (connection);
927 GNUNET_NETWORK_socket_connect (connection->sock,
929 connection->addrlen)) &&
930 (EINPROGRESS != errno) )
932 /* Just return; we expect everything to work eventually so don't fail HARD */
933 GNUNET_break (GNUNET_OK ==
934 GNUNET_NETWORK_socket_close (connection->sock));
935 connection->sock = NULL;
938 connect_success_continuation (connection);
947 * Create a connection handle by (asynchronously) connecting to a host.
948 * This function returns immediately, even if the connection has not
949 * yet been established. This function only creates TCP connections.
951 * @param s socket to connect
952 * @param serv_addr server address
953 * @param addrlen length of @a serv_addr
954 * @return the connection handle
956 struct GNUNET_CONNECTION_Handle *
957 GNUNET_CONNECTION_connect_socket (struct GNUNET_NETWORK_Handle *s,
958 const struct sockaddr *serv_addr,
961 struct GNUNET_CONNECTION_Handle *connection;
964 GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
965 (EINPROGRESS != errno) )
967 /* maybe refused / unsupported address, try next */
968 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
970 LOG (GNUNET_ERROR_TYPE_DEBUG,
971 "Attempt to connect to `%s' failed\n",
972 GNUNET_a2s (serv_addr,
974 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
977 connection = GNUNET_CONNECTION_create_from_existing (s);
978 connection->addr = GNUNET_malloc (addrlen);
979 GNUNET_memcpy (connection->addr, serv_addr, addrlen);
980 connection->addrlen = addrlen;
981 LOG (GNUNET_ERROR_TYPE_INFO,
982 "Trying to connect to `%s' (%p)\n",
983 GNUNET_a2s (serv_addr, addrlen),
990 * Create a connection handle by creating a socket and
991 * (asynchronously) connecting to a host. This function returns
992 * immediately, even if the connection has not yet been established.
993 * This function only creates TCP connections.
995 * @param af_family address family to use
996 * @param serv_addr server address
997 * @param addrlen length of @a serv_addr
998 * @return the connection handle
1000 struct GNUNET_CONNECTION_Handle *
1001 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
1002 const struct sockaddr *serv_addr,
1005 struct GNUNET_NETWORK_Handle *s;
1007 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
1010 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
1014 return GNUNET_CONNECTION_connect_socket (s,
1021 * Check if connection is valid (no fatal errors have happened so far).
1022 * Note that a connection that is still trying to connect is considered
1025 * @param connection connection to check
1026 * @return #GNUNET_YES if valid, #GNUNET_NO otherwise
1029 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
1031 if ((NULL != connection->ap_head) ||
1032 (NULL != connection->dns_active) ||
1033 (NULL != connection->proxy_handshake))
1034 return GNUNET_YES; /* still trying to connect */
1035 if ( (0 != connection->destroy_later) ||
1036 (NULL == connection->sock) )
1043 * Close the connection and free associated resources. There must
1044 * not be any pending requests for reading or writing to the
1045 * connection at this time.
1047 * @param connection connection to destroy
1050 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
1052 struct AddressProbe *pos;
1054 if (0 != connection->destroy_later)
1056 connection->destroy_later = -1;
1059 LOG (GNUNET_ERROR_TYPE_DEBUG,
1060 "Shutting down connection (%p)\n",
1062 GNUNET_assert (NULL == connection->nth.notify_ready);
1063 GNUNET_assert (NULL == connection->receiver);
1064 if (NULL != connection->write_task)
1066 GNUNET_SCHEDULER_cancel (connection->write_task);
1067 connection->write_task = NULL;
1068 connection->write_buffer_off = 0;
1070 if (NULL != connection->read_task)
1072 GNUNET_SCHEDULER_cancel (connection->read_task);
1073 connection->read_task = NULL;
1075 if (NULL != connection->nth.timeout_task)
1077 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1078 connection->nth.timeout_task = NULL;
1080 connection->nth.notify_ready = NULL;
1081 if (NULL != connection->dns_active)
1083 GNUNET_RESOLVER_request_cancel (connection->dns_active);
1084 connection->dns_active = NULL;
1086 if (NULL != connection->proxy_handshake)
1088 /* GNUNET_CONNECTION_destroy (connection->proxy_handshake); */
1089 connection->proxy_handshake->destroy_later = -1;
1090 connection->proxy_handshake = NULL; /* Not leaked ??? */
1092 while (NULL != (pos = connection->ap_head))
1094 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1095 GNUNET_SCHEDULER_cancel (pos->task);
1096 GNUNET_CONTAINER_DLL_remove (connection->ap_head,
1097 connection->ap_tail,
1101 if ( (NULL != connection->sock) &&
1102 (GNUNET_YES != connection->persist) )
1105 GNUNET_NETWORK_socket_shutdown (connection->sock,
1107 (ENOTCONN != errno) &&
1108 (ECONNRESET != errno) )
1109 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1112 if (NULL != connection->sock)
1114 if (GNUNET_YES != connection->persist)
1116 GNUNET_break (GNUNET_OK ==
1117 GNUNET_NETWORK_socket_close (connection->sock));
1121 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1122 * leak the socket in this special case) ... */
1125 GNUNET_free_non_null (connection->addr);
1126 GNUNET_free_non_null (connection->hostname);
1127 GNUNET_free (connection->write_buffer);
1128 GNUNET_free (connection);
1133 * This function is called once we either timeout
1134 * or have data ready to read.
1136 * @param cls connection to read from
1139 receive_ready (void *cls)
1141 struct GNUNET_CONNECTION_Handle *connection = cls;
1142 const struct GNUNET_SCHEDULER_TaskContext *tc;
1143 char buffer[connection->max];
1145 GNUNET_CONNECTION_Receiver receiver;
1147 connection->read_task = NULL;
1148 tc = GNUNET_SCHEDULER_get_task_context ();
1149 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1151 LOG (GNUNET_ERROR_TYPE_DEBUG,
1152 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1153 GNUNET_a2s (connection->addr,
1154 connection->addrlen),
1155 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout),
1158 signal_receive_timeout (connection);
1161 if (NULL == connection->sock)
1163 /* connect failed for good */
1164 signal_receive_error (connection, ECONNREFUSED);
1167 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready,
1170 ret = GNUNET_NETWORK_socket_recv (connection->sock,
1177 signal_receive_error (connection, errno);
1180 LOG (GNUNET_ERROR_TYPE_DEBUG,
1181 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1184 GNUNET_a2s (connection->addr,
1185 connection->addrlen),
1187 GNUNET_assert (NULL != (receiver = connection->receiver));
1188 connection->receiver = NULL;
1189 receiver (connection->receiver_cls,
1193 connection->addrlen,
1199 * Receive data from the given connection. Note that this function
1200 * will call @a receiver asynchronously using the scheduler. It will
1201 * "immediately" return. Note that there MUST only be one active
1202 * receive call per connection at any given point in time (so do not
1203 * call receive again until the receiver callback has been invoked).
1205 * @param connection connection handle
1206 * @param max maximum number of bytes to read
1207 * @param timeout maximum amount of time to wait
1208 * @param receiver function to call with received data
1209 * @param receiver_cls closure for @a receiver
1212 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection,
1214 struct GNUNET_TIME_Relative timeout,
1215 GNUNET_CONNECTION_Receiver receiver,
1218 GNUNET_assert ((NULL == connection->read_task) &&
1219 (NULL == connection->receiver));
1220 GNUNET_assert (NULL != receiver);
1221 connection->receiver = receiver;
1222 connection->receiver_cls = receiver_cls;
1223 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1224 connection->max = max;
1225 if (NULL != connection->sock)
1227 connection->read_task =
1228 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1229 (connection->receive_timeout),
1235 if ((NULL == connection->dns_active) &&
1236 (NULL == connection->ap_head) &&
1237 (NULL == connection->proxy_handshake))
1239 connection->receiver = NULL;
1240 receiver (receiver_cls,
1250 * Cancel receive job on the given connection. Note that the
1251 * receiver callback must not have been called yet in order
1252 * for the cancellation to be valid.
1254 * @param connection connection handle
1255 * @return closure of the original receiver callback closure
1258 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1260 if (NULL != connection->read_task)
1262 GNUNET_assert (connection ==
1263 GNUNET_SCHEDULER_cancel (connection->read_task));
1264 connection->read_task = NULL;
1266 connection->receiver = NULL;
1267 return connection->receiver_cls;
1272 * Try to call the transmit notify method (check if we do
1273 * have enough space available first)!
1275 * @param connection connection for which we should do this processing
1276 * @return #GNUNET_YES if we were able to call notify
1279 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1284 GNUNET_CONNECTION_TransmitReadyNotify notify;
1286 LOG (GNUNET_ERROR_TYPE_DEBUG,
1287 "process_notify is running\n");
1288 GNUNET_assert (NULL == connection->write_task);
1289 if (NULL == (notify = connection->nth.notify_ready))
1291 LOG (GNUNET_ERROR_TYPE_DEBUG,
1292 "No one to notify\n");
1295 used = connection->write_buffer_off - connection->write_buffer_pos;
1296 avail = connection->write_buffer_size - used;
1297 size = connection->nth.notify_size;
1300 LOG (GNUNET_ERROR_TYPE_DEBUG,
1301 "Not enough buffer\n");
1304 connection->nth.notify_ready = NULL;
1305 if (connection->write_buffer_size - connection->write_buffer_off < size)
1307 /* need to compact */
1308 memmove (connection->write_buffer,
1309 &connection->write_buffer[connection->write_buffer_pos],
1311 connection->write_buffer_off -= connection->write_buffer_pos;
1312 connection->write_buffer_pos = 0;
1314 avail = connection->write_buffer_size - connection->write_buffer_off;
1315 GNUNET_assert (avail >= size);
1317 notify (connection->nth.notify_ready_cls, avail,
1318 &connection->write_buffer[connection->write_buffer_off]);
1319 GNUNET_assert (size <= avail);
1321 connection->write_buffer_off += size;
1327 * Task invoked by the scheduler when a call to transmit
1328 * is timing out (we never got enough buffer space to call
1329 * the callback function before the specified timeout
1332 * This task notifies the client about the timeout.
1334 * @param cls the `struct GNUNET_CONNECTION_Handle`
1337 transmit_timeout (void *cls)
1339 struct GNUNET_CONNECTION_Handle *connection = cls;
1340 GNUNET_CONNECTION_TransmitReadyNotify notify;
1342 connection->nth.timeout_task = NULL;
1343 LOG (GNUNET_ERROR_TYPE_DEBUG,
1344 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1345 connection->hostname,
1347 GNUNET_a2s (connection->addr,
1348 connection->addrlen),
1350 notify = connection->nth.notify_ready;
1351 GNUNET_assert (NULL != notify);
1352 connection->nth.notify_ready = NULL;
1353 notify (connection->nth.notify_ready_cls,
1360 * Task invoked by the scheduler when we failed to connect
1361 * at the time of being asked to transmit.
1363 * This task notifies the client about the error.
1365 * @param cls the `struct GNUNET_CONNECTION_Handle`
1368 connect_error (void *cls)
1370 struct GNUNET_CONNECTION_Handle *connection = cls;
1371 GNUNET_CONNECTION_TransmitReadyNotify notify;
1373 LOG (GNUNET_ERROR_TYPE_DEBUG,
1374 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1375 connection->nth.notify_size,
1376 connection->hostname,
1379 connection->write_task = NULL;
1380 notify = connection->nth.notify_ready;
1381 connection->nth.notify_ready = NULL;
1382 notify (connection->nth.notify_ready_cls,
1389 * We are ready to transmit (or got a timeout).
1391 * @param cls our connection handle
1394 transmit_ready (void *cls)
1396 struct GNUNET_CONNECTION_Handle *connection = cls;
1397 GNUNET_CONNECTION_TransmitReadyNotify notify;
1398 const struct GNUNET_SCHEDULER_TaskContext *tc;
1402 LOG (GNUNET_ERROR_TYPE_DEBUG,
1403 "transmit_ready running (%p).\n",
1405 GNUNET_assert (NULL != connection->write_task);
1406 connection->write_task = NULL;
1407 GNUNET_assert (NULL == connection->nth.timeout_task);
1408 tc = GNUNET_SCHEDULER_get_task_context ();
1409 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1411 LOG (GNUNET_ERROR_TYPE_DEBUG,
1412 "Transmit to `%s' fails, time out reached (%p).\n",
1413 GNUNET_a2s (connection->addr,
1414 connection->addrlen),
1416 notify = connection->nth.notify_ready;
1417 GNUNET_assert (NULL != notify);
1418 connection->nth.notify_ready = NULL;
1419 notify (connection->nth.notify_ready_cls, 0, NULL);
1422 GNUNET_assert (NULL != connection->sock);
1423 if (NULL == tc->write_ready)
1425 /* special circumstances (in particular, PREREQ_DONE after
1426 * connect): not yet ready to write, but no "fatal" error either.
1428 goto SCHEDULE_WRITE;
1430 if (! GNUNET_NETWORK_fdset_isset (tc->write_ready,
1433 GNUNET_assert (NULL == connection->write_task);
1434 /* special circumstances (in particular, shutdown): not yet ready
1435 * to write, but no "fatal" error either. Hence retry. */
1436 goto SCHEDULE_WRITE;
1438 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1439 if ((NULL != connection->nth.notify_ready) &&
1440 (connection->write_buffer_size < connection->nth.notify_size))
1442 connection->write_buffer =
1443 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1444 connection->write_buffer_size = connection->nth.notify_size;
1446 process_notify (connection);
1447 have = connection->write_buffer_off - connection->write_buffer_pos;
1450 /* no data ready for writing, terminate write loop */
1453 GNUNET_assert (have <= connection->write_buffer_size);
1454 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1455 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1458 GNUNET_NETWORK_socket_send (connection->sock,
1459 &connection->write_buffer[connection->write_buffer_pos],
1465 if (NULL != connection->write_task)
1467 GNUNET_SCHEDULER_cancel (connection->write_task);
1468 connection->write_task = NULL;
1470 signal_transmit_error (connection, errno);
1473 LOG (GNUNET_ERROR_TYPE_DEBUG,
1474 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1477 GNUNET_a2s (connection->addr,
1478 connection->addrlen),
1480 connection->write_buffer_pos += ret;
1481 if (connection->write_buffer_pos == connection->write_buffer_off)
1483 /* transmitted all pending data */
1484 connection->write_buffer_pos = 0;
1485 connection->write_buffer_off = 0;
1487 if ( (0 == connection->write_buffer_off) &&
1488 (NULL == connection->nth.notify_ready) )
1489 return; /* all data sent! */
1490 /* not done writing, schedule more */
1492 LOG (GNUNET_ERROR_TYPE_DEBUG,
1493 "Re-scheduling transmit_ready (more to do) (%p).\n",
1495 have = connection->write_buffer_off - connection->write_buffer_pos;
1496 GNUNET_assert ( (NULL != connection->nth.notify_ready) ||
1498 if (NULL == connection->write_task)
1499 connection->write_task =
1500 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1501 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1502 GNUNET_TIME_absolute_get_remaining
1503 (connection->nth.transmit_timeout),
1505 &transmit_ready, connection);
1510 * Ask the connection to call us once the specified number of bytes
1511 * are free in the transmission buffer. Will never call the @a notify
1512 * callback in this task, but always first go into the scheduler.
1514 * @param connection connection
1515 * @param size number of bytes to send
1516 * @param timeout after how long should we give up (and call
1517 * @a notify with buf NULL and size 0)?
1518 * @param notify function to call
1519 * @param notify_cls closure for @a notify
1520 * @return non-NULL if the notify callback was queued,
1521 * NULL if we are already going to notify someone else (busy)
1523 struct GNUNET_CONNECTION_TransmitHandle *
1524 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1526 struct GNUNET_TIME_Relative timeout,
1527 GNUNET_CONNECTION_TransmitReadyNotify notify,
1530 if (NULL != connection->nth.notify_ready)
1535 GNUNET_assert (NULL != notify);
1536 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1537 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1538 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1539 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1540 connection->nth.notify_ready = notify;
1541 connection->nth.notify_ready_cls = notify_cls;
1542 connection->nth.connection = connection;
1543 connection->nth.notify_size = size;
1544 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1545 GNUNET_assert (NULL == connection->nth.timeout_task);
1546 if ((NULL == connection->sock) &&
1547 (NULL == connection->ap_head) &&
1548 (NULL == connection->dns_active) &&
1549 (NULL == connection->proxy_handshake))
1551 if (NULL != connection->write_task)
1552 GNUNET_SCHEDULER_cancel (connection->write_task);
1553 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error,
1555 return &connection->nth;
1557 if (NULL != connection->write_task)
1558 return &connection->nth; /* previous transmission still in progress */
1559 if (NULL != connection->sock)
1561 /* connected, try to transmit now */
1562 LOG (GNUNET_ERROR_TYPE_DEBUG,
1563 "Scheduling transmission (%p).\n",
1565 connection->write_task =
1566 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1567 (connection->nth.transmit_timeout),
1569 &transmit_ready, connection);
1570 return &connection->nth;
1572 /* not yet connected, wait for connection */
1573 LOG (GNUNET_ERROR_TYPE_DEBUG,
1574 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n",
1576 connection->nth.timeout_task =
1577 GNUNET_SCHEDULER_add_delayed (timeout,
1580 return &connection->nth;
1585 * Cancel the specified transmission-ready notification.
1587 * @param th notification to cancel
1590 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct GNUNET_CONNECTION_TransmitHandle *th)
1592 GNUNET_assert (NULL != th->notify_ready);
1593 th->notify_ready = NULL;
1594 if (NULL != th->timeout_task)
1596 GNUNET_SCHEDULER_cancel (th->timeout_task);
1597 th->timeout_task = NULL;
1599 if (NULL != th->connection->write_task)
1601 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1602 th->connection->write_task = NULL;
1608 * Create a connection to be proxied using a given connection.
1610 * @param cph connection to proxy server
1611 * @return connection to be proxied
1613 struct GNUNET_CONNECTION_Handle *
1614 GNUNET_CONNECTION_create_proxied_from_handshake (struct GNUNET_CONNECTION_Handle *cph)
1616 struct GNUNET_CONNECTION_Handle *proxied = GNUNET_CONNECTION_create_from_existing (NULL);
1618 proxied->proxy_handshake = cph;
1624 * Activate proxied connection and destroy initial proxy handshake connection.
1625 * There must not be any pending requests for reading or writing to the
1626 * proxy hadshake connection at this time.
1628 * @param proxied connection connection to proxy server
1631 GNUNET_CONNECTION_acivate_proxied (struct GNUNET_CONNECTION_Handle *proxied)
1633 struct GNUNET_CONNECTION_Handle *cph = proxied->proxy_handshake;
1635 GNUNET_assert (NULL != cph);
1636 GNUNET_assert (NULL == proxied->sock);
1637 GNUNET_assert (NULL != cph->sock);
1638 proxied->sock = cph->sock;
1640 GNUNET_CONNECTION_destroy (cph);
1641 connect_success_continuation (proxied);
1645 /* end of connection.c */