2 This file is part of GNUnet.
3 (C) 2009, 2012 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.c
23 * @brief basic, low-level networking interface
28 #include "gnunet_disk_lib.h"
30 #include "gnunet_container_lib.h"
32 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
33 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
34 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
36 #define DEBUG_NETWORK GNUNET_EXTRA_LOGGING
39 #ifndef INVALID_SOCKET
40 #define INVALID_SOCKET -1
44 struct GNUNET_NETWORK_Handle
53 * Address family / domain.
58 * Number of bytes in addr.
63 * Address we were bound to, or NULL.
65 struct sockaddr *addr;
71 #define FD_COPY(s, d) (memcpy ((d), (s), sizeof (fd_set)))
76 * Set if a socket should use blocking or non-blocking IO.
78 * @param doBlock blocking mode
79 * @return GNUNET_OK on success, GNUNET_SYSERR on error
82 socket_set_blocking (struct GNUNET_NETWORK_Handle *fd, int doBlock)
89 if (ioctlsocket (fd->fd, FIONBIO, &mode) == SOCKET_ERROR)
92 SetErrnoFromWinsockError (WSAGetLastError ());
93 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "ioctlsocket");
100 int flags = fcntl (fd->fd, F_GETFL);
105 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "fcntl");
106 return GNUNET_SYSERR;
109 flags &= ~O_NONBLOCK;
113 if (0 != fcntl (fd->fd, F_SETFL, flags))
116 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "fcntl");
117 return GNUNET_SYSERR;
126 * Make a socket non-inheritable to child processes
128 * @param h the socket to make non-inheritable
129 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
130 * @warning Not implemented on Windows
133 socket_set_inheritable (const struct GNUNET_NETWORK_Handle *h)
137 i = fcntl (h->fd, F_GETFD);
139 return GNUNET_SYSERR;
140 if (i == (i | FD_CLOEXEC))
143 if (fcntl (h->fd, F_SETFD, i) < 0)
144 return GNUNET_SYSERR;
152 * The MSG_NOSIGNAL equivalent on Mac OS X
154 * @param h the socket to make non-delaying
157 socket_set_nosigpipe (const struct GNUNET_NETWORK_Handle *h)
162 setsockopt (h->fd, SOL_SOCKET, SO_NOSIGPIPE, &abs_value,
164 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
170 * Disable delays when sending data via the socket.
171 * (GNUnet makes sure that messages are as big as
174 * @param h the socket to make non-delaying
177 socket_set_nodelay (const struct GNUNET_NETWORK_Handle *h)
182 if (0 != setsockopt (h->fd, IPPROTO_TCP, TCP_NODELAY, &value, sizeof (value)))
183 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
185 const char *abs_value = "1";
188 setsockopt (h->fd, IPPROTO_TCP, TCP_NODELAY, abs_value,
190 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
196 * Perform proper canonical initialization for a network handle.
197 * Set it to non-blocking, make it non-inheritable to child
198 * processes, disable SIGPIPE, enable "nodelay" (if non-UNIX
199 * stream socket) and check that it is smaller than FS_SETSIZE.
201 * @param h socket to initialize
202 * @param af address family of the socket
203 * @param type socket type
204 * @return GNUNET_OK on success, GNUNET_SYSERR if initialization
205 * failed and the handle was destroyed
208 initialize_network_handle (struct GNUNET_NETWORK_Handle *h,
212 if (h->fd == INVALID_SOCKET)
215 SetErrnoFromWinsockError (WSAGetLastError ());
218 return GNUNET_SYSERR;
221 if (h->fd >= FD_SETSIZE)
223 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
225 return GNUNET_SYSERR;
227 if (GNUNET_OK != socket_set_inheritable (h))
228 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
229 "socket_set_inheritable");
231 if (GNUNET_SYSERR == socket_set_blocking (h, GNUNET_NO))
234 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
235 return GNUNET_SYSERR;
238 socket_set_nosigpipe (h);
240 if ( (type == SOCK_STREAM)
245 socket_set_nodelay (h);
251 * accept a new connection on a socket
253 * @param desc bound socket
254 * @param address address of the connecting peer, may be NULL
255 * @param address_len length of address
256 * @return client socket
258 struct GNUNET_NETWORK_Handle *
259 GNUNET_NETWORK_socket_accept (const struct GNUNET_NETWORK_Handle *desc,
260 struct sockaddr *address, socklen_t * address_len)
262 struct GNUNET_NETWORK_Handle *ret;
264 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
267 struct sockaddr name;
268 socklen_t namelen = sizeof (name);
269 int gsn = getsockname (desc->fd, &name, &namelen);
272 LOG (GNUNET_ERROR_TYPE_DEBUG, "Accepting connection on `%s'\n",
273 GNUNET_a2s (&name, namelen));
276 ret->fd = accept (desc->fd, address, address_len);
277 if (GNUNET_OK != initialize_network_handle (ret,
278 (NULL != address) ? address->sa_family : desc->af,
286 * Bind to a connected socket
288 * @param address address to be bound
289 * @param address_len length of address
290 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
293 GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc,
294 const struct sockaddr *address,
295 socklen_t address_len)
303 if (desc->af == AF_INET6)
304 if (0 != setsockopt (desc->fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
305 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG, "setsockopt");
309 /* This is required, and required here, but only on UNIX */
310 if (0 != setsockopt (desc->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)))
311 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG, "setsockopt");
315 if (address->sa_family == AF_UNIX)
317 const struct sockaddr_un *un = (const struct sockaddr_un *) address;
319 (void) unlink (un->sun_path);
323 ret = bind (desc->fd, address, address_len);
325 if (SOCKET_ERROR == ret)
326 SetErrnoFromWinsockError (WSAGetLastError ());
329 return GNUNET_SYSERR;
332 desc->addr = GNUNET_malloc (address_len);
333 memcpy (desc->addr, address, address_len);
334 desc->addrlen = address_len;
344 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
347 GNUNET_NETWORK_socket_close (struct GNUNET_NETWORK_Handle *desc)
355 ret = closesocket (desc->fd);
356 error = WSAGetLastError ();
357 SetErrnoFromWinsockError (error);
358 LOG (GNUNET_ERROR_TYPE_DEBUG,
359 "Closed 0x%x, closesocket() returned %d, GLE is %u\n", desc->fd, ret,
362 ret = close (desc->fd);
366 if ((desc->af == AF_UNIX) && (NULL != desc->addr))
368 const struct sockaddr_un *un = (const struct sockaddr_un *) desc->addr;
370 if (0 != unlink (un->sun_path))
371 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", un->sun_path);
375 GNUNET_free_non_null (desc->addr);
377 return (ret == 0) ? GNUNET_OK : GNUNET_SYSERR;
382 * Box a native socket (and check that it is a socket).
384 * @param fd socket to box
385 * @return NULL on error (including not supported on target platform)
387 struct GNUNET_NETWORK_Handle *
388 GNUNET_NETWORK_socket_box_native (SOCKTYPE fd)
390 struct GNUNET_NETWORK_Handle *ret;
394 /* FIXME: Find a better call to check that FD is valid */
395 if (WSAIoctl (fd, FIONBIO, (void *) &i, sizeof (i), NULL, 0, &d, NULL, NULL) != 0)
396 return NULL; /* invalid FD */
397 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
402 if (fcntl (fd, F_GETFD) < 0)
403 return NULL; /* invalid FD */
404 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
415 * @param address peer address
416 * @param address_len length of address
417 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
420 GNUNET_NETWORK_socket_connect (const struct GNUNET_NETWORK_Handle *desc,
421 const struct sockaddr *address,
422 socklen_t address_len)
426 ret = connect (desc->fd, address, address_len);
429 if (SOCKET_ERROR == ret)
431 SetErrnoFromWinsockError (WSAGetLastError ());
432 if (errno == EWOULDBLOCK)
436 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
444 * @param level protocol level of the option
445 * @param optname identifier of the option
446 * @param optval options
447 * @param optlen length of optval
448 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
451 GNUNET_NETWORK_socket_getsockopt (const struct GNUNET_NETWORK_Handle *desc,
452 int level, int optname, void *optval,
457 ret = getsockopt (desc->fd, level, optname, optval, optlen);
460 if (ret == 0 && level == SOL_SOCKET && optname == SO_ERROR)
461 *((int *) optval) = GetErrnoFromWinsockError (*((int *) optval));
463 else if (SOCKET_ERROR == ret)
464 SetErrnoFromWinsockError (WSAGetLastError ());
466 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
473 * @param backlog length of the listen queue
474 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
477 GNUNET_NETWORK_socket_listen (const struct GNUNET_NETWORK_Handle *desc,
482 ret = listen (desc->fd, backlog);
485 if (SOCKET_ERROR == ret)
486 SetErrnoFromWinsockError (WSAGetLastError ());
489 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
494 * How much data is available to be read on this descriptor?
496 * Returns GNUNET_NO if no data is available, or on error!
500 GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle *
505 /* How much is there to be read? */
509 error = ioctl (desc->fd, FIONREAD, &pending);
511 return (ssize_t) pending;
516 error = ioctlsocket (desc->fd, FIONREAD, &pending);
517 if (error != SOCKET_ERROR)
518 return (ssize_t) pending;
525 * Read data from a connected socket (always non-blocking).
527 * @param buffer buffer
528 * @param length length of buffer
529 * @param src_addr either the source to recv from, or all zeroes
530 * to be filled in by recvfrom
531 * @param addrlen length of the addr
534 GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle * desc,
535 void *buffer, size_t length,
536 struct sockaddr * src_addr, socklen_t * addrlen)
544 flags |= MSG_DONTWAIT;
547 ret = recvfrom (desc->fd, buffer, length, flags, src_addr, addrlen);
549 if (SOCKET_ERROR == ret)
550 SetErrnoFromWinsockError (WSAGetLastError ());
557 * Read data from a connected socket (always non-blocking).
559 * @param buffer buffer
560 * @param length length of buffer
563 GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle * desc,
564 void *buffer, size_t length)
572 flags |= MSG_DONTWAIT;
574 ret = recv (desc->fd, buffer, length, flags);
576 if (SOCKET_ERROR == ret)
577 SetErrnoFromWinsockError (WSAGetLastError ());
584 * Send data (always non-blocking).
587 * @param buffer data to send
588 * @param length size of the buffer
589 * @return number of bytes sent, GNUNET_SYSERR on error
592 GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle * desc,
593 const void *buffer, size_t length)
601 flags |= MSG_DONTWAIT;
605 flags |= MSG_NOSIGNAL;
608 ret = send (desc->fd, buffer, length, flags);
611 if (SOCKET_ERROR == ret)
612 SetErrnoFromWinsockError (WSAGetLastError ());
620 * Send data to a particular destination (always non-blocking).
621 * This function only works for UDP sockets.
624 * @param message data to send
625 * @param length size of the data
626 * @param dest_addr destination address
627 * @param dest_len length of address
628 * @return number of bytes sent, GNUNET_SYSERR on error
631 GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle * desc,
632 const void *message, size_t length,
633 const struct sockaddr * dest_addr,
642 flags |= MSG_DONTWAIT;
645 flags |= MSG_NOSIGNAL;
647 ret = sendto (desc->fd, message, length, flags, dest_addr, dest_len);
649 if (SOCKET_ERROR == ret)
650 SetErrnoFromWinsockError (WSAGetLastError ());
659 * @param level protocol level of the option
660 * @param option_name option identifier
661 * @param option_value value to set
662 * @param option_len size of option_value
663 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
666 GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd, int level,
667 int option_name, const void *option_value,
668 socklen_t option_len)
672 ret = setsockopt (fd->fd, level, option_name, option_value, option_len);
674 if (SOCKET_ERROR == ret)
675 SetErrnoFromWinsockError (WSAGetLastError ());
677 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
682 * Create a new socket. Configure it for non-blocking IO and
683 * mark it as non-inheritable to child processes (set the
684 * close-on-exec flag).
686 * @param domain domain of the socket
687 * @param type socket type
688 * @param protocol network protocol
689 * @return new socket, NULL on error
691 struct GNUNET_NETWORK_Handle *
692 GNUNET_NETWORK_socket_create (int domain, int type, int protocol)
694 struct GNUNET_NETWORK_Handle *ret;
696 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
697 ret->fd = socket (domain, type, protocol);
699 initialize_network_handle (ret, domain, type))
706 * Shut down socket operations
708 * @param how type of shutdown
709 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
712 GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc, int how)
716 ret = shutdown (desc->fd, how);
719 SetErrnoFromWinsockError (WSAGetLastError ());
721 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
726 * Disable the "CORK" feature for communication with the given socket,
727 * forcing the OS to immediately flush the buffer on transmission
728 * instead of potentially buffering multiple messages. Essentially
729 * reduces the OS send buffers to zero.
732 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
735 GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc)
744 setsockopt (desc->fd, SOL_SOCKET, SO_SNDBUF, (char *) &value,
746 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
749 setsockopt (desc->fd, SOL_SOCKET, SO_RCVBUF, (char *) &value,
751 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
757 setsockopt (desc->fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof (value))))
758 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
761 setsockopt (desc->fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof (value))))
762 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
764 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
773 GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds)
778 GNUNET_CONTAINER_slist_clear (fds->handles);
783 * Add a socket to the FD set
785 * @param desc socket to add
788 GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds,
789 const struct GNUNET_NETWORK_Handle *desc)
791 FD_SET (desc->fd, &fds->sds);
792 if (desc->fd + 1 > fds->nsds)
793 fds->nsds = desc->fd + 1;
798 * Check whether a socket is part of the fd set
801 * @return 0 if the FD is not set
804 GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds,
805 const struct GNUNET_NETWORK_Handle *desc)
807 return FD_ISSET (desc->fd, &fds->sds);
812 * Add one fd set to another
813 * @param dst the fd set to add to
814 * @param src the fd set to add from
817 GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst,
818 const struct GNUNET_NETWORK_FDSet *src)
822 for (nfds = src->nsds; nfds > 0; nfds--)
823 if (FD_ISSET (nfds, &src->sds))
826 FD_SET (nfds, &dst->sds);
827 if (nfds + 1 > dst->nsds)
828 dst->nsds = nfds + 1;
831 GNUNET_CONTAINER_slist_append (dst->handles, src->handles);
837 * Copy one fd set to another
839 * @param to destination
843 GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to,
844 const struct GNUNET_NETWORK_FDSet *from)
846 FD_COPY (&from->sds, &to->sds);
847 to->nsds = from->nsds;
850 GNUNET_CONTAINER_slist_clear (to->handles);
851 GNUNET_CONTAINER_slist_append (to->handles, from->handles);
857 * Return file descriptor for this network handle
859 * @param desc wrapper to process
860 * @return POSIX file descriptor
863 GNUNET_NETWORK_get_fd (struct GNUNET_NETWORK_Handle *desc)
869 * Return sockaddr for this network handle
871 * @param desc wrapper to process
875 GNUNET_NETWORK_get_addr (struct GNUNET_NETWORK_Handle *desc)
881 * Return sockaddr length for this network handle
883 * @param desc wrapper to process
884 * @return socklen_t for sockaddr
887 GNUNET_NETWORK_get_addrlen (struct GNUNET_NETWORK_Handle *desc)
889 return desc->addrlen;
892 * Copy a native fd set
894 * @param to destination
895 * @param from native source set
896 * @param nfds the biggest socket number in from + 1
899 GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to,
900 const fd_set * from, int nfds)
902 FD_COPY (from, &to->sds);
908 * Set a native fd in a set
910 * @param to destination
911 * @param nfd native FD to set
914 GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to, int nfd)
916 GNUNET_assert ((nfd >= 0) && (nfd < FD_SETSIZE));
917 FD_SET (nfd, &to->sds);
918 to->nsds = GNUNET_MAX (nfd + 1, to->nsds);
923 * Test native fd in a set
925 * @param to set to test, NULL for empty set
926 * @param nfd native FD to test, or -1 for none
927 * @return GNUNET_YES if FD is set in the set
930 GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to,
933 if ((nfd == -1) || (to == NULL))
935 return FD_ISSET (nfd, &to->sds) ? GNUNET_YES : GNUNET_NO;
940 * Add a file handle to the fd set
942 * @param h the file handle to add
945 GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds,
946 const struct GNUNET_DISK_FileHandle *h)
949 GNUNET_CONTAINER_slist_add (fds->handles,
950 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT, h,
951 sizeof (struct GNUNET_DISK_FileHandle));
956 GNUNET_DISK_internal_file_handle_ (h, &fd, sizeof (int));
957 FD_SET (fd, &fds->sds);
958 if (fd + 1 > fds->nsds)
966 * Check if a file handle is part of an fd set
968 * @param h file handle
969 * @return GNUNET_YES if the file handle is part of the set
972 GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds,
973 const struct GNUNET_DISK_FileHandle *h)
977 return GNUNET_CONTAINER_slist_contains (fds->handles, h,
979 GNUNET_DISK_FileHandle));
981 return FD_ISSET (h->fd, &fds->sds);
987 * Checks if two fd sets overlap
988 * @param fds1 first fd set
989 * @param fds2 second fd set
990 * @return GNUNET_YES if they do overlap, GNUNET_NO otherwise
993 GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1,
994 const struct GNUNET_NETWORK_FDSet *fds2)
1000 if (nfds > fds2->nsds)
1005 if (FD_ISSET (nfds, &fds1->sds) && FD_ISSET (nfds, &fds2->sds))
1009 struct GNUNET_CONTAINER_SList_Iterator it;
1010 struct GNUNET_DISK_FileHandle *h;
1014 /*This code is somewhat hacky, we are not supposed to know what's
1015 * inside of fd_set; also the O(n^2) is really bad... */
1017 for (i = 0; i < fds1->sds.fd_count; i++)
1019 for (j = 0; j < fds2->sds.fd_count; j++)
1021 if (fds1->sds.fd_array[i] == fds2->sds.fd_array[j])
1025 it = GNUNET_CONTAINER_slist_begin (fds1->handles);
1026 while (GNUNET_CONTAINER_slist_end (&it) != GNUNET_YES)
1029 struct GNUNET_CONTAINER_SList_Iterator t;
1031 h = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&it,
1034 LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking that FD 0x%x is in another set:\n",
1036 for (t = GNUNET_CONTAINER_slist_begin (fds2->handles);
1037 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1038 GNUNET_CONTAINER_slist_next (&t))
1040 struct GNUNET_DISK_FileHandle *fh;
1042 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1044 LOG (GNUNET_ERROR_TYPE_DEBUG, "0x%x\n", fh->h);
1047 if (GNUNET_CONTAINER_slist_contains
1048 (fds2->handles, h, sizeof (struct GNUNET_DISK_FileHandle)))
1052 GNUNET_CONTAINER_slist_next (&it);
1061 * @return a new fd set
1063 struct GNUNET_NETWORK_FDSet *
1064 GNUNET_NETWORK_fdset_create ()
1066 struct GNUNET_NETWORK_FDSet *fds;
1068 fds = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_FDSet));
1070 fds->handles = GNUNET_CONTAINER_slist_create ();
1072 GNUNET_NETWORK_fdset_zero (fds);
1078 * Releases the associated memory of an fd set
1082 GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds)
1085 GNUNET_CONTAINER_slist_destroy (fds->handles);
1091 struct _select_params
\r
1096 struct timeval *tv;
\r
1099 SOCKET wakeup_socket;
\r
1103 static DWORD WINAPI
\r
1104 _selector (LPVOID p)
\r
1106 struct _select_params *sp = p;
\r
1110 WaitForSingleObject (sp->standby, INFINITE);
\r
1111 ResetEvent (sp->standby);
\r
1112 sp->status = select (1, sp->r, sp->w, sp->e, sp->tv);
\r
1113 if (FD_ISSET (sp->wakeup_socket, sp->r))
\r
1115 FD_CLR (sp->wakeup_socket, sp->r);
\r
1118 SetEvent (sp->wakeup);
\r
1125 * Check if sockets or pipes meet certain conditions
1126 * @param rfds set of sockets or pipes to be checked for readability
1127 * @param wfds set of sockets or pipes to be checked for writability
1128 * @param efds set of sockets or pipes to be checked for exceptions
1129 * @param timeout relative value when to return
1130 * @return number of selected sockets or pipes, GNUNET_SYSERR on error
1133 GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1134 struct GNUNET_NETWORK_FDSet *wfds,
1135 struct GNUNET_NETWORK_FDSet *efds,
1136 const struct GNUNET_TIME_Relative timeout)
1142 int read_handles = 0;
1143 int write_handles = 0;
1151 static HANDLE hEventPipeWrite = 0;
1152 static HANDLE hEventReadReady = 0;
1154 static struct _select_params sp;
\r
1155 static HANDLE select_thread = NULL;
1156 static HANDLE select_finished_event = NULL;
1157 static HANDLE select_standby_event = NULL;
1158 static SOCKET select_wakeup_socket = -1;
\r
1159 static SOCKET select_send_socket = -1;
\r
1160 static struct timeval select_timeout;
1163 int writePipePos = 0;
1165 HANDLE handle_array[FD_SETSIZE + 2];
1166 int returncode = -1;
1167 int returnedpos = 0;
1169 struct GNUNET_CONTAINER_SList *handles_read;
1170 struct GNUNET_CONTAINER_SList *handles_write;
1171 struct GNUNET_CONTAINER_SList *handles_except;
1183 /* TODO: Make this growable */
1184 struct GNUNET_DISK_FileHandle *readArray[50];
1192 handles += read_handles = GNUNET_CONTAINER_slist_count (rfds->handles);
1195 struct GNUNET_CONTAINER_SList_Iterator t;
1197 for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1198 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1199 GNUNET_CONTAINER_slist_next (&t))
1201 struct GNUNET_DISK_FileHandle *fh;
1203 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1205 LOG (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x (0x%x) is SET in rfds\n", fh->h,
1214 nfds = GNUNET_MAX (nfds, wfds->nsds);
1216 handles += write_handles = GNUNET_CONTAINER_slist_count (wfds->handles);
1221 nfds = GNUNET_MAX (nfds, efds->nsds);
1223 handles += ex_handles = GNUNET_CONTAINER_slist_count (efds->handles);
1228 (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1234 LOG (GNUNET_ERROR_TYPE_ERROR,
1236 ("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1241 tv.tv_sec = timeout.rel_value / GNUNET_TIME_UNIT_SECONDS.rel_value;
1243 1000 * (timeout.rel_value -
1244 (tv.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value));
1245 return select (nfds, (rfds != NULL) ? &rfds->sds : NULL,
1246 (wfds != NULL) ? &wfds->sds : NULL,
1247 (efds != NULL) ? &efds->sds : NULL,
1248 (timeout.rel_value ==
1249 GNUNET_TIME_UNIT_FOREVER_REL.rel_value) ? NULL : &tv);
1252 #define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set))
1253 /* calculate how long we need to wait in milliseconds */
1254 if (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1255 ms_total = INFINITE;
1257 ms_total = timeout.rel_value / GNUNET_TIME_UNIT_MILLISECONDS.rel_value;
1258 /* select() may be used as a portable way to sleep */
1259 if (!(rfds || wfds || efds))
1265 if (select_thread == NULL)
1267 SOCKET select_listening_socket = -1;
\r
1268 struct sockaddr_in s_in;
\r
1273 select_standby_event = CreateEvent (NULL, TRUE, FALSE, NULL);
\r
1274 select_finished_event = CreateEvent (NULL, TRUE, FALSE, NULL);
\r
1276 select_wakeup_socket = WSASocket (AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
\r
1278 select_listening_socket = WSASocket (AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
\r
1281 res = ioctlsocket (select_wakeup_socket, FIONBIO, &p);
\r
1283 alen = sizeof (s_in);
\r
1284 s_in.sin_family = AF_INET;
\r
1285 s_in.sin_port = 0;
\r
1286 s_in.sin_addr.S_un.S_un_b.s_b1 = 127;
\r
1287 s_in.sin_addr.S_un.S_un_b.s_b2 = 0;
\r
1288 s_in.sin_addr.S_un.S_un_b.s_b3 = 0;
\r
1289 s_in.sin_addr.S_un.S_un_b.s_b4 = 1;
\r
1290 res = bind (select_listening_socket, (const struct sockaddr *) &s_in, sizeof (s_in));
\r
1292 res = getsockname (select_listening_socket, (struct sockaddr *) &s_in, &alen);
\r
1294 res = listen (select_listening_socket, SOMAXCONN);
\r
1296 res = connect (select_wakeup_socket, (const struct sockaddr *) &s_in, sizeof (s_in));
\r
1298 select_send_socket = accept (select_listening_socket, (struct sockaddr *) &s_in, &alen);
\r
1300 closesocket (select_listening_socket);
\r
1302 sp.wakeup = select_finished_event;
\r
1303 sp.standby = select_standby_event;
\r
1304 sp.wakeup_socket = select_wakeup_socket;
1306 select_thread = CreateThread (NULL, 0, _selector, &sp, 0, NULL);
\r
1309 /* Events for pipes */
1310 if (!hEventReadReady)
1311 hEventReadReady = CreateEvent (NULL, TRUE, TRUE, NULL);
1312 if (!hEventPipeWrite)
1313 hEventPipeWrite = CreateEvent (NULL, TRUE, TRUE, NULL);
1317 handles_read = GNUNET_CONTAINER_slist_create ();
1318 handles_write = GNUNET_CONTAINER_slist_create ();
1319 handles_except = GNUNET_CONTAINER_slist_create ();
1330 FD_COPY (&rfds->sds, &aread);
1332 FD_COPY (&rfds->sds, &bread);
1337 FD_COPY (&wfds->sds, &awrite);
1339 FD_COPY (&wfds->sds, &bwrite);
1344 FD_COPY (&efds->sds, &aexcept);
1346 FD_COPY (&efds->sds, &bexcept);
1349 /* We will first Add the PIPES to the events */
1351 if (rfds && read_handles)
1353 struct GNUNET_CONTAINER_SList_Iterator i;
1355 for (i = GNUNET_CONTAINER_slist_begin (rfds->handles);
1356 GNUNET_CONTAINER_slist_end (&i) != GNUNET_YES;
1357 GNUNET_CONTAINER_slist_next (&i))
1359 struct GNUNET_DISK_FileHandle *fh;
1361 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&i,
1363 if (fh->type == GNUNET_PIPE)
1365 /* Read zero bytes to check the status of the pipe */
1366 LOG (GNUNET_ERROR_TYPE_DEBUG, "Reading 0 bytes from the pipe 0x%x\n",
1368 if (!ReadFile (fh->h, NULL, 0, NULL, fh->oOverlapRead))
1370 DWORD error_code = GetLastError ();
1372 if (error_code == ERROR_IO_PENDING)
1374 LOG (GNUNET_ERROR_TYPE_DEBUG,
1375 "Adding the pipe's 0x%x overlapped event to the array as %d\n",
1377 handle_array[nhandles++] = fh->oOverlapRead->hEvent;
1378 readArray[readPipes++] = fh;
1382 LOG (GNUNET_ERROR_TYPE_DEBUG,
1383 "Read failed, adding the read ready event to the array as %d\n", nhandles);
1384 handle_array[nhandles++] = hEventReadReady;
1385 readArray[readPipes++] = fh;
1390 LOG (GNUNET_ERROR_TYPE_DEBUG,
1391 "Adding the read ready event to the array as %d\n", nhandles);
1392 handle_array[nhandles++] = hEventReadReady;
1393 readArray[readPipes++] = fh;
1398 GNUNET_CONTAINER_slist_add (handles_read,
1399 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1400 fh, sizeof (struct GNUNET_DISK_FileHandle));
1404 if (wfds && write_handles)
1406 LOG (GNUNET_ERROR_TYPE_DEBUG,
1407 "Adding the write ready event to the array as %d\n", nhandles);
1408 handle_array[nhandles++] = hEventPipeWrite;
1409 writePipePos = nhandles;
1411 if (efds && ex_handles)
1413 struct GNUNET_CONTAINER_SList_Iterator i;
1415 for (i = GNUNET_CONTAINER_slist_begin (efds->handles);
1416 GNUNET_CONTAINER_slist_end (&i) != GNUNET_YES;
1417 GNUNET_CONTAINER_slist_next (&i))
1419 struct GNUNET_DISK_FileHandle *fh;
1422 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&i,
1424 if (fh->type == GNUNET_PIPE)
1426 if (!PeekNamedPipe (fh->h, NULL, 0, NULL, &dwBytes, NULL))
1428 GNUNET_CONTAINER_slist_add (handles_except,
1429 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1431 sizeof (struct GNUNET_DISK_FileHandle));
1441 LOG (GNUNET_ERROR_TYPE_DEBUG,
1442 "Adding the socket event to the array as %d\n", nhandles);
1443 handle_array[nhandles++] = select_finished_event;
1444 if (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1448 select_timeout.tv_sec = timeout.rel_value / GNUNET_TIME_UNIT_SECONDS.rel_value;
1449 select_timeout.tv_usec = 1000 * (timeout.rel_value -
1450 (select_timeout.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value));
1451 sp.tv = &select_timeout;
1453 FD_SET (select_wakeup_socket, &aread);
1457 /* Failed connections cause sockets to be set in errorfds on W32,
1458 * but on POSIX it should set them in writefds.
1459 * First copy all awrite sockets to aexcept, later we'll
1460 * check aexcept and set its contents in awrite as well
1461 * Sockets are also set in errorfds when OOB data is available,
1462 * but we don't use OOB data.
1464 for (i = 0; i < awrite.fd_count; i++)
1466 if (awrite.fd_array[i] != 0 && awrite.fd_array[i] != -1)
1467 FD_SET (awrite.fd_array[i], &aexcept);
1469 ResetEvent (select_finished_event);
1470 SetEvent (select_standby_event);
1473 handle_array[nhandles] = NULL;
1474 LOG (GNUNET_ERROR_TYPE_DEBUG, "nfds: %d, handles: %d, will wait: %d ms\n",
1475 nfds, nhandles, ms_total);
1478 WaitForMultipleObjects (nhandles, handle_array, FALSE, ms_total);
1479 LOG (GNUNET_ERROR_TYPE_DEBUG, "WaitForMultipleObjects Returned : %d\n",
1484 /* Don't wake up select-thread when delay is 0, it should return immediately
1485 * and wake up by itself.
1488 i = send (select_send_socket, (const char *) &returnedpos, 1, 0);
\r
1489 i = (int) WaitForSingleObject (select_finished_event, INFINITE);
\r
1490 LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished waiting for the select thread: %d %d\n", i, sp.status);
1495 i = recv (select_wakeup_socket, (char *) &returnedpos, 1, 0);
\r
1498 /* Check aexcept, add its contents to awrite */
1499 for (i = 0; i < aexcept.fd_count; i++)
1501 if (aexcept.fd_array[i] != 0 && aexcept.fd_array[i] != -1)
1502 FD_SET (aexcept.fd_array[i], &awrite);
1506 returnedpos = returncode - WAIT_OBJECT_0;
1507 LOG (GNUNET_ERROR_TYPE_DEBUG, "return pos is : %d\n", returnedpos);
1509 if (nhandles && (returnedpos < nhandles))
1514 retcode += sp.status;
1516 if ((writePipePos != -1) && (returnedpos < writePipePos))
1518 GNUNET_CONTAINER_slist_append (handles_write, wfds->handles);
1519 retcode += write_handles;
1520 LOG (GNUNET_ERROR_TYPE_DEBUG, "Added write pipe\n");
1522 LOG (GNUNET_ERROR_TYPE_DEBUG, "ReadPipes is : %d\n", readPipes);
1523 /* We have some pipes ready for read. */
1524 if (returnedpos < readPipes)
1526 for (i = 0; i < readPipes; i++)
1534 PeekNamedPipe (readArray[i]->h, NULL, 0, NULL, &waitstatus, NULL);
1535 error = GetLastError ();
1536 LOG (GNUNET_ERROR_TYPE_DEBUG,
1537 "Peek at read pipe %d (0x%x) returned %d (%d bytes available) GLE %u\n",
1538 i, readArray[i]->h, bret, waitstatus, error);
1541 if (error != ERROR_BROKEN_PIPE)
1544 else if (waitstatus <= 0)
1546 GNUNET_CONTAINER_slist_add (handles_read,
1547 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1549 sizeof (struct GNUNET_DISK_FileHandle));
1551 LOG (GNUNET_ERROR_TYPE_DEBUG, "Added read Pipe 0x%x (0x%x)\n",
1552 readArray[i], readArray[i]->h);
1556 if (!nhandles || (returnedpos >= nhandles))
1557 LOG (GNUNET_ERROR_TYPE_DEBUG, "Returning from _select() with nothing!\n");
1560 struct GNUNET_CONTAINER_SList_Iterator t;
1562 for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1563 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1564 GNUNET_CONTAINER_slist_next (&t))
1566 struct GNUNET_DISK_FileHandle *fh;
1568 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1570 if (fh->type == GNUNET_PIPE)
1575 LOG (GNUNET_ERROR_TYPE_DEBUG, "Zeroing rfds%s\n", (retcode != -1 && nhandles && (returnedpos < nhandles)) ? ", copying fdset" : "");
1576 GNUNET_NETWORK_fdset_zero (rfds);
1577 if (retcode != -1 && nhandles && (returnedpos < nhandles))
1578 GNUNET_NETWORK_fdset_copy_native (rfds, &aread, retcode);
1579 GNUNET_CONTAINER_slist_append (rfds->handles, handles_read);
1583 LOG (GNUNET_ERROR_TYPE_DEBUG, "Zeroing wfds%s\n", (retcode != -1 && nhandles && (returnedpos < nhandles)) ? ", copying fdset" : "");
1584 GNUNET_NETWORK_fdset_zero (wfds);
1585 if (retcode != -1 && nhandles && (returnedpos < nhandles))
1586 GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, retcode);
1587 GNUNET_CONTAINER_slist_append (wfds->handles, handles_write);
1591 LOG (GNUNET_ERROR_TYPE_DEBUG, "Zeroing efds%s\n", (retcode != -1 && nhandles && (returnedpos < nhandles)) ? ", copying fdset" : "");
1592 GNUNET_NETWORK_fdset_zero (efds);
1593 if (retcode != -1 && nhandles && (returnedpos < nhandles))
1594 GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, retcode);
1595 GNUNET_CONTAINER_slist_append (efds->handles, handles_except);
1597 GNUNET_CONTAINER_slist_destroy (handles_read);
1598 GNUNET_CONTAINER_slist_destroy (handles_write);
1599 GNUNET_CONTAINER_slist_destroy (handles_except);
1603 struct GNUNET_CONTAINER_SList_Iterator t;
1605 LOG (GNUNET_ERROR_TYPE_DEBUG, "rfds:\n");
1606 for (i = 0; i < rfds->sds.fd_count; i++)
1608 LOG (GNUNET_ERROR_TYPE_DEBUG, "%d\n", rfds->sds.fd_array[i]);
1610 for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1611 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1612 GNUNET_CONTAINER_slist_next (&t))
1614 struct GNUNET_DISK_FileHandle *fh;
1616 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1618 LOG (GNUNET_ERROR_TYPE_DEBUG, "%d\n", fh->h);
1623 LOG (GNUNET_ERROR_TYPE_DEBUG, "wfds:\n");
1624 for (i = 0; i < wfds->sds.fd_count; i++)
1626 LOG (GNUNET_ERROR_TYPE_DEBUG, "%d\n", wfds->sds.fd_array[i]);
1631 LOG (GNUNET_ERROR_TYPE_DEBUG, "efds:\n");
1632 for (i = 0; i < efds->sds.fd_count; i++)
1634 LOG (GNUNET_ERROR_TYPE_DEBUG, "%d\n", efds->sds.fd_array[i]);
1637 LOG (GNUNET_ERROR_TYPE_DEBUG, "Returning %d or 0\n", retcode);
1639 if (nhandles && (returnedpos < nhandles))
1646 /* end of network.c */