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/network/network.c
23 * @brief basic, low-level TCP networking interface
24 * @author Christian Grothoff
26 * This code is rather complex. Only modify it if you
27 * 1) Have a NEW testcase showing that the new code
28 * is needed and correct
29 * 2) All EXISTING testcases pass with the new code
30 * These rules should apply in general, but for this
31 * module they are VERY, VERY important.
34 * - can we merge receive_ready and receive_again?
35 * - can we integrate the nth.timeout_task with the write_task's timeout?
39 #include "gnunet_common.h"
40 #include "gnunet_network_lib.h"
41 #include "gnunet_scheduler_lib.h"
43 #define DEBUG_NETWORK GNUNET_NO
45 struct GNUNET_NETWORK_TransmitHandle
49 * Function to call if the send buffer has notify_size
52 GNUNET_NETWORK_TransmitReadyNotify notify_ready;
55 * Closure for notify_ready.
57 void *notify_ready_cls;
62 struct GNUNET_NETWORK_SocketHandle *sh;
65 * Timeout for receiving (in absolute time).
67 struct GNUNET_TIME_Absolute transmit_timeout;
70 * Task called on timeout.
72 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
75 * At what number of bytes available in the
76 * write buffer should the notify method be called?
83 * @brief handle for a network socket
85 struct GNUNET_NETWORK_SocketHandle
89 * Scheduler that was used for the connect task.
91 struct GNUNET_SCHEDULER_Handle *sched;
94 * Address information for connect (may be NULL).
99 * Index for the next struct addrinfo for connect attempts (may be NULL)
101 struct addrinfo *ai_pos;
104 * Network address of the other end-point, may be NULL.
106 struct sockaddr *addr;
109 * Pointer to our write buffer.
114 * Size of our write buffer.
116 size_t write_buffer_size;
119 * Current write-offset in write buffer (where
120 * would we write next).
122 size_t write_buffer_off;
125 * Current read-offset in write buffer (how many
126 * bytes have already been send).
128 size_t write_buffer_pos;
136 * Connect task that we may need to wait for.
138 GNUNET_SCHEDULER_TaskIdentifier connect_task;
141 * Read task that we may need to wait for.
143 GNUNET_SCHEDULER_TaskIdentifier read_task;
146 * Write task that we may need to wait for.
148 GNUNET_SCHEDULER_TaskIdentifier write_task;
151 * The handle we return for GNUNET_NETWORK_notify_transmit_ready.
153 struct GNUNET_NETWORK_TransmitHandle nth;
156 * Underlying OS's socket, set to -1 after fatal errors.
161 * Port to connect to.
166 * Function to call on data received, NULL
167 * if no receive is pending.
169 GNUNET_NETWORK_Receiver receiver;
172 * Closure for receiver.
177 * Timeout for receiving (in absolute time).
179 struct GNUNET_TIME_Absolute receive_timeout;
182 * Maximum number of bytes to read
191 * Create a socket handle by boxing an existing OS socket. The OS
192 * socket should henceforth be no longer used directly.
193 * GNUNET_socket_destroy will close it.
195 * @param sched scheduler to use
196 * @param osSocket existing socket to box
197 * @param maxbuf maximum write buffer size for the socket (use
198 * 0 for sockets that need no write buffers, such as listen sockets)
199 * @return the boxed socket handle
201 struct GNUNET_NETWORK_SocketHandle *
202 GNUNET_NETWORK_socket_create_from_existing (struct GNUNET_SCHEDULER_Handle
203 *sched, int osSocket,
206 struct GNUNET_NETWORK_SocketHandle *ret;
207 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_SocketHandle) + maxbuf);
208 ret->write_buffer = (char *) &ret[1];
209 ret->write_buffer_size = maxbuf;
210 ret->sock = osSocket;
217 * Create a socket handle by accepting on a listen socket. This
218 * function may block if the listen socket has no connection ready.
220 * @param sched scheduler to use
221 * @param access function to use to check if access is allowed
222 * @param access_cls closure for access
223 * @param lsock listen socket
224 * @param maxbuf maximum write buffer size for the socket (use
225 * 0 for sockets that need no write buffers, such as listen sockets)
226 * @return the socket handle, NULL on error
228 struct GNUNET_NETWORK_SocketHandle *
229 GNUNET_NETWORK_socket_create_from_accept (struct GNUNET_SCHEDULER_Handle
231 GNUNET_NETWORK_AccessCheck access,
232 void *access_cls, int lsock,
235 struct GNUNET_NETWORK_SocketHandle *ret;
240 struct sockaddr_in *v4;
241 struct sockaddr_in6 *v6;
245 addrlen = sizeof (addr);
246 fd = accept (lsock, (struct sockaddr *) &addr, &addrlen);
249 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "accept");
252 if (0 != fcntl (fd, F_SETFD, fcntl (fd, F_GETFD) | FD_CLOEXEC))
253 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
255 if (addrlen > sizeof (addr))
258 GNUNET_break (0 == CLOSE (fd));
262 sa = (struct sockaddr *) addr;
263 v6 = (struct sockaddr_in6 *) addr;
264 if ((sa->sa_family == AF_INET6) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
266 /* convert to V4 address */
267 v4 = GNUNET_malloc (sizeof (struct sockaddr_in));
268 memset (v4, 0, sizeof (struct sockaddr_in));
269 v4->sin_family = AF_INET;
270 memcpy (&v4->sin_addr,
271 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
272 sizeof (struct in_addr)],
273 sizeof (struct in_addr));
274 v4->sin_port = v6->sin6_port;
276 addrlen = sizeof (struct sockaddr_in);
280 uaddr = GNUNET_malloc (addrlen);
281 memcpy (uaddr, addr, addrlen);
284 if ((access != NULL) &&
285 (GNUNET_YES != (aret = access (access_cls, uaddr, addrlen))))
287 if (aret == GNUNET_NO)
288 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
289 _("Access denied to `%s'\n"),
290 GNUNET_a2s(uaddr, addrlen));
291 GNUNET_break (0 == SHUTDOWN (fd, SHUT_RDWR));
292 GNUNET_break (0 == CLOSE (fd));
297 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
298 _("Accepting connection from `%s'\n"),
299 GNUNET_a2s(uaddr, addrlen));
301 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_SocketHandle) + maxbuf);
302 ret->write_buffer = (char *) &ret[1];
303 ret->write_buffer_size = maxbuf;
305 ret->addrlen = addrlen;
312 * Obtain the network address of the other party.
314 * @param sock the client to get the address for
315 * @param addr where to store the address
316 * @param addrlen where to store the length of the address
317 * @return GNUNET_OK on success
320 GNUNET_NETWORK_socket_get_address (struct GNUNET_NETWORK_SocketHandle *sock,
321 void **addr, size_t * addrlen)
323 if ((sock->addr == NULL) || (sock->addrlen == 0))
325 *addr = GNUNET_malloc (sock->addrlen);
326 memcpy (*addr, sock->addr, sock->addrlen);
327 *addrlen = sock->addrlen;
333 * Set if a socket should use blocking or non-blocking IO.
335 * @return GNUNET_OK on success, GNUNET_SYSERR on error
338 socket_set_blocking (int handle, int doBlock)
344 if (ioctlsocket (plibc_fd_get_handle (handle), FIONBIO, &mode) ==
347 SetErrnoFromWinsockError (WSAGetLastError ());
348 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "ioctlsocket");
349 return GNUNET_SYSERR;
352 if (ioctlsocket (handle, FIONBIO, &mode) == SOCKET_ERROR)
354 SetErrnoFromWinsockError (WSAGetLastError ());
355 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "ioctlsocket");
356 return GNUNET_SYSERR;
359 /* store the blocking mode */
361 plibc_fd_set_blocking (handle, doBlock);
363 __win_SetHandleBlockingMode (handle, doBlock);
369 int flags = fcntl (handle, F_GETFL);
372 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fcntl");
373 return GNUNET_SYSERR;
376 flags &= ~O_NONBLOCK;
379 if (0 != fcntl (handle, F_SETFL, flags))
381 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fcntl");
382 return GNUNET_SYSERR;
390 * Initiate asynchronous TCP connect request.
392 * @param sock what socket to connect
393 * @return GNUNET_SYSERR error (no more addresses to try)
396 try_connect (struct GNUNET_NETWORK_SocketHandle *sock)
400 if (sock->addr != NULL)
402 GNUNET_free (sock->addr);
408 if (sock->ai_pos == NULL)
410 /* no more addresses to try, fatal! */
411 return GNUNET_SYSERR;
413 switch (sock->ai_pos->ai_family)
416 ((struct sockaddr_in *) sock->ai_pos->ai_addr)->sin_port =
420 ((struct sockaddr_in6 *) sock->ai_pos->ai_addr)->sin6_port =
424 sock->ai_pos = sock->ai_pos->ai_next;
427 s = SOCKET (sock->ai_pos->ai_family, SOCK_STREAM, 0);
430 /* maybe unsupported address family, try next */
431 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "socket");
432 sock->ai_pos = sock->ai_pos->ai_next;
435 if (0 != fcntl (s, F_SETFD, fcntl (s, F_GETFD) | FD_CLOEXEC))
436 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
438 if (GNUNET_SYSERR == socket_set_blocking (s, GNUNET_NO))
440 /* we'll treat this one as fatal */
441 GNUNET_break (0 == CLOSE (s));
442 return GNUNET_SYSERR;
445 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
446 _("Trying to connect to `%s'\n"),
447 GNUNET_a2s(sock->ai_pos->ai_addr,
448 sock->ai_pos->ai_addrlen));
450 if ((0 != CONNECT (s,
451 sock->ai_pos->ai_addr,
452 sock->ai_pos->ai_addrlen)) && (errno != EINPROGRESS))
454 /* maybe refused / unsupported address, try next */
455 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
456 GNUNET_break (0 == CLOSE (s));
461 /* got one! copy address information! */
462 sock->addrlen = sock->ai_pos->ai_addrlen;
463 sock->addr = GNUNET_malloc (sock->addrlen);
464 memcpy (sock->addr, sock->ai_pos->ai_addr, sock->addrlen);
465 sock->ai_pos = sock->ai_pos->ai_next;
472 * Scheduler let us know that we're either ready to
473 * write on the socket OR connect timed out. Do the
477 connect_continuation (void *cls,
478 const struct GNUNET_SCHEDULER_TaskContext *tc)
480 struct GNUNET_NETWORK_SocketHandle *sock = cls;
484 /* nobody needs to wait for us anymore... */
485 sock->connect_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
486 /* Note: write-ready does NOT mean connect succeeded,
487 we need to use getsockopt to be sure */
488 len = sizeof (error);
491 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
492 (0 != getsockopt (sock->sock, SOL_SOCKET, SO_ERROR, &error, &len)) ||
493 (error != 0) || (errno != 0))
496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
497 "Failed to establish TCP connection to `%s'\n",
498 GNUNET_a2s(sock->addr, sock->addrlen));
500 /* connect failed / timed out */
501 GNUNET_break (0 == CLOSE (sock->sock));
503 if (GNUNET_SYSERR == try_connect (sock))
505 /* failed for good */
507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
508 "Failed to establish TCP connection, no further addresses to try.\n");
510 /* connect failed / timed out */
511 GNUNET_break (sock->ai_pos == NULL);
512 freeaddrinfo (sock->ai);
516 sock->connect_task = GNUNET_SCHEDULER_add_write (tc->sched, GNUNET_NO, /* abort on shutdown */
517 GNUNET_SCHEDULER_PRIORITY_KEEP,
518 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
519 GNUNET_NETWORK_CONNECT_RETRY_TIMEOUT,
521 &connect_continuation,
525 /* connect succeeded! clean up "ai" */
527 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
528 "Connection to `%s' succeeded!\n",
529 GNUNET_a2s(sock->addr, sock->addrlen));
531 freeaddrinfo (sock->ai);
538 * Create a socket handle by (asynchronously) connecting to a host.
539 * This function returns immediately, even if the connection has not
540 * yet been established. This function only creates TCP connections.
542 * @param sched scheduler to use
543 * @param hostname name of the host to connect to
544 * @param port port to connect to
545 * @param maxbuf maximum write buffer size for the socket (use
546 * 0 for sockets that need no write buffers, such as listen sockets)
547 * @return the socket handle
549 struct GNUNET_NETWORK_SocketHandle *
550 GNUNET_NETWORK_socket_create_from_connect (struct GNUNET_SCHEDULER_Handle
551 *sched, const char *hostname,
552 uint16_t port, size_t maxbuf)
554 struct GNUNET_NETWORK_SocketHandle *ret;
555 struct addrinfo hints;
558 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_SocketHandle) + maxbuf);
561 ret->write_buffer = (char *) &ret[1];
562 ret->write_buffer_size = maxbuf;
564 memset (&hints, 0, sizeof (hints));
565 hints.ai_family = AF_UNSPEC;
566 hints.ai_socktype = SOCK_STREAM;
567 if (0 != (ec = getaddrinfo (hostname, NULL, &hints, &ret->ai)))
569 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
570 "`%s' failed for hostname `%s': %s\n",
571 "getaddrinfo", hostname, gai_strerror (ec));
575 ret->ai_pos = ret->ai;
576 if (GNUNET_SYSERR == try_connect (ret))
578 freeaddrinfo (ret->ai);
582 ret->connect_task = GNUNET_SCHEDULER_add_write (sched, GNUNET_NO, /* abort on shutdown */
583 GNUNET_SCHEDULER_PRIORITY_KEEP,
584 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
585 GNUNET_NETWORK_CONNECT_RETRY_TIMEOUT,
587 &connect_continuation, ret);
594 * Create a socket handle by (asynchronously) connecting to a host.
595 * This function returns immediately, even if the connection has not
596 * yet been established. This function only creates TCP connections.
598 * @param sched scheduler to use
599 * @param af_family address family to use
600 * @param serv_addr server address
601 * @param addrlen length of server address
602 * @param maxbuf maximum write buffer size for the socket (use
603 * 0 for sockets that need no write buffers, such as listen sockets)
604 * @return the socket handle
606 struct GNUNET_NETWORK_SocketHandle *
607 GNUNET_NETWORK_socket_create_from_sockaddr (struct GNUNET_SCHEDULER_Handle
608 *sched, int af_family,
609 const struct sockaddr *serv_addr,
610 socklen_t addrlen, size_t maxbuf)
613 struct GNUNET_NETWORK_SocketHandle *ret;
615 s = SOCKET (af_family, SOCK_STREAM, 0);
618 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING |
619 GNUNET_ERROR_TYPE_BULK, "socket");
622 if (0 != fcntl (s, F_SETFD, fcntl (s, F_GETFD) | FD_CLOEXEC))
623 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
625 if (GNUNET_SYSERR == socket_set_blocking (s, GNUNET_NO))
627 /* we'll treat this one as fatal */
628 GNUNET_break (0 == CLOSE (s));
632 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
633 _("Trying to connect to `%s'\n"),
634 GNUNET_a2s(serv_addr, addrlen));
636 if ((0 != CONNECT (s, serv_addr, addrlen)) && (errno != EINPROGRESS))
638 /* maybe refused / unsupported address, try next */
639 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
640 GNUNET_break (0 == CLOSE (s));
643 ret = GNUNET_NETWORK_socket_create_from_existing (sched, s, maxbuf);
644 ret->addr = GNUNET_malloc (addrlen);
645 memcpy (ret->addr, serv_addr, addrlen);
646 ret->addrlen = addrlen;
652 * Check if socket is valid (no fatal errors have happened so far).
653 * Note that a socket that is still trying to connect is considered
656 * @param sock socket to check
657 * @return GNUNET_YES if valid, GNUNET_NO otherwise
660 GNUNET_NETWORK_socket_check (struct GNUNET_NETWORK_SocketHandle *sock)
662 if (sock->ai != NULL)
663 return GNUNET_YES; /* still trying to connect */
664 return (sock->sock == -1) ? GNUNET_NO : GNUNET_YES;
669 * Scheduler let us know that the connect task is finished (or was
670 * cancelled due to shutdown). Now really clean up.
673 destroy_continuation (void *cls,
674 const struct GNUNET_SCHEDULER_TaskContext *tc)
676 struct GNUNET_NETWORK_SocketHandle *sock = cls;
677 GNUNET_NETWORK_TransmitReadyNotify notify;
679 if (sock->write_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
681 GNUNET_SCHEDULER_add_after (sock->sched,
683 GNUNET_SCHEDULER_PRIORITY_KEEP,
685 &destroy_continuation, sock);
688 if (sock->sock != -1)
691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutting down socket.\n");
693 SHUTDOWN (sock->sock, SHUT_RDWR);
695 if (sock->read_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
697 GNUNET_SCHEDULER_add_after (sock->sched,
699 GNUNET_SCHEDULER_PRIORITY_KEEP,
701 &destroy_continuation, sock);
704 if (NULL != (notify = sock->nth.notify_ready))
706 sock->nth.notify_ready = NULL;
707 notify (sock->nth.notify_ready_cls, 0, NULL);
708 if (sock->nth.timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
710 GNUNET_SCHEDULER_cancel (sock->sched, sock->nth.timeout_task);
711 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
714 if (sock->sock != -1)
715 GNUNET_break (0 == CLOSE (sock->sock));
716 GNUNET_free_non_null (sock->addr);
717 if (sock->ai != NULL)
718 freeaddrinfo (sock->ai);
724 * Close the socket and free associated resources. Pending
725 * transmissions are simply dropped. A pending receive call will be
726 * called with an error code of "EPIPE".
728 * @param sock socket to destroy
731 GNUNET_NETWORK_socket_destroy (struct GNUNET_NETWORK_SocketHandle *sock)
733 if (sock->write_buffer_off == 0)
734 sock->ai_pos = NULL; /* if we're still trying to connect and have
735 no message pending, stop trying! */
736 GNUNET_assert (sock->sched != NULL);
737 GNUNET_SCHEDULER_add_after (sock->sched,
739 GNUNET_SCHEDULER_PRIORITY_KEEP,
741 &destroy_continuation, sock);
745 * Tell the receiver callback that a timeout was reached.
748 signal_timeout (struct GNUNET_NETWORK_SocketHandle *sh)
750 GNUNET_NETWORK_Receiver receiver;
753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
754 "Network signals time out to receiver!\n");
756 GNUNET_assert (NULL != (receiver = sh->receiver));
758 receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
763 * Tell the receiver callback that we had an IO error.
766 signal_error (struct GNUNET_NETWORK_SocketHandle *sh, int errcode)
768 GNUNET_NETWORK_Receiver receiver;
769 GNUNET_assert (NULL != (receiver = sh->receiver));
771 receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
776 * This function is called once we either timeout
777 * or have data ready to read.
780 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
782 struct GNUNET_NETWORK_SocketHandle *sh = cls;
783 struct GNUNET_TIME_Absolute now;
784 char buffer[sh->max];
786 GNUNET_NETWORK_Receiver receiver;
788 sh->read_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
789 now = GNUNET_TIME_absolute_get ();
790 if ((now.value > sh->receive_timeout.value) ||
791 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
792 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
796 "Receive encounters error: time out...\n");
803 /* connect failed for good */
805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
806 "Receive encounters error, socket closed...\n");
808 signal_error (sh, ECONNREFUSED);
811 GNUNET_assert (FD_ISSET (sh->sock, tc->read_ready));
813 ret = RECV (sh->sock, buffer, sh->max, MSG_DONTWAIT);
819 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
820 "Error receiving: %s\n", STRERROR (errno));
822 signal_error (sh, errno);
826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
827 "receive_ready read %u/%u bytes from `%s'!\n",
830 GNUNET_a2s(sh->addr, sh->addrlen));
832 GNUNET_assert (NULL != (receiver = sh->receiver));
834 receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
839 * This function is called after establishing a connection either has
840 * succeeded or timed out. Note that it is possible that the attempt
841 * timed out and that we're immediately retrying. If we are retrying,
842 * we need to wait again (or timeout); if we succeeded, we need to
843 * wait for data (or timeout).
846 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
848 struct GNUNET_NETWORK_SocketHandle *sh = cls;
849 struct GNUNET_TIME_Absolute now;
851 sh->read_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
852 if ((sh->sock == -1) &&
853 (sh->connect_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK))
855 /* not connected and no longer trying */
857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
858 "Receive encounters error, socket closed...\n");
860 signal_error (sh, ECONNREFUSED);
863 now = GNUNET_TIME_absolute_get ();
864 if ((now.value > sh->receive_timeout.value) ||
865 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
869 "Receive encounters error: time out...\n");
874 if (sh->connect_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
876 /* connect was retried */
877 sh->read_task = GNUNET_SCHEDULER_add_after (tc->sched,
879 GNUNET_SCHEDULER_PRIORITY_KEEP,
884 /* connect succeeded, wait for data! */
885 sh->read_task = GNUNET_SCHEDULER_add_read (tc->sched,
887 GNUNET_SCHEDULER_PRIORITY_KEEP,
889 GNUNET_TIME_absolute_get_remaining
890 (sh->receive_timeout),
891 sh->sock, &receive_ready,
897 * Receive data from the given socket. Note that this function will
898 * call "receiver" asynchronously using the scheduler. It will
899 * "immediately" return. Note that there MUST only be one active
900 * receive call per socket at any given point in time (so do not
901 * call receive again until the receiver callback has been invoked).
903 * @param sched scheduler to use
904 * @param sock socket handle
905 * @param max maximum number of bytes to read
906 * @param timeout maximum amount of time to wait (use -1 for "forever")
907 * @param receiver function to call with received data
908 * @param receiver_cls closure for receiver
909 * @return scheduler task ID used for receiving, GNUNET_SCHEDULER_NO_PREREQUISITE_TASK on error
911 GNUNET_SCHEDULER_TaskIdentifier
912 GNUNET_NETWORK_receive (struct GNUNET_NETWORK_SocketHandle *sock,
914 struct GNUNET_TIME_Relative timeout,
915 GNUNET_NETWORK_Receiver receiver, void *receiver_cls)
917 struct GNUNET_SCHEDULER_TaskContext tc;
919 GNUNET_assert ((sock->read_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK) &&
920 (sock->receiver == NULL));
921 sock->receiver = receiver;
922 sock->receiver_cls = receiver_cls;
923 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
925 memset (&tc, 0, sizeof (tc));
926 tc.sched = sock->sched;
927 tc.reason = GNUNET_SCHEDULER_REASON_PREREQ_DONE;
928 receive_again (sock, &tc);
929 return sock->read_task;
934 * Cancel receive job on the given socket. Note that the
935 * receiver callback must not have been called yet in order
936 * for the cancellation to be valid.
938 * @param sock socket handle
939 * @param task task identifier returned from the receive call
940 * @return closure of the original receiver callback
943 GNUNET_NETWORK_receive_cancel (struct GNUNET_NETWORK_SocketHandle *sock,
944 GNUNET_SCHEDULER_TaskIdentifier task)
946 GNUNET_assert (sock->read_task == task);
947 GNUNET_assert (sock == GNUNET_SCHEDULER_cancel (sock->sched, task));
948 sock->read_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
949 sock->receiver = NULL;
950 return sock->receiver_cls;
955 * Try to call the transmit notify method (check if we do
956 * have enough space available first)!
958 * @param sock socket for which we should do this processing
959 * @return GNUNET_YES if we were able to call notify
962 process_notify (struct GNUNET_NETWORK_SocketHandle *sock)
967 GNUNET_NETWORK_TransmitReadyNotify notify;
969 GNUNET_assert (sock->write_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
970 if (NULL == (notify = sock->nth.notify_ready))
972 used = sock->write_buffer_off - sock->write_buffer_pos;
973 avail = sock->write_buffer_size - used;
974 size = sock->nth.notify_size;
975 if (sock->nth.notify_size > avail)
977 sock->nth.notify_ready = NULL;
978 if (sock->nth.timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
980 GNUNET_SCHEDULER_cancel (sock->sched, sock->nth.timeout_task);
981 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
983 if (sock->write_buffer_size - sock->write_buffer_off < size)
985 /* need to compact */
986 memmove (sock->write_buffer,
987 &sock->write_buffer[sock->write_buffer_pos], used);
988 sock->write_buffer_off -= sock->write_buffer_pos;
989 sock->write_buffer_pos = 0;
991 GNUNET_assert (sock->write_buffer_size - sock->write_buffer_off >= size);
992 size = notify (sock->nth.notify_ready_cls,
993 sock->write_buffer_size - sock->write_buffer_off,
994 &sock->write_buffer[sock->write_buffer_off]);
995 sock->write_buffer_off += size;
1001 * Task invoked by the scheduler when a call to transmit
1002 * is timing out (we never got enough buffer space to call
1003 * the callback function before the specified timeout
1006 * This task notifies the client about the timeout.
1009 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1011 struct GNUNET_NETWORK_SocketHandle *sock = cls;
1012 GNUNET_NETWORK_TransmitReadyNotify notify;
1015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmit fails, time out reached.\n");
1017 notify = sock->nth.notify_ready;
1018 sock->nth.notify_ready = NULL;
1019 notify (sock->nth.notify_ready_cls, 0, NULL);
1024 transmit_error (struct GNUNET_NETWORK_SocketHandle *sock)
1026 if (sock->nth.notify_ready == NULL)
1027 return; /* nobody to tell about it */
1028 if (sock->nth.timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1030 GNUNET_SCHEDULER_cancel (sock->sched, sock->nth.timeout_task);
1031 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1033 transmit_timeout (sock, NULL);
1038 * See if we are now connected. If not, wait longer for
1039 * connect to succeed. If connected, we should be able
1040 * to write now as well, unless we timed out.
1043 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1045 struct GNUNET_NETWORK_SocketHandle *sock = cls;
1049 GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1050 sock->write_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1051 if (sock->connect_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1053 /* still waiting for connect */
1054 GNUNET_assert (sock->write_task ==
1055 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1057 GNUNET_SCHEDULER_add_delayed (tc->sched, GNUNET_NO,
1058 GNUNET_SCHEDULER_PRIORITY_KEEP,
1060 GNUNET_TIME_UNIT_ZERO, &transmit_ready,
1064 if (sock->sock == -1)
1067 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1068 _("Could not satisfy pending transmission request, socket closed or connect failed.\n"));
1070 transmit_error (sock);
1071 return; /* connect failed for good, we're finished */
1073 if ((tc->write_ready == NULL) || (!FD_ISSET (sock->sock, tc->write_ready)))
1075 /* special circumstances: not yet ready to write */
1076 goto SCHEDULE_WRITE;
1078 GNUNET_assert (sock->write_buffer_off >= sock->write_buffer_pos);
1079 process_notify (sock);
1080 have = sock->write_buffer_off - sock->write_buffer_pos;
1083 /* no data ready for writing, terminate write loop */
1087 ret = SEND (sock->sock,
1088 &sock->write_buffer[sock->write_buffer_pos],
1089 have, MSG_DONTWAIT | MSG_NOSIGNAL);
1095 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send");
1097 SHUTDOWN (sock->sock, SHUT_RDWR);
1098 GNUNET_break (0 == CLOSE (sock->sock));
1100 transmit_error (sock);
1104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1105 "transmit_ready transmitted %u/%u bytes to `%s'\n",
1108 GNUNET_a2s(sock->addr, sock->addrlen));
1110 sock->write_buffer_pos += ret;
1111 if (sock->write_buffer_pos == sock->write_buffer_off)
1113 /* transmitted all pending data */
1114 sock->write_buffer_pos = 0;
1115 sock->write_buffer_off = 0;
1117 if ((sock->write_buffer_off == 0) && (NULL == sock->nth.notify_ready))
1118 return; /* all data sent! */
1119 /* not done writing, schedule more */
1121 if (sock->write_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1123 GNUNET_SCHEDULER_add_write (tc->sched,
1125 GNUNET_SCHEDULER_PRIORITY_KEEP,
1126 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1127 GNUNET_TIME_UNIT_FOREVER_REL,
1128 sock->sock, &transmit_ready, sock);
1133 * Ask the socket to call us once the specified number of bytes
1134 * are free in the transmission buffer. May call the notify
1135 * method immediately if enough space is available.
1137 * @param sock socket
1138 * @param size number of bytes to send
1139 * @param timeout after how long should we give up (and call
1140 * notify with buf NULL and size 0)?
1141 * @param notify function to call
1142 * @param notify_cls closure for notify
1143 * @return non-NULL if the notify callback was queued,
1144 * NULL if we are already going to notify someone else (busy)
1146 struct GNUNET_NETWORK_TransmitHandle *
1147 GNUNET_NETWORK_notify_transmit_ready (struct GNUNET_NETWORK_SocketHandle
1149 struct GNUNET_TIME_Relative timeout,
1150 GNUNET_NETWORK_TransmitReadyNotify
1151 notify, void *notify_cls)
1153 if (sock->nth.notify_ready != NULL)
1155 GNUNET_assert (notify != NULL);
1156 GNUNET_assert (sock->write_buffer_size >= size);
1158 if ((sock->sock == -1) &&
1159 (sock->connect_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK))
1162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1163 "Transmission request fails, connection failed.\n");
1165 notify (notify_cls, 0, NULL);
1168 GNUNET_assert (sock->write_buffer_off <= sock->write_buffer_size);
1169 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1170 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_off);
1171 sock->nth.notify_ready = notify;
1172 sock->nth.notify_ready_cls = notify_cls;
1173 sock->nth.sh = sock;
1174 sock->nth.notify_size = size;
1175 sock->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1176 sock->nth.timeout_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1178 GNUNET_SCHEDULER_PRIORITY_KEEP,
1179 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1183 if (sock->write_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1184 sock->write_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1186 GNUNET_SCHEDULER_PRIORITY_KEEP,
1188 GNUNET_TIME_UNIT_ZERO,
1189 &transmit_ready, sock);
1195 * Cancel the specified transmission-ready
1199 GNUNET_NETWORK_notify_transmit_ready_cancel (struct
1200 GNUNET_NETWORK_TransmitHandle *h)
1202 GNUNET_assert (h->notify_ready != NULL);
1203 GNUNET_SCHEDULER_cancel (h->sh->sched, h->timeout_task);
1204 h->timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1205 h->notify_ready = NULL;
1209 #if 0 /* keep Emacsens' auto-indent happy */