2 This file is part of GNUnet.
3 (C) 2009 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"
41 #define DEBUG_CONNECTION GNUNET_NO
45 * Possible functions to call after connect failed or succeeded.
47 enum ConnectContinuations
55 * Call "receive_again".
57 COCO_RECEIVE_AGAIN = 1,
60 * Call "transmit_ready".
62 COCO_TRANSMIT_READY = 2,
65 * Call "destroy_continuation".
67 COCO_DESTROY_CONTINUATION = 4
72 * Transmission handle. There can only be one for each connection.
74 struct GNUNET_CONNECTION_TransmitHandle
78 * Function to call if the send buffer has notify_size
81 GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
84 * Closure for notify_ready.
86 void *notify_ready_cls;
91 struct GNUNET_CONNECTION_Handle *sh;
94 * Timeout for receiving (in absolute time).
96 struct GNUNET_TIME_Absolute transmit_timeout;
99 * Task called on timeout.
101 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
104 * At what number of bytes available in the
105 * write buffer should the notify method be called?
113 * During connect, we try multiple possible IP addresses
114 * to find out which one might work.
120 * This is a linked list.
122 struct AddressProbe *next;
125 * This is a doubly-linked list.
127 struct AddressProbe *prev;
130 * The address; do not free (allocated at the end of this struct).
132 const struct sockaddr *addr;
135 * Underlying OS's socket.
137 struct GNUNET_NETWORK_Handle *sock;
140 * Connection for which we are probing.
142 struct GNUNET_CONNECTION_Handle *h;
150 * Task waiting for the socket to finish connecting.
152 GNUNET_SCHEDULER_TaskIdentifier task;
157 * @brief handle for a network socket
159 struct GNUNET_CONNECTION_Handle
163 * Scheduler that was used for the connect task.
165 struct GNUNET_SCHEDULER_Handle *sched;
168 * Configuration to use.
170 const struct GNUNET_CONFIGURATION_Handle *cfg;
173 * Linked list of sockets we are currently trying out
176 struct AddressProbe *ap_head;
179 * Linked list of sockets we are currently trying out
182 struct AddressProbe *ap_tail;
185 * Network address of the other end-point, may be NULL.
187 struct sockaddr *addr;
190 * Pointer to the hostname if socket was
191 * created using DNS lookup, otherwise NULL.
196 * Underlying OS's socket, set to NULL after fatal errors.
198 struct GNUNET_NETWORK_Handle *sock;
201 * Function to call on data received, NULL if no receive is pending.
203 GNUNET_CONNECTION_Receiver receiver;
206 * Closure for receiver.
211 * Pointer to our write buffer.
216 * Size of our write buffer.
218 size_t write_buffer_size;
221 * Current write-offset in write buffer (where
222 * would we write next).
224 size_t write_buffer_off;
227 * Current read-offset in write buffer (how many
228 * bytes have already been send).
230 size_t write_buffer_pos;
238 * Read task that we may need to wait for.
240 GNUNET_SCHEDULER_TaskIdentifier read_task;
243 * Write task that we may need to wait for.
245 GNUNET_SCHEDULER_TaskIdentifier write_task;
248 * The handle we return for GNUNET_CONNECTION_notify_transmit_ready.
250 struct GNUNET_CONNECTION_TransmitHandle nth;
253 * Timeout for receiving (in absolute time).
255 struct GNUNET_TIME_Absolute receive_timeout;
258 * Functions to call after connect failed or succeeded.
260 enum ConnectContinuations ccs;
263 * Maximum number of bytes to read (for receiving).
268 * Are we still waiting for DNS replies (on connect)?
269 * GNUNET_YES if we are, GNUNET_NO if we are not waiting for DNS,
270 * GNUNET_SYSERR if destroying the handle was deferred due to
271 * a pending DNS lookup.
276 * Port to connect to.
284 * Create a socket handle by boxing an existing OS socket. The OS
285 * socket should henceforth be no longer used directly.
286 * GNUNET_socket_destroy will close it.
288 * @param sched scheduler to use
289 * @param osSocket existing socket to box
290 * @param maxbuf maximum write buffer size for the socket (use
291 * 0 for sockets that need no write buffers, such as listen sockets)
292 * @return the boxed socket handle
294 struct GNUNET_CONNECTION_Handle *
295 GNUNET_CONNECTION_create_from_existing (struct GNUNET_SCHEDULER_Handle
296 *sched, struct GNUNET_NETWORK_Handle *osSocket,
299 struct GNUNET_CONNECTION_Handle *ret;
300 ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle) + maxbuf);
301 ret->write_buffer = (char *) &ret[1];
302 ret->write_buffer_size = maxbuf;
303 ret->sock = osSocket;
310 * Create a socket handle by accepting on a listen socket. This
311 * function may block if the listen socket has no connection ready.
313 * @param sched scheduler to use
314 * @param access function to use to check if access is allowed
315 * @param access_cls closure for access
316 * @param lsock listen socket
317 * @param maxbuf maximum write buffer size for the socket (use
318 * 0 for sockets that need no write buffers, such as listen sockets)
319 * @return the socket handle, NULL on error
321 struct GNUNET_CONNECTION_Handle *
322 GNUNET_CONNECTION_create_from_accept (struct GNUNET_SCHEDULER_Handle
324 GNUNET_CONNECTION_AccessCheck access,
325 void *access_cls, struct GNUNET_NETWORK_Handle *lsock,
328 struct GNUNET_CONNECTION_Handle *ret;
331 struct GNUNET_NETWORK_Handle *sock;
333 struct sockaddr_in *v4;
334 struct sockaddr_in6 *v6;
338 addrlen = sizeof (addr);
339 sock = GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
342 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "accept");
345 if (addrlen > sizeof (addr))
348 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
352 sa = (struct sockaddr *) addr;
353 v6 = (struct sockaddr_in6 *) addr;
354 if ((sa->sa_family == AF_INET6) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
356 /* convert to V4 address */
357 v4 = GNUNET_malloc (sizeof (struct sockaddr_in));
358 memset (v4, 0, sizeof (struct sockaddr_in));
359 v4->sin_family = AF_INET;
360 memcpy (&v4->sin_addr,
361 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
362 sizeof (struct in_addr)],
363 sizeof (struct in_addr));
364 v4->sin_port = v6->sin6_port;
366 addrlen = sizeof (struct sockaddr_in);
370 uaddr = GNUNET_malloc (addrlen);
371 memcpy (uaddr, addr, addrlen);
374 if ((access != NULL) &&
375 (GNUNET_YES != (aret = access (access_cls, uaddr, addrlen))))
377 if (aret == GNUNET_NO)
378 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
379 _("Access denied to `%s'\n"),
380 GNUNET_a2s(uaddr, addrlen));
381 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
382 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
386 ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle) + maxbuf);
387 ret->write_buffer = (char *) &ret[1];
388 ret->write_buffer_size = maxbuf;
390 ret->addrlen = addrlen;
394 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
395 _("Accepting connection from `%s': %p\n"),
396 GNUNET_a2s(uaddr, addrlen),
403 * Obtain the network address of the other party.
405 * @param sock the client to get the address for
406 * @param addr where to store the address
407 * @param addrlen where to store the length of the address
408 * @return GNUNET_OK on success
411 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *sock,
412 void **addr, size_t * addrlen)
414 if ((sock->addr == NULL) || (sock->addrlen == 0))
416 *addr = GNUNET_malloc (sock->addrlen);
417 memcpy (*addr, sock->addr, sock->addrlen);
418 *addrlen = sock->addrlen;
424 * It is time to re-try connecting.
426 * @param cls the handle for the connection that should be re-tried
427 * @param tc unused scheduler taks context
430 retry_connect_continuation (void *cls,
431 const struct GNUNET_SCHEDULER_TaskContext *tc);
435 * This function is called after establishing a connection either has
436 * succeeded or timed out. Note that it is possible that the attempt
437 * timed out and that we're immediately retrying. If we are retrying,
438 * we need to wait again (or timeout); if we succeeded, we need to
439 * wait for data (or timeout).
441 * @param cls our connection handle
442 * @param tc task context describing why we are here
445 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
449 * Scheduler let us know that the connect task is finished (or was
450 * cancelled due to shutdown). Now really clean up.
452 * @param cls our "struct GNUNET_CONNECTION_Handle *"
456 destroy_continuation (void *cls,
457 const struct GNUNET_SCHEDULER_TaskContext *tc)
459 struct GNUNET_CONNECTION_Handle *sock = cls;
460 GNUNET_CONNECTION_TransmitReadyNotify notify;
462 if (sock->dns_active == GNUNET_YES)
464 sock->dns_active = GNUNET_SYSERR;
467 if (0 != (sock->ccs & COCO_TRANSMIT_READY))
470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
471 "Destroy waits for CCS-TR to be done (%p)\n",
474 sock->ccs |= COCO_DESTROY_CONTINUATION;
477 if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
481 "Destroy waits for write_task to be done (%p)\n",
484 GNUNET_SCHEDULER_add_after (sock->sched,
486 GNUNET_SCHEDULER_PRIORITY_KEEP,
488 &destroy_continuation, sock);
491 if (0 != (sock->ccs & COCO_RECEIVE_AGAIN))
493 sock->ccs |= COCO_DESTROY_CONTINUATION;
496 if (sock->sock != NULL)
499 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
500 "Shutting down socket (%p)\n",
503 GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
505 if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
507 GNUNET_SCHEDULER_add_after (sock->sched,
509 GNUNET_SCHEDULER_PRIORITY_KEEP,
511 &destroy_continuation, sock);
515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
516 "Destroy actually runs (%p)!\n",
519 GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
520 GNUNET_assert (sock->ccs == COCO_NONE);
521 if (NULL != (notify = sock->nth.notify_ready))
523 sock->nth.notify_ready = NULL;
524 notify (sock->nth.notify_ready_cls, 0, NULL);
526 if (sock->sock != NULL)
527 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
528 GNUNET_free_non_null (sock->addr);
529 GNUNET_free_non_null (sock->hostname);
531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
532 "Freeing memory of connection %p.\n",
541 * See if we are now connected. If not, wait longer for
542 * connect to succeed. If connected, we should be able
543 * to write now as well, unless we timed out.
545 * @param cls our connection handle
546 * @param tc task context describing why we are here
549 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
553 * We've failed for good to establish a connection.
555 * @param h the connection we tried to establish
558 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *h)
561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
562 "Failed to establish TCP connection to `%s:%u', no further addresses to try (%p).\n",
567 /* connect failed / timed out */
568 GNUNET_break (h->ap_head == NULL);
569 GNUNET_break (h->ap_tail == NULL);
570 GNUNET_break (h->dns_active == GNUNET_NO);
571 GNUNET_break (h->sock == NULL);
573 /* FIXME: trigger delayed reconnect attempt... */
574 /* trigger jobs that used to wait on "connect_task" */
575 if (0 != (h->ccs & COCO_RECEIVE_AGAIN))
578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
579 "connect_timeout_continuation triggers receive_again (%p)\n",
582 h->ccs -= COCO_RECEIVE_AGAIN;
583 h->read_task = GNUNET_SCHEDULER_add_after (h->sched,
585 GNUNET_SCHEDULER_PRIORITY_KEEP,
586 GNUNET_SCHEDULER_NO_TASK,
590 if (0 != (h->ccs & COCO_TRANSMIT_READY))
593 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
594 "connect_timeout_continuation cancels timeout_task, triggers transmit_ready (%p)\n",
597 GNUNET_assert (h->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
598 GNUNET_SCHEDULER_cancel (h->sched, h->nth.timeout_task);
599 h->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
600 h->ccs -= COCO_TRANSMIT_READY;
601 h->write_task = GNUNET_SCHEDULER_add_after (h->sched,
603 GNUNET_SCHEDULER_PRIORITY_KEEP,
604 GNUNET_SCHEDULER_NO_TASK,
608 if (0 != (h->ccs & COCO_DESTROY_CONTINUATION))
611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
612 "connect_timeout_continuation runs destroy_continuation (%p)\n",
615 h->ccs -= COCO_DESTROY_CONTINUATION;
616 GNUNET_SCHEDULER_add_continuation (h->sched,
618 &destroy_continuation,
620 GNUNET_SCHEDULER_REASON_TIMEOUT);
626 * We've succeeded in establishing a connection.
628 * @param h the connection we tried to establish
631 connect_success_continuation (struct GNUNET_CONNECTION_Handle *h)
634 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
635 "Connection to `%s' succeeded! (%p)\n",
636 GNUNET_a2s(h->addr, h->addrlen),
639 /* trigger jobs that waited for the connection */
640 if (0 != (h->ccs & COCO_RECEIVE_AGAIN))
643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
644 "connect_success_continuation runs receive_again (%p)\n",
647 h->ccs -= COCO_RECEIVE_AGAIN;
648 h->read_task = GNUNET_SCHEDULER_add_after (h->sched,
650 GNUNET_SCHEDULER_PRIORITY_KEEP,
651 GNUNET_SCHEDULER_NO_TASK,
655 if (0 != (h->ccs & COCO_TRANSMIT_READY))
658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
659 "connect_success_continuation runs transmit_ready, cancels timeout_task (%p)\n",
662 GNUNET_assert (h->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
663 GNUNET_SCHEDULER_cancel (h->sched, h->nth.timeout_task);
664 h->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
665 h->ccs -= COCO_TRANSMIT_READY;
667 GNUNET_SCHEDULER_add_write_net (h->sched,
669 GNUNET_SCHEDULER_PRIORITY_KEEP,
670 GNUNET_SCHEDULER_NO_TASK,
671 GNUNET_TIME_absolute_get_remaining (h->nth.transmit_timeout),
672 h->sock, &transmit_ready, h);
674 if (0 != (h->ccs & COCO_DESTROY_CONTINUATION))
677 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
678 "connect_success_continuation runs destroy_continuation (%p)\n",
681 h->ccs -= COCO_DESTROY_CONTINUATION;
682 GNUNET_SCHEDULER_add_continuation (h->sched,
684 &destroy_continuation,
686 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
692 * Scheduler let us know that we're either ready to write on the
693 * socket OR connect timed out. Do the right thing.
695 * @param cls the "struct AddressProbe*" with the address that we are probing
696 * @param tc success or failure info about the connect attempt.
699 connect_probe_continuation (void *cls,
700 const struct GNUNET_SCHEDULER_TaskContext *tc)
702 struct AddressProbe *ap = cls;
703 struct GNUNET_CONNECTION_Handle *h = ap->h;
704 struct AddressProbe *pos;
708 GNUNET_CONTAINER_DLL_remove (h->ap_head, h->ap_tail, ap);
709 len = sizeof (error);
712 if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
713 (GNUNET_OK != GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error, &len)) ||
714 (error != 0) || (errno != 0) )
716 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
718 if ( (NULL == h->ap_head) &&
719 (h->dns_active == GNUNET_NO) )
720 connect_fail_continuation (h);
724 GNUNET_assert (h->addr == NULL);
725 h->addr = GNUNET_malloc (ap->addrlen);
726 memcpy (h->addr, ap->addr, ap->addrlen);
727 h->addrlen = ap->addrlen;
729 /* cancel all other attempts */
730 while (NULL != (pos = h->ap_head))
732 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
733 GNUNET_SCHEDULER_cancel (h->sched, pos->task);
734 GNUNET_CONTAINER_DLL_remove (h->ap_head, h->ap_tail, pos);
737 connect_success_continuation (h);
742 * Try to establish a socket connection given the specified address.
743 * This function is called by the resolver once we have a DNS reply.
745 * @param cls our "struct GNUNET_CONNECTION_Handle *"
746 * @param addr address to try, NULL for "last call"
747 * @param addrlen length of addr
750 try_connect_using_address (void *cls,
751 const struct sockaddr * addr,
754 struct GNUNET_CONNECTION_Handle *h = cls;
755 struct AddressProbe *ap;
756 struct GNUNET_TIME_Relative delay;
760 if (h->dns_active == GNUNET_SYSERR)
762 h->dns_active = GNUNET_NO;
763 GNUNET_SCHEDULER_add_after (h->sched,
765 GNUNET_SCHEDULER_PRIORITY_KEEP,
767 &destroy_continuation,
771 h->dns_active = GNUNET_NO;
772 if (NULL == h->ap_head)
773 connect_fail_continuation (h);
777 return; /* already connected */
778 if (h->dns_active == GNUNET_SYSERR)
781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
782 "Connection %p has already been destroyed.\n",
785 return; /* already destroyed */
789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
790 "Trying to connect using address `%s:%u/%s:%u'\n",
793 GNUNET_a2s (addr, addrlen),
796 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
797 ap->addr = (const struct sockaddr*) &ap[1];
798 memcpy (&ap[1], addr, addrlen);
799 ap->addrlen = addrlen;
802 switch (ap->addr->sa_family)
805 ((struct sockaddr_in *) ap->addr)->sin_port = htons (h->port);
808 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (h->port);
813 return; /* not supported by us */
815 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
816 if (ap->sock == NULL)
819 return; /* not supported by OS */
822 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
823 _("Trying to connect to `%s' (%p)\n"),
828 if ( (GNUNET_OK != GNUNET_NETWORK_socket_connect (ap->sock,
831 (errno != EINPROGRESS))
833 /* maybe refused / unsupported address, try next */
834 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
835 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
839 GNUNET_CONTAINER_DLL_insert (h->ap_head, h->ap_tail, ap);
840 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
841 if (h->nth.notify_ready != NULL)
842 delay = GNUNET_TIME_relative_min (delay,
843 GNUNET_TIME_absolute_get_remaining (h->nth.transmit_timeout));
844 if (h->receiver != NULL)
845 delay = GNUNET_TIME_relative_min (delay,
846 GNUNET_TIME_absolute_get_remaining (h->receive_timeout));
847 ap->task = GNUNET_SCHEDULER_add_write_net (h->sched,
849 GNUNET_SCHEDULER_PRIORITY_KEEP,
850 GNUNET_SCHEDULER_NO_TASK,
853 &connect_probe_continuation,
859 * It is time to re-try connecting.
861 * @param cls the handle for the connection that should be re-tried
862 * @param tc unused scheduler taks context
865 retry_connect_continuation (void *cls,
866 const struct GNUNET_SCHEDULER_TaskContext *tc)
868 struct GNUNET_CONNECTION_Handle *sock = cls;
870 sock->dns_active = GNUNET_YES;
871 GNUNET_RESOLVER_ip_get (sock->sched,
875 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
876 &try_connect_using_address,
882 * Create a socket handle by (asynchronously) connecting to a host.
883 * This function returns immediately, even if the connection has not
884 * yet been established. This function only creates TCP connections.
886 * @param sched scheduler to use
887 * @param cfg configuration to use
888 * @param hostname name of the host to connect to
889 * @param port port to connect to
890 * @param maxbuf maximum write buffer size for the socket (use
891 * 0 for sockets that need no write buffers, such as listen sockets)
892 * @return the socket handle
894 struct GNUNET_CONNECTION_Handle *
895 GNUNET_CONNECTION_create_from_connect (struct GNUNET_SCHEDULER_Handle *sched,
896 const struct GNUNET_CONFIGURATION_Handle *cfg,
897 const char *hostname,
898 uint16_t port, size_t maxbuf)
900 struct GNUNET_CONNECTION_Handle *ret;
902 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
903 ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle) + maxbuf);
906 ret->write_buffer = (char *) &ret[1];
907 ret->write_buffer_size = maxbuf;
909 ret->hostname = GNUNET_strdup (hostname);
910 retry_connect_continuation (ret, NULL);
916 * Create a socket handle by (asynchronously) connecting to a host.
917 * This function returns immediately, even if the connection has not
918 * yet been established. This function only creates TCP connections.
920 * @param sched scheduler to use
921 * @param af_family address family to use
922 * @param serv_addr server address
923 * @param addrlen length of server address
924 * @param maxbuf maximum write buffer size for the socket (use
925 * 0 for sockets that need no write buffers, such as listen sockets)
926 * @return the socket handle
928 struct GNUNET_CONNECTION_Handle *
929 GNUNET_CONNECTION_create_from_sockaddr (struct GNUNET_SCHEDULER_Handle
930 *sched, int af_family,
931 const struct sockaddr *serv_addr,
932 socklen_t addrlen, size_t maxbuf)
934 struct GNUNET_NETWORK_Handle *s;
935 struct GNUNET_CONNECTION_Handle *ret;
937 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
940 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING |
941 GNUNET_ERROR_TYPE_BULK, "socket");
944 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) && (errno != EINPROGRESS))
946 /* maybe refused / unsupported address, try next */
947 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
948 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
951 ret = GNUNET_CONNECTION_create_from_existing (sched, s, maxbuf);
952 ret->addr = GNUNET_malloc (addrlen);
953 memcpy (ret->addr, serv_addr, addrlen);
954 ret->addrlen = addrlen;
956 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
957 _("Trying to connect to `%s' (%p)\n"),
958 GNUNET_a2s(serv_addr, addrlen),
966 * Check if socket is valid (no fatal errors have happened so far).
967 * Note that a socket that is still trying to connect is considered
970 * @param sock socket to check
971 * @return GNUNET_YES if valid, GNUNET_NO otherwise
974 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *sock)
976 if ( (sock->ap_head != NULL) ||
977 (sock->dns_active == GNUNET_YES) )
978 return GNUNET_YES; /* still trying to connect */
979 return (sock->sock == NULL) ? GNUNET_NO : GNUNET_YES;
984 * Close the socket and free associated resources. Pending
985 * transmissions are simply dropped. A pending receive call will be
986 * called with an error code of "EPIPE".
988 * @param sock socket to destroy
991 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *sock)
993 if ( (sock->write_buffer_off == 0) &&
994 (sock->dns_active == GNUNET_YES) )
996 sock->dns_active = GNUNET_SYSERR; /* if we're still trying to connect and have
997 no message pending, stop trying! */
1000 GNUNET_assert (sock->sched != NULL);
1001 GNUNET_SCHEDULER_add_after (sock->sched,
1003 GNUNET_SCHEDULER_PRIORITY_KEEP,
1004 GNUNET_SCHEDULER_NO_TASK,
1005 &destroy_continuation, sock);
1010 * Tell the receiver callback that a timeout was reached.
1013 signal_timeout (struct GNUNET_CONNECTION_Handle *sh)
1015 GNUNET_CONNECTION_Receiver receiver;
1017 #if DEBUG_CONNECTION
1018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1019 "Network signals time out to receiver (%p)!\n",
1022 GNUNET_assert (NULL != (receiver = sh->receiver));
1023 sh->receiver = NULL;
1024 receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
1029 * Tell the receiver callback that we had an IO error.
1032 signal_error (struct GNUNET_CONNECTION_Handle *sh, int errcode)
1034 GNUNET_CONNECTION_Receiver receiver;
1035 GNUNET_assert (NULL != (receiver = sh->receiver));
1036 sh->receiver = NULL;
1037 receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
1042 * This function is called once we either timeout
1043 * or have data ready to read.
1046 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1048 struct GNUNET_CONNECTION_Handle *sh = cls;
1049 struct GNUNET_TIME_Absolute now;
1050 char buffer[sh->max];
1052 GNUNET_CONNECTION_Receiver receiver;
1054 sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1055 now = GNUNET_TIME_absolute_get ();
1056 if ( (now.value > sh->receive_timeout.value) ||
1057 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
1058 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)) )
1060 #if DEBUG_CONNECTION
1061 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1063 "Receive from `%s' encounters error: time out by %llums... (%p)\n",
1064 GNUNET_a2s (sh->addr, sh->addrlen),
1065 GNUNET_TIME_absolute_get_duration (sh->receive_timeout).value,
1068 signal_timeout (sh);
1071 if (sh->sock == NULL)
1073 /* connect failed for good */
1074 #if DEBUG_CONNECTION
1075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1076 "Receive encounters error, socket closed... (%p)\n",
1079 signal_error (sh, ECONNREFUSED);
1082 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, sh->sock));
1084 ret = GNUNET_NETWORK_socket_recv (sh->sock, buffer, sh->max);
1089 #if DEBUG_CONNECTION
1090 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1091 "Error receiving: %s\n",
1094 signal_error (sh, errno);
1097 #if DEBUG_CONNECTION
1098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1099 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1102 GNUNET_a2s(sh->addr, sh->addrlen),
1105 GNUNET_assert (NULL != (receiver = sh->receiver));
1106 sh->receiver = NULL;
1107 receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
1112 * This function is called after establishing a connection either has
1113 * succeeded or timed out. Note that it is possible that the attempt
1114 * timed out and that we're immediately retrying. If we are retrying,
1115 * we need to wait again (or timeout); if we succeeded, we need to
1116 * wait for data (or timeout).
1118 * @param cls our connection handle
1119 * @param tc task context describing why we are here
1122 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1124 struct GNUNET_CONNECTION_Handle *sh = cls;
1125 struct GNUNET_TIME_Absolute now;
1127 sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1128 if (sh->sock == NULL)
1130 /* not connected and no longer trying */
1131 #if DEBUG_CONNECTION
1132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1133 "Receive encounters error, socket closed (%p)...\n",
1136 signal_error (sh, ECONNREFUSED);
1139 now = GNUNET_TIME_absolute_get ();
1140 if ((now.value > sh->receive_timeout.value) ||
1141 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1143 #if DEBUG_CONNECTION
1144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1145 "Receive encounters error: time out (%p)...\n",
1148 signal_timeout (sh);
1151 GNUNET_assert (sh->sock != NULL);
1152 /* connect succeeded, wait for data! */
1153 sh->read_task = GNUNET_SCHEDULER_add_read_net (tc->sched,
1155 GNUNET_SCHEDULER_PRIORITY_KEEP,
1156 GNUNET_SCHEDULER_NO_TASK,
1157 GNUNET_TIME_absolute_get_remaining
1158 (sh->receive_timeout),
1166 * Receive data from the given socket. Note that this function will
1167 * call "receiver" asynchronously using the scheduler. It will
1168 * "immediately" return. Note that there MUST only be one active
1169 * receive call per socket at any given point in time (so do not
1170 * call receive again until the receiver callback has been invoked).
1172 * @param sock socket handle
1173 * @param max maximum number of bytes to read
1174 * @param timeout maximum amount of time to wait (use -1 for "forever")
1175 * @param receiver function to call with received data
1176 * @param receiver_cls closure for receiver
1179 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *sock,
1181 struct GNUNET_TIME_Relative timeout,
1182 GNUNET_CONNECTION_Receiver receiver, void *receiver_cls)
1184 struct GNUNET_SCHEDULER_TaskContext tc;
1186 GNUNET_assert ((sock->read_task == GNUNET_SCHEDULER_NO_TASK) &&
1187 (0 == (sock->ccs & COCO_RECEIVE_AGAIN)) &&
1188 (sock->receiver == NULL));
1189 sock->receiver = receiver;
1190 sock->receiver_cls = receiver_cls;
1191 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1193 if (sock->sock != NULL)
1195 memset (&tc, 0, sizeof (tc));
1196 tc.sched = sock->sched;
1197 tc.reason = GNUNET_SCHEDULER_REASON_PREREQ_DONE;
1198 receive_again (sock, &tc);
1201 if ( (sock->dns_active != GNUNET_YES) &&
1202 (sock->ap_head == NULL) )
1204 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1207 sock->ccs += COCO_RECEIVE_AGAIN;
1212 * Cancel receive job on the given socket. Note that the
1213 * receiver callback must not have been called yet in order
1214 * for the cancellation to be valid.
1216 * @param sock socket handle
1217 * @return closure of the original receiver callback closure
1220 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *sock)
1222 if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1224 GNUNET_assert (sock == GNUNET_SCHEDULER_cancel (sock->sched,
1226 sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1230 GNUNET_assert (0 != (sock->ccs & COCO_RECEIVE_AGAIN));
1231 sock->ccs -= COCO_RECEIVE_AGAIN;
1233 sock->receiver = NULL;
1234 return sock->receiver_cls;
1239 * Try to call the transmit notify method (check if we do
1240 * have enough space available first)!
1242 * @param sock socket for which we should do this processing
1243 * @return GNUNET_YES if we were able to call notify
1246 process_notify (struct GNUNET_CONNECTION_Handle *sock)
1251 GNUNET_CONNECTION_TransmitReadyNotify notify;
1253 GNUNET_assert (sock->write_task == GNUNET_SCHEDULER_NO_TASK);
1254 if (NULL == (notify = sock->nth.notify_ready))
1256 used = sock->write_buffer_off - sock->write_buffer_pos;
1257 avail = sock->write_buffer_size - used;
1258 size = sock->nth.notify_size;
1259 if (sock->nth.notify_size > avail)
1261 sock->nth.notify_ready = NULL;
1262 if (sock->write_buffer_size - sock->write_buffer_off < size)
1264 /* need to compact */
1265 memmove (sock->write_buffer,
1266 &sock->write_buffer[sock->write_buffer_pos], used);
1267 sock->write_buffer_off -= sock->write_buffer_pos;
1268 sock->write_buffer_pos = 0;
1270 GNUNET_assert (sock->write_buffer_size - sock->write_buffer_off >= size);
1271 size = notify (sock->nth.notify_ready_cls,
1272 sock->write_buffer_size - sock->write_buffer_off,
1273 &sock->write_buffer[sock->write_buffer_off]);
1274 sock->write_buffer_off += size;
1280 * Task invoked by the scheduler when a call to transmit
1281 * is timing out (we never got enough buffer space to call
1282 * the callback function before the specified timeout
1285 * This task notifies the client about the timeout.
1288 transmit_timeout (void *cls,
1289 const struct GNUNET_SCHEDULER_TaskContext *tc)
1291 struct GNUNET_CONNECTION_Handle *sock = cls;
1292 GNUNET_CONNECTION_TransmitReadyNotify notify;
1294 #if DEBUG_CONNECTION
1295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1296 "transmit_timeout running (%p)\n",
1299 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1300 #if DEBUG_CONNECTION
1301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1302 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1305 GNUNET_a2s (sock->addr, sock->addrlen),
1308 GNUNET_assert (0 != (sock->ccs & COCO_TRANSMIT_READY));
1309 sock->ccs -= COCO_TRANSMIT_READY; /* remove request */
1310 notify = sock->nth.notify_ready;
1311 sock->nth.notify_ready = NULL;
1312 notify (sock->nth.notify_ready_cls, 0, NULL);
1317 * Task invoked by the scheduler when we failed to connect
1318 * at the time of being asked to transmit.
1320 * This task notifies the client about the error.
1323 connect_error (void *cls,
1324 const struct GNUNET_SCHEDULER_TaskContext *tc)
1326 struct GNUNET_CONNECTION_Handle *sock = cls;
1327 GNUNET_CONNECTION_TransmitReadyNotify notify;
1329 #if DEBUG_CONNECTION
1330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1331 "Transmission request of size %u fails, connection failed (%p).\n",
1332 sock->nth.notify_size,
1335 sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1336 notify = sock->nth.notify_ready;
1337 sock->nth.notify_ready = NULL;
1338 notify (sock->nth.notify_ready_cls, 0, NULL);
1343 transmit_error (struct GNUNET_CONNECTION_Handle *sock)
1345 GNUNET_CONNECTION_TransmitReadyNotify notify;
1347 if (sock->nth.notify_ready == NULL)
1348 return; /* nobody to tell about it */
1349 notify = sock->nth.notify_ready;
1350 sock->nth.notify_ready = NULL;
1351 notify (sock->nth.notify_ready_cls, 0, NULL);
1356 * See if we are now connected. If not, wait longer for
1357 * connect to succeed. If connected, we should be able
1358 * to write now as well, unless we timed out.
1360 * @param cls our connection handle
1361 * @param tc task context describing why we are here
1364 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1366 struct GNUNET_CONNECTION_Handle *sock = cls;
1367 GNUNET_CONNECTION_TransmitReadyNotify notify;
1371 #if DEBUG_CONNECTION
1372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1373 "transmit_ready running (%p).\n",
1376 GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_TASK);
1377 sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1378 GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
1379 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1381 #if DEBUG_CONNECTION
1382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1383 "Transmit to `%s' fails, time out reached (%p).\n",
1384 GNUNET_a2s (sock->addr, sock->addrlen),
1387 notify = sock->nth.notify_ready;
1388 sock->nth.notify_ready = NULL;
1389 notify (sock->nth.notify_ready_cls, 0, NULL);
1392 GNUNET_assert (NULL != sock->sock);
1393 if (tc->write_ready == NULL)
1395 /* special circumstances (in particular,
1396 PREREQ_DONE after connect): not yet ready to write,
1397 but no "fatal" error either. Hence retry. */
1398 goto SCHEDULE_WRITE;
1400 if (! GNUNET_NETWORK_fdset_isset (tc->write_ready,
1403 #if DEBUG_CONNECTION
1404 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1405 _("Could not satisfy pending transmission request, socket closed or connect failed (%p).\n"),
1408 if (NULL != sock->sock)
1410 GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
1411 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
1414 transmit_error (sock);
1415 return; /* connect failed for good, we're finished */
1417 GNUNET_assert (sock->write_buffer_off >= sock->write_buffer_pos);
1418 process_notify (sock);
1419 have = sock->write_buffer_off - sock->write_buffer_pos;
1422 /* no data ready for writing, terminate write loop */
1426 ret = GNUNET_NETWORK_socket_send (sock->sock,
1427 &sock->write_buffer[sock->write_buffer_pos],
1433 #if DEBUG_CONNECTION
1434 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send");
1436 GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
1437 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
1439 transmit_error (sock);
1442 #if DEBUG_CONNECTION
1443 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1444 "transmit_ready transmitted %u/%u bytes to `%s' (%p)\n",
1447 GNUNET_a2s(sock->addr, sock->addrlen),
1450 sock->write_buffer_pos += ret;
1451 if (sock->write_buffer_pos == sock->write_buffer_off)
1453 /* transmitted all pending data */
1454 sock->write_buffer_pos = 0;
1455 sock->write_buffer_off = 0;
1457 if ( (sock->write_buffer_off == 0) &&
1458 (NULL == sock->nth.notify_ready))
1459 return; /* all data sent! */
1460 /* not done writing, schedule more */
1462 #if DEBUG_CONNECTION
1463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1464 "Re-scheduling transmit_ready (more to do) (%p).\n",
1467 if (sock->write_task == GNUNET_SCHEDULER_NO_TASK)
1469 GNUNET_SCHEDULER_add_write_net (tc->sched,
1471 GNUNET_SCHEDULER_PRIORITY_KEEP,
1472 GNUNET_SCHEDULER_NO_TASK,
1473 GNUNET_TIME_absolute_get_remaining (sock->nth.transmit_timeout),
1475 &transmit_ready, sock);
1480 * Ask the socket to call us once the specified number of bytes
1481 * are free in the transmission buffer. May call the notify
1482 * method immediately if enough space is available.
1484 * @param sock socket
1485 * @param size number of bytes to send
1486 * @param timeout after how long should we give up (and call
1487 * notify with buf NULL and size 0)?
1488 * @param notify function to call
1489 * @param notify_cls closure for notify
1490 * @return non-NULL if the notify callback was queued,
1491 * NULL if we are already going to notify someone else (busy)
1493 struct GNUNET_CONNECTION_TransmitHandle *
1494 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle
1496 struct GNUNET_TIME_Relative timeout,
1497 GNUNET_CONNECTION_TransmitReadyNotify
1498 notify, void *notify_cls)
1500 if (sock->nth.notify_ready != NULL)
1502 GNUNET_assert (notify != NULL);
1503 GNUNET_assert (sock->write_buffer_size >= size);
1504 GNUNET_assert (sock->write_buffer_off <= sock->write_buffer_size);
1505 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1506 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_off);
1507 sock->nth.notify_ready = notify;
1508 sock->nth.notify_ready_cls = notify_cls;
1509 sock->nth.sh = sock;
1510 sock->nth.notify_size = size;
1511 sock->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1512 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->nth.timeout_task);
1513 if ( (sock->sock == NULL) &&
1514 (sock->ap_head == NULL) &&
1515 (sock->dns_active != GNUNET_YES) )
1517 sock->write_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1519 GNUNET_SCHEDULER_PRIORITY_KEEP,
1520 GNUNET_SCHEDULER_NO_TASK,
1521 GNUNET_TIME_UNIT_ZERO,
1526 if (GNUNET_SCHEDULER_NO_TASK != sock->write_task)
1528 if (sock->sock != NULL)
1530 #if DEBUG_CONNECTION
1531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1532 "Scheduling transmit_ready (%p).\n",
1535 sock->write_task = GNUNET_SCHEDULER_add_write_net (sock->sched,
1537 GNUNET_SCHEDULER_PRIORITY_KEEP,
1538 GNUNET_SCHEDULER_NO_TASK,
1539 GNUNET_TIME_absolute_get_remaining (sock->nth.transmit_timeout),
1541 &transmit_ready, sock);
1545 #if DEBUG_CONNECTION
1546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1547 "CCS-Scheduling transmit_ready, adding timeout task (%p).\n",
1550 sock->ccs |= COCO_TRANSMIT_READY;
1551 sock->nth.timeout_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1553 GNUNET_SCHEDULER_PRIORITY_KEEP,
1554 GNUNET_SCHEDULER_NO_TASK,
1564 * Cancel the specified transmission-ready
1568 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1569 GNUNET_CONNECTION_TransmitHandle *h)
1571 GNUNET_assert (h->notify_ready != NULL);
1572 if (0 != (h->sh->ccs & COCO_TRANSMIT_READY))
1574 #if DEBUG_CONNECTION
1575 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1576 "notify_transmit_ready_cancel cancels timeout_task (%p)\n",
1579 GNUNET_SCHEDULER_cancel (h->sh->sched, h->timeout_task);
1580 h->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1581 h->sh->ccs -= COCO_TRANSMIT_READY;
1585 GNUNET_SCHEDULER_cancel (h->sh->sched,
1587 h->sh->write_task = GNUNET_SCHEDULER_NO_TASK;
1589 h->notify_ready = NULL;
1592 /* end of connection.c */