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 * Ignore GNUNET_SCHEDULER_REASON_SHUTDOWN for this socket.
278 * Port to connect to.
286 * Create a socket handle by boxing an existing OS socket. The OS
287 * socket should henceforth be no longer used directly.
288 * GNUNET_socket_destroy will close it.
290 * @param sched scheduler to use
291 * @param osSocket existing socket to box
292 * @param maxbuf maximum write buffer size for the socket (use
293 * 0 for sockets that need no write buffers, such as listen sockets)
294 * @return the boxed socket handle
296 struct GNUNET_CONNECTION_Handle *
297 GNUNET_CONNECTION_create_from_existing (struct GNUNET_SCHEDULER_Handle
299 struct GNUNET_NETWORK_Handle
300 *osSocket, size_t maxbuf)
302 struct GNUNET_CONNECTION_Handle *ret;
303 ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle) + maxbuf);
304 ret->write_buffer = (char *) &ret[1];
305 ret->write_buffer_size = maxbuf;
306 ret->sock = osSocket;
313 * Create a socket handle by accepting on a listen socket. This
314 * function may block if the listen socket has no connection ready.
316 * @param sched scheduler to use
317 * @param access function to use to check if access is allowed
318 * @param access_cls closure for access
319 * @param lsock listen socket
320 * @param maxbuf maximum write buffer size for the socket (use
321 * 0 for sockets that need no write buffers, such as listen sockets)
322 * @return the socket handle, NULL on error
324 struct GNUNET_CONNECTION_Handle *
325 GNUNET_CONNECTION_create_from_accept (struct GNUNET_SCHEDULER_Handle
327 GNUNET_CONNECTION_AccessCheck access,
329 struct GNUNET_NETWORK_Handle *lsock,
332 struct GNUNET_CONNECTION_Handle *ret;
335 struct GNUNET_NETWORK_Handle *sock;
337 struct sockaddr_in *v4;
338 struct sockaddr_in6 *v6;
342 addrlen = sizeof (addr);
344 GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
347 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "accept");
350 if (addrlen > sizeof (addr))
353 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
357 sa = (struct sockaddr *) addr;
358 v6 = (struct sockaddr_in6 *) addr;
359 if ((sa->sa_family == AF_INET6) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
361 /* convert to V4 address */
362 v4 = GNUNET_malloc (sizeof (struct sockaddr_in));
363 memset (v4, 0, sizeof (struct sockaddr_in));
364 v4->sin_family = AF_INET;
365 memcpy (&v4->sin_addr,
366 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
367 sizeof (struct in_addr)],
368 sizeof (struct in_addr));
369 v4->sin_port = v6->sin6_port;
371 addrlen = sizeof (struct sockaddr_in);
375 uaddr = GNUNET_malloc (addrlen);
376 memcpy (uaddr, addr, addrlen);
379 if ((access != NULL) &&
380 (GNUNET_YES != (aret = access (access_cls, uaddr, addrlen))))
382 if (aret == GNUNET_NO)
383 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
384 _("Access denied to `%s'\n"),
385 GNUNET_a2s (uaddr, addrlen));
386 GNUNET_break (GNUNET_OK ==
387 GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
388 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
392 ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle) + maxbuf);
393 ret->write_buffer = (char *) &ret[1];
394 ret->write_buffer_size = maxbuf;
396 ret->addrlen = addrlen;
400 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
401 _("Accepting connection from `%s': %p\n"),
402 GNUNET_a2s (uaddr, addrlen), ret);
408 * Obtain the network address of the other party.
410 * @param sock the client to get the address for
411 * @param addr where to store the address
412 * @param addrlen where to store the length of the address
413 * @return GNUNET_OK on success
416 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *sock,
417 void **addr, size_t * addrlen)
419 if ((sock->addr == NULL) || (sock->addrlen == 0))
421 *addr = GNUNET_malloc (sock->addrlen);
422 memcpy (*addr, sock->addr, sock->addrlen);
423 *addrlen = sock->addrlen;
429 * This function is called after establishing a connection either has
430 * succeeded or timed out. Note that it is possible that the attempt
431 * timed out and that we're immediately retrying. If we are retrying,
432 * we need to wait again (or timeout); if we succeeded, we need to
433 * wait for data (or timeout).
435 * @param cls our connection handle
436 * @param tc task context describing why we are here
439 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
443 * Scheduler let us know that the connect task is finished (or was
444 * cancelled due to shutdown). Now really clean up.
446 * @param cls our "struct GNUNET_CONNECTION_Handle *"
450 destroy_continuation (void *cls,
451 const struct GNUNET_SCHEDULER_TaskContext *tc)
453 struct GNUNET_CONNECTION_Handle *sock = cls;
454 GNUNET_CONNECTION_TransmitReadyNotify notify;
455 struct AddressProbe *pos;
457 GNUNET_assert (sock->dns_active == NULL);
458 if (0 != (sock->ccs & COCO_TRANSMIT_READY))
461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
462 "Destroy waits for CCS-TR to be done (%p)\n", sock);
464 sock->ccs |= COCO_DESTROY_CONTINUATION;
467 if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
471 "Destroy waits for write_task to be done (%p)\n", sock);
473 GNUNET_SCHEDULER_add_after (sock->sched,
475 &destroy_continuation, sock);
478 if (0 != (sock->ccs & COCO_RECEIVE_AGAIN))
480 sock->ccs |= COCO_DESTROY_CONTINUATION;
483 if (sock->sock != NULL)
486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
487 "Shutting down socket (%p)\n", sock);
489 GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
491 if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
493 GNUNET_SCHEDULER_add_after (sock->sched,
495 &destroy_continuation, sock);
499 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
500 "Destroy actually runs (%p)!\n", sock);
502 if (sock->dns_active != NULL)
504 GNUNET_RESOLVER_request_cancel (sock->dns_active);
505 sock->dns_active = NULL;
507 while (NULL != (pos = sock->ap_head))
509 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
510 GNUNET_SCHEDULER_cancel (sock->sched, pos->task);
511 GNUNET_CONTAINER_DLL_remove (sock->ap_head, sock->ap_tail, pos);
514 GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
515 GNUNET_assert (sock->ccs == COCO_NONE);
516 if (NULL != (notify = sock->nth.notify_ready))
518 sock->nth.notify_ready = NULL;
519 notify (sock->nth.notify_ready_cls, 0, NULL);
521 if (sock->sock != NULL)
522 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock->sock));
523 GNUNET_free_non_null (sock->addr);
524 GNUNET_free_non_null (sock->hostname);
526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
527 "Freeing memory of connection %p.\n", sock);
535 * See if we are now connected. If not, wait longer for
536 * connect to succeed. If connected, we should be able
537 * to write now as well, unless we timed out.
539 * @param cls our connection handle
540 * @param tc task context describing why we are here
543 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
547 * We've failed for good to establish a connection.
549 * @param h the connection we tried to establish
552 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *h)
555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
556 "Failed to establish TCP connection to `%s:%u', no further addresses to try (%p).\n",
557 h->hostname, h->port, h);
559 /* connect failed / timed out */
560 GNUNET_break (h->ap_head == NULL);
561 GNUNET_break (h->ap_tail == NULL);
562 GNUNET_break (h->dns_active == GNUNET_NO);
563 GNUNET_break (h->sock == NULL);
565 /* trigger jobs that used to wait on "connect_task" */
566 if (0 != (h->ccs & COCO_RECEIVE_AGAIN))
569 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
570 "connect_timeout_continuation triggers receive_again (%p)\n",
573 h->ccs -= COCO_RECEIVE_AGAIN;
574 h->read_task = GNUNET_SCHEDULER_add_after (h->sched,
575 GNUNET_SCHEDULER_NO_TASK,
578 if (0 != (h->ccs & COCO_TRANSMIT_READY))
581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
582 "connect_timeout_continuation cancels timeout_task, triggers transmit_ready (%p)\n",
585 GNUNET_assert (h->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
586 GNUNET_SCHEDULER_cancel (h->sched, h->nth.timeout_task);
587 h->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
588 h->ccs -= COCO_TRANSMIT_READY;
589 h->write_task = GNUNET_SCHEDULER_add_after (h->sched,
590 GNUNET_SCHEDULER_NO_TASK,
593 if (0 != (h->ccs & COCO_DESTROY_CONTINUATION))
596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
597 "connect_timeout_continuation runs destroy_continuation (%p)\n",
600 h->ccs -= COCO_DESTROY_CONTINUATION;
601 GNUNET_SCHEDULER_add_continuation (h->sched,
602 &destroy_continuation,
603 h, GNUNET_SCHEDULER_REASON_TIMEOUT);
609 * We've succeeded in establishing a connection.
611 * @param h the connection we tried to establish
614 connect_success_continuation (struct GNUNET_CONNECTION_Handle *h)
617 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
618 "Connection to `%s' succeeded! (%p)\n",
619 GNUNET_a2s (h->addr, h->addrlen), h);
621 /* trigger jobs that waited for the connection */
622 if (0 != (h->ccs & COCO_RECEIVE_AGAIN))
625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
626 "connect_success_continuation runs receive_again (%p)\n",
629 h->ccs -= COCO_RECEIVE_AGAIN;
630 h->read_task = GNUNET_SCHEDULER_add_after (h->sched,
631 GNUNET_SCHEDULER_NO_TASK,
634 if (0 != (h->ccs & COCO_TRANSMIT_READY))
637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
638 "connect_success_continuation runs transmit_ready, cancels timeout_task (%p)\n",
641 GNUNET_assert (h->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
642 GNUNET_SCHEDULER_cancel (h->sched, h->nth.timeout_task);
643 h->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
644 h->ccs -= COCO_TRANSMIT_READY;
646 GNUNET_SCHEDULER_add_write_net (h->sched,
647 GNUNET_TIME_absolute_get_remaining
648 (h->nth.transmit_timeout), h->sock,
651 if (0 != (h->ccs & COCO_DESTROY_CONTINUATION))
654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
655 "connect_success_continuation runs destroy_continuation (%p)\n",
658 h->ccs -= COCO_DESTROY_CONTINUATION;
659 GNUNET_SCHEDULER_add_continuation (h->sched,
660 &destroy_continuation,
662 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
668 * Scheduler let us know that we're either ready to write on the
669 * socket OR connect timed out. Do the right thing.
671 * @param cls the "struct AddressProbe*" with the address that we are probing
672 * @param tc success or failure info about the connect attempt.
675 connect_probe_continuation (void *cls,
676 const struct GNUNET_SCHEDULER_TaskContext *tc)
678 struct AddressProbe *ap = cls;
679 struct GNUNET_CONNECTION_Handle *h = ap->h;
680 struct AddressProbe *pos;
684 GNUNET_CONTAINER_DLL_remove (h->ap_head, h->ap_tail, ap);
685 len = sizeof (error);
688 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
690 GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR,
691 &error, &len)) || (error != 0)
694 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
696 if ((NULL == h->ap_head) && (h->dns_active == GNUNET_NO))
697 connect_fail_continuation (h);
700 GNUNET_assert (h->sock == NULL);
701 GNUNET_assert (ap->sock != NULL);
703 GNUNET_assert (h->addr == NULL);
704 h->addr = GNUNET_malloc (ap->addrlen);
705 memcpy (h->addr, ap->addr, ap->addrlen);
706 h->addrlen = ap->addrlen;
708 /* cancel all other attempts */
709 while (NULL != (pos = h->ap_head))
711 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
712 GNUNET_SCHEDULER_cancel (h->sched, pos->task);
713 GNUNET_CONTAINER_DLL_remove (h->ap_head, h->ap_tail, pos);
716 connect_success_continuation (h);
721 * Try to establish a socket connection given the specified address.
722 * This function is called by the resolver once we have a DNS reply.
724 * @param cls our "struct GNUNET_CONNECTION_Handle *"
725 * @param addr address to try, NULL for "last call"
726 * @param addrlen length of addr
729 try_connect_using_address (void *cls,
730 const struct sockaddr *addr, socklen_t addrlen)
732 struct GNUNET_CONNECTION_Handle *h = cls;
733 struct AddressProbe *ap;
734 struct GNUNET_TIME_Relative delay;
738 h->dns_active = NULL;
739 if (NULL == h->ap_head)
740 connect_fail_continuation (h);
744 return; /* already connected */
745 GNUNET_assert (h->addr == NULL);
748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
749 "Trying to connect using address `%s:%u/%s:%u'\n",
750 h->hostname, h->port, GNUNET_a2s (addr, addrlen), h->port);
752 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
753 ap->addr = (const struct sockaddr *) &ap[1];
754 memcpy (&ap[1], addr, addrlen);
755 ap->addrlen = addrlen;
758 switch (ap->addr->sa_family)
761 ((struct sockaddr_in *) ap->addr)->sin_port = htons (h->port);
764 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (h->port);
769 return; /* not supported by us */
772 GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
773 if (ap->sock == NULL)
776 return; /* not supported by OS */
779 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
780 _("Trying to connect to `%s' (%p)\n"),
781 GNUNET_a2s (ap->addr, ap->addrlen), h);
783 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (ap->sock,
786 (errno != EINPROGRESS))
788 /* maybe refused / unsupported address, try next */
789 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
790 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
794 GNUNET_CONTAINER_DLL_insert (h->ap_head, h->ap_tail, ap);
795 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
796 if (h->nth.notify_ready != NULL)
797 delay = GNUNET_TIME_relative_min (delay,
798 GNUNET_TIME_absolute_get_remaining
799 (h->nth.transmit_timeout));
800 if (h->receiver != NULL)
801 delay = GNUNET_TIME_relative_min (delay,
802 GNUNET_TIME_absolute_get_remaining
803 (h->receive_timeout));
805 GNUNET_SCHEDULER_add_write_net (h->sched, delay, ap->sock,
806 &connect_probe_continuation, ap);
811 * Create a socket handle by (asynchronously) connecting to a host.
812 * This function returns immediately, even if the connection has not
813 * yet been established. This function only creates TCP connections.
815 * @param sched scheduler to use
816 * @param cfg configuration to use
817 * @param hostname name of the host to connect to
818 * @param port port to connect to
819 * @param maxbuf maximum write buffer size for the socket (use
820 * 0 for sockets that need no write buffers, such as listen sockets)
821 * @return the socket handle
823 struct GNUNET_CONNECTION_Handle *
824 GNUNET_CONNECTION_create_from_connect (struct GNUNET_SCHEDULER_Handle *sched,
826 GNUNET_CONFIGURATION_Handle *cfg,
827 const char *hostname, uint16_t port,
830 struct GNUNET_CONNECTION_Handle *ret;
832 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
833 ret = GNUNET_malloc (sizeof (struct GNUNET_CONNECTION_Handle) + maxbuf);
836 ret->write_buffer = (char *) &ret[1];
837 ret->write_buffer_size = maxbuf;
839 ret->hostname = GNUNET_strdup (hostname);
840 ret->dns_active = GNUNET_RESOLVER_ip_get (sched,
844 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
845 &try_connect_using_address, ret);
851 * Create a socket handle by (asynchronously) connecting to a host.
852 * This function returns immediately, even if the connection has not
853 * yet been established. This function only creates TCP connections.
855 * @param sched scheduler to use
856 * @param af_family address family to use
857 * @param serv_addr server address
858 * @param addrlen length of server address
859 * @param maxbuf maximum write buffer size for the socket (use
860 * 0 for sockets that need no write buffers, such as listen sockets)
861 * @return the socket handle
863 struct GNUNET_CONNECTION_Handle *
864 GNUNET_CONNECTION_create_from_sockaddr (struct GNUNET_SCHEDULER_Handle
865 *sched, int af_family,
866 const struct sockaddr *serv_addr,
867 socklen_t addrlen, size_t maxbuf)
869 struct GNUNET_NETWORK_Handle *s;
870 struct GNUNET_CONNECTION_Handle *ret;
872 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
875 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING |
876 GNUNET_ERROR_TYPE_BULK, "socket");
879 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen))
880 && (errno != EINPROGRESS))
882 /* maybe refused / unsupported address, try next */
883 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
884 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
887 ret = GNUNET_CONNECTION_create_from_existing (sched, s, maxbuf);
888 ret->addr = GNUNET_malloc (addrlen);
889 memcpy (ret->addr, serv_addr, addrlen);
890 ret->addrlen = addrlen;
892 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
893 _("Trying to connect to `%s' (%p)\n"),
894 GNUNET_a2s (serv_addr, addrlen), ret);
901 * Check if socket is valid (no fatal errors have happened so far).
902 * Note that a socket that is still trying to connect is considered
905 * @param sock socket to check
906 * @return GNUNET_YES if valid, GNUNET_NO otherwise
909 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *sock)
911 if ((sock->ap_head != NULL) || (sock->dns_active != NULL))
912 return GNUNET_YES; /* still trying to connect */
913 return (sock->sock == NULL) ? GNUNET_NO : GNUNET_YES;
918 * Close the socket and free associated resources. Pending
919 * transmissions may be completed or dropped depending on the
920 * arguments. If a receive call is pending and should
921 * NOT be completed, 'GNUNET_CONNECTION_receive_cancel'
922 * should be called explicitly first.
924 * @param sock socket to destroy
925 * @param finish_pending_write should pending writes be completed or aborted?
926 * (this applies to transmissions where the data has already been
927 * read from the application; all other transmissions should be
928 * aborted using 'GNUNET_CONNECTION_notify_transmit_ready_cancel').
931 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *sock,
932 int finish_pending_write)
934 if (GNUNET_NO == finish_pending_write)
936 if (sock->write_task != GNUNET_SCHEDULER_NO_TASK)
938 GNUNET_SCHEDULER_cancel (sock->sched,
940 sock->write_task = GNUNET_SCHEDULER_NO_TASK;
941 sock->write_buffer_off = 0;
944 if ((sock->write_buffer_off == 0) && (sock->dns_active != NULL))
946 GNUNET_RESOLVER_request_cancel (sock->dns_active);
947 sock->dns_active = NULL;
949 GNUNET_assert (sock->sched != NULL);
950 GNUNET_SCHEDULER_add_now (sock->sched,
951 &destroy_continuation, sock);
956 * Tell the receiver callback that a timeout was reached.
959 signal_timeout (struct GNUNET_CONNECTION_Handle *sh)
961 GNUNET_CONNECTION_Receiver receiver;
964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
965 "Network signals time out to receiver (%p)!\n", sh);
967 GNUNET_assert (NULL != (receiver = sh->receiver));
969 receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
974 * Tell the receiver callback that we had an IO error.
977 signal_error (struct GNUNET_CONNECTION_Handle *sh, int errcode)
979 GNUNET_CONNECTION_Receiver receiver;
980 GNUNET_assert (NULL != (receiver = sh->receiver));
982 receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
987 * This function is called once we either timeout
988 * or have data ready to read.
991 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
993 struct GNUNET_CONNECTION_Handle *sh = cls;
994 struct GNUNET_TIME_Absolute now;
995 char buffer[sh->max];
997 GNUNET_CONNECTION_Receiver receiver;
999 sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1000 if ( (GNUNET_YES == sh->ignore_shutdown) &&
1001 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1003 /* ignore shutdown request, go again immediately */
1004 #if DEBUG_CONNECTION
1005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1006 "Ignoring shutdown signal per configuration\n");
1008 sh->read_task = GNUNET_SCHEDULER_add_read_net (tc->sched,
1009 GNUNET_TIME_absolute_get_remaining
1010 (sh->receive_timeout),
1012 &receive_ready, sh);
1015 now = GNUNET_TIME_absolute_get ();
1016 if ((now.value > sh->receive_timeout.value) ||
1017 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
1018 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1020 #if DEBUG_CONNECTION
1021 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1023 "Receive from `%s' encounters error: time out by %llums... (%p)\n",
1024 GNUNET_a2s (sh->addr, sh->addrlen),
1025 GNUNET_TIME_absolute_get_duration (sh->receive_timeout).
1028 signal_timeout (sh);
1031 if (sh->sock == NULL)
1033 /* connect failed for good */
1034 #if DEBUG_CONNECTION
1035 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1036 "Receive encounters error, socket closed... (%p)\n", sh);
1038 signal_error (sh, ECONNREFUSED);
1041 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, sh->sock));
1043 ret = GNUNET_NETWORK_socket_recv (sh->sock, buffer, sh->max);
1048 #if DEBUG_CONNECTION
1049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1050 "Error receiving: %s\n", STRERROR (errno));
1052 signal_error (sh, errno);
1055 #if DEBUG_CONNECTION
1056 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1057 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1059 sh->max, GNUNET_a2s (sh->addr, sh->addrlen), sh);
1061 GNUNET_assert (NULL != (receiver = sh->receiver));
1062 sh->receiver = NULL;
1063 receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
1068 * This function is called after establishing a connection either has
1069 * succeeded or timed out. Note that it is possible that the attempt
1070 * timed out and that we're immediately retrying. If we are retrying,
1071 * we need to wait again (or timeout); if we succeeded, we need to
1072 * wait for data (or timeout).
1074 * @param cls our connection handle
1075 * @param tc task context describing why we are here
1078 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1080 struct GNUNET_CONNECTION_Handle *sh = cls;
1081 struct GNUNET_TIME_Absolute now;
1083 sh->read_task = GNUNET_SCHEDULER_NO_TASK;
1084 if (sh->sock == NULL)
1086 /* not connected and no longer trying */
1087 #if DEBUG_CONNECTION
1088 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1089 "Receive encounters error, socket closed (%p)...\n", sh);
1091 signal_error (sh, ECONNREFUSED);
1094 now = GNUNET_TIME_absolute_get ();
1095 if ((now.value > sh->receive_timeout.value) ||
1096 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
1098 #if DEBUG_CONNECTION
1099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100 "Receive encounters error: time out (%p)...\n", sh);
1102 signal_timeout (sh);
1105 GNUNET_assert (sh->sock != NULL);
1106 /* connect succeeded, wait for data! */
1107 sh->read_task = GNUNET_SCHEDULER_add_read_net (tc->sched,
1108 GNUNET_TIME_absolute_get_remaining
1109 (sh->receive_timeout),
1111 &receive_ready, sh);
1116 * Receive data from the given socket. Note that this function will
1117 * call "receiver" asynchronously using the scheduler. It will
1118 * "immediately" return. Note that there MUST only be one active
1119 * receive call per socket at any given point in time (so do not
1120 * call receive again until the receiver callback has been invoked).
1122 * @param sock socket handle
1123 * @param max maximum number of bytes to read
1124 * @param timeout maximum amount of time to wait (use -1 for "forever")
1125 * @param receiver function to call with received data
1126 * @param receiver_cls closure for receiver
1129 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *sock,
1131 struct GNUNET_TIME_Relative timeout,
1132 GNUNET_CONNECTION_Receiver receiver,
1135 struct GNUNET_SCHEDULER_TaskContext tc;
1137 GNUNET_assert ((sock->read_task == GNUNET_SCHEDULER_NO_TASK) &&
1138 (0 == (sock->ccs & COCO_RECEIVE_AGAIN)) &&
1139 (sock->receiver == NULL));
1140 sock->receiver = receiver;
1141 sock->receiver_cls = receiver_cls;
1142 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1144 if (sock->sock != NULL)
1146 memset (&tc, 0, sizeof (tc));
1147 tc.sched = sock->sched;
1148 tc.reason = GNUNET_SCHEDULER_REASON_PREREQ_DONE;
1149 receive_again (sock, &tc);
1152 if ((sock->dns_active == NULL) && (sock->ap_head == NULL))
1154 receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1157 sock->ccs += COCO_RECEIVE_AGAIN;
1162 * Configure this connection to ignore shutdown signals.
1164 * @param sock socket handle
1165 * @param do_ignore GNUNET_YES to ignore, GNUNET_NO to restore default
1168 GNUNET_CONNECTION_ignore_shutdown (struct GNUNET_CONNECTION_Handle *sock,
1171 sock->ignore_shutdown = do_ignore;
1176 * Cancel receive job on the given socket. Note that the
1177 * receiver callback must not have been called yet in order
1178 * for the cancellation to be valid.
1180 * @param sock socket handle
1181 * @return closure of the original receiver callback closure
1184 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *sock)
1186 if (sock->read_task != GNUNET_SCHEDULER_NO_TASK)
1188 GNUNET_assert (sock == GNUNET_SCHEDULER_cancel (sock->sched,
1190 sock->read_task = GNUNET_SCHEDULER_NO_TASK;
1194 GNUNET_assert (0 != (sock->ccs & COCO_RECEIVE_AGAIN));
1195 sock->ccs -= COCO_RECEIVE_AGAIN;
1197 sock->receiver = NULL;
1198 return sock->receiver_cls;
1203 * Try to call the transmit notify method (check if we do
1204 * have enough space available first)!
1206 * @param sock socket for which we should do this processing
1207 * @return GNUNET_YES if we were able to call notify
1210 process_notify (struct GNUNET_CONNECTION_Handle *sock)
1215 GNUNET_CONNECTION_TransmitReadyNotify notify;
1217 GNUNET_assert (sock->write_task == GNUNET_SCHEDULER_NO_TASK);
1218 if (NULL == (notify = sock->nth.notify_ready))
1220 used = sock->write_buffer_off - sock->write_buffer_pos;
1221 avail = sock->write_buffer_size - used;
1222 size = sock->nth.notify_size;
1223 if (sock->nth.notify_size > avail)
1225 sock->nth.notify_ready = NULL;
1226 if (sock->write_buffer_size - sock->write_buffer_off < size)
1228 /* need to compact */
1229 memmove (sock->write_buffer,
1230 &sock->write_buffer[sock->write_buffer_pos], used);
1231 sock->write_buffer_off -= sock->write_buffer_pos;
1232 sock->write_buffer_pos = 0;
1234 GNUNET_assert (sock->write_buffer_size - sock->write_buffer_off >= size);
1235 size = notify (sock->nth.notify_ready_cls,
1236 sock->write_buffer_size - sock->write_buffer_off,
1237 &sock->write_buffer[sock->write_buffer_off]);
1238 sock->write_buffer_off += size;
1244 * Task invoked by the scheduler when a call to transmit
1245 * is timing out (we never got enough buffer space to call
1246 * the callback function before the specified timeout
1249 * This task notifies the client about the timeout.
1252 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1254 struct GNUNET_CONNECTION_Handle *sock = cls;
1255 GNUNET_CONNECTION_TransmitReadyNotify notify;
1257 #if DEBUG_CONNECTION
1258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1259 "transmit_timeout running (%p)\n", sock);
1261 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1262 #if DEBUG_CONNECTION
1263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1264 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1266 sock->port, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1268 GNUNET_assert (0 != (sock->ccs & COCO_TRANSMIT_READY));
1269 sock->ccs -= COCO_TRANSMIT_READY; /* remove request */
1270 notify = sock->nth.notify_ready;
1271 sock->nth.notify_ready = NULL;
1272 notify (sock->nth.notify_ready_cls, 0, NULL);
1277 * Task invoked by the scheduler when we failed to connect
1278 * at the time of being asked to transmit.
1280 * This task notifies the client about the error.
1283 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1285 struct GNUNET_CONNECTION_Handle *sock = cls;
1286 GNUNET_CONNECTION_TransmitReadyNotify notify;
1288 #if DEBUG_CONNECTION
1289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1290 "Transmission request of size %u fails, connection failed (%p).\n",
1291 sock->nth.notify_size, sock);
1293 sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1294 notify = sock->nth.notify_ready;
1295 sock->nth.notify_ready = NULL;
1296 notify (sock->nth.notify_ready_cls, 0, NULL);
1301 transmit_error (struct GNUNET_CONNECTION_Handle *sock)
1303 GNUNET_CONNECTION_TransmitReadyNotify notify;
1305 if (sock->nth.notify_ready == NULL)
1306 return; /* nobody to tell about it */
1307 notify = sock->nth.notify_ready;
1308 sock->nth.notify_ready = NULL;
1309 notify (sock->nth.notify_ready_cls, 0, NULL);
1314 * See if we are now connected. If not, wait longer for
1315 * connect to succeed. If connected, we should be able
1316 * to write now as well, unless we timed out.
1318 * @param cls our connection handle
1319 * @param tc task context describing why we are here
1322 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1324 struct GNUNET_CONNECTION_Handle *sock = cls;
1325 GNUNET_CONNECTION_TransmitReadyNotify notify;
1329 #if DEBUG_CONNECTION
1330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1331 "transmit_ready running (%p).\n", sock);
1333 GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_TASK);
1334 sock->write_task = GNUNET_SCHEDULER_NO_TASK;
1335 GNUNET_assert (sock->nth.timeout_task == GNUNET_SCHEDULER_NO_TASK);
1336 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1338 if (sock->ignore_shutdown == GNUNET_YES)
1339 goto SCHEDULE_WRITE; /* ignore shutdown, go again immediately */
1340 #if DEBUG_CONNECTION
1341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1342 "Transmit to `%s' fails, shutdown happened (%p).\n",
1343 GNUNET_a2s (sock->addr, sock->addrlen), sock);
1345 notify = sock->nth.notify_ready;
1346 sock->nth.notify_ready = NULL;
1347 notify (sock->nth.notify_ready_cls, 0, NULL);
1350 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1352 #if DEBUG_CONNECTION
1353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1354 "Transmit to `%s' fails, time out reached (%p).\n",
1355 GNUNET_a2s (sock->addr, sock->addrlen), sock);
1357 notify = sock->nth.notify_ready;
1358 sock->nth.notify_ready = NULL;
1359 notify (sock->nth.notify_ready_cls, 0, NULL);
1362 GNUNET_assert (NULL != sock->sock);
1363 if (tc->write_ready == NULL)
1365 /* special circumstances (in particular,
1366 PREREQ_DONE after connect): not yet ready to write,
1367 but no "fatal" error either. Hence retry. */
1368 goto SCHEDULE_WRITE;
1370 if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, sock->sock))
1372 #if DEBUG_CONNECTION
1373 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1375 ("Could not satisfy pending transmission request, socket closed or connect failed (%p).\n"),
1378 if (NULL != sock->sock)
1380 GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_RDWR);
1381 GNUNET_break (GNUNET_OK ==
1382 GNUNET_NETWORK_socket_close (sock->sock));
1385 transmit_error (sock);
1386 return; /* connect failed for good, we're finished */
1388 GNUNET_assert (sock->write_buffer_off >= sock->write_buffer_pos);
1389 process_notify (sock);
1390 have = sock->write_buffer_off - sock->write_buffer_pos;
1393 /* no data ready for writing, terminate write loop */
1396 GNUNET_assert (have <= sock->write_buffer_size);
1397 GNUNET_assert (have + sock->write_buffer_pos <= sock->write_buffer_size);
1398 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1400 ret = GNUNET_NETWORK_socket_send (sock->sock,
1401 &sock->write_buffer[sock->
1408 #if DEBUG_CONNECTION
1409 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send");
1411 GNUNET_NETWORK_socket_shutdown (sock->sock, SHUT_WR);
1412 transmit_error (sock);
1415 #if DEBUG_CONNECTION
1416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1417 "transmit_ready transmitted %u/%u bytes to `%s' (%p)\n",
1419 have, GNUNET_a2s (sock->addr, sock->addrlen), sock);
1421 sock->write_buffer_pos += ret;
1422 if (sock->write_buffer_pos == sock->write_buffer_off)
1424 /* transmitted all pending data */
1425 sock->write_buffer_pos = 0;
1426 sock->write_buffer_off = 0;
1428 if ((sock->write_buffer_off == 0) && (NULL == sock->nth.notify_ready))
1429 return; /* all data sent! */
1430 /* not done writing, schedule more */
1432 #if DEBUG_CONNECTION
1433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1434 "Re-scheduling transmit_ready (more to do) (%p).\n", sock);
1436 if (sock->write_task == GNUNET_SCHEDULER_NO_TASK)
1438 GNUNET_SCHEDULER_add_write_net (tc->sched,
1439 GNUNET_TIME_absolute_get_remaining
1440 (sock->nth.transmit_timeout),
1441 sock->sock, &transmit_ready, sock);
1446 * Ask the socket to call us once the specified number of bytes
1447 * are free in the transmission buffer. May call the notify
1448 * method immediately if enough space is available.
1450 * @param sock socket
1451 * @param size number of bytes to send
1452 * @param timeout after how long should we give up (and call
1453 * notify with buf NULL and size 0)?
1454 * @param notify function to call
1455 * @param notify_cls closure for notify
1456 * @return non-NULL if the notify callback was queued,
1457 * NULL if we are already going to notify someone else (busy)
1459 struct GNUNET_CONNECTION_TransmitHandle *
1460 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle
1462 struct GNUNET_TIME_Relative timeout,
1463 GNUNET_CONNECTION_TransmitReadyNotify
1464 notify, void *notify_cls)
1466 if (sock->nth.notify_ready != NULL)
1468 GNUNET_assert (notify != NULL);
1469 GNUNET_assert (sock->write_buffer_size >= size);
1470 GNUNET_assert (sock->write_buffer_off <= sock->write_buffer_size);
1471 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1472 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_off);
1473 sock->nth.notify_ready = notify;
1474 sock->nth.notify_ready_cls = notify_cls;
1475 sock->nth.sh = sock;
1476 sock->nth.notify_size = size;
1477 sock->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1478 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->nth.timeout_task);
1479 if ((sock->sock == NULL) &&
1480 (sock->ap_head == NULL) && (sock->dns_active == NULL))
1482 sock->write_task = GNUNET_SCHEDULER_add_now (sock->sched,
1483 &connect_error, sock);
1486 if (GNUNET_SCHEDULER_NO_TASK != sock->write_task)
1488 if (sock->sock != NULL)
1490 #if DEBUG_CONNECTION
1491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1492 "Scheduling transmit_ready (%p).\n", sock);
1494 sock->write_task = GNUNET_SCHEDULER_add_write_net (sock->sched,
1495 GNUNET_TIME_absolute_get_remaining
1504 #if DEBUG_CONNECTION
1505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1506 "CCS-Scheduling transmit_ready, adding timeout task (%p).\n",
1509 sock->ccs |= COCO_TRANSMIT_READY;
1510 sock->nth.timeout_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1520 * Cancel the specified transmission-ready
1524 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1525 GNUNET_CONNECTION_TransmitHandle
1528 GNUNET_assert (h->notify_ready != NULL);
1529 if (0 != (h->sh->ccs & COCO_TRANSMIT_READY))
1531 #if DEBUG_CONNECTION
1532 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1533 "notify_transmit_ready_cancel cancels timeout_task (%p)\n",
1536 GNUNET_SCHEDULER_cancel (h->sh->sched, h->timeout_task);
1537 h->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1538 h->sh->ccs -= COCO_TRANSMIT_READY;
1542 if (h->sh->write_task != GNUNET_SCHEDULER_NO_TASK)
1544 GNUNET_SCHEDULER_cancel (h->sh->sched, h->sh->write_task);
1545 h->sh->write_task = GNUNET_SCHEDULER_NO_TASK;
1548 h->notify_ready = NULL;
1551 /* end of connection.c */