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
25 * @author Christian Grothoff
29 #include "gnunet_util_lib.h"
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
32 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
35 #define DEBUG_NETWORK GNUNET_EXTRA_LOGGING
38 #ifndef INVALID_SOCKET
39 #define INVALID_SOCKET -1
43 struct GNUNET_NETWORK_Handle
52 * Address family / domain.
57 * Number of bytes in addr.
62 * Address we were bound to, or NULL.
64 struct sockaddr *addr;
70 * Given a unixpath that is too long (larger than UNIX_PATH_MAX),
71 * shorten it to an acceptable length while keeping it unique
72 * and making sure it remains a valid filename (if possible).
74 * @param unixpath long path, will be freed (or same pointer returned
75 * with moved 0-termination).
76 * @return shortened unixpath, NULL on error
79 GNUNET_NETWORK_shorten_unixpath (char *unixpath)
81 struct sockaddr_un dummy;
84 struct GNUNET_CRYPTO_ShortHashCode sh;
85 struct GNUNET_CRYPTO_ShortHashAsciiEncoded ae;
88 upm = sizeof (dummy.sun_path);
89 slen = strlen (unixpath);
91 return unixpath; /* no shortening required */
92 GNUNET_CRYPTO_short_hash (unixpath, slen, &sh);
93 while (sizeof (struct GNUNET_CRYPTO_ShortHashAsciiEncoded) +
94 strlen (unixpath) >= upm)
96 if (NULL == (end = strrchr (unixpath, '/')))
98 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
99 _("Unable to shorten unix path `%s' while keeping name unique\n"),
101 GNUNET_free (unixpath);
106 GNUNET_CRYPTO_short_hash_to_enc (&sh, &ae);
107 strcat (unixpath, (char*) ae.short_encoding);
113 #define FD_COPY(s, d) (memcpy ((d), (s), sizeof (fd_set)))
118 * Set if a socket should use blocking or non-blocking IO.
120 * @param doBlock blocking mode
121 * @return GNUNET_OK on success, GNUNET_SYSERR on error
124 socket_set_blocking (struct GNUNET_NETWORK_Handle *fd, int doBlock)
131 if (ioctlsocket (fd->fd, FIONBIO, &mode) == SOCKET_ERROR)
134 SetErrnoFromWinsockError (WSAGetLastError ());
135 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "ioctlsocket");
136 return GNUNET_SYSERR;
142 int flags = fcntl (fd->fd, F_GETFL);
147 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "fcntl");
148 return GNUNET_SYSERR;
151 flags &= ~O_NONBLOCK;
155 if (0 != fcntl (fd->fd, F_SETFL, flags))
158 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "fcntl");
159 return GNUNET_SYSERR;
168 * Make a socket non-inheritable to child processes
170 * @param h the socket to make non-inheritable
171 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
172 * @warning Not implemented on Windows
175 socket_set_inheritable (const struct GNUNET_NETWORK_Handle *h)
179 i = fcntl (h->fd, F_GETFD);
181 return GNUNET_SYSERR;
182 if (i == (i | FD_CLOEXEC))
185 if (fcntl (h->fd, F_SETFD, i) < 0)
186 return GNUNET_SYSERR;
194 * The MSG_NOSIGNAL equivalent on Mac OS X
196 * @param h the socket to make non-delaying
199 socket_set_nosigpipe (const struct GNUNET_NETWORK_Handle *h)
204 setsockopt (h->fd, SOL_SOCKET, SO_NOSIGPIPE, &abs_value,
206 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
212 * Disable delays when sending data via the socket.
213 * (GNUnet makes sure that messages are as big as
216 * @param h the socket to make non-delaying
219 socket_set_nodelay (const struct GNUNET_NETWORK_Handle *h)
224 if (0 != setsockopt (h->fd, IPPROTO_TCP, TCP_NODELAY, &value, sizeof (value)))
225 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
227 const char *abs_value = "1";
230 setsockopt (h->fd, IPPROTO_TCP, TCP_NODELAY, abs_value,
232 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
238 * Perform proper canonical initialization for a network handle.
239 * Set it to non-blocking, make it non-inheritable to child
240 * processes, disable SIGPIPE, enable "nodelay" (if non-UNIX
241 * stream socket) and check that it is smaller than FS_SETSIZE.
243 * @param h socket to initialize
244 * @param af address family of the socket
245 * @param type socket type
246 * @return GNUNET_OK on success, GNUNET_SYSERR if initialization
247 * failed and the handle was destroyed
250 initialize_network_handle (struct GNUNET_NETWORK_Handle *h,
254 if (h->fd == INVALID_SOCKET)
257 SetErrnoFromWinsockError (WSAGetLastError ());
260 return GNUNET_SYSERR;
263 if (h->fd >= FD_SETSIZE)
265 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
267 return GNUNET_SYSERR;
269 if (GNUNET_OK != socket_set_inheritable (h))
270 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
271 "socket_set_inheritable");
273 if (GNUNET_SYSERR == socket_set_blocking (h, GNUNET_NO))
276 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
277 return GNUNET_SYSERR;
280 socket_set_nosigpipe (h);
282 if ( (type == SOCK_STREAM)
287 socket_set_nodelay (h);
293 * accept a new connection on a socket
295 * @param desc bound socket
296 * @param address address of the connecting peer, may be NULL
297 * @param address_len length of address
298 * @return client socket
300 struct GNUNET_NETWORK_Handle *
301 GNUNET_NETWORK_socket_accept (const struct GNUNET_NETWORK_Handle *desc,
302 struct sockaddr *address, socklen_t * address_len)
304 struct GNUNET_NETWORK_Handle *ret;
306 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
309 struct sockaddr name;
310 socklen_t namelen = sizeof (name);
311 int gsn = getsockname (desc->fd, &name, &namelen);
314 LOG (GNUNET_ERROR_TYPE_DEBUG, "Accepting connection on `%s'\n",
315 GNUNET_a2s (&name, namelen));
318 ret->fd = accept (desc->fd, address, address_len);
319 if (GNUNET_OK != initialize_network_handle (ret,
320 (NULL != address) ? address->sa_family : desc->af,
328 * Bind to a connected socket
330 * @param address address to be bound
331 * @param address_len length of address
332 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
335 GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc,
336 const struct sockaddr *address,
337 socklen_t address_len)
345 if (desc->af == AF_INET6)
346 if (0 != setsockopt (desc->fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
347 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG, "setsockopt");
351 /* This is required, and required here, but only on UNIX */
352 if (0 != setsockopt (desc->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)))
353 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG, "setsockopt");
357 if (address->sa_family == AF_UNIX)
359 const struct sockaddr_un *un = (const struct sockaddr_un *) address;
361 (void) unlink (un->sun_path);
365 ret = bind (desc->fd, address, address_len);
367 if (SOCKET_ERROR == ret)
368 SetErrnoFromWinsockError (WSAGetLastError ());
371 return GNUNET_SYSERR;
374 desc->addr = GNUNET_malloc (address_len);
375 memcpy (desc->addr, address, address_len);
376 desc->addrlen = address_len;
386 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
389 GNUNET_NETWORK_socket_close (struct GNUNET_NETWORK_Handle *desc)
397 ret = closesocket (desc->fd);
398 error = WSAGetLastError ();
399 SetErrnoFromWinsockError (error);
400 LOG (GNUNET_ERROR_TYPE_DEBUG,
401 "Closed 0x%x, closesocket() returned %d, GLE is %u\n", desc->fd, ret,
404 ret = close (desc->fd);
408 if ((desc->af == AF_UNIX) && (NULL != desc->addr))
410 const struct sockaddr_un *un = (const struct sockaddr_un *) desc->addr;
412 if (0 != unlink (un->sun_path))
413 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", un->sun_path);
417 GNUNET_free_non_null (desc->addr);
419 return (ret == 0) ? GNUNET_OK : GNUNET_SYSERR;
424 * Box a native socket (and check that it is a socket).
426 * @param fd socket to box
427 * @return NULL on error (including not supported on target platform)
429 struct GNUNET_NETWORK_Handle *
430 GNUNET_NETWORK_socket_box_native (SOCKTYPE fd)
432 struct GNUNET_NETWORK_Handle *ret;
436 /* FIXME: Find a better call to check that FD is valid */
437 if (WSAIoctl (fd, FIONBIO, (void *) &i, sizeof (i), NULL, 0, &d, NULL, NULL) != 0)
438 return NULL; /* invalid FD */
439 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
444 if (fcntl (fd, F_GETFD) < 0)
445 return NULL; /* invalid FD */
446 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
457 * @param address peer address
458 * @param address_len length of address
459 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
462 GNUNET_NETWORK_socket_connect (const struct GNUNET_NETWORK_Handle *desc,
463 const struct sockaddr *address,
464 socklen_t address_len)
468 ret = connect (desc->fd, address, address_len);
471 if (SOCKET_ERROR == ret)
473 SetErrnoFromWinsockError (WSAGetLastError ());
474 if (errno == EWOULDBLOCK)
478 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
486 * @param level protocol level of the option
487 * @param optname identifier of the option
488 * @param optval options
489 * @param optlen length of optval
490 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
493 GNUNET_NETWORK_socket_getsockopt (const struct GNUNET_NETWORK_Handle *desc,
494 int level, int optname, void *optval,
499 ret = getsockopt (desc->fd, level, optname, optval, optlen);
502 if (ret == 0 && level == SOL_SOCKET && optname == SO_ERROR)
503 *((int *) optval) = GetErrnoFromWinsockError (*((int *) optval));
505 else if (SOCKET_ERROR == ret)
506 SetErrnoFromWinsockError (WSAGetLastError ());
508 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
515 * @param backlog length of the listen queue
516 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
519 GNUNET_NETWORK_socket_listen (const struct GNUNET_NETWORK_Handle *desc,
524 ret = listen (desc->fd, backlog);
527 if (SOCKET_ERROR == ret)
528 SetErrnoFromWinsockError (WSAGetLastError ());
531 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
536 * How much data is available to be read on this descriptor?
538 * Returns GNUNET_NO if no data is available, or on error!
542 GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle *
547 /* How much is there to be read? */
551 error = ioctl (desc->fd, FIONREAD, &pending);
553 return (ssize_t) pending;
558 error = ioctlsocket (desc->fd, FIONREAD, &pending);
559 if (error != SOCKET_ERROR)
560 return (ssize_t) pending;
567 * Read data from a connected socket (always non-blocking).
569 * @param buffer buffer
570 * @param length length of buffer
571 * @param src_addr either the source to recv from, or all zeroes
572 * to be filled in by recvfrom
573 * @param addrlen length of the addr
576 GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle * desc,
577 void *buffer, size_t length,
578 struct sockaddr * src_addr, socklen_t * addrlen)
586 flags |= MSG_DONTWAIT;
589 ret = recvfrom (desc->fd, buffer, length, flags, src_addr, addrlen);
591 if (SOCKET_ERROR == ret)
592 SetErrnoFromWinsockError (WSAGetLastError ());
599 * Read data from a connected socket (always non-blocking).
601 * @param buffer buffer
602 * @param length length of buffer
605 GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle * desc,
606 void *buffer, size_t length)
614 flags |= MSG_DONTWAIT;
616 ret = recv (desc->fd, buffer, length, flags);
618 if (SOCKET_ERROR == ret)
619 SetErrnoFromWinsockError (WSAGetLastError ());
626 * Send data (always non-blocking).
629 * @param buffer data to send
630 * @param length size of the buffer
631 * @return number of bytes sent, GNUNET_SYSERR on error
634 GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle * desc,
635 const void *buffer, size_t length)
643 flags |= MSG_DONTWAIT;
647 flags |= MSG_NOSIGNAL;
650 ret = send (desc->fd, buffer, length, flags);
653 if (SOCKET_ERROR == ret)
654 SetErrnoFromWinsockError (WSAGetLastError ());
662 * Send data to a particular destination (always non-blocking).
663 * This function only works for UDP sockets.
666 * @param message data to send
667 * @param length size of the data
668 * @param dest_addr destination address
669 * @param dest_len length of address
670 * @return number of bytes sent, GNUNET_SYSERR on error
673 GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle * desc,
674 const void *message, size_t length,
675 const struct sockaddr * dest_addr,
684 flags |= MSG_DONTWAIT;
687 flags |= MSG_NOSIGNAL;
689 ret = sendto (desc->fd, message, length, flags, dest_addr, dest_len);
691 if (SOCKET_ERROR == ret)
692 SetErrnoFromWinsockError (WSAGetLastError ());
701 * @param level protocol level of the option
702 * @param option_name option identifier
703 * @param option_value value to set
704 * @param option_len size of option_value
705 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
708 GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd, int level,
709 int option_name, const void *option_value,
710 socklen_t option_len)
714 ret = setsockopt (fd->fd, level, option_name, option_value, option_len);
716 if (SOCKET_ERROR == ret)
717 SetErrnoFromWinsockError (WSAGetLastError ());
719 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
724 * Create a new socket. Configure it for non-blocking IO and
725 * mark it as non-inheritable to child processes (set the
726 * close-on-exec flag).
728 * @param domain domain of the socket
729 * @param type socket type
730 * @param protocol network protocol
731 * @return new socket, NULL on error
733 struct GNUNET_NETWORK_Handle *
734 GNUNET_NETWORK_socket_create (int domain, int type, int protocol)
736 struct GNUNET_NETWORK_Handle *ret;
738 ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
739 ret->fd = socket (domain, type, protocol);
741 initialize_network_handle (ret, domain, type))
748 * Shut down socket operations
750 * @param how type of shutdown
751 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
754 GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc, int how)
758 ret = shutdown (desc->fd, how);
761 SetErrnoFromWinsockError (WSAGetLastError ());
763 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
768 * Disable the "CORK" feature for communication with the given socket,
769 * forcing the OS to immediately flush the buffer on transmission
770 * instead of potentially buffering multiple messages. Essentially
771 * reduces the OS send buffers to zero.
774 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
777 GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc)
786 setsockopt (desc->fd, SOL_SOCKET, SO_SNDBUF, (char *) &value,
788 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
791 setsockopt (desc->fd, SOL_SOCKET, SO_RCVBUF, (char *) &value,
793 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
799 setsockopt (desc->fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof (value))))
800 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
803 setsockopt (desc->fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof (value))))
804 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
806 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
815 GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds)
820 GNUNET_CONTAINER_slist_clear (fds->handles);
825 * Add a socket to the FD set
827 * @param desc socket to add
830 GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds,
831 const struct GNUNET_NETWORK_Handle *desc)
833 FD_SET (desc->fd, &fds->sds);
834 if (desc->fd + 1 > fds->nsds)
835 fds->nsds = desc->fd + 1;
840 * Check whether a socket is part of the fd set
843 * @return 0 if the FD is not set
846 GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds,
847 const struct GNUNET_NETWORK_Handle *desc)
849 return FD_ISSET (desc->fd, &fds->sds);
854 * Add one fd set to another
855 * @param dst the fd set to add to
856 * @param src the fd set to add from
859 GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst,
860 const struct GNUNET_NETWORK_FDSet *src)
864 for (nfds = src->nsds; nfds > 0; nfds--)
865 if (FD_ISSET (nfds, &src->sds))
868 FD_SET (nfds, &dst->sds);
869 if (nfds + 1 > dst->nsds)
870 dst->nsds = nfds + 1;
873 GNUNET_CONTAINER_slist_append (dst->handles, src->handles);
879 * Copy one fd set to another
881 * @param to destination
885 GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to,
886 const struct GNUNET_NETWORK_FDSet *from)
888 FD_COPY (&from->sds, &to->sds);
889 to->nsds = from->nsds;
892 GNUNET_CONTAINER_slist_clear (to->handles);
893 GNUNET_CONTAINER_slist_append (to->handles, from->handles);
899 * Return file descriptor for this network handle
901 * @param desc wrapper to process
902 * @return POSIX file descriptor
905 GNUNET_NETWORK_get_fd (struct GNUNET_NETWORK_Handle *desc)
911 * Return sockaddr for this network handle
913 * @param desc wrapper to process
917 GNUNET_NETWORK_get_addr (struct GNUNET_NETWORK_Handle *desc)
923 * Return sockaddr length for this network handle
925 * @param desc wrapper to process
926 * @return socklen_t for sockaddr
929 GNUNET_NETWORK_get_addrlen (struct GNUNET_NETWORK_Handle *desc)
931 return desc->addrlen;
934 * Copy a native fd set
936 * @param to destination
937 * @param from native source set
938 * @param nfds the biggest socket number in from + 1
941 GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to,
942 const fd_set * from, int nfds)
944 FD_COPY (from, &to->sds);
950 * Set a native fd in a set
952 * @param to destination
953 * @param nfd native FD to set
956 GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to, int nfd)
958 GNUNET_assert ((nfd >= 0) && (nfd < FD_SETSIZE));
959 FD_SET (nfd, &to->sds);
960 to->nsds = GNUNET_MAX (nfd + 1, to->nsds);
965 * Test native fd in a set
967 * @param to set to test, NULL for empty set
968 * @param nfd native FD to test, or -1 for none
969 * @return GNUNET_YES if FD is set in the set
972 GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to,
975 if ((nfd == -1) || (to == NULL))
977 return FD_ISSET (nfd, &to->sds) ? GNUNET_YES : GNUNET_NO;
982 * Add a file handle to the fd set
984 * @param h the file handle to add
987 GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds,
988 const struct GNUNET_DISK_FileHandle *h)
991 GNUNET_CONTAINER_slist_add (fds->handles,
992 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT, h,
993 sizeof (struct GNUNET_DISK_FileHandle));
998 GNUNET_DISK_internal_file_handle_ (h, &fd, sizeof (int));
999 FD_SET (fd, &fds->sds);
1000 if (fd + 1 > fds->nsds)
1008 * Check if a file handle is part of an fd set
1010 * @param h file handle
1011 * @return GNUNET_YES if the file handle is part of the set
1014 GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds,
1015 const struct GNUNET_DISK_FileHandle *h)
1019 return GNUNET_CONTAINER_slist_contains (fds->handles, h,
1021 GNUNET_DISK_FileHandle));
1023 return FD_ISSET (h->fd, &fds->sds);
1029 * Checks if two fd sets overlap
1030 * @param fds1 first fd set
1031 * @param fds2 second fd set
1032 * @return GNUNET_YES if they do overlap, GNUNET_NO otherwise
1035 GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1,
1036 const struct GNUNET_NETWORK_FDSet *fds2)
1042 if (nfds > fds2->nsds)
1047 if (FD_ISSET (nfds, &fds1->sds) && FD_ISSET (nfds, &fds2->sds))
1051 struct GNUNET_CONTAINER_SList_Iterator it;
1052 struct GNUNET_DISK_FileHandle *h;
1056 /*This code is somewhat hacky, we are not supposed to know what's
1057 * inside of fd_set; also the O(n^2) is really bad... */
1059 for (i = 0; i < fds1->sds.fd_count; i++)
1061 for (j = 0; j < fds2->sds.fd_count; j++)
1063 if (fds1->sds.fd_array[i] == fds2->sds.fd_array[j])
1067 it = GNUNET_CONTAINER_slist_begin (fds1->handles);
1068 while (GNUNET_CONTAINER_slist_end (&it) != GNUNET_YES)
1071 struct GNUNET_CONTAINER_SList_Iterator t;
1073 h = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&it,
1076 LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking that FD 0x%x is in another set:\n",
1078 for (t = GNUNET_CONTAINER_slist_begin (fds2->handles);
1079 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1080 GNUNET_CONTAINER_slist_next (&t))
1082 struct GNUNET_DISK_FileHandle *fh;
1084 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1086 LOG (GNUNET_ERROR_TYPE_DEBUG, "0x%x\n", fh->h);
1089 if (GNUNET_CONTAINER_slist_contains
1090 (fds2->handles, h, sizeof (struct GNUNET_DISK_FileHandle)))
1094 GNUNET_CONTAINER_slist_next (&it);
1103 * @return a new fd set
1105 struct GNUNET_NETWORK_FDSet *
1106 GNUNET_NETWORK_fdset_create ()
1108 struct GNUNET_NETWORK_FDSet *fds;
1110 fds = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_FDSet));
1112 fds->handles = GNUNET_CONTAINER_slist_create ();
1114 GNUNET_NETWORK_fdset_zero (fds);
1120 * Releases the associated memory of an fd set
1124 GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds)
1127 GNUNET_CONTAINER_slist_destroy (fds->handles);
1133 struct _select_params
\r
1138 struct timeval *tv;
\r
1141 SOCKET wakeup_socket;
\r
1145 static DWORD WINAPI
\r
1146 _selector (LPVOID p)
\r
1148 struct _select_params *sp = p;
\r
1152 WaitForSingleObject (sp->standby, INFINITE);
\r
1153 ResetEvent (sp->standby);
\r
1154 sp->status = select (1, sp->r, sp->w, sp->e, sp->tv);
\r
1155 if (FD_ISSET (sp->wakeup_socket, sp->r))
\r
1157 FD_CLR (sp->wakeup_socket, sp->r);
\r
1160 SetEvent (sp->wakeup);
\r
1167 * Check if sockets or pipes meet certain conditions
1168 * @param rfds set of sockets or pipes to be checked for readability
1169 * @param wfds set of sockets or pipes to be checked for writability
1170 * @param efds set of sockets or pipes to be checked for exceptions
1171 * @param timeout relative value when to return
1172 * @return number of selected sockets or pipes, GNUNET_SYSERR on error
1175 GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1176 struct GNUNET_NETWORK_FDSet *wfds,
1177 struct GNUNET_NETWORK_FDSet *efds,
1178 const struct GNUNET_TIME_Relative timeout)
1184 int read_handles = 0;
1185 int write_handles = 0;
1193 static HANDLE hEventPipeWrite = 0;
1194 static HANDLE hEventReadReady = 0;
1196 static struct _select_params sp;
\r
1197 static HANDLE select_thread = NULL;
1198 static HANDLE select_finished_event = NULL;
1199 static HANDLE select_standby_event = NULL;
1200 static SOCKET select_wakeup_socket = -1;
\r
1201 static SOCKET select_send_socket = -1;
\r
1202 static struct timeval select_timeout;
1205 int writePipePos = 0;
1207 HANDLE handle_array[FD_SETSIZE + 2];
1208 int returncode = -1;
1209 int returnedpos = 0;
1211 struct GNUNET_CONTAINER_SList *handles_read;
1212 struct GNUNET_CONTAINER_SList *handles_write;
1213 struct GNUNET_CONTAINER_SList *handles_except;
1225 /* TODO: Make this growable */
1226 struct GNUNET_DISK_FileHandle *readArray[50];
1234 handles += read_handles = GNUNET_CONTAINER_slist_count (rfds->handles);
1237 struct GNUNET_CONTAINER_SList_Iterator t;
1239 for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1240 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1241 GNUNET_CONTAINER_slist_next (&t))
1243 struct GNUNET_DISK_FileHandle *fh;
1245 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1247 LOG (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x (0x%x) is SET in rfds\n", fh->h,
1256 nfds = GNUNET_MAX (nfds, wfds->nsds);
1258 handles += write_handles = GNUNET_CONTAINER_slist_count (wfds->handles);
1263 nfds = GNUNET_MAX (nfds, efds->nsds);
1265 handles += ex_handles = GNUNET_CONTAINER_slist_count (efds->handles);
1270 (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1276 LOG (GNUNET_ERROR_TYPE_ERROR,
1278 ("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1283 tv.tv_sec = timeout.rel_value / GNUNET_TIME_UNIT_SECONDS.rel_value;
1285 1000 * (timeout.rel_value -
1286 (tv.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value));
1287 return select (nfds, (rfds != NULL) ? &rfds->sds : NULL,
1288 (wfds != NULL) ? &wfds->sds : NULL,
1289 (efds != NULL) ? &efds->sds : NULL,
1290 (timeout.rel_value ==
1291 GNUNET_TIME_UNIT_FOREVER_REL.rel_value) ? NULL : &tv);
1294 #define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set))
1295 /* calculate how long we need to wait in milliseconds */
1296 if (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1297 ms_total = INFINITE;
1299 ms_total = timeout.rel_value / GNUNET_TIME_UNIT_MILLISECONDS.rel_value;
1300 /* select() may be used as a portable way to sleep */
1301 if (!(rfds || wfds || efds))
1307 if (select_thread == NULL)
1309 SOCKET select_listening_socket = -1;
\r
1310 struct sockaddr_in s_in;
\r
1315 select_standby_event = CreateEvent (NULL, TRUE, FALSE, NULL);
\r
1316 select_finished_event = CreateEvent (NULL, TRUE, FALSE, NULL);
\r
1318 select_wakeup_socket = WSASocket (AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
\r
1320 select_listening_socket = WSASocket (AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
\r
1323 res = ioctlsocket (select_wakeup_socket, FIONBIO, &p);
\r
1325 alen = sizeof (s_in);
\r
1326 s_in.sin_family = AF_INET;
\r
1327 s_in.sin_port = 0;
\r
1328 s_in.sin_addr.S_un.S_un_b.s_b1 = 127;
\r
1329 s_in.sin_addr.S_un.S_un_b.s_b2 = 0;
\r
1330 s_in.sin_addr.S_un.S_un_b.s_b3 = 0;
\r
1331 s_in.sin_addr.S_un.S_un_b.s_b4 = 1;
\r
1332 res = bind (select_listening_socket, (const struct sockaddr *) &s_in, sizeof (s_in));
\r
1334 res = getsockname (select_listening_socket, (struct sockaddr *) &s_in, &alen);
\r
1336 res = listen (select_listening_socket, SOMAXCONN);
\r
1338 res = connect (select_wakeup_socket, (const struct sockaddr *) &s_in, sizeof (s_in));
\r
1340 select_send_socket = accept (select_listening_socket, (struct sockaddr *) &s_in, &alen);
\r
1342 closesocket (select_listening_socket);
\r
1344 sp.wakeup = select_finished_event;
\r
1345 sp.standby = select_standby_event;
\r
1346 sp.wakeup_socket = select_wakeup_socket;
1348 select_thread = CreateThread (NULL, 0, _selector, &sp, 0, NULL);
\r
1351 /* Events for pipes */
1352 if (!hEventReadReady)
1353 hEventReadReady = CreateEvent (NULL, TRUE, TRUE, NULL);
1354 if (!hEventPipeWrite)
1355 hEventPipeWrite = CreateEvent (NULL, TRUE, TRUE, NULL);
1359 handles_read = GNUNET_CONTAINER_slist_create ();
1360 handles_write = GNUNET_CONTAINER_slist_create ();
1361 handles_except = GNUNET_CONTAINER_slist_create ();
1372 FD_COPY (&rfds->sds, &aread);
1374 FD_COPY (&rfds->sds, &bread);
1379 FD_COPY (&wfds->sds, &awrite);
1381 FD_COPY (&wfds->sds, &bwrite);
1386 FD_COPY (&efds->sds, &aexcept);
1388 FD_COPY (&efds->sds, &bexcept);
1391 /* We will first Add the PIPES to the events */
1393 if (rfds && read_handles)
1395 struct GNUNET_CONTAINER_SList_Iterator i;
1397 for (i = GNUNET_CONTAINER_slist_begin (rfds->handles);
1398 GNUNET_CONTAINER_slist_end (&i) != GNUNET_YES;
1399 GNUNET_CONTAINER_slist_next (&i))
1401 struct GNUNET_DISK_FileHandle *fh;
1403 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&i,
1405 if (fh->type == GNUNET_PIPE)
1407 /* Read zero bytes to check the status of the pipe */
1408 LOG (GNUNET_ERROR_TYPE_DEBUG, "Reading 0 bytes from the pipe 0x%x\n",
1410 if (!ReadFile (fh->h, NULL, 0, NULL, fh->oOverlapRead))
1412 DWORD error_code = GetLastError ();
1414 if (error_code == ERROR_IO_PENDING)
1416 LOG (GNUNET_ERROR_TYPE_DEBUG,
1417 "Adding the pipe's 0x%x overlapped event to the array as %d\n",
1419 handle_array[nhandles++] = fh->oOverlapRead->hEvent;
1420 readArray[readPipes++] = fh;
1424 LOG (GNUNET_ERROR_TYPE_DEBUG,
1425 "Read failed, adding the read ready event to the array as %d\n", nhandles);
1426 handle_array[nhandles++] = hEventReadReady;
1427 readArray[readPipes++] = fh;
1432 LOG (GNUNET_ERROR_TYPE_DEBUG,
1433 "Adding the read ready event to the array as %d\n", nhandles);
1434 handle_array[nhandles++] = hEventReadReady;
1435 readArray[readPipes++] = fh;
1440 GNUNET_CONTAINER_slist_add (handles_read,
1441 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1442 fh, sizeof (struct GNUNET_DISK_FileHandle));
1446 if (wfds && write_handles)
1448 LOG (GNUNET_ERROR_TYPE_DEBUG,
1449 "Adding the write ready event to the array as %d\n", nhandles);
1450 handle_array[nhandles++] = hEventPipeWrite;
1451 writePipePos = nhandles;
1453 if (efds && ex_handles)
1455 struct GNUNET_CONTAINER_SList_Iterator i;
1457 for (i = GNUNET_CONTAINER_slist_begin (efds->handles);
1458 GNUNET_CONTAINER_slist_end (&i) != GNUNET_YES;
1459 GNUNET_CONTAINER_slist_next (&i))
1461 struct GNUNET_DISK_FileHandle *fh;
1464 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&i,
1466 if (fh->type == GNUNET_PIPE)
1468 if (!PeekNamedPipe (fh->h, NULL, 0, NULL, &dwBytes, NULL))
1470 GNUNET_CONTAINER_slist_add (handles_except,
1471 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1473 sizeof (struct GNUNET_DISK_FileHandle));
1483 LOG (GNUNET_ERROR_TYPE_DEBUG,
1484 "Adding the socket event to the array as %d\n", nhandles);
1485 handle_array[nhandles++] = select_finished_event;
1486 if (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1490 select_timeout.tv_sec = timeout.rel_value / GNUNET_TIME_UNIT_SECONDS.rel_value;
1491 select_timeout.tv_usec = 1000 * (timeout.rel_value -
1492 (select_timeout.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value));
1493 sp.tv = &select_timeout;
1495 FD_SET (select_wakeup_socket, &aread);
1499 /* Failed connections cause sockets to be set in errorfds on W32,
1500 * but on POSIX it should set them in writefds.
1501 * First copy all awrite sockets to aexcept, later we'll
1502 * check aexcept and set its contents in awrite as well
1503 * Sockets are also set in errorfds when OOB data is available,
1504 * but we don't use OOB data.
1506 for (i = 0; i < awrite.fd_count; i++)
1508 if (awrite.fd_array[i] != 0 && awrite.fd_array[i] != -1)
1509 FD_SET (awrite.fd_array[i], &aexcept);
1511 ResetEvent (select_finished_event);
1512 SetEvent (select_standby_event);
1515 handle_array[nhandles] = NULL;
1516 LOG (GNUNET_ERROR_TYPE_DEBUG, "nfds: %d, handles: %d, will wait: %d ms\n",
1517 nfds, nhandles, ms_total);
1520 WaitForMultipleObjects (nhandles, handle_array, FALSE, ms_total);
1521 LOG (GNUNET_ERROR_TYPE_DEBUG, "WaitForMultipleObjects Returned : %d\n",
1526 /* Don't wake up select-thread when delay is 0, it should return immediately
1527 * and wake up by itself.
1530 i = send (select_send_socket, (const char *) &returnedpos, 1, 0);
\r
1531 i = (int) WaitForSingleObject (select_finished_event, INFINITE);
\r
1532 LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished waiting for the select thread: %d %d\n", i, sp.status);
1537 i = recv (select_wakeup_socket, (char *) &returnedpos, 1, 0);
\r
1540 /* Check aexcept, add its contents to awrite */
1541 for (i = 0; i < aexcept.fd_count; i++)
1543 if (aexcept.fd_array[i] != 0 && aexcept.fd_array[i] != -1)
1544 FD_SET (aexcept.fd_array[i], &awrite);
1548 returnedpos = returncode - WAIT_OBJECT_0;
1549 LOG (GNUNET_ERROR_TYPE_DEBUG, "return pos is : %d\n", returnedpos);
1551 if (nhandles && (returnedpos < nhandles))
1556 retcode += sp.status;
1558 if ((writePipePos != -1) && (returnedpos < writePipePos))
1560 GNUNET_CONTAINER_slist_append (handles_write, wfds->handles);
1561 retcode += write_handles;
1562 LOG (GNUNET_ERROR_TYPE_DEBUG, "Added write pipe\n");
1564 LOG (GNUNET_ERROR_TYPE_DEBUG, "ReadPipes is : %d\n", readPipes);
1565 /* We have some pipes ready for read. */
1566 if (returnedpos < readPipes)
1568 for (i = 0; i < readPipes; i++)
1576 PeekNamedPipe (readArray[i]->h, NULL, 0, NULL, &waitstatus, NULL);
1577 error = GetLastError ();
1578 LOG (GNUNET_ERROR_TYPE_DEBUG,
1579 "Peek at read pipe %d (0x%x) returned %d (%d bytes available) GLE %u\n",
1580 i, readArray[i]->h, bret, waitstatus, error);
1583 if (error != ERROR_BROKEN_PIPE)
1586 else if (waitstatus <= 0)
1588 GNUNET_CONTAINER_slist_add (handles_read,
1589 GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1591 sizeof (struct GNUNET_DISK_FileHandle));
1593 LOG (GNUNET_ERROR_TYPE_DEBUG, "Added read Pipe 0x%x (0x%x)\n",
1594 readArray[i], readArray[i]->h);
1598 if (!nhandles || (returnedpos >= nhandles))
1599 LOG (GNUNET_ERROR_TYPE_DEBUG, "Returning from _select() with nothing!\n");
1602 struct GNUNET_CONTAINER_SList_Iterator t;
1604 for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1605 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1606 GNUNET_CONTAINER_slist_next (&t))
1608 struct GNUNET_DISK_FileHandle *fh;
1610 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1612 if (fh->type == GNUNET_PIPE)
1617 LOG (GNUNET_ERROR_TYPE_DEBUG, "Zeroing rfds%s\n", (retcode != -1 && nhandles && (returnedpos < nhandles)) ? ", copying fdset" : "");
1618 GNUNET_NETWORK_fdset_zero (rfds);
1619 if (retcode != -1 && nhandles && (returnedpos < nhandles))
1620 GNUNET_NETWORK_fdset_copy_native (rfds, &aread, retcode);
1621 GNUNET_CONTAINER_slist_append (rfds->handles, handles_read);
1625 LOG (GNUNET_ERROR_TYPE_DEBUG, "Zeroing wfds%s\n", (retcode != -1 && nhandles && (returnedpos < nhandles)) ? ", copying fdset" : "");
1626 GNUNET_NETWORK_fdset_zero (wfds);
1627 if (retcode != -1 && nhandles && (returnedpos < nhandles))
1628 GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, retcode);
1629 GNUNET_CONTAINER_slist_append (wfds->handles, handles_write);
1633 LOG (GNUNET_ERROR_TYPE_DEBUG, "Zeroing efds%s\n", (retcode != -1 && nhandles && (returnedpos < nhandles)) ? ", copying fdset" : "");
1634 GNUNET_NETWORK_fdset_zero (efds);
1635 if (retcode != -1 && nhandles && (returnedpos < nhandles))
1636 GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, retcode);
1637 GNUNET_CONTAINER_slist_append (efds->handles, handles_except);
1639 GNUNET_CONTAINER_slist_destroy (handles_read);
1640 GNUNET_CONTAINER_slist_destroy (handles_write);
1641 GNUNET_CONTAINER_slist_destroy (handles_except);
1645 struct GNUNET_CONTAINER_SList_Iterator t;
1647 LOG (GNUNET_ERROR_TYPE_DEBUG, "rfds:\n");
1648 for (i = 0; i < rfds->sds.fd_count; i++)
1650 LOG (GNUNET_ERROR_TYPE_DEBUG, "%d\n", rfds->sds.fd_array[i]);
1652 for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1653 GNUNET_CONTAINER_slist_end (&t) != GNUNET_YES;
1654 GNUNET_CONTAINER_slist_next (&t))
1656 struct GNUNET_DISK_FileHandle *fh;
1658 fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (&t,
1660 LOG (GNUNET_ERROR_TYPE_DEBUG, "%d\n", fh->h);
1665 LOG (GNUNET_ERROR_TYPE_DEBUG, "wfds:\n");
1666 for (i = 0; i < wfds->sds.fd_count; i++)
1668 LOG (GNUNET_ERROR_TYPE_DEBUG, "%d\n", wfds->sds.fd_array[i]);
1673 LOG (GNUNET_ERROR_TYPE_DEBUG, "efds:\n");
1674 for (i = 0; i < efds->sds.fd_count; i++)
1676 LOG (GNUNET_ERROR_TYPE_DEBUG, "%d\n", efds->sds.fd_array[i]);
1679 LOG (GNUNET_ERROR_TYPE_DEBUG, "Returning %d or 0\n", retcode);
1681 if (nhandles && (returnedpos < nhandles))
1688 /* end of network.c */