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));
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)
609 struct GNUNET_NETWORK_SocketHandle *ret;
611 s = SOCKET (af_family, SOCK_STREAM, 0);
614 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING |
615 GNUNET_ERROR_TYPE_BULK, "socket");
618 if (0 != fcntl (s, F_SETFD, fcntl (s, F_GETFD) | FD_CLOEXEC))
619 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
621 if (GNUNET_SYSERR == socket_set_blocking (s, GNUNET_NO))
623 /* we'll treat this one as fatal */
624 GNUNET_break (0 == CLOSE (s));
627 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
628 _("Trying to connect to `%s'\n"),
629 GNUNET_a2s(serv_addr, addrlen));
630 if ((0 != CONNECT (s, serv_addr, addrlen)) && (errno != EINPROGRESS))
632 /* maybe refused / unsupported address, try next */
633 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "connect");
634 GNUNET_break (0 == CLOSE (s));
637 ret = GNUNET_NETWORK_socket_create_from_existing (sched, s, maxbuf);
638 ret->addr = GNUNET_malloc (addrlen);
639 memcpy (ret->addr, serv_addr, addrlen);
640 ret->addrlen = addrlen;
646 * Check if socket is valid (no fatal errors have happened so far).
647 * Note that a socket that is still trying to connect is considered
650 * @param sock socket to check
651 * @return GNUNET_YES if valid, GNUNET_NO otherwise
654 GNUNET_NETWORK_socket_check (struct GNUNET_NETWORK_SocketHandle *sock)
656 if (sock->ai != NULL)
657 return GNUNET_YES; /* still trying to connect */
658 return (sock->sock == -1) ? GNUNET_NO : GNUNET_YES;
663 * Scheduler let us know that the connect task is finished (or was
664 * cancelled due to shutdown). Now really clean up.
667 destroy_continuation (void *cls,
668 const struct GNUNET_SCHEDULER_TaskContext *tc)
670 struct GNUNET_NETWORK_SocketHandle *sock = cls;
671 GNUNET_NETWORK_TransmitReadyNotify notify;
673 if (sock->write_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
675 GNUNET_SCHEDULER_add_after (sock->sched,
677 GNUNET_SCHEDULER_PRIORITY_KEEP,
679 &destroy_continuation, sock);
682 if (sock->sock != -1)
685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutting down socket.\n");
687 SHUTDOWN (sock->sock, SHUT_RDWR);
689 if (sock->read_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
691 GNUNET_SCHEDULER_add_after (sock->sched,
693 GNUNET_SCHEDULER_PRIORITY_KEEP,
695 &destroy_continuation, sock);
698 if (NULL != (notify = sock->nth.notify_ready))
700 sock->nth.notify_ready = NULL;
701 notify (sock->nth.notify_ready_cls, 0, NULL);
702 if (sock->nth.timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
704 GNUNET_SCHEDULER_cancel (sock->sched, sock->nth.timeout_task);
705 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
708 if (sock->sock != -1)
709 GNUNET_break (0 == CLOSE (sock->sock));
710 GNUNET_free_non_null (sock->addr);
711 if (sock->ai != NULL)
712 freeaddrinfo (sock->ai);
718 * Close the socket and free associated resources. Pending
719 * transmissions are simply dropped. A pending receive call will be
720 * called with an error code of "EPIPE".
722 * @param sock socket to destroy
725 GNUNET_NETWORK_socket_destroy (struct GNUNET_NETWORK_SocketHandle *sock)
727 if (sock->write_buffer_off == 0)
728 sock->ai_pos = NULL; /* if we're still trying to connect and have
729 no message pending, stop trying! */
730 GNUNET_assert (sock->sched != NULL);
731 GNUNET_SCHEDULER_add_after (sock->sched,
733 GNUNET_SCHEDULER_PRIORITY_KEEP,
735 &destroy_continuation, sock);
739 * Tell the receiver callback that a timeout was reached.
742 signal_timeout (struct GNUNET_NETWORK_SocketHandle *sh)
744 GNUNET_NETWORK_Receiver receiver;
747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
748 "Network signals time out to receiver!\n");
750 GNUNET_assert (NULL != (receiver = sh->receiver));
752 receiver (sh->receiver_cls, NULL, 0, NULL, 0, 0);
757 * Tell the receiver callback that we had an IO error.
760 signal_error (struct GNUNET_NETWORK_SocketHandle *sh, int errcode)
762 GNUNET_NETWORK_Receiver receiver;
763 GNUNET_assert (NULL != (receiver = sh->receiver));
765 receiver (sh->receiver_cls, NULL, 0, sh->addr, sh->addrlen, errcode);
770 * This function is called once we either timeout
771 * or have data ready to read.
774 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
776 struct GNUNET_NETWORK_SocketHandle *sh = cls;
777 struct GNUNET_TIME_Absolute now;
778 char buffer[sh->max];
780 GNUNET_NETWORK_Receiver receiver;
782 sh->read_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
783 now = GNUNET_TIME_absolute_get ();
784 if ((now.value > sh->receive_timeout.value) ||
785 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT)) ||
786 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
790 "Receive encounters error: time out...\n");
797 /* connect failed for good */
799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
800 "Receive encounters error, socket closed...\n");
802 signal_error (sh, ECONNREFUSED);
805 GNUNET_assert (FD_ISSET (sh->sock, tc->read_ready));
807 ret = RECV (sh->sock, buffer, sh->max, MSG_DONTWAIT);
813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
814 "Error receiving: %s\n", STRERROR (errno));
816 signal_error (sh, errno);
820 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
821 "receive_ready read %u/%u bytes from `%s'!\n",
824 GNUNET_a2s(sh->addr, sh->addrlen));
826 GNUNET_assert (NULL != (receiver = sh->receiver));
828 receiver (sh->receiver_cls, buffer, ret, sh->addr, sh->addrlen, 0);
833 * This function is called after establishing a connection either has
834 * succeeded or timed out. Note that it is possible that the attempt
835 * timed out and that we're immediately retrying. If we are retrying,
836 * we need to wait again (or timeout); if we succeeded, we need to
837 * wait for data (or timeout).
840 receive_again (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
842 struct GNUNET_NETWORK_SocketHandle *sh = cls;
843 struct GNUNET_TIME_Absolute now;
845 sh->read_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
846 if ((sh->sock == -1) &&
847 (sh->connect_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK))
849 /* not connected and no longer trying */
851 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
852 "Receive encounters error, socket closed...\n");
854 signal_error (sh, ECONNREFUSED);
857 now = GNUNET_TIME_absolute_get ();
858 if ((now.value > sh->receive_timeout.value) ||
859 (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)))
862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
863 "Receive encounters error: time out...\n");
868 if (sh->connect_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
870 /* connect was retried */
871 sh->read_task = GNUNET_SCHEDULER_add_after (tc->sched,
873 GNUNET_SCHEDULER_PRIORITY_KEEP,
878 /* connect succeeded, wait for data! */
879 sh->read_task = GNUNET_SCHEDULER_add_read (tc->sched,
881 GNUNET_SCHEDULER_PRIORITY_KEEP,
883 GNUNET_TIME_absolute_get_remaining
884 (sh->receive_timeout),
885 sh->sock, &receive_ready,
891 * Receive data from the given socket. Note that this function will
892 * call "receiver" asynchronously using the scheduler. It will
893 * "immediately" return. Note that there MUST only be one active
894 * receive call per socket at any given point in time (so do not
895 * call receive again until the receiver callback has been invoked).
897 * @param sched scheduler to use
898 * @param sock socket handle
899 * @param max maximum number of bytes to read
900 * @param timeout maximum amount of time to wait (use -1 for "forever")
901 * @param receiver function to call with received data
902 * @param receiver_cls closure for receiver
903 * @return scheduler task ID used for receiving, GNUNET_SCHEDULER_NO_PREREQUISITE_TASK on error
905 GNUNET_SCHEDULER_TaskIdentifier
906 GNUNET_NETWORK_receive (struct GNUNET_NETWORK_SocketHandle *sock,
908 struct GNUNET_TIME_Relative timeout,
909 GNUNET_NETWORK_Receiver receiver, void *receiver_cls)
911 struct GNUNET_SCHEDULER_TaskContext tc;
913 GNUNET_assert ((sock->read_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK) &&
914 (sock->receiver == NULL));
915 sock->receiver = receiver;
916 sock->receiver_cls = receiver_cls;
917 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
919 memset (&tc, 0, sizeof (tc));
920 tc.sched = sock->sched;
921 tc.reason = GNUNET_SCHEDULER_REASON_PREREQ_DONE;
922 receive_again (sock, &tc);
923 return sock->read_task;
928 * Cancel receive job on the given socket. Note that the
929 * receiver callback must not have been called yet in order
930 * for the cancellation to be valid.
932 * @param sock socket handle
933 * @param task task identifier returned from the receive call
934 * @return closure of the original receiver callback
937 GNUNET_NETWORK_receive_cancel (struct GNUNET_NETWORK_SocketHandle *sock,
938 GNUNET_SCHEDULER_TaskIdentifier task)
940 GNUNET_assert (sock->read_task == task);
941 GNUNET_assert (sock == GNUNET_SCHEDULER_cancel (sock->sched, task));
942 sock->read_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
943 sock->receiver = NULL;
944 return sock->receiver_cls;
949 * Try to call the transmit notify method (check if we do
950 * have enough space available first)!
952 * @param sock socket for which we should do this processing
953 * @return GNUNET_YES if we were able to call notify
956 process_notify (struct GNUNET_NETWORK_SocketHandle *sock)
961 GNUNET_NETWORK_TransmitReadyNotify notify;
963 GNUNET_assert (sock->write_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
964 if (NULL == (notify = sock->nth.notify_ready))
966 used = sock->write_buffer_off - sock->write_buffer_pos;
967 avail = sock->write_buffer_size - used;
968 size = sock->nth.notify_size;
969 if (sock->nth.notify_size > avail)
971 sock->nth.notify_ready = NULL;
972 if (sock->nth.timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
974 GNUNET_SCHEDULER_cancel (sock->sched, sock->nth.timeout_task);
975 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
977 if (sock->write_buffer_size - sock->write_buffer_off < size)
979 /* need to compact */
980 memmove (sock->write_buffer,
981 &sock->write_buffer[sock->write_buffer_pos], used);
982 sock->write_buffer_off -= sock->write_buffer_pos;
983 sock->write_buffer_pos = 0;
985 GNUNET_assert (sock->write_buffer_size - sock->write_buffer_off >= size);
986 size = notify (sock->nth.notify_ready_cls,
987 sock->write_buffer_size - sock->write_buffer_off,
988 &sock->write_buffer[sock->write_buffer_off]);
989 sock->write_buffer_off += size;
995 * Task invoked by the scheduler when a call to transmit
996 * is timing out (we never got enough buffer space to call
997 * the callback function before the specified timeout
1000 * This task notifies the client about the timeout.
1003 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1005 struct GNUNET_NETWORK_SocketHandle *sock = cls;
1006 GNUNET_NETWORK_TransmitReadyNotify notify;
1009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmit fails, time out reached.\n");
1011 notify = sock->nth.notify_ready;
1012 sock->nth.notify_ready = NULL;
1013 notify (sock->nth.notify_ready_cls, 0, NULL);
1018 transmit_error (struct GNUNET_NETWORK_SocketHandle *sock)
1020 if (sock->nth.notify_ready == NULL)
1021 return; /* nobody to tell about it */
1022 if (sock->nth.timeout_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1024 GNUNET_SCHEDULER_cancel (sock->sched, sock->nth.timeout_task);
1025 sock->nth.timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1027 transmit_timeout (sock, NULL);
1032 * See if we are now connected. If not, wait longer for
1033 * connect to succeed. If connected, we should be able
1034 * to write now as well, unless we timed out.
1037 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1039 struct GNUNET_NETWORK_SocketHandle *sock = cls;
1043 GNUNET_assert (sock->write_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1044 sock->write_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1045 if (sock->connect_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1047 /* still waiting for connect */
1048 GNUNET_assert (sock->write_task ==
1049 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK);
1051 GNUNET_SCHEDULER_add_delayed (tc->sched, GNUNET_NO,
1052 GNUNET_SCHEDULER_PRIORITY_KEEP,
1054 GNUNET_TIME_UNIT_ZERO, &transmit_ready,
1058 if (sock->sock == -1)
1060 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1061 _("Could not satisfy pending transmission request, socket closed or connect failed.\n"));
1062 transmit_error (sock);
1063 return; /* connect failed for good, we're finished */
1065 if ((tc->write_ready == NULL) || (!FD_ISSET (sock->sock, tc->write_ready)))
1067 /* special circumstances: not yet ready to write */
1068 goto SCHEDULE_WRITE;
1070 GNUNET_assert (sock->write_buffer_off >= sock->write_buffer_pos);
1071 process_notify (sock);
1072 have = sock->write_buffer_off - sock->write_buffer_pos;
1075 /* no data ready for writing, terminate write loop */
1079 ret = SEND (sock->sock,
1080 &sock->write_buffer[sock->write_buffer_pos],
1081 have, MSG_DONTWAIT | MSG_NOSIGNAL);
1087 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send");
1089 SHUTDOWN (sock->sock, SHUT_RDWR);
1090 GNUNET_break (0 == CLOSE (sock->sock));
1092 transmit_error (sock);
1096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1097 "transmit_ready transmitted %u/%u bytes to `%s'\n",
1100 GNUNET_a2s(sock->addr, sock->addrlen));
1102 sock->write_buffer_pos += ret;
1103 if (sock->write_buffer_pos == sock->write_buffer_off)
1105 /* transmitted all pending data */
1106 sock->write_buffer_pos = 0;
1107 sock->write_buffer_off = 0;
1109 if ((sock->write_buffer_off == 0) && (NULL == sock->nth.notify_ready))
1110 return; /* all data sent! */
1111 /* not done writing, schedule more */
1113 if (sock->write_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1115 GNUNET_SCHEDULER_add_write (tc->sched,
1117 GNUNET_SCHEDULER_PRIORITY_KEEP,
1118 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1119 GNUNET_TIME_UNIT_FOREVER_REL,
1120 sock->sock, &transmit_ready, sock);
1125 * Ask the socket to call us once the specified number of bytes
1126 * are free in the transmission buffer. May call the notify
1127 * method immediately if enough space is available.
1129 * @param sock socket
1130 * @param size number of bytes to send
1131 * @param timeout after how long should we give up (and call
1132 * notify with buf NULL and size 0)?
1133 * @param notify function to call
1134 * @param notify_cls closure for notify
1135 * @return non-NULL if the notify callback was queued,
1136 * NULL if we are already going to notify someone else (busy)
1138 struct GNUNET_NETWORK_TransmitHandle *
1139 GNUNET_NETWORK_notify_transmit_ready (struct GNUNET_NETWORK_SocketHandle
1141 struct GNUNET_TIME_Relative timeout,
1142 GNUNET_NETWORK_TransmitReadyNotify
1143 notify, void *notify_cls)
1145 if (sock->nth.notify_ready != NULL)
1147 GNUNET_assert (notify != NULL);
1148 GNUNET_assert (sock->write_buffer_size >= size);
1150 if ((sock->sock == -1) &&
1151 (sock->connect_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK))
1154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1155 "Transmission request fails, connection failed.\n");
1157 notify (notify_cls, 0, NULL);
1160 GNUNET_assert (sock->write_buffer_off <= sock->write_buffer_size);
1161 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_size);
1162 GNUNET_assert (sock->write_buffer_pos <= sock->write_buffer_off);
1163 sock->nth.notify_ready = notify;
1164 sock->nth.notify_ready_cls = notify_cls;
1165 sock->nth.sh = sock;
1166 sock->nth.notify_size = size;
1167 sock->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1168 sock->nth.timeout_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1170 GNUNET_SCHEDULER_PRIORITY_KEEP,
1171 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1175 if (sock->write_task == GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1176 sock->write_task = GNUNET_SCHEDULER_add_delayed (sock->sched,
1178 GNUNET_SCHEDULER_PRIORITY_KEEP,
1180 GNUNET_TIME_UNIT_ZERO,
1181 &transmit_ready, sock);
1187 * Cancel the specified transmission-ready
1191 GNUNET_NETWORK_notify_transmit_ready_cancel (struct
1192 GNUNET_NETWORK_TransmitHandle *h)
1194 GNUNET_assert (h->notify_ready != NULL);
1195 GNUNET_SCHEDULER_cancel (h->sh->sched, h->timeout_task);
1196 h->timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1197 h->notify_ready = NULL;
1201 #if 0 /* keep Emacsens' auto-indent happy */