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);
514 error = ioctlsocket (desc->fd, FIONREAD, &pending);
515 if (error != SOCKET_ERROR)
524 * Read data from a connected socket (always non-blocking).
526 * @param buffer buffer
527 * @param length length of buffer
528 * @param src_addr either the source to recv from, or all zeroes
529 * to be filled in by recvfrom
530 * @param addrlen length of the addr
533 GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle * desc,
534 void *buffer, size_t length,
535 struct sockaddr * src_addr, socklen_t * addrlen)
543 flags |= MSG_DONTWAIT;
546 ret = recvfrom (desc->fd, buffer, length, flags, src_addr, addrlen);
548 if (SOCKET_ERROR == ret)
549 SetErrnoFromWinsockError (WSAGetLastError ());
556 * Read data from a connected socket (always non-blocking).
558 * @param buffer buffer
559 * @param length length of buffer
562 GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle * desc,
563 void *buffer, size_t length)
571 flags |= MSG_DONTWAIT;
573 ret = recv (desc->fd, buffer, length, flags);
575 if (SOCKET_ERROR == ret)
576 SetErrnoFromWinsockError (WSAGetLastError ());
583 * Send data (always non-blocking).
586 * @param buffer data to send
587 * @param length size of the buffer
588 * @return number of bytes sent, GNUNET_SYSERR on error
591 GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle * desc,
592 const void *buffer, size_t length)
600 flags |= MSG_DONTWAIT;
604 flags |= MSG_NOSIGNAL;
607 ret = send (desc->fd, buffer, length, flags);
610 if (SOCKET_ERROR == ret)
611 SetErrnoFromWinsockError (WSAGetLastError ());
619 * Send data to a particular destination (always non-blocking).
620 * This function only works for UDP sockets.
623 * @param message data to send
624 * @param length size of the data
625 * @param dest_addr destination address
626 * @param dest_len length of address
627 * @return number of bytes sent, GNUNET_SYSERR on error
630 GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle * desc,
631 const void *message, size_t length,
632 const struct sockaddr * dest_addr,
641 flags |= MSG_DONTWAIT;
644 flags |= MSG_NOSIGNAL;
646 ret = sendto (desc->fd, message, length, flags, dest_addr, dest_len);
648 if (SOCKET_ERROR == ret)
649 SetErrnoFromWinsockError (WSAGetLastError ());
658 * @param level protocol level of the option
659 * @param option_name option identifier
660 * @param option_value value to set
661 * @param option_len size of option_value
662 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
665 GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd, int level,
666 int option_name, const void *option_value,
667 socklen_t option_len)
671 ret = setsockopt (fd->fd, level, option_name, option_value, option_len);
673 if (SOCKET_ERROR == ret)
674 SetErrnoFromWinsockError (WSAGetLastError ());
676 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
681 * Create a new socket. Configure it for non-blocking IO and
682 * mark it as non-inheritable to child processes (set the
683 * close-on-exec flag).
685 * @param domain domain of the socket
686 * @param type socket type
687 * @param protocol network protocol
688 * @return new socket, NULL on error
690 struct GNUNET_NETWORK_Handle *
691 GNUNET_NETWORK_socket_create (int domain, int type, int protocol)
693 struct GNUNET_NETWORK_Handle *ret;
695 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
696 ret->fd = socket (domain, type, protocol);
698 initialize_network_handle (ret, domain, type))
705 * Shut down socket operations
707 * @param how type of shutdown
708 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
711 GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc, int how)
715 ret = shutdown (desc->fd, how);
718 SetErrnoFromWinsockError (WSAGetLastError ());
720 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
725 * Disable the "CORK" feature for communication with the given socket,
726 * forcing the OS to immediately flush the buffer on transmission
727 * instead of potentially buffering multiple messages. Essentially
728 * reduces the OS send buffers to zero.
731 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
734 GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc)
743 setsockopt (desc->fd, SOL_SOCKET, SO_SNDBUF, (char *) &value,
745 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
748 setsockopt (desc->fd, SOL_SOCKET, SO_RCVBUF, (char *) &value,
750 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
756 setsockopt (desc->fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof (value))))
757 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
760 setsockopt (desc->fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof (value))))
761 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
763 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
772 GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds)
777 GNUNET_CONTAINER_slist_clear (fds->handles);
782 * Add a socket to the FD set
784 * @param desc socket to add
787 GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds,
788 const struct GNUNET_NETWORK_Handle *desc)
790 FD_SET (desc->fd, &fds->sds);
791 if (desc->fd + 1 > fds->nsds)
792 fds->nsds = desc->fd + 1;
797 * Check whether a socket is part of the fd set
800 * @return 0 if the FD is not set
803 GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds,
804 const struct GNUNET_NETWORK_Handle *desc)
806 return FD_ISSET (desc->fd, &fds->sds);
811 * Add one fd set to another
812 * @param dst the fd set to add to
813 * @param src the fd set to add from
816 GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst,
817 const struct GNUNET_NETWORK_FDSet *src)
821 for (nfds = src->nsds; nfds > 0; nfds--)
822 if (FD_ISSET (nfds, &src->sds))
825 FD_SET (nfds, &dst->sds);
826 if (nfds + 1 > dst->nsds)
827 dst->nsds = nfds + 1;
830 GNUNET_CONTAINER_slist_append (dst->handles, src->handles);
836 * Copy one fd set to another
838 * @param to destination
842 GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to,
843 const struct GNUNET_NETWORK_FDSet *from)
845 FD_COPY (&from->sds, &to->sds);
846 to->nsds = from->nsds;
849 GNUNET_CONTAINER_slist_clear (to->handles);
850 GNUNET_CONTAINER_slist_append (to->handles, from->handles);
856 * Return file descriptor for this network handle
858 * @param desc wrapper to process
859 * @return POSIX file descriptor
862 GNUNET_NETWORK_get_fd (struct GNUNET_NETWORK_Handle *desc)
869 * Copy a native fd set
871 * @param to destination
872 * @param from native source set
873 * @param nfds the biggest socket number in from + 1
876 GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to,
877 const fd_set * from, int nfds)
879 FD_COPY (from, &to->sds);
885 * Set a native fd in a set
887 * @param to destination
888 * @param nfd native FD to set
891 GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to, int nfd)
893 GNUNET_assert ((nfd >= 0) && (nfd < FD_SETSIZE));
894 FD_SET (nfd, &to->sds);
895 to->nsds = GNUNET_MAX (nfd + 1, to->nsds);
900 * Test native fd in a set
902 * @param to set to test, NULL for empty set
903 * @param nfd native FD to test, or -1 for none
904 * @return GNUNET_YES if FD is set in the set
907 GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to,
910 if ((nfd == -1) || (to == NULL))
912 return FD_ISSET (nfd, &to->sds) ? GNUNET_YES : GNUNET_NO;
917 * Add a file handle to the fd set
919 * @param h the file handle to add
922 GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds,
923 const struct GNUNET_DISK_FileHandle *h)
926 GNUNET_CONTAINER_slist_add (fds->handles,
927 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT, h,
928 sizeof (struct GNUNET_DISK_FileHandle));
933 GNUNET_DISK_internal_file_handle_ (h, &fd, sizeof (int));
934 FD_SET (fd, &fds->sds);
935 if (fd + 1 > fds->nsds)
943 * Check if a file handle is part of an fd set
945 * @param h file handle
946 * @return GNUNET_YES if the file handle is part of the set
949 GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds,
950 const struct GNUNET_DISK_FileHandle *h)
954 return GNUNET_CONTAINER_slist_contains (fds->handles, h,
956 GNUNET_DISK_FileHandle));
958 return FD_ISSET (h->fd, &fds->sds);
964 * Checks if two fd sets overlap
965 * @param fds1 first fd set
966 * @param fds2 second fd set
967 * @return GNUNET_YES if they do overlap, GNUNET_NO otherwise
970 GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1,
971 const struct GNUNET_NETWORK_FDSet *fds2)
977 if (nfds > fds2->nsds)
982 if (FD_ISSET (nfds, &fds1->sds) && FD_ISSET (nfds, &fds2->sds))
986 struct GNUNET_CONTAINER_SList_Iterator it;
987 struct GNUNET_DISK_FileHandle *h;
991 /*This code is somewhat hacky, we are not supposed to know what's
992 * inside of fd_set; also the O(n^2) is really bad... */
994 for (i = 0; i < fds1->sds.fd_count; i++)
996 for (j = 0; j < fds2->sds.fd_count; j++)
998 if (fds1->sds.fd_array[i] == fds2->sds.fd_array[j])
1002 it = GNUNET_CONTAINER_slist_begin (fds1->handles);
1003 while (GNUNET_CONTAINER_slist_end (&it) != GNUNET_YES)
1006 struct GNUNET_CONTAINER_SList_Iterator t;
1008 h = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&it,
1011 LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking that FD 0x%x is in another set:\n",
1013 for (t = GNUNET_CONTAINER_slist_begin (fds2->handles);
1014 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1015 GNUNET_CONTAINER_slist_next (&t))
1017 struct GNUNET_DISK_FileHandle *fh;
1019 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1021 LOG (GNUNET_ERROR_TYPE_DEBUG, "0x%x\n", fh->h);
1024 if (GNUNET_CONTAINER_slist_contains
1025 (fds2->handles, h, sizeof (struct GNUNET_DISK_FileHandle)))
1029 GNUNET_CONTAINER_slist_next (&it);
1038 * @return a new fd set
1040 struct GNUNET_NETWORK_FDSet *
1041 GNUNET_NETWORK_fdset_create ()
1043 struct GNUNET_NETWORK_FDSet *fds;
1045 fds = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_FDSet));
1047 fds->handles = GNUNET_CONTAINER_slist_create ();
1049 GNUNET_NETWORK_fdset_zero (fds);
1055 * Releases the associated memory of an fd set
1059 GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds)
1062 GNUNET_CONTAINER_slist_destroy (fds->handles);
1068 * Check if sockets meet certain conditions
1069 * @param rfds set of sockets to be checked for readability
1070 * @param wfds set of sockets to be checked for writability
1071 * @param efds set of sockets to be checked for exceptions
1072 * @param timeout relative value when to return
1073 * @return number of selected sockets, GNUNET_SYSERR on error
1076 GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1077 struct GNUNET_NETWORK_FDSet *wfds,
1078 struct GNUNET_NETWORK_FDSet *efds,
1079 const struct GNUNET_TIME_Relative timeout)
1086 int read_handles = 0;
1087 int write_handles = 0;
1093 int nsock = 0, nhandles = 0, nSockEvents = 0;
1095 static HANDLE hEventRead = 0;
1096 static HANDLE hEventWrite = 0;
1097 static HANDLE hEventException = 0;
1098 static HANDLE hEventPipeWrite = 0;
1099 static HANDLE hEventReadReady = 0;
1102 int writePipePos = 0;
1104 HANDLE handle_array[FD_SETSIZE + 2];
1105 int returncode = -1;
1106 DWORD newretcode = 0;
1107 int returnedpos = 0;
1109 struct GNUNET_CONTAINER_SList *handles_read, *handles_write, *handles_except;
1111 fd_set aread, awrite, aexcept;
1114 fd_set bread, bwrite, bexcept;
1117 /* TODO: Make this growable */
1118 struct GNUNET_DISK_FileHandle *readArray[50];
1126 handles += read_handles = GNUNET_CONTAINER_slist_count (rfds->handles);
1129 struct GNUNET_CONTAINER_SList_Iterator t;
1131 for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1132 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1133 GNUNET_CONTAINER_slist_next (&t))
1135 struct GNUNET_DISK_FileHandle *fh;
1137 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1139 LOG (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x (0x%x) is SET in rfds\n", fh->h,
1148 nfds = GNUNET_MAX (nfds, wfds->nsds);
1150 handles += write_handles = GNUNET_CONTAINER_slist_count (wfds->handles);
1155 nfds = GNUNET_MAX (nfds, efds->nsds);
1157 handles += ex_handles = GNUNET_CONTAINER_slist_count (efds->handles);
1162 (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1168 LOG (GNUNET_ERROR_TYPE_ERROR,
1170 ("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1175 tv.tv_sec = timeout.rel_value / GNUNET_TIME_UNIT_SECONDS.rel_value;
1177 1000 * (timeout.rel_value -
1178 (tv.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value));
1179 return select (nfds, (rfds != NULL) ? &rfds->sds : NULL,
1180 (wfds != NULL) ? &wfds->sds : NULL,
1181 (efds != NULL) ? &efds->sds : NULL,
1182 (timeout.rel_value ==
1183 GNUNET_TIME_UNIT_FOREVER_REL.rel_value) ? NULL : &tv);
1186 #define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set))
1187 /* calculate how long we need to wait in milliseconds */
1188 if (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1189 ms_total = INFINITE;
1191 ms_total = timeout.rel_value / GNUNET_TIME_UNIT_MILLISECONDS.rel_value;
1192 /* select() may be used as a portable way to sleep */
1193 if (!(rfds || wfds || efds))
1199 /* Events for sockets */
1201 hEventRead = CreateEvent (NULL, TRUE, FALSE, NULL);
1203 ResetEvent (hEventRead);
1204 if (!hEventReadReady)
1205 hEventReadReady = CreateEvent (NULL, TRUE, TRUE, NULL);
1207 hEventWrite = CreateEvent (NULL, TRUE, FALSE, NULL);
1209 ResetEvent (hEventWrite);
1210 if (!hEventException)
1211 hEventException = CreateEvent (NULL, TRUE, FALSE, NULL);
1213 ResetEvent (hEventException);
1215 /* Event for pipes */
1216 if (!hEventPipeWrite)
1217 hEventPipeWrite = CreateEvent (NULL, TRUE, TRUE, NULL);
1221 handles_read = GNUNET_CONTAINER_slist_create ();
1222 handles_write = GNUNET_CONTAINER_slist_create ();
1223 handles_except = GNUNET_CONTAINER_slist_create ();
1234 FD_COPY (&rfds->sds, &aread);
1236 FD_COPY (&rfds->sds, &bread);
1241 FD_COPY (&wfds->sds, &awrite);
1243 FD_COPY (&wfds->sds, &bwrite);
1248 FD_COPY (&efds->sds, &aexcept);
1250 FD_COPY (&efds->sds, &bexcept);
1253 /* We will first Add the PIPES to the events */
1255 if (rfds && read_handles)
1257 struct GNUNET_CONTAINER_SList_Iterator i;
1259 for (i = GNUNET_CONTAINER_slist_begin (rfds->handles);
1260 GNUNET_CONTAINER_slist_end (&i) != GNUNET_YES;
1261 GNUNET_CONTAINER_slist_next (&i))
1263 struct GNUNET_DISK_FileHandle *fh;
1265 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&i,
1267 if (fh->type == GNUNET_PIPE)
1269 /* Read zero bytes to check the status of the pipe */
1270 LOG (GNUNET_ERROR_TYPE_DEBUG, "Reading 0 bytes from the pipe 0x%x\n",
1272 if (!ReadFile (fh->h, NULL, 0, NULL, fh->oOverlapRead))
1274 DWORD error_code = GetLastError ();
1276 if (error_code == ERROR_IO_PENDING)
1278 LOG (GNUNET_ERROR_TYPE_DEBUG,
1279 "Adding the pipe's 0x%x overlapped event to the array as %d\n",
1281 handle_array[nhandles++] = fh->oOverlapRead->hEvent;
1282 readArray[readPipes++] = fh;
1286 LOG (GNUNET_ERROR_TYPE_DEBUG,
1287 "Read failed, adding the read ready event to the array as %d\n", nhandles);
1288 handle_array[nhandles++] = hEventReadReady;
1289 readArray[readPipes++] = fh;
1294 LOG (GNUNET_ERROR_TYPE_DEBUG,
1295 "Adding the read ready event to the array as %d\n", nhandles);
1296 handle_array[nhandles++] = hEventReadReady;
1297 readArray[readPipes++] = fh;
1302 GNUNET_CONTAINER_slist_add (handles_read,
1303 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1304 fh, sizeof (struct GNUNET_DISK_FileHandle));
1308 if (wfds && write_handles)
1310 LOG (GNUNET_ERROR_TYPE_DEBUG,
1311 "Adding the write ready event to the array as %d\n", nhandles);
1312 handle_array[nhandles++] = hEventPipeWrite;
1313 writePipePos = nhandles;
1315 if (efds && ex_handles)
1317 struct GNUNET_CONTAINER_SList_Iterator i;
1319 for (i = GNUNET_CONTAINER_slist_begin (efds->handles);
1320 GNUNET_CONTAINER_slist_end (&i) != GNUNET_YES;
1321 GNUNET_CONTAINER_slist_next (&i))
1323 struct GNUNET_DISK_FileHandle *fh;
1326 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&i,
1328 if (fh->type == GNUNET_PIPE)
1330 if (!PeekNamedPipe (fh->h, NULL, 0, NULL, &dwBytes, NULL))
1332 GNUNET_CONTAINER_slist_add (handles_except,
1333 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1335 sizeof (struct GNUNET_DISK_FileHandle));
1345 LOG (GNUNET_ERROR_TYPE_DEBUG,
1346 "Adding the socket read event to the array as %d\n", nhandles);
1347 handle_array[nhandles++] = hEventRead;
1349 for (i = 0; i < rfds->sds.fd_count; i++)
1351 WSAEventSelect (rfds->sds.fd_array[i], hEventRead,
1352 FD_ACCEPT | FD_READ | FD_CLOSE);
1360 LOG (GNUNET_ERROR_TYPE_DEBUG,
1361 "Adding the socket write event to the array as %d\n", nhandles);
1362 handle_array[nhandles++] = hEventWrite;
1364 for (i = 0; i < wfds->sds.fd_count; i++)
1369 status = send (wfds->sds.fd_array[i], NULL, 0, 0);
1370 error = GetLastError ();
1371 LOG (GNUNET_ERROR_TYPE_DEBUG,
1372 "pre-send to the socket %d returned %d (%u)\n", i, status, error);
1373 if (status == 0 || (error != WSAEWOULDBLOCK && error != WSAENOTCONN))
1375 WSAEventSelect (wfds->sds.fd_array[i], hEventWrite,
1376 FD_WRITE | FD_CONNECT | FD_CLOSE);
1380 SetEvent (hEventWrite);
1384 LOG (GNUNET_ERROR_TYPE_DEBUG,
1385 "Adding the socket error event to the array as %d\n", nhandles);
1386 handle_array[nhandles++] = hEventException;
1388 for (i = 0; i < efds->sds.fd_count; i++)
1390 WSAEventSelect (efds->sds.fd_array[i], hEventException,
1397 handle_array[nhandles] = NULL;
1398 LOG (GNUNET_ERROR_TYPE_DEBUG,
1399 "Number nfds: %d, handles: %d, return code: %u will wait: %d ms\n",
1400 nfds, nhandles, newretcode, ms_total);
1403 WaitForMultipleObjects (nhandles, handle_array, FALSE, ms_total);
1404 LOG (GNUNET_ERROR_TYPE_DEBUG, "WaitForMultipleObjects Returned : %d\n",
1407 returnedpos = returncode - WAIT_OBJECT_0;
1408 LOG (GNUNET_ERROR_TYPE_DEBUG, "return pos is : %d\n", returnedpos);
1410 /* FIXME: THIS LINE IS WRONG !! We should add to handles only handles that fired the events, not all ! */
1413 * GNUNET_CONTAINER_slist_append (handles_read, rfds->handles);
1415 if (nhandles && (returnedpos < nhandles))
1422 struct timeval tvslice;
1425 tvslice.tv_usec = 10;
1426 retcode = select (nfds, &aread, &awrite, &aexcept, &tvslice);
1429 LOG (GNUNET_ERROR_TYPE_DEBUG, "Select retcode : %d\n", retcode);
1431 /* FIXME: <= writePipePos? Really? */
1432 if ((writePipePos != -1) && (returnedpos <= writePipePos))
1434 GNUNET_CONTAINER_slist_append (handles_write, wfds->handles);
1435 retcode += write_handles;
1436 LOG (GNUNET_ERROR_TYPE_DEBUG, "Added write pipe\n");
1438 LOG (GNUNET_ERROR_TYPE_DEBUG, "ReadPipes is : %d\n", readPipes);
1439 /* We have some pipes ready for read. */
1440 /* FIXME: it is supposed to work !! Only choose the Pipes who fired the event, but it is not working */
1442 if (returnedpos < readPipes)
1445 * for (i = 0; i < readPipes; i++)
1447 * waitstatus = WaitForSingleObject (handle_array[i], 0);
1448 * LOG (GNUNET_ERROR_TYPE_DEBUG, "Read pipe %d wait status is : %d\n", i, waitstatus);
1449 * if (waitstatus != WAIT_OBJECT_0)
1451 * GNUNET_CONTAINER_slist_add (handles_read,
1452 * GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1453 * readArray[i], sizeof (struct GNUNET_DISK_FileHandle));
1455 * LOG (GNUNET_ERROR_TYPE_DEBUG, "Added read Pipe\n");
1458 for (i = 0; i < readPipes; i++)
1466 PeekNamedPipe (readArray[i]->h, NULL, 0, NULL, &waitstatus, NULL);
1467 error = GetLastError ();
1468 LOG (GNUNET_ERROR_TYPE_DEBUG,
1469 "Peek at read pipe %d (0x%x) returned %d (%d bytes available) GLE %u\n",
1470 i, readArray[i]->h, bret, waitstatus, error);
1473 if (error != ERROR_BROKEN_PIPE)
1476 else if (waitstatus <= 0)
1478 GNUNET_CONTAINER_slist_add (handles_read,
1479 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1481 sizeof (struct GNUNET_DISK_FileHandle));
1483 LOG (GNUNET_ERROR_TYPE_DEBUG, "Added read Pipe 0x%x (0x%x)\n",
1484 readArray[i], readArray[i]->h);
1487 waitstatus = WaitForSingleObject (hEventWrite, 0);
1488 LOG (GNUNET_ERROR_TYPE_DEBUG, "Wait for the write event returned %d\n",
1490 if (waitstatus == WAIT_OBJECT_0)
1492 for (i = 0; i < wfds->sds.fd_count; i++)
1497 int sizeof_so_error = sizeof (so_error);
1499 getsockopt (wfds->sds.fd_array[i], SOL_SOCKET, SO_ERROR,
1500 (char *) &so_error, &sizeof_so_error);
1502 status = send (wfds->sds.fd_array[i], NULL, 0, 0);
1503 error = GetLastError ();
1504 LOG (GNUNET_ERROR_TYPE_DEBUG,
1505 "send to the socket %d returned %d (%u)\n", i, status, error);
1506 if (status == 0 || (error != WSAEWOULDBLOCK && error != WSAENOTCONN) ||
1507 (status == -1 && gso_result == 0 && error == WSAENOTCONN &&
1508 so_error == WSAECONNREFUSED))
1510 FD_SET (wfds->sds.fd_array[i], &awrite);
1516 if (!nhandles || (returnedpos >= nhandles))
1517 LOG (GNUNET_ERROR_TYPE_DEBUG, "Returning from _select() with nothing!\n");
1520 struct GNUNET_CONTAINER_SList_Iterator t;
1522 for (i = 0; i < rfds->sds.fd_count; i++)
1524 WSAEventSelect (rfds->sds.fd_array[i], hEventRead, 0);
1527 for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1528 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1529 GNUNET_CONTAINER_slist_next (&t))
1531 struct GNUNET_DISK_FileHandle *fh;
1533 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1535 if (fh->type == GNUNET_PIPE)
1540 LOG (GNUNET_ERROR_TYPE_DEBUG, "Zeroing rfds\n");
1541 GNUNET_NETWORK_fdset_zero (rfds);
1542 if (retcode != -1 && nhandles && (returnedpos < nhandles))
1543 GNUNET_NETWORK_fdset_copy_native (rfds, &aread, retcode);
1544 GNUNET_CONTAINER_slist_append (rfds->handles, handles_read);
1548 for (i = 0; i < wfds->sds.fd_count; i++)
1550 WSAEventSelect (wfds->sds.fd_array[i], hEventWrite, 0);
1553 LOG (GNUNET_ERROR_TYPE_DEBUG, "Zeroing wfds\n");
1554 GNUNET_NETWORK_fdset_zero (wfds);
1555 if (retcode != -1 && nhandles && (returnedpos < nhandles))
1556 GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, retcode);
1557 GNUNET_CONTAINER_slist_append (wfds->handles, handles_write);
1561 for (i = 0; i < efds->sds.fd_count; i++)
1563 WSAEventSelect (efds->sds.fd_array[i], hEventException, 0);
1566 LOG (GNUNET_ERROR_TYPE_DEBUG, "Zeroing efds\n");
1567 GNUNET_NETWORK_fdset_zero (efds);
1568 if (retcode != -1 && nhandles && (returnedpos < nhandles))
1569 GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, retcode);
1570 GNUNET_CONTAINER_slist_append (efds->handles, handles_except);
1572 GNUNET_CONTAINER_slist_destroy (handles_read);
1573 GNUNET_CONTAINER_slist_destroy (handles_write);
1574 GNUNET_CONTAINER_slist_destroy (handles_except);
1578 struct GNUNET_CONTAINER_SList_Iterator t;
1580 for (i = 0; i < bread.fd_count; i++)
1582 if (bread.fd_array[i] != 0)
1583 LOG (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x is %s in rfds\n",
1585 (SAFE_FD_ISSET (bread.fd_array[i], rfds)) ? "SET" : "NOT SET");
1587 for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1588 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1589 GNUNET_CONTAINER_slist_next (&t))
1591 struct GNUNET_DISK_FileHandle *fh;
1593 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1595 LOG (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x is SET in rfds\n", fh->h);
1600 for (i = 0; i < bwrite.fd_count; i++)
1602 if (bwrite.fd_array[i] != 0)
1603 LOG (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x is %s in wfds\n",
1605 (SAFE_FD_ISSET (bwrite.fd_array[i], rfds)) ? "SET" : "NOT SET");
1610 for (i = 0; i < bexcept.fd_count; i++)
1612 if (bexcept.fd_array[i] != 0)
1613 LOG (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x is %s in efds\n",
1614 bexcept.fd_array[i],
1615 (SAFE_FD_ISSET (bexcept.fd_array[i], rfds)) ? "SET" : "NOT SET");
1618 LOG (GNUNET_ERROR_TYPE_DEBUG, "Returning %d or 0\n", retcode);
1620 if (nhandles && (returnedpos < nhandles))
1627 /* end of network.c */