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 * Handle to a pending DNS lookup request.
250 struct GNUNET_RESOLVER_RequestHandle *dns_active;
253 * The handle we return for GNUNET_CONNECTION_notify_transmit_ready.
255 struct GNUNET_CONNECTION_TransmitHandle nth;
258 * Timeout for receiving (in absolute time).
260 struct GNUNET_TIME_Absolute receive_timeout;
263 * Functions to call after connect failed or succeeded.
265 enum ConnectContinuations ccs;
268 * Maximum number of bytes to read (for receiving).
273 * Port to connect to.
281 * Create a socket handle by boxing an existing OS socket. The OS
282 * socket should henceforth be no longer used directly.
283 * GNUNET_socket_destroy will close it.
285 * @param sched scheduler to use
286 * @param osSocket existing socket to box
287 * @param maxbuf maximum write buffer size for the socket (use
288 * 0 for sockets that need no write buffers, such as listen sockets)
289 * @return the boxed socket handle
291 struct GNUNET_CONNECTION_Handle *
292 GNUNET_CONNECTION_create_from_existing (struct GNUNET_SCHEDULER_Handle
294 struct GNUNET_NETWORK_Handle
295 *osSocket, size_t maxbuf)
297 struct GNUNET_CONNECTION_Handle *ret;
298 ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle) + maxbuf);
299 ret->write_buffer = (char *) &ret[1];
300 ret->write_buffer_size = maxbuf;
301 ret->sock = osSocket;
308 * Create a socket handle by accepting on a listen socket. This
309 * function may block if the listen socket has no connection ready.
311 * @param sched scheduler to use
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 * @param maxbuf maximum write buffer size for the socket (use
316 * 0 for sockets that need no write buffers, such as listen sockets)
317 * @return the socket handle, NULL on error
319 struct GNUNET_CONNECTION_Handle *
320 GNUNET_CONNECTION_create_from_accept (struct GNUNET_SCHEDULER_Handle
322 GNUNET_CONNECTION_AccessCheck access,
324 struct GNUNET_NETWORK_Handle *lsock,
327 struct GNUNET_CONNECTION_Handle *ret;
330 struct GNUNET_NETWORK_Handle *sock;
332 struct sockaddr_in *v4;
333 struct sockaddr_in6 *v6;
337 addrlen = sizeof (addr);
339 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 ==
382 GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
383 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
387 ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle) + maxbuf);
388 ret->write_buffer = (char *) &ret[1];
389 ret->write_buffer_size = maxbuf;
391 ret->addrlen = addrlen;
395 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
396 _("Accepting connection from `%s': %p\n"),
397 GNUNET_a2s (uaddr, addrlen), ret);
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 * This function is called after establishing a connection either has
425 * succeeded or timed out. Note that it is possible that the attempt
426 * timed out and that we're immediately retrying. If we are retrying,
427 * we need to wait again (or timeout); if we succeeded, we need to
428 * wait for data (or timeout).
430 * @param cls our connection handle
431 * @param tc task context describing why we are here
434 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
438 * Scheduler let us know that the connect task is finished (or was
439 * cancelled due to shutdown). Now really clean up.
441 * @param cls our "struct GNUNET_CONNECTION_Handle *"
445 destroy_continuation (void *cls,
446 const struct GNUNET_SCHEDULER_TaskContext *tc)
448 struct GNUNET_CONNECTION_Handle *sock = cls;
449 GNUNET_CONNECTION_TransmitReadyNotify notify;
451 GNUNET_assert (sock->dns_active == NULL);
452 if (0 != (sock->ccs & COCO_TRANSMIT_READY))
455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
456 "Destroy waits for CCS-TR to be done (%p)\n", sock);
458 sock->ccs |= COCO_DESTROY_CONTINUATION;
461 if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
465 "Destroy waits for write_task to be done (%p)\n", sock);
467 GNUNET_SCHEDULER_add_after (sock->sched,
469 &destroy_continuation, sock);
472 if (0 != (sock->ccs & COCO_RECEIVE_AGAIN))
474 sock->ccs |= COCO_DESTROY_CONTINUATION;
477 if (sock->sock != NULL)
480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
481 "Shutting down socket (%p)\n", sock);
483 GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
485 if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
487 GNUNET_SCHEDULER_add_after (sock->sched,
489 &destroy_continuation, sock);
493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Destroy actually runs (%p)!\n", sock);
495 GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
496 GNUNET_assert (sock->ccs == COCO_NONE);
497 if (NULL != (notify = sock->nth.notify_ready))
499 sock->nth.notify_ready = NULL;
500 notify (sock->nth.notify_ready_cls, 0, NULL);
502 if (sock->sock != NULL)
503 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
504 GNUNET_free_non_null (sock->addr);
505 GNUNET_free_non_null (sock->hostname);
507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
508 "Freeing memory of connection %p.\n", sock);
516 * See if we are now connected. If not, wait longer for
517 * connect to succeed. If connected, we should be able
518 * to write now as well, unless we timed out.
520 * @param cls our connection handle
521 * @param tc task context describing why we are here
524 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
528 * We've failed for good to establish a connection.
530 * @param h the connection we tried to establish
533 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *h)
536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
537 "Failed to establish TCP connection to `%s:%u', no further addresses to try (%p).\n",
538 h->hostname, h->port, h);
540 /* connect failed / timed out */
541 GNUNET_break (h->ap_head == NULL);
542 GNUNET_break (h->ap_tail == NULL);
543 GNUNET_break (h->dns_active == GNUNET_NO);
544 GNUNET_break (h->sock == NULL);
546 /* trigger jobs that used to wait on "connect_task" */
547 if (0 != (h->ccs & COCO_RECEIVE_AGAIN))
550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551 "connect_timeout_continuation triggers receive_again (%p)\n",
554 h->ccs -= COCO_RECEIVE_AGAIN;
555 h->read_task = GNUNET_SCHEDULER_add_after (h->sched,
556 GNUNET_SCHEDULER_NO_TASK,
559 if (0 != (h->ccs & COCO_TRANSMIT_READY))
562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
563 "connect_timeout_continuation cancels timeout_task, triggers transmit_ready (%p)\n",
566 GNUNET_assert (h->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
567 GNUNET_SCHEDULER_cancel (h->sched, h->nth.timeout_task);
568 h->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
569 h->ccs -= COCO_TRANSMIT_READY;
570 h->write_task = GNUNET_SCHEDULER_add_after (h->sched,
571 GNUNET_SCHEDULER_NO_TASK,
574 if (0 != (h->ccs & COCO_DESTROY_CONTINUATION))
577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
578 "connect_timeout_continuation runs destroy_continuation (%p)\n",
581 h->ccs -= COCO_DESTROY_CONTINUATION;
582 GNUNET_SCHEDULER_add_continuation (h->sched,
583 &destroy_continuation,
584 h, GNUNET_SCHEDULER_REASON_TIMEOUT);
590 * We've succeeded in establishing a connection.
592 * @param h the connection we tried to establish
595 connect_success_continuation (struct GNUNET_CONNECTION_Handle *h)
598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
599 "Connection to `%s' succeeded! (%p)\n",
600 GNUNET_a2s (h->addr, h->addrlen), h);
602 /* trigger jobs that waited for the connection */
603 if (0 != (h->ccs & COCO_RECEIVE_AGAIN))
606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
607 "connect_success_continuation runs receive_again (%p)\n",
610 h->ccs -= COCO_RECEIVE_AGAIN;
611 h->read_task = GNUNET_SCHEDULER_add_after (h->sched,
612 GNUNET_SCHEDULER_NO_TASK,
615 if (0 != (h->ccs & COCO_TRANSMIT_READY))
618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
619 "connect_success_continuation runs transmit_ready, cancels timeout_task (%p)\n",
622 GNUNET_assert (h->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
623 GNUNET_SCHEDULER_cancel (h->sched, h->nth.timeout_task);
624 h->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
625 h->ccs -= COCO_TRANSMIT_READY;
627 GNUNET_SCHEDULER_add_write_net (h->sched,
628 GNUNET_TIME_absolute_get_remaining
629 (h->nth.transmit_timeout), h->sock,
632 if (0 != (h->ccs & COCO_DESTROY_CONTINUATION))
635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
636 "connect_success_continuation runs destroy_continuation (%p)\n",
639 h->ccs -= COCO_DESTROY_CONTINUATION;
640 GNUNET_SCHEDULER_add_continuation (h->sched,
641 &destroy_continuation,
643 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
649 * Scheduler let us know that we're either ready to write on the
650 * socket OR connect timed out. Do the right thing.
652 * @param cls the "struct AddressProbe*" with the address that we are probing
653 * @param tc success or failure info about the connect attempt.
656 connect_probe_continuation (void *cls,
657 const struct GNUNET_SCHEDULER_TaskContext *tc)
659 struct AddressProbe *ap = cls;
660 struct GNUNET_CONNECTION_Handle *h = ap->h;
661 struct AddressProbe *pos;
665 GNUNET_CONTAINER_DLL_remove (h->ap_head, h->ap_tail, ap);
666 len = sizeof (error);
669 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
671 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR,
672 &error, &len)) || (error != 0)
675 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
677 if ((NULL == h->ap_head) && (h->dns_active == GNUNET_NO))
678 connect_fail_continuation (h);
681 GNUNET_assert (h->sock == NULL);
682 GNUNET_assert (ap->sock != NULL);
684 GNUNET_assert (h->addr == NULL);
685 h->addr = GNUNET_malloc (ap->addrlen);
686 memcpy (h->addr, ap->addr, ap->addrlen);
687 h->addrlen = ap->addrlen;
689 /* cancel all other attempts */
690 while (NULL != (pos = h->ap_head))
692 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
693 GNUNET_SCHEDULER_cancel (h->sched, pos->task);
694 GNUNET_CONTAINER_DLL_remove (h->ap_head, h->ap_tail, pos);
697 connect_success_continuation (h);
702 * Try to establish a socket connection given the specified address.
703 * This function is called by the resolver once we have a DNS reply.
705 * @param cls our "struct GNUNET_CONNECTION_Handle *"
706 * @param addr address to try, NULL for "last call"
707 * @param addrlen length of addr
710 try_connect_using_address (void *cls,
711 const struct sockaddr *addr, socklen_t addrlen)
713 struct GNUNET_CONNECTION_Handle *h = cls;
714 struct AddressProbe *ap;
715 struct GNUNET_TIME_Relative delay;
719 h->dns_active = NULL;
720 if (NULL == h->ap_head)
721 connect_fail_continuation (h);
725 return; /* already connected */
726 GNUNET_assert (h->addr == NULL);
729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
730 "Trying to connect using address `%s:%u/%s:%u'\n",
731 h->hostname, h->port, GNUNET_a2s (addr, addrlen), h->port);
733 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
734 ap->addr = (const struct sockaddr *) &ap[1];
735 memcpy (&ap[1], addr, addrlen);
736 ap->addrlen = addrlen;
739 switch (ap->addr->sa_family)
742 ((struct sockaddr_in *) ap->addr)->sin_port = htons (h->port);
745 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (h->port);
750 return; /* not supported by us */
753 GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
754 if (ap->sock == NULL)
757 return; /* not supported by OS */
760 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
761 _("Trying to connect to `%s' (%p)\n"),
762 GNUNET_a2s (ap->addr, ap->addrlen), h);
764 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (ap->sock,
767 (errno != EINPROGRESS))
769 /* maybe refused / unsupported address, try next */
770 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
771 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
775 GNUNET_CONTAINER_DLL_insert (h->ap_head, h->ap_tail, ap);
776 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
777 if (h->nth.notify_ready != NULL)
778 delay = GNUNET_TIME_relative_min (delay,
779 GNUNET_TIME_absolute_get_remaining
780 (h->nth.transmit_timeout));
781 if (h->receiver != NULL)
782 delay = GNUNET_TIME_relative_min (delay,
783 GNUNET_TIME_absolute_get_remaining
784 (h->receive_timeout));
786 GNUNET_SCHEDULER_add_write_net (h->sched, delay, ap->sock,
787 &connect_probe_continuation, ap);
792 * Create a socket handle by (asynchronously) connecting to a host.
793 * This function returns immediately, even if the connection has not
794 * yet been established. This function only creates TCP connections.
796 * @param sched scheduler to use
797 * @param cfg configuration to use
798 * @param hostname name of the host to connect to
799 * @param port port to connect to
800 * @param maxbuf maximum write buffer size for the socket (use
801 * 0 for sockets that need no write buffers, such as listen sockets)
802 * @return the socket handle
804 struct GNUNET_CONNECTION_Handle *
805 GNUNET_CONNECTION_create_from_connect (struct GNUNET_SCHEDULER_Handle *sched,
807 GNUNET_CONFIGURATION_Handle *cfg,
808 const char *hostname, uint16_t port,
811 struct GNUNET_CONNECTION_Handle *ret;
813 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
814 ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle) + maxbuf);
817 ret->write_buffer = (char *) &ret[1];
818 ret->write_buffer_size = maxbuf;
820 ret->hostname = GNUNET_strdup (hostname);
821 ret->dns_active = GNUNET_RESOLVER_ip_get (sched,
825 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
826 &try_connect_using_address, ret);
832 * Create a socket handle by (asynchronously) connecting to a host.
833 * This function returns immediately, even if the connection has not
834 * yet been established. This function only creates TCP connections.
836 * @param sched scheduler to use
837 * @param af_family address family to use
838 * @param serv_addr server address
839 * @param addrlen length of server address
840 * @param maxbuf maximum write buffer size for the socket (use
841 * 0 for sockets that need no write buffers, such as listen sockets)
842 * @return the socket handle
844 struct GNUNET_CONNECTION_Handle *
845 GNUNET_CONNECTION_create_from_sockaddr (struct GNUNET_SCHEDULER_Handle
846 *sched, int af_family,
847 const struct sockaddr *serv_addr,
848 socklen_t addrlen, size_t maxbuf)
850 struct GNUNET_NETWORK_Handle *s;
851 struct GNUNET_CONNECTION_Handle *ret;
853 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
856 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING |
857 GNUNET_ERROR_TYPE_BULK, "socket");
860 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen))
861 && (errno != EINPROGRESS))
863 /* maybe refused / unsupported address, try next */
864 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
865 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
868 ret = GNUNET_CONNECTION_create_from_existing (sched, s, maxbuf);
869 ret->addr = GNUNET_malloc (addrlen);
870 memcpy (ret->addr, serv_addr, addrlen);
871 ret->addrlen = addrlen;
873 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
874 _("Trying to connect to `%s' (%p)\n"),
875 GNUNET_a2s (serv_addr, addrlen), ret);
882 * Check if socket is valid (no fatal errors have happened so far).
883 * Note that a socket that is still trying to connect is considered
886 * @param sock socket to check
887 * @return GNUNET_YES if valid, GNUNET_NO otherwise
890 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *sock)
892 if ((sock->ap_head != NULL) || (sock->dns_active != NULL))
893 return GNUNET_YES; /* still trying to connect */
894 return (sock->sock == NULL) ? GNUNET_NO : GNUNET_YES;
899 * Close the socket and free associated resources. Pending
900 * transmissions are simply dropped. A pending receive call will be
901 * called with an error code of "EPIPE".
903 * @param sock socket to destroy
906 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *sock)
908 if ((sock->write_buffer_off == 0) && (sock->dns_active != NULL))
910 GNUNET_RESOLVER_request_cancel (sock->dns_active);
911 sock->dns_active = NULL;
913 GNUNET_assert (sock->sched != NULL);
914 GNUNET_SCHEDULER_add_after (sock->sched,
915 GNUNET_SCHEDULER_NO_TASK,
916 &destroy_continuation, sock);
921 * Tell the receiver callback that a timeout was reached.
924 signal_timeout (struct GNUNET_CONNECTION_Handle *sh)
926 GNUNET_CONNECTION_Receiver receiver;
929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930 "Network signals time out to receiver (%p)!\n", sh);
932 GNUNET_assert (NULL != (receiver = sh->receiver));
934 receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
939 * Tell the receiver callback that we had an IO error.
942 signal_error (struct GNUNET_CONNECTION_Handle *sh, int errcode)
944 GNUNET_CONNECTION_Receiver receiver;
945 GNUNET_assert (NULL != (receiver = sh->receiver));
947 receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
952 * This function is called once we either timeout
953 * or have data ready to read.
956 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
958 struct GNUNET_CONNECTION_Handle *sh = cls;
959 struct GNUNET_TIME_Absolute now;
960 char buffer[sh->max];
962 GNUNET_CONNECTION_Receiver receiver;
964 sh->read_task = GNUNET_SCHEDULER_NO_TASK;
965 now = GNUNET_TIME_absolute_get ();
966 if ((now.value > sh->receive_timeout.value) ||
967 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
968 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
971 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
972 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
973 "Receive from `%s' encounters error: time out by %llums... (%p)\n",
974 GNUNET_a2s (sh->addr, sh->addrlen),
975 GNUNET_TIME_absolute_get_duration (sh->receive_timeout).
981 if (sh->sock == NULL)
983 /* connect failed for good */
985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
986 "Receive encounters error, socket closed... (%p)\n", sh);
988 signal_error (sh, ECONNREFUSED);
991 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, sh->sock));
993 ret = GNUNET_NETWORK_socket_recv (sh->sock, buffer, sh->max);
999 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1000 "Error receiving: %s\n", STRERROR (errno));
1002 signal_error (sh, errno);
1005 #if DEBUG_CONNECTION
1006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1007 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1009 sh->max, GNUNET_a2s (sh->addr, sh->addrlen), sh);
1011 GNUNET_assert (NULL != (receiver = sh->receiver));
1012 sh->receiver = NULL;
1013 receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
1018 * This function is called after establishing a connection either has
1019 * succeeded or timed out. Note that it is possible that the attempt
1020 * timed out and that we're immediately retrying. If we are retrying,
1021 * we need to wait again (or timeout); if we succeeded, we need to
1022 * wait for data (or timeout).
1024 * @param cls our connection handle
1025 * @param tc task context describing why we are here
1028 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1030 struct GNUNET_CONNECTION_Handle *sh = cls;
1031 struct GNUNET_TIME_Absolute now;
1033 sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1034 if (sh->sock == NULL)
1036 /* not connected and no longer trying */
1037 #if DEBUG_CONNECTION
1038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1039 "Receive encounters error, socket closed (%p)...\n", sh);
1041 signal_error (sh, ECONNREFUSED);
1044 now = GNUNET_TIME_absolute_get ();
1045 if ((now.value > sh->receive_timeout.value) ||
1046 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1048 #if DEBUG_CONNECTION
1049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1050 "Receive encounters error: time out (%p)...\n", sh);
1052 signal_timeout (sh);
1055 GNUNET_assert (sh->sock != NULL);
1056 /* connect succeeded, wait for data! */
1057 sh->read_task = GNUNET_SCHEDULER_add_read_net (tc->sched,
1058 GNUNET_TIME_absolute_get_remaining
1059 (sh->receive_timeout),
1061 &receive_ready, sh);
1066 * Receive data from the given socket. Note that this function will
1067 * call "receiver" asynchronously using the scheduler. It will
1068 * "immediately" return. Note that there MUST only be one active
1069 * receive call per socket at any given point in time (so do not
1070 * call receive again until the receiver callback has been invoked).
1072 * @param sock socket handle
1073 * @param max maximum number of bytes to read
1074 * @param timeout maximum amount of time to wait (use -1 for "forever")
1075 * @param receiver function to call with received data
1076 * @param receiver_cls closure for receiver
1079 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *sock,
1081 struct GNUNET_TIME_Relative timeout,
1082 GNUNET_CONNECTION_Receiver receiver,
1085 struct GNUNET_SCHEDULER_TaskContext tc;
1087 GNUNET_assert ((sock->read_task == GNUNET_SCHEDULER_NO_TASK) &&
1088 (0 == (sock->ccs & COCO_RECEIVE_AGAIN)) &&
1089 (sock->receiver == NULL));
1090 sock->receiver = receiver;
1091 sock->receiver_cls = receiver_cls;
1092 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1094 if (sock->sock != NULL)
1096 memset (&tc, 0, sizeof (tc));
1097 tc.sched = sock->sched;
1098 tc.reason = GNUNET_SCHEDULER_REASON_PREREQ_DONE;
1099 receive_again (sock, &tc);
1102 if ((sock->dns_active == NULL) && (sock->ap_head == NULL))
1104 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1107 sock->ccs += COCO_RECEIVE_AGAIN;
1112 * Cancel receive job on the given socket. Note that the
1113 * receiver callback must not have been called yet in order
1114 * for the cancellation to be valid.
1116 * @param sock socket handle
1117 * @return closure of the original receiver callback closure
1120 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *sock)
1122 if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1124 GNUNET_assert (sock == GNUNET_SCHEDULER_cancel (sock->sched,
1126 sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1130 GNUNET_assert (0 != (sock->ccs & COCO_RECEIVE_AGAIN));
1131 sock->ccs -= COCO_RECEIVE_AGAIN;
1133 sock->receiver = NULL;
1134 return sock->receiver_cls;
1139 * Try to call the transmit notify method (check if we do
1140 * have enough space available first)!
1142 * @param sock socket for which we should do this processing
1143 * @return GNUNET_YES if we were able to call notify
1146 process_notify (struct GNUNET_CONNECTION_Handle *sock)
1151 GNUNET_CONNECTION_TransmitReadyNotify notify;
1153 GNUNET_assert (sock->write_task == GNUNET_SCHEDULER_NO_TASK);
1154 if (NULL == (notify = sock->nth.notify_ready))
1156 used = sock->write_buffer_off - sock->write_buffer_pos;
1157 avail = sock->write_buffer_size - used;
1158 size = sock->nth.notify_size;
1159 if (sock->nth.notify_size > avail)
1161 sock->nth.notify_ready = NULL;
1162 if (sock->write_buffer_size - sock->write_buffer_off < size)
1164 /* need to compact */
1165 memmove (sock->write_buffer,
1166 &sock->write_buffer[sock->write_buffer_pos], used);
1167 sock->write_buffer_off -= sock->write_buffer_pos;
1168 sock->write_buffer_pos = 0;
1170 GNUNET_assert (sock->write_buffer_size - sock->write_buffer_off >= size);
1171 size = notify (sock->nth.notify_ready_cls,
1172 sock->write_buffer_size - sock->write_buffer_off,
1173 &sock->write_buffer[sock->write_buffer_off]);
1174 sock->write_buffer_off += size;
1180 * Task invoked by the scheduler when a call to transmit
1181 * is timing out (we never got enough buffer space to call
1182 * the callback function before the specified timeout
1185 * This task notifies the client about the timeout.
1188 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1190 struct GNUNET_CONNECTION_Handle *sock = cls;
1191 GNUNET_CONNECTION_TransmitReadyNotify notify;
1193 #if DEBUG_CONNECTION
1194 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1195 "transmit_timeout running (%p)\n", sock);
1197 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1198 #if DEBUG_CONNECTION
1199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1200 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1202 sock->port, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1204 GNUNET_assert (0 != (sock->ccs & COCO_TRANSMIT_READY));
1205 sock->ccs -= COCO_TRANSMIT_READY; /* remove request */
1206 notify = sock->nth.notify_ready;
1207 sock->nth.notify_ready = NULL;
1208 notify (sock->nth.notify_ready_cls, 0, NULL);
1213 * Task invoked by the scheduler when we failed to connect
1214 * at the time of being asked to transmit.
1216 * This task notifies the client about the error.
1219 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1221 struct GNUNET_CONNECTION_Handle *sock = cls;
1222 GNUNET_CONNECTION_TransmitReadyNotify notify;
1224 #if DEBUG_CONNECTION
1225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1226 "Transmission request of size %u fails, connection failed (%p).\n",
1227 sock->nth.notify_size, sock);
1229 sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1230 notify = sock->nth.notify_ready;
1231 sock->nth.notify_ready = NULL;
1232 notify (sock->nth.notify_ready_cls, 0, NULL);
1237 transmit_error (struct GNUNET_CONNECTION_Handle *sock)
1239 GNUNET_CONNECTION_TransmitReadyNotify notify;
1241 if (sock->nth.notify_ready == NULL)
1242 return; /* nobody to tell about it */
1243 notify = sock->nth.notify_ready;
1244 sock->nth.notify_ready = NULL;
1245 notify (sock->nth.notify_ready_cls, 0, NULL);
1250 * See if we are now connected. If not, wait longer for
1251 * connect to succeed. If connected, we should be able
1252 * to write now as well, unless we timed out.
1254 * @param cls our connection handle
1255 * @param tc task context describing why we are here
1258 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1260 struct GNUNET_CONNECTION_Handle *sock = cls;
1261 GNUNET_CONNECTION_TransmitReadyNotify notify;
1265 #if DEBUG_CONNECTION
1266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1267 "transmit_ready running (%p).\n", sock);
1269 GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_TASK);
1270 sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1271 GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
1272 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1274 #if DEBUG_CONNECTION
1275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1276 "Transmit to `%s' fails, time out reached (%p).\n",
1277 GNUNET_a2s (sock->addr, sock->addrlen), sock);
1279 notify = sock->nth.notify_ready;
1280 sock->nth.notify_ready = NULL;
1281 notify (sock->nth.notify_ready_cls, 0, NULL);
1284 GNUNET_assert (NULL != sock->sock);
1285 if (tc->write_ready == NULL)
1287 /* special circumstances (in particular,
1288 PREREQ_DONE after connect): not yet ready to write,
1289 but no "fatal" error either. Hence retry. */
1290 goto SCHEDULE_WRITE;
1292 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, sock->sock))
1294 #if DEBUG_CONNECTION
1295 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1297 ("Could not satisfy pending transmission request, socket closed or connect failed (%p).\n"),
1300 if (NULL != sock->sock)
1302 GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
1303 GNUNET_break (GNUNET_OK ==
1304 GNUNET_NETWORK_socket_close (sock->sock));
1307 transmit_error (sock);
1308 return; /* connect failed for good, we're finished */
1310 GNUNET_assert (sock->write_buffer_off >= sock->write_buffer_pos);
1311 process_notify (sock);
1312 have = sock->write_buffer_off - sock->write_buffer_pos;
1315 /* no data ready for writing, terminate write loop */
1318 GNUNET_assert (have <= sock->write_buffer_size);
1319 GNUNET_assert (have + sock->write_buffer_pos <= sock->write_buffer_size);
1320 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1322 ret = GNUNET_NETWORK_socket_send (sock->sock,
1323 &sock->write_buffer[sock->
1330 #if DEBUG_CONNECTION
1331 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send");
1333 GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
1334 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
1336 transmit_error (sock);
1339 #if DEBUG_CONNECTION
1340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1341 "transmit_ready transmitted %u/%u bytes to `%s' (%p)\n",
1343 have, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1345 sock->write_buffer_pos += ret;
1346 if (sock->write_buffer_pos == sock->write_buffer_off)
1348 /* transmitted all pending data */
1349 sock->write_buffer_pos = 0;
1350 sock->write_buffer_off = 0;
1352 if ((sock->write_buffer_off == 0) && (NULL == sock->nth.notify_ready))
1353 return; /* all data sent! */
1354 /* not done writing, schedule more */
1356 #if DEBUG_CONNECTION
1357 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1358 "Re-scheduling transmit_ready (more to do) (%p).\n", sock);
1360 if (sock->write_task == GNUNET_SCHEDULER_NO_TASK)
1362 GNUNET_SCHEDULER_add_write_net (tc->sched,
1363 GNUNET_TIME_absolute_get_remaining
1364 (sock->nth.transmit_timeout),
1365 sock->sock, &transmit_ready, sock);
1370 * Ask the socket to call us once the specified number of bytes
1371 * are free in the transmission buffer. May call the notify
1372 * method immediately if enough space is available.
1374 * @param sock socket
1375 * @param size number of bytes to send
1376 * @param timeout after how long should we give up (and call
1377 * notify with buf NULL and size 0)?
1378 * @param notify function to call
1379 * @param notify_cls closure for notify
1380 * @return non-NULL if the notify callback was queued,
1381 * NULL if we are already going to notify someone else (busy)
1383 struct GNUNET_CONNECTION_TransmitHandle *
1384 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle
1386 struct GNUNET_TIME_Relative timeout,
1387 GNUNET_CONNECTION_TransmitReadyNotify
1388 notify, void *notify_cls)
1390 if (sock->nth.notify_ready != NULL)
1392 GNUNET_assert (notify != NULL);
1393 GNUNET_assert (sock->write_buffer_size >= size);
1394 GNUNET_assert (sock->write_buffer_off <= sock->write_buffer_size);
1395 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1396 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_off);
1397 sock->nth.notify_ready = notify;
1398 sock->nth.notify_ready_cls = notify_cls;
1399 sock->nth.sh = sock;
1400 sock->nth.notify_size = size;
1401 sock->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1402 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->nth.timeout_task);
1403 if ((sock->sock == NULL) &&
1404 (sock->ap_head == NULL) && (sock->dns_active == NULL))
1406 sock->write_task = GNUNET_SCHEDULER_add_now (sock->sched,
1407 &connect_error, sock);
1410 if (GNUNET_SCHEDULER_NO_TASK != sock->write_task)
1412 if (sock->sock != NULL)
1414 #if DEBUG_CONNECTION
1415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1416 "Scheduling transmit_ready (%p).\n", sock);
1418 sock->write_task = GNUNET_SCHEDULER_add_write_net (sock->sched,
1419 GNUNET_TIME_absolute_get_remaining
1428 #if DEBUG_CONNECTION
1429 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1430 "CCS-Scheduling transmit_ready, adding timeout task (%p).\n",
1433 sock->ccs |= COCO_TRANSMIT_READY;
1434 sock->nth.timeout_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1444 * Cancel the specified transmission-ready
1448 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1449 GNUNET_CONNECTION_TransmitHandle
1452 GNUNET_assert (h->notify_ready != NULL);
1453 if (0 != (h->sh->ccs & COCO_TRANSMIT_READY))
1455 #if DEBUG_CONNECTION
1456 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1457 "notify_transmit_ready_cancel cancels timeout_task (%p)\n",
1460 GNUNET_SCHEDULER_cancel (h->sh->sched, h->timeout_task);
1461 h->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1462 h->sh->ccs -= COCO_TRANSMIT_READY;
1466 GNUNET_SCHEDULER_cancel (h->sh->sched, h->sh->write_task);
1467 h->sh->write_task = GNUNET_SCHEDULER_NO_TASK;
1469 h->notify_ready = NULL;
1472 /* end of connection.c */