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_YES
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));
296 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
297 _("Accepting connection from `%s'\n"),
298 GNUNET_a2s(uaddr, addrlen));
299 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_SocketHandle) + maxbuf);
300 ret->write_buffer = (char *) &ret[1];
301 ret->write_buffer_size = maxbuf;
303 ret->addrlen = addrlen;
310 * Obtain the network address of the other party.
312 * @param sock the client to get the address for
313 * @param addr where to store the address
314 * @param addrlen where to store the length of the address
315 * @return GNUNET_OK on success
318 GNUNET_NETWORK_socket_get_address (struct GNUNET_NETWORK_SocketHandle *sock,
319 void **addr, size_t * addrlen)
321 if ((sock->addr == NULL) || (sock->addrlen == 0))
323 *addr = GNUNET_malloc (sock->addrlen);
324 memcpy (*addr, sock->addr, sock->addrlen);
325 *addrlen = sock->addrlen;
331 * Set if a socket should use blocking or non-blocking IO.
333 * @return GNUNET_OK on success, GNUNET_SYSERR on error
336 socket_set_blocking (int handle, int doBlock)
342 if (ioctlsocket (plibc_fd_get_handle (handle), FIONBIO, &mode) ==
345 SetErrnoFromWinsockError (WSAGetLastError ());
346 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "ioctlsocket");
347 return GNUNET_SYSERR;
350 if (ioctlsocket (handle, FIONBIO, &mode) == SOCKET_ERROR)
352 SetErrnoFromWinsockError (WSAGetLastError ());
353 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "ioctlsocket");
354 return GNUNET_SYSERR;
357 /* store the blocking mode */
359 plibc_fd_set_blocking (handle, doBlock);
361 __win_SetHandleBlockingMode (handle, doBlock);
367 int flags = fcntl (handle, F_GETFL);
370 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fcntl");
371 return GNUNET_SYSERR;
374 flags &= ~O_NONBLOCK;
377 if (0 != fcntl (handle, F_SETFL, flags))
379 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fcntl");
380 return GNUNET_SYSERR;
388 * Initiate asynchronous TCP connect request.
390 * @param sock what socket to connect
391 * @return GNUNET_SYSERR error (no more addresses to try)
394 try_connect (struct GNUNET_NETWORK_SocketHandle *sock)
398 if (sock->addr != NULL)
400 GNUNET_free (sock->addr);
406 if (sock->ai_pos == NULL)
408 /* no more addresses to try, fatal! */
409 return GNUNET_SYSERR;
411 switch (sock->ai_pos->ai_family)
414 ((struct sockaddr_in *) sock->ai_pos->ai_addr)->sin_port =
418 ((struct sockaddr_in6 *) sock->ai_pos->ai_addr)->sin6_port =
422 sock->ai_pos = sock->ai_pos->ai_next;
425 s = SOCKET (sock->ai_pos->ai_family, SOCK_STREAM, 0);
428 /* maybe unsupported address family, try next */
429 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "socket");
430 sock->ai_pos = sock->ai_pos->ai_next;
433 if (0 != fcntl (s, F_SETFD, fcntl (s, F_GETFD) | FD_CLOEXEC))
434 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
436 if (GNUNET_SYSERR == socket_set_blocking (s, GNUNET_NO))
438 /* we'll treat this one as fatal */
439 GNUNET_break (0 == CLOSE (s));
440 return GNUNET_SYSERR;
442 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
443 _("Trying to connect to `%s'\n"),
444 GNUNET_a2s(sock->ai_pos->ai_addr,
445 sock->ai_pos->ai_addrlen));
446 if ((0 != CONNECT (s,
447 sock->ai_pos->ai_addr,
448 sock->ai_pos->ai_addrlen)) && (errno != EINPROGRESS))
450 /* maybe refused / unsupported address, try next */
451 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
452 GNUNET_break (0 == CLOSE (s));
457 /* got one! copy address information! */
458 sock->addrlen = sock->ai_pos->ai_addrlen;
459 sock->addr = GNUNET_malloc (sock->addrlen);
460 memcpy (sock->addr, sock->ai_pos->ai_addr, sock->addrlen);
461 sock->ai_pos = sock->ai_pos->ai_next;
468 * Scheduler let us know that we're either ready to
469 * write on the socket OR connect timed out. Do the
473 connect_continuation (void *cls,
474 const struct GNUNET_SCHEDULER_TaskContext *tc)
476 struct GNUNET_NETWORK_SocketHandle *sock = cls;
480 /* nobody needs to wait for us anymore... */
481 sock->connect_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
482 /* Note: write-ready does NOT mean connect succeeded,
483 we need to use getsockopt to be sure */
484 len = sizeof (error);
487 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
488 (0 != getsockopt (sock->sock, SOL_SOCKET, SO_ERROR, &error, &len)) ||
489 (error != 0) || (errno != 0))
492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
493 "Failed to establish TCP connection to `%s'\n",
494 GNUNET_a2s(sock->addr, sock->addrlen));
496 /* connect failed / timed out */
497 GNUNET_break (0 == CLOSE (sock->sock));
499 if (GNUNET_SYSERR == try_connect (sock))
501 /* failed for good */
503 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
504 "Failed to establish TCP connection, no further addresses to try.\n");
506 /* connect failed / timed out */
507 GNUNET_break (sock->ai_pos == NULL);
508 freeaddrinfo (sock->ai);
512 sock->connect_task = GNUNET_SCHEDULER_add_write (tc->sched, GNUNET_NO, /* abort on shutdown */
513 GNUNET_SCHEDULER_PRIORITY_KEEP,
514 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
515 GNUNET_NETWORK_CONNECT_RETRY_TIMEOUT,
517 &connect_continuation,
521 /* connect succeeded! clean up "ai" */
523 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
524 "Connection to `%s' succeeded!\n",
525 GNUNET_a2s(sock->addr, sock->addrlen));
527 freeaddrinfo (sock->ai);
534 * Create a socket handle by (asynchronously) connecting to a host.
535 * This function returns immediately, even if the connection has not
536 * yet been established. This function only creates TCP connections.
538 * @param sched scheduler to use
539 * @param hostname name of the host to connect to
540 * @param port port to connect to
541 * @param maxbuf maximum write buffer size for the socket (use
542 * 0 for sockets that need no write buffers, such as listen sockets)
543 * @return the socket handle
545 struct GNUNET_NETWORK_SocketHandle *
546 GNUNET_NETWORK_socket_create_from_connect (struct GNUNET_SCHEDULER_Handle
547 *sched, const char *hostname,
548 uint16_t port, size_t maxbuf)
550 struct GNUNET_NETWORK_SocketHandle *ret;
551 struct addrinfo hints;
554 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_SocketHandle) + maxbuf);
557 ret->write_buffer = (char *) &ret[1];
558 ret->write_buffer_size = maxbuf;
560 memset (&hints, 0, sizeof (hints));
561 hints.ai_family = AF_UNSPEC;
562 hints.ai_socktype = SOCK_STREAM;
563 if (0 != (ec = getaddrinfo (hostname, NULL, &hints, &ret->ai)))
565 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
566 "`%s' failed for hostname `%s': %s\n",
567 "getaddrinfo", hostname, gai_strerror (ec));
571 ret->ai_pos = ret->ai;
572 if (GNUNET_SYSERR == try_connect (ret))
574 freeaddrinfo (ret->ai);
578 ret->connect_task = GNUNET_SCHEDULER_add_write (sched, GNUNET_NO, /* abort on shutdown */
579 GNUNET_SCHEDULER_PRIORITY_KEEP,
580 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
581 GNUNET_NETWORK_CONNECT_RETRY_TIMEOUT,
583 &connect_continuation, ret);
590 * Create a socket handle by (asynchronously) connecting to a host.
591 * This function returns immediately, even if the connection has not
592 * yet been established. This function only creates TCP connections.
594 * @param sched scheduler to use
595 * @param af_family address family to use
596 * @param serv_addr server address
597 * @param addrlen length of server address
598 * @param maxbuf maximum write buffer size for the socket (use
599 * 0 for sockets that need no write buffers, such as listen sockets)
600 * @return the socket handle
602 struct GNUNET_NETWORK_SocketHandle *
603 GNUNET_NETWORK_socket_create_from_sockaddr (struct GNUNET_SCHEDULER_Handle
604 *sched, int af_family,
605 const struct sockaddr *serv_addr,
606 socklen_t addrlen, size_t maxbuf)
610 s = SOCKET (af_family, SOCK_STREAM, 0);
613 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING |
614 GNUNET_ERROR_TYPE_BULK, "socket");
617 if (0 != fcntl (s, F_SETFD, fcntl (s, F_GETFD) | FD_CLOEXEC))
618 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
620 if (GNUNET_SYSERR == socket_set_blocking (s, GNUNET_NO))
622 /* we'll treat this one as fatal */
623 GNUNET_break (0 == CLOSE (s));
626 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
627 _("Trying to connect to `%s'\n"),
628 GNUNET_a2s(serv_addr, addrlen));
629 if ((0 != CONNECT (s, serv_addr, addrlen)) && (errno != EINPROGRESS))
631 /* maybe refused / unsupported address, try next */
632 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
633 GNUNET_break (0 == CLOSE (s));
636 return GNUNET_NETWORK_socket_create_from_existing (sched, s, maxbuf);
641 * Check if socket is valid (no fatal errors have happened so far).
642 * Note that a socket that is still trying to connect is considered
645 * @param sock socket to check
646 * @return GNUNET_YES if valid, GNUNET_NO otherwise
649 GNUNET_NETWORK_socket_check (struct GNUNET_NETWORK_SocketHandle *sock)
651 if (sock->ai != NULL)
652 return GNUNET_YES; /* still trying to connect */
653 return (sock->sock == -1) ? GNUNET_NO : GNUNET_YES;
658 * Scheduler let us know that the connect task is finished (or was
659 * cancelled due to shutdown). Now really clean up.
662 destroy_continuation (void *cls,
663 const struct GNUNET_SCHEDULER_TaskContext *tc)
665 struct GNUNET_NETWORK_SocketHandle *sock = cls;
666 GNUNET_NETWORK_TransmitReadyNotify notify;
668 if (sock->write_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
670 GNUNET_SCHEDULER_add_after (sock->sched,
672 GNUNET_SCHEDULER_PRIORITY_KEEP,
674 &destroy_continuation, sock);
677 if (sock->sock != -1)
680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutting down socket.\n");
682 SHUTDOWN (sock->sock, SHUT_RDWR);
684 if (sock->read_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
686 GNUNET_SCHEDULER_add_after (sock->sched,
688 GNUNET_SCHEDULER_PRIORITY_KEEP,
690 &destroy_continuation, sock);
693 if (NULL != (notify = sock->nth.notify_ready))
695 sock->nth.notify_ready = NULL;
696 notify (sock->nth.notify_ready_cls, 0, NULL);
697 if (sock->nth.timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
699 GNUNET_SCHEDULER_cancel (sock->sched, sock->nth.timeout_task);
700 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
703 if (sock->sock != -1)
704 GNUNET_break (0 == CLOSE (sock->sock));
705 GNUNET_free_non_null (sock->addr);
706 if (sock->ai != NULL)
707 freeaddrinfo (sock->ai);
713 * Close the socket and free associated resources. Pending
714 * transmissions are simply dropped. A pending receive call will be
715 * called with an error code of "EPIPE".
717 * @param sock socket to destroy
720 GNUNET_NETWORK_socket_destroy (struct GNUNET_NETWORK_SocketHandle *sock)
722 if (sock->write_buffer_off == 0)
723 sock->ai_pos = NULL; /* if we're still trying to connect and have
724 no message pending, stop trying! */
725 GNUNET_assert (sock->sched != NULL);
726 GNUNET_SCHEDULER_add_after (sock->sched,
728 GNUNET_SCHEDULER_PRIORITY_KEEP,
730 &destroy_continuation, sock);
734 * Tell the receiver callback that a timeout was reached.
737 signal_timeout (struct GNUNET_NETWORK_SocketHandle *sh)
739 GNUNET_NETWORK_Receiver receiver;
742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
743 "Network signals time out to receiver!\n");
745 GNUNET_assert (NULL != (receiver = sh->receiver));
747 receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
752 * Tell the receiver callback that we had an IO error.
755 signal_error (struct GNUNET_NETWORK_SocketHandle *sh, int errcode)
757 GNUNET_NETWORK_Receiver receiver;
758 GNUNET_assert (NULL != (receiver = sh->receiver));
760 receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
765 * This function is called once we either timeout
766 * or have data ready to read.
769 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
771 struct GNUNET_NETWORK_SocketHandle *sh = cls;
772 struct GNUNET_TIME_Absolute now;
773 char buffer[sh->max];
775 GNUNET_NETWORK_Receiver receiver;
777 sh->read_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
778 now = GNUNET_TIME_absolute_get ();
779 if ((now.value > sh->receive_timeout.value) ||
780 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
781 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
785 "Receive encounters error: time out...\n");
792 /* connect failed for good */
794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
795 "Receive encounters error, socket closed...\n");
797 signal_error (sh, ECONNREFUSED);
800 GNUNET_assert (FD_ISSET (sh->sock, tc->read_ready));
802 ret = RECV (sh->sock, buffer, sh->max, MSG_DONTWAIT);
808 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
809 "Error receiving: %s\n", STRERROR (errno));
811 signal_error (sh, errno);
815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
816 "receive_ready read %u/%u bytes from `%s'!\n",
819 GNUNET_a2s(sh->addr, sh->addrlen));
821 GNUNET_assert (NULL != (receiver = sh->receiver));
823 receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
828 * This function is called after establishing a connection either has
829 * succeeded or timed out. Note that it is possible that the attempt
830 * timed out and that we're immediately retrying. If we are retrying,
831 * we need to wait again (or timeout); if we succeeded, we need to
832 * wait for data (or timeout).
835 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
837 struct GNUNET_NETWORK_SocketHandle *sh = cls;
838 struct GNUNET_TIME_Absolute now;
840 sh->read_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
841 if ((sh->sock == -1) &&
842 (sh->connect_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK))
844 /* not connected and no longer trying */
846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847 "Receive encounters error, socket closed...\n");
849 signal_error (sh, ECONNREFUSED);
852 now = GNUNET_TIME_absolute_get ();
853 if ((now.value > sh->receive_timeout.value) ||
854 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
858 "Receive encounters error: time out...\n");
863 if (sh->connect_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
865 /* connect was retried */
866 sh->read_task = GNUNET_SCHEDULER_add_after (tc->sched,
868 GNUNET_SCHEDULER_PRIORITY_KEEP,
873 /* connect succeeded, wait for data! */
874 sh->read_task = GNUNET_SCHEDULER_add_read (tc->sched,
876 GNUNET_SCHEDULER_PRIORITY_KEEP,
878 GNUNET_TIME_absolute_get_remaining
879 (sh->receive_timeout),
880 sh->sock, &receive_ready,
886 * Receive data from the given socket. Note that this function will
887 * call "receiver" asynchronously using the scheduler. It will
888 * "immediately" return. Note that there MUST only be one active
889 * receive call per socket at any given point in time (so do not
890 * call receive again until the receiver callback has been invoked).
892 * @param sched scheduler to use
893 * @param sock socket handle
894 * @param max maximum number of bytes to read
895 * @param timeout maximum amount of time to wait (use -1 for "forever")
896 * @param receiver function to call with received data
897 * @param receiver_cls closure for receiver
898 * @return scheduler task ID used for receiving, GNUNET_SCHEDULER_NO_PREREQUISITE_TASK on error
900 GNUNET_SCHEDULER_TaskIdentifier
901 GNUNET_NETWORK_receive (struct GNUNET_NETWORK_SocketHandle *sock,
903 struct GNUNET_TIME_Relative timeout,
904 GNUNET_NETWORK_Receiver receiver, void *receiver_cls)
906 struct GNUNET_SCHEDULER_TaskContext tc;
908 GNUNET_assert ((sock->read_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK) &&
909 (sock->receiver == NULL));
910 sock->receiver = receiver;
911 sock->receiver_cls = receiver_cls;
912 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
914 memset (&tc, 0, sizeof (tc));
915 tc.sched = sock->sched;
916 tc.reason = GNUNET_SCHEDULER_REASON_PREREQ_DONE;
917 receive_again (sock, &tc);
918 return sock->read_task;
923 * Cancel receive job on the given socket. Note that the
924 * receiver callback must not have been called yet in order
925 * for the cancellation to be valid.
927 * @param sock socket handle
928 * @param task task identifier returned from the receive call
929 * @return closure of the original receiver callback
932 GNUNET_NETWORK_receive_cancel (struct GNUNET_NETWORK_SocketHandle *sock,
933 GNUNET_SCHEDULER_TaskIdentifier task)
935 GNUNET_assert (sock->read_task == task);
936 GNUNET_assert (sock == GNUNET_SCHEDULER_cancel (sock->sched, task));
937 sock->read_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
938 sock->receiver = NULL;
939 return sock->receiver_cls;
944 * Try to call the transmit notify method (check if we do
945 * have enough space available first)!
947 * @param sock socket for which we should do this processing
948 * @return GNUNET_YES if we were able to call notify
951 process_notify (struct GNUNET_NETWORK_SocketHandle *sock)
956 GNUNET_NETWORK_TransmitReadyNotify notify;
958 GNUNET_assert (sock->write_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
959 if (NULL == (notify = sock->nth.notify_ready))
961 used = sock->write_buffer_off - sock->write_buffer_pos;
962 avail = sock->write_buffer_size - used;
963 size = sock->nth.notify_size;
964 if (sock->nth.notify_size > avail)
966 sock->nth.notify_ready = NULL;
967 if (sock->nth.timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
969 GNUNET_SCHEDULER_cancel (sock->sched, sock->nth.timeout_task);
970 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
972 if (sock->write_buffer_size - sock->write_buffer_off < size)
974 /* need to compact */
975 memmove (sock->write_buffer,
976 &sock->write_buffer[sock->write_buffer_pos], used);
977 sock->write_buffer_off -= sock->write_buffer_pos;
978 sock->write_buffer_pos = 0;
980 GNUNET_assert (sock->write_buffer_size - sock->write_buffer_off >= size);
981 size = notify (sock->nth.notify_ready_cls,
982 sock->write_buffer_size - sock->write_buffer_off,
983 &sock->write_buffer[sock->write_buffer_off]);
984 sock->write_buffer_off += size;
990 * Task invoked by the scheduler when a call to transmit
991 * is timing out (we never got enough buffer space to call
992 * the callback function before the specified timeout
995 * This task notifies the client about the timeout.
998 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1000 struct GNUNET_NETWORK_SocketHandle *sock = cls;
1001 GNUNET_NETWORK_TransmitReadyNotify notify;
1004 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmit fails, time out reached.\n");
1006 notify = sock->nth.notify_ready;
1007 sock->nth.notify_ready = NULL;
1008 notify (sock->nth.notify_ready_cls, 0, NULL);
1013 transmit_error (struct GNUNET_NETWORK_SocketHandle *sock)
1015 if (sock->nth.notify_ready == NULL)
1016 return; /* nobody to tell about it */
1017 if (sock->nth.timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1019 GNUNET_SCHEDULER_cancel (sock->sched, sock->nth.timeout_task);
1020 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1022 transmit_timeout (sock, NULL);
1027 * See if we are now connected. If not, wait longer for
1028 * connect to succeed. If connected, we should be able
1029 * to write now as well, unless we timed out.
1032 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1034 struct GNUNET_NETWORK_SocketHandle *sock = cls;
1038 GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1039 sock->write_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1040 if (sock->connect_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1042 /* still waiting for connect */
1043 GNUNET_assert (sock->write_task ==
1044 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1046 GNUNET_SCHEDULER_add_delayed (tc->sched, GNUNET_NO,
1047 GNUNET_SCHEDULER_PRIORITY_KEEP,
1049 GNUNET_TIME_UNIT_ZERO, &transmit_ready,
1053 if (sock->sock == -1)
1055 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1056 _("Could not satisfy pending transmission request, socket closed or connect failed.\n"));
1057 transmit_error (sock);
1058 return; /* connect failed for good, we're finished */
1060 if ((tc->write_ready == NULL) || (!FD_ISSET (sock->sock, tc->write_ready)))
1062 /* special circumstances: not yet ready to write */
1063 goto SCHEDULE_WRITE;
1065 GNUNET_assert (sock->write_buffer_off >= sock->write_buffer_pos);
1066 process_notify (sock);
1067 have = sock->write_buffer_off - sock->write_buffer_pos;
1070 /* no data ready for writing, terminate write loop */
1074 ret = SEND (sock->sock,
1075 &sock->write_buffer[sock->write_buffer_pos],
1076 have, MSG_DONTWAIT | MSG_NOSIGNAL);
1082 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send");
1084 SHUTDOWN (sock->sock, SHUT_RDWR);
1085 GNUNET_break (0 == CLOSE (sock->sock));
1087 transmit_error (sock);
1091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1092 "transmit_ready transmitted %u/%u bytes to `%s'\n",
1095 GNUNET_a2s(sock->addr, sock->addrlen));
1097 sock->write_buffer_pos += ret;
1098 if (sock->write_buffer_pos == sock->write_buffer_off)
1100 /* transmitted all pending data */
1101 sock->write_buffer_pos = 0;
1102 sock->write_buffer_off = 0;
1104 if ((sock->write_buffer_off == 0) && (NULL == sock->nth.notify_ready))
1105 return; /* all data sent! */
1106 /* not done writing, schedule more */
1108 if (sock->write_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1110 GNUNET_SCHEDULER_add_write (tc->sched,
1112 GNUNET_SCHEDULER_PRIORITY_KEEP,
1113 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1114 GNUNET_TIME_UNIT_FOREVER_REL,
1115 sock->sock, &transmit_ready, sock);
1120 * Ask the socket to call us once the specified number of bytes
1121 * are free in the transmission buffer. May call the notify
1122 * method immediately if enough space is available.
1124 * @param sock socket
1125 * @param size number of bytes to send
1126 * @param timeout after how long should we give up (and call
1127 * notify with buf NULL and size 0)?
1128 * @param notify function to call
1129 * @param notify_cls closure for notify
1130 * @return non-NULL if the notify callback was queued,
1131 * NULL if we are already going to notify someone else (busy)
1133 struct GNUNET_NETWORK_TransmitHandle *
1134 GNUNET_NETWORK_notify_transmit_ready (struct GNUNET_NETWORK_SocketHandle
1136 struct GNUNET_TIME_Relative timeout,
1137 GNUNET_NETWORK_TransmitReadyNotify
1138 notify, void *notify_cls)
1140 if (sock->nth.notify_ready != NULL)
1142 GNUNET_assert (notify != NULL);
1143 GNUNET_assert (sock->write_buffer_size >= size);
1145 if ((sock->sock == -1) &&
1146 (sock->connect_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK))
1149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1150 "Transmission request fails, connection failed.\n");
1152 notify (notify_cls, 0, NULL);
1155 GNUNET_assert (sock->write_buffer_off <= sock->write_buffer_size);
1156 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1157 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_off);
1158 sock->nth.notify_ready = notify;
1159 sock->nth.notify_ready_cls = notify_cls;
1160 sock->nth.sh = sock;
1161 sock->nth.notify_size = size;
1162 sock->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1163 sock->nth.timeout_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1165 GNUNET_SCHEDULER_PRIORITY_KEEP,
1166 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1170 if (sock->write_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1171 sock->write_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1173 GNUNET_SCHEDULER_PRIORITY_KEEP,
1175 GNUNET_TIME_UNIT_ZERO,
1176 &transmit_ready, sock);
1182 * Cancel the specified transmission-ready
1186 GNUNET_NETWORK_notify_transmit_ready_cancel (struct
1187 GNUNET_NETWORK_TransmitHandle *h)
1189 GNUNET_assert (h->notify_ready != NULL);
1190 GNUNET_SCHEDULER_cancel (h->sh->sched, h->timeout_task);
1191 h->timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1192 h->notify_ready = NULL;
1196 #if 0 /* keep Emacsens' auto-indent happy */