2 This file is part of GNUnet.
3 Copyright (C) 2009-2013 GNUnet e.V.
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 3, 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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
22 * @file util/network.c
23 * @brief basic, low-level networking interface
25 * @author Christian Grothoff
28 #include "gnunet_util_lib.h"
31 #define LOG(kind,...) GNUNET_log_from (kind, "util-network", __VA_ARGS__)
32 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-network", syscall, filename)
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-network", syscall)
35 #define DEBUG_NETWORK GNUNET_EXTRA_LOGGING
38 #ifndef INVALID_SOCKET
39 #define INVALID_SOCKET -1
44 * @brief handle to a socket
46 struct GNUNET_NETWORK_Handle
55 * Address family / domain.
65 * Number of bytes in addr.
70 * Address we were bound to, or NULL.
72 struct sockaddr *addr;
78 * Test if the given protocol family is supported by this system.
80 * @param pf protocol family to test (PF_INET, PF_INET6, PF_UNIX)
81 * @return #GNUNET_OK if the PF is supported
84 GNUNET_NETWORK_test_pf (int pf)
88 s = socket (pf, SOCK_STREAM, 0);
91 if (EAFNOSUPPORT == errno)
93 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
94 "Failed to create test socket: %s\n",
108 * Given a unixpath that is too long (larger than UNIX_PATH_MAX),
109 * shorten it to an acceptable length while keeping it unique
110 * and making sure it remains a valid filename (if possible).
112 * @param unixpath long path, will be freed (or same pointer returned
113 * with moved 0-termination).
114 * @return shortened unixpath, NULL on error
117 GNUNET_NETWORK_shorten_unixpath (char *unixpath)
119 struct sockaddr_un dummy;
122 struct GNUNET_HashCode sh;
123 struct GNUNET_CRYPTO_HashAsciiEncoded ae;
126 upm = sizeof (dummy.sun_path);
127 slen = strlen (unixpath);
129 return unixpath; /* no shortening required */
130 GNUNET_CRYPTO_hash (unixpath, slen, &sh);
132 strlen (unixpath) >= upm)
134 if (NULL == (end = strrchr (unixpath, '/')))
136 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
137 _("Unable to shorten unix path `%s' while keeping name unique\n"),
139 GNUNET_free (unixpath);
144 GNUNET_CRYPTO_hash_to_enc (&sh, &ae);
145 strncat (unixpath, (char*) ae.encoding, 16);
152 * If services crash, they can leave a unix domain socket file on the
153 * disk. This needs to be manually removed, because otherwise both
154 * bind() and connect() for the respective address will fail. In this
155 * function, we test if such a left-over file exists, and if so,
156 * remove it (unless there is a listening service at the address).
158 * @param un unix domain socket address to check
161 GNUNET_NETWORK_unix_precheck (const struct sockaddr_un *un)
168 s = socket (AF_UNIX, SOCK_STREAM, 0);
171 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
172 "Failed to open AF_UNIX socket");
176 (struct sockaddr *) un,
177 sizeof (struct sockaddr_un));
179 GNUNET_break (0 == close (s));
181 return; /* another process is listening, do not remove! */
182 if (ECONNREFUSED != eno)
183 return; /* some other error, likely "no such file or directory" -- all well */
184 /* should unlink, but sanity checks first */
185 if (0 != stat (un->sun_path,
187 return; /* failed to 'stat', likely does not exist after all */
188 if (S_IFSOCK != (S_IFMT & sbuf.st_mode))
189 return; /* refuse to unlink anything except sockets */
190 /* finally, really unlink */
191 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
192 "Removing left-over `%s' from previous exeuction\n",
194 if (0 != unlink (un->sun_path))
195 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
204 #define FD_COPY(s, d) do { GNUNET_memcpy ((d), (s), sizeof (fd_set)); } while (0)
209 * Set if a socket should use blocking or non-blocking IO.
212 * @param doBlock blocking mode
213 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
216 GNUNET_NETWORK_socket_set_blocking (struct GNUNET_NETWORK_Handle *fd,
230 SetErrnoFromWinsockError (WSAGetLastError ());
231 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
233 return GNUNET_SYSERR;
239 int flags = fcntl (fd->fd, F_GETFL);
244 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
246 return GNUNET_SYSERR;
249 flags &= ~O_NONBLOCK;
253 if (0 != fcntl (fd->fd,
258 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
260 return GNUNET_SYSERR;
268 * Make a socket non-inheritable to child processes
270 * @param h the socket to make non-inheritable
271 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
272 * @warning Not implemented on Windows
275 socket_set_inheritable (const struct GNUNET_NETWORK_Handle *h)
279 i = fcntl (h->fd, F_GETFD);
281 return GNUNET_SYSERR;
282 if (i == (i | FD_CLOEXEC))
285 if (fcntl (h->fd, F_SETFD, i) < 0)
286 return GNUNET_SYSERR;
290 b = SetHandleInformation ((HANDLE) h->fd, HANDLE_FLAG_INHERIT, 0);
293 SetErrnoFromWinsockError (WSAGetLastError ());
294 return GNUNET_SYSERR;
303 * The MSG_NOSIGNAL equivalent on Mac OS X
305 * @param h the socket to make non-delaying
308 socket_set_nosigpipe (const struct GNUNET_NETWORK_Handle *h)
313 setsockopt (h->fd, SOL_SOCKET, SO_NOSIGPIPE,
314 (const void *) &abs_value,
316 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
322 * Disable delays when sending data via the socket.
323 * (GNUnet makes sure that messages are as big as
326 * @param h the socket to make non-delaying
329 socket_set_nodelay (const struct GNUNET_NETWORK_Handle *h)
338 &value, sizeof (value)))
339 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
342 const char *abs_value = "1";
345 setsockopt (h->fd, IPPROTO_TCP, TCP_NODELAY,
346 (const void *) abs_value,
348 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
355 * Perform proper canonical initialization for a network handle.
356 * Set it to non-blocking, make it non-inheritable to child
357 * processes, disable SIGPIPE, enable "nodelay" (if non-UNIX
358 * stream socket) and check that it is smaller than FD_SETSIZE.
360 * @param h socket to initialize
361 * @param af address family of the socket
362 * @param type socket type
363 * @return #GNUNET_OK on success, #GNUNET_SYSERR if initialization
364 * failed and the handle was destroyed
367 initialize_network_handle (struct GNUNET_NETWORK_Handle *h,
375 if (h->fd == INVALID_SOCKET)
378 SetErrnoFromWinsockError (WSAGetLastError ());
383 return GNUNET_SYSERR;
386 if (h->fd >= FD_SETSIZE)
388 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
390 return GNUNET_SYSERR;
393 if (GNUNET_OK != socket_set_inheritable (h))
394 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
395 "socket_set_inheritable");
397 if (GNUNET_SYSERR == GNUNET_NETWORK_socket_set_blocking (h, GNUNET_NO))
401 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
403 return GNUNET_SYSERR;
406 socket_set_nosigpipe (h);
408 if ( (type == SOCK_STREAM)
413 socket_set_nodelay (h);
419 * accept a new connection on a socket
421 * @param desc bound socket
422 * @param address address of the connecting peer, may be NULL
423 * @param address_len length of @a address
424 * @return client socket
426 struct GNUNET_NETWORK_Handle *
427 GNUNET_NETWORK_socket_accept (const struct GNUNET_NETWORK_Handle *desc,
428 struct sockaddr *address,
429 socklen_t *address_len)
431 struct GNUNET_NETWORK_Handle *ret;
434 ret = GNUNET_new (struct GNUNET_NETWORK_Handle);
437 struct sockaddr_storage name;
438 socklen_t namelen = sizeof (name);
440 int gsn = getsockname (desc->fd,
441 (struct sockaddr *) &name,
445 LOG (GNUNET_ERROR_TYPE_DEBUG,
446 "Accepting connection on `%s'\n",
447 GNUNET_a2s ((const struct sockaddr *) &name,
451 ret->fd = accept (desc->fd,
462 initialize_network_handle (ret,
463 (NULL != address) ? address->sa_family : desc->af,
474 * Bind a socket to a particular address.
476 * @param desc socket to bind
477 * @param address address to be bound
478 * @param address_len length of @a address
479 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
482 GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc,
483 const struct sockaddr *address,
484 socklen_t address_len)
493 if (AF_INET6 == desc->af)
494 if (setsockopt (desc->fd, IPPROTO_IPV6, IPV6_V6ONLY,
497 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
503 if (AF_UNIX == address->sa_family)
504 GNUNET_NETWORK_unix_precheck ((const struct sockaddr_un *) address);
508 /* This is required here for TCP sockets, but only on UNIX */
509 if ( (SOCK_STREAM == desc->type) &&
510 (0 != setsockopt (desc->fd,
514 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
518 /* set permissions of newly created non-abstract UNIX domain socket to
519 "user-only"; applications can choose to relax this later */
520 mode_t old_mask = 0; /* assigned to make compiler happy */
521 const struct sockaddr_un *un = (const struct sockaddr_un *) address;
522 int not_abstract = 0;
524 if ((AF_UNIX == address->sa_family)
525 && ('\0' != un->sun_path[0]) ) /* Not an abstract socket */
528 old_mask = umask (S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IROTH | S_IXOTH);
531 ret = bind (desc->fd,
537 (void) umask (old_mask);
541 if (SOCKET_ERROR == ret)
542 SetErrnoFromWinsockError (WSAGetLastError ());
545 return GNUNET_SYSERR;
547 desc->addr = GNUNET_malloc (address_len);
548 GNUNET_memcpy (desc->addr, address, address_len);
549 desc->addrlen = address_len;
559 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
562 GNUNET_NETWORK_socket_close (struct GNUNET_NETWORK_Handle *desc)
570 ret = closesocket (desc->fd);
571 error = WSAGetLastError ();
572 SetErrnoFromWinsockError (error);
573 LOG (GNUNET_ERROR_TYPE_DEBUG,
574 "Closed 0x%x, closesocket() returned %d, GLE is %u\n",
579 ret = close (desc->fd);
582 const struct sockaddr_un *un = (const struct sockaddr_un *) desc->addr;
584 /* Cleanup the UNIX domain socket and its parent directories in case of non
586 if ( (AF_UNIX == desc->af) &&
587 (NULL != desc->addr) &&
588 ('\0' != un->sun_path[0]) )
590 char *dirname = GNUNET_strndup (un->sun_path,
591 sizeof (un->sun_path));
593 if (0 != unlink (dirname))
595 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
603 len = strlen (dirname);
604 while ((len > 0) && (dirname[len] != DIR_SEPARATOR))
607 if ((0 != len) && (0 != rmdir (dirname)))
614 /* these are normal and can just be ignored */
617 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
624 GNUNET_free (dirname);
627 GNUNET_NETWORK_socket_free_memory_only_ (desc);
628 return (ret == 0) ? GNUNET_OK : GNUNET_SYSERR;
633 * Only free memory of a socket, keep the file descriptor untouched.
638 GNUNET_NETWORK_socket_free_memory_only_ (struct GNUNET_NETWORK_Handle *desc)
640 GNUNET_free_non_null (desc->addr);
646 * Box a native socket (and check that it is a socket).
648 * @param fd socket to box
649 * @return NULL on error (including not supported on target platform)
651 struct GNUNET_NETWORK_Handle *
652 GNUNET_NETWORK_socket_box_native (SOCKTYPE fd)
654 struct GNUNET_NETWORK_Handle *ret;
658 /* FIXME: Find a better call to check that FD is valid */
660 WSAIoctl (fd, FIONBIO,
661 (void *) &i, sizeof (i),
664 return NULL; /* invalid FD */
665 ret = GNUNET_new (struct GNUNET_NETWORK_Handle);
670 if (fcntl (fd, F_GETFD) < 0)
671 return NULL; /* invalid FD */
672 ret = GNUNET_new (struct GNUNET_NETWORK_Handle);
681 * Connect a socket to some remote address.
684 * @param address peer address
685 * @param address_len length of @a address
686 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
689 GNUNET_NETWORK_socket_connect (const struct GNUNET_NETWORK_Handle *desc,
690 const struct sockaddr *address,
691 socklen_t address_len)
695 ret = connect (desc->fd,
699 if (SOCKET_ERROR == ret)
701 SetErrnoFromWinsockError (WSAGetLastError ());
702 if (errno == EWOULDBLOCK)
706 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
714 * @param level protocol level of the option
715 * @param optname identifier of the option
716 * @param optval options
717 * @param optlen length of @a optval
718 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
721 GNUNET_NETWORK_socket_getsockopt (const struct GNUNET_NETWORK_Handle *desc,
729 ret = getsockopt (desc->fd,
736 (SOL_SOCKET == level) &&
737 (SO_ERROR == optname) )
738 *((int *) optval) = GetErrnoFromWinsockError (*((int *) optval));
739 else if (SOCKET_ERROR == ret)
740 SetErrnoFromWinsockError (WSAGetLastError ());
742 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
750 * @param backlog length of the listen queue
751 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
754 GNUNET_NETWORK_socket_listen (const struct GNUNET_NETWORK_Handle *desc,
759 ret = listen (desc->fd,
762 if (SOCKET_ERROR == ret)
763 SetErrnoFromWinsockError (WSAGetLastError ());
765 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
770 * How much data is available to be read on this descriptor?
773 * @returns #GNUNET_SYSERR if no data is available, or on error!
776 GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle *desc)
780 /* How much is there to be read? */
784 error = ioctl (desc->fd,
788 return (ssize_t) pending;
789 return GNUNET_SYSERR;
793 error = ioctlsocket (desc->fd,
796 if (error != SOCKET_ERROR)
797 return (ssize_t) pending;
798 return GNUNET_SYSERR;
804 * Read data from a socket (always non-blocking).
807 * @param buffer buffer
808 * @param length length of @a buffer
809 * @param src_addr either the source to recv from, or all zeroes
810 * to be filled in by recvfrom
811 * @param addrlen length of the @a src_addr
814 GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle *desc,
817 struct sockaddr *src_addr,
826 flags |= MSG_DONTWAIT;
829 ret = recvfrom (desc->fd,
836 if (SOCKET_ERROR == ret)
837 SetErrnoFromWinsockError (WSAGetLastError ());
844 * Read data from a connected socket (always non-blocking).
847 * @param buffer buffer
848 * @param length length of @a buffer
849 * @return number of bytes received, -1 on error
852 GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle *desc,
862 flags |= MSG_DONTWAIT;
864 ret = recv (desc->fd,
869 if (SOCKET_ERROR == ret)
870 SetErrnoFromWinsockError (WSAGetLastError ());
877 * Send data (always non-blocking).
880 * @param buffer data to send
881 * @param length size of the @a buffer
882 * @return number of bytes sent, #GNUNET_SYSERR on error
885 GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle *desc,
894 flags |= MSG_DONTWAIT;
898 flags |= MSG_NOSIGNAL;
901 ret = send (desc->fd,
906 if (SOCKET_ERROR == ret)
907 SetErrnoFromWinsockError (WSAGetLastError ());
915 * Send data to a particular destination (always non-blocking).
916 * This function only works for UDP sockets.
919 * @param message data to send
920 * @param length size of the @a message
921 * @param dest_addr destination address
922 * @param dest_len length of @a address
923 * @return number of bytes sent, #GNUNET_SYSERR on error
926 GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle *desc,
929 const struct sockaddr *dest_addr,
938 flags |= MSG_DONTWAIT;
941 flags |= MSG_NOSIGNAL;
943 ret = sendto (desc->fd, message, length, flags, dest_addr, dest_len);
945 if (SOCKET_ERROR == ret)
946 SetErrnoFromWinsockError (WSAGetLastError ());
956 * @param level protocol level of the option
957 * @param option_name option identifier
958 * @param option_value value to set
959 * @param option_len size of @a option_value
960 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
963 GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd,
966 const void *option_value,
967 socklen_t option_len)
971 ret = setsockopt (fd->fd,
977 if (SOCKET_ERROR == ret)
978 SetErrnoFromWinsockError (WSAGetLastError ());
980 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
985 * Create a new socket. Configure it for non-blocking IO and
986 * mark it as non-inheritable to child processes (set the
987 * close-on-exec flag).
989 * @param domain domain of the socket
990 * @param type socket type
991 * @param protocol network protocol
992 * @return new socket, NULL on error
994 struct GNUNET_NETWORK_Handle *
995 GNUNET_NETWORK_socket_create (int domain,
999 struct GNUNET_NETWORK_Handle *ret;
1002 fd = socket (domain, type, protocol);
1005 ret = GNUNET_new (struct GNUNET_NETWORK_Handle);
1008 initialize_network_handle (ret,
1017 * Shut down socket operations
1018 * @param desc socket
1019 * @param how type of shutdown
1020 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1023 GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc,
1028 ret = shutdown (desc->fd, how);
1031 SetErrnoFromWinsockError (WSAGetLastError ());
1033 return (0 == ret) ? GNUNET_OK : GNUNET_SYSERR;
1038 * Disable the "CORK" feature for communication with the given socket,
1039 * forcing the OS to immediately flush the buffer on transmission
1040 * instead of potentially buffering multiple messages. Essentially
1041 * reduces the OS send buffers to zero.
1043 * @param desc socket
1044 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1047 GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc)
1056 setsockopt (desc->fd,
1061 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1065 setsockopt (desc->fd,
1070 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1077 setsockopt (desc->fd,
1082 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1086 setsockopt (desc->fd,
1091 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1094 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
1104 GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds)
1106 FD_ZERO (&fds->sds);
1109 fds->handles_pos = 0;
1115 * Add a socket to the FD set
1118 * @param desc socket to add
1121 GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds,
1122 const struct GNUNET_NETWORK_Handle *desc)
1126 fds->nsds = GNUNET_MAX (fds->nsds,
1132 * Check whether a socket is part of the fd set
1135 * @param desc socket
1136 * @return 0 if the FD is not set
1139 GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds,
1140 const struct GNUNET_NETWORK_Handle *desc)
1142 return FD_ISSET (desc->fd,
1148 * Add one fd set to another
1150 * @param dst the fd set to add to
1151 * @param src the fd set to add from
1154 GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst,
1155 const struct GNUNET_NETWORK_FDSet *src)
1160 for (nfds = src->nsds; nfds >= 0; nfds--)
1161 if (FD_ISSET (nfds, &src->sds))
1162 FD_SET (nfds, &dst->sds);
1163 dst->nsds = GNUNET_MAX (dst->nsds,
1166 /* This is MinGW32-specific implementation that relies on the code that
1167 * winsock2.h defines for FD_SET. Namely, it relies on FD_SET checking
1168 * that fd being added is not already in the set.
1169 * Also relies on us knowing what's inside fd_set (fd_count and fd_array).
1171 * NOTE: I don't understand why the UNIX-logic wouldn't work
1172 * for the first part here as well. -CG
1176 for (i = 0; i < src->sds.fd_count; i++)
1177 FD_SET (src->sds.fd_array[i],
1179 dst->nsds = GNUNET_MAX (src->nsds,
1182 /* also copy over `struct GNUNET_DISK_FileHandle` array */
1183 if (dst->handles_pos + src->handles_pos > dst->handles_size)
1184 GNUNET_array_grow (dst->handles,
1186 ((dst->handles_pos + src->handles_pos) << 1));
1187 for (i = 0; i < src->handles_pos; i++)
1188 dst->handles[dst->handles_pos++] = src->handles[i];
1194 * Copy one fd set to another
1196 * @param to destination
1197 * @param from source
1200 GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to,
1201 const struct GNUNET_NETWORK_FDSet *from)
1203 FD_COPY (&from->sds,
1205 to->nsds = from->nsds;
1207 if (from->handles_pos > to->handles_size)
1208 GNUNET_array_grow (to->handles,
1210 from->handles_pos * 2);
1211 GNUNET_memcpy (to->handles,
1213 from->handles_pos * sizeof (struct GNUNET_NETWORK_Handle *));
1214 to->handles_pos = from->handles_pos;
1220 * Return file descriptor for this network handle
1222 * @param desc wrapper to process
1223 * @return POSIX file descriptor
1226 GNUNET_NETWORK_get_fd (struct GNUNET_NETWORK_Handle *desc)
1233 * Return sockaddr for this network handle
1235 * @param desc wrapper to process
1239 GNUNET_NETWORK_get_addr (struct GNUNET_NETWORK_Handle *desc)
1246 * Return sockaddr length for this network handle
1248 * @param desc wrapper to process
1249 * @return socklen_t for sockaddr
1252 GNUNET_NETWORK_get_addrlen (struct GNUNET_NETWORK_Handle *desc)
1254 return desc->addrlen;
1259 * Copy a native fd set
1261 * @param to destination
1262 * @param from native source set
1263 * @param nfds the biggest socket number in from + 1
1266 GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to,
1277 * Set a native fd in a set
1279 * @param to destination
1280 * @param nfd native FD to set
1283 GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to,
1286 GNUNET_assert ((nfd >= 0) && (nfd < FD_SETSIZE));
1287 FD_SET (nfd, &to->sds);
1288 to->nsds = GNUNET_MAX (nfd + 1,
1294 * Test native fd in a set
1296 * @param to set to test, NULL for empty set
1297 * @param nfd native FD to test, or -1 for none
1298 * @return #GNUNET_YES if FD is set in the set
1301 GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to,
1307 return FD_ISSET (nfd, &to->sds) ? GNUNET_YES : GNUNET_NO;
1312 * Add a file handle to the fd set
1314 * @param h the file handle to add
1317 GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds,
1318 const struct GNUNET_DISK_FileHandle *h)
1321 if (fds->handles_pos == fds->handles_size)
1322 GNUNET_array_grow (fds->handles,
1324 fds->handles_size * 2 + 2);
1325 fds->handles[fds->handles_pos++] = h;
1329 GNUNET_DISK_internal_file_handle_ (h,
1334 fds->nsds = GNUNET_MAX (fd + 1,
1341 * Add a file handle to the fd set
1343 * @param h the file handle to add
1346 GNUNET_NETWORK_fdset_handle_set_first (struct GNUNET_NETWORK_FDSet *fds,
1347 const struct GNUNET_DISK_FileHandle *h)
1350 if (fds->handles_pos == fds->handles_size)
1351 GNUNET_array_grow (fds->handles,
1353 fds->handles_size * 2 + 2);
1354 fds->handles[fds->handles_pos] = h;
1355 if (fds->handles[0] != h)
1357 const struct GNUNET_DISK_FileHandle *bak = fds->handles[0];
1358 fds->handles[0] = h;
1359 fds->handles[fds->handles_pos] = bak;
1363 GNUNET_NETWORK_fdset_handle_set (fds, h);
1369 * Check if a file handle is part of an fd set
1372 * @param h file handle
1373 * @return #GNUNET_YES if the file handle is part of the set
1376 GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds,
1377 const struct GNUNET_DISK_FileHandle *h)
1382 for (i=0;i<fds->handles_pos;i++)
1383 if (fds->handles[i] == h)
1387 return FD_ISSET (h->fd,
1395 * Numerically compare pointers to sort them.
1396 * Used to test for overlap in the arrays.
1398 * @param p1 a pointer
1399 * @param p2 a pointer
1400 * @return -1, 0 or 1, if the p1 < p2, p1==p2 or p1 > p2.
1403 ptr_cmp (const void *p1,
1408 if ((intptr_t) p1 < (intptr_t) p2)
1416 * Checks if two fd sets overlap
1418 * @param fds1 first fd set
1419 * @param fds2 second fd set
1420 * @return #GNUNET_YES if they do overlap, #GNUNET_NO otherwise
1423 GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1,
1424 const struct GNUNET_NETWORK_FDSet *fds2)
1429 nfds = GNUNET_MIN (fds1->nsds,
1434 if ( (FD_ISSET (nfds,
1445 /* This code is somewhat hacky, we are not supposed to know what's
1446 * inside of fd_set; also the O(n^2) is really bad... */
1447 for (i = 0; i < fds1->sds.fd_count; i++)
1448 for (j = 0; j < fds2->sds.fd_count; j++)
1449 if (fds1->sds.fd_array[i] == fds2->sds.fd_array[j])
1452 /* take a short cut if possible */
1453 if ( (0 == fds1->handles_pos) ||
1454 (0 == fds2->handles_pos) )
1457 /* Sort file handles array to avoid quadratic complexity when
1458 checking for overlap */
1459 qsort (fds1->handles,
1463 qsort (fds2->handles,
1469 while ( (i < fds1->handles_pos) &&
1470 (j < fds2->handles_pos) )
1472 switch (ptr_cmp (fds1->handles[i],
1492 * @return a new fd set
1494 struct GNUNET_NETWORK_FDSet *
1495 GNUNET_NETWORK_fdset_create ()
1497 struct GNUNET_NETWORK_FDSet *fds;
1499 fds = GNUNET_new (struct GNUNET_NETWORK_FDSet);
1500 GNUNET_NETWORK_fdset_zero (fds);
1506 * Releases the associated memory of an fd set
1511 GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds)
1514 GNUNET_array_grow (fds->handles,
1526 struct _select_params
1544 * Timeout for select().
1561 SOCKET wakeup_socket;
1564 * Set to return value from select.
1574 _selector (LPVOID p)
1576 struct _select_params *sp = p;
1580 WaitForSingleObject (sp->standby,
1582 ResetEvent (sp->standby);
1583 sp->status = select (1,
1588 if (FD_ISSET (sp->wakeup_socket,
1591 FD_CLR (sp->wakeup_socket,
1595 SetEvent (sp->wakeup);
1601 static HANDLE hEventPipeWrite;
1603 static HANDLE hEventReadReady;
1605 static struct _select_params sp;
1607 static HANDLE select_thread;
1609 static HANDLE select_finished_event;
1611 static HANDLE select_standby_event;
1613 static SOCKET select_wakeup_socket = -1;
1615 static SOCKET select_send_socket = -1;
1617 static struct timeval select_timeout;
1621 * On W32, we actually use a thread to help with the
1622 * event loop due to W32-API limitations. This function
1623 * initializes that thread.
1626 initialize_select_thread ()
1628 SOCKET select_listening_socket = -1;
1629 struct sockaddr_in s_in;
1634 select_standby_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1635 select_finished_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1637 select_wakeup_socket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1639 select_listening_socket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1642 res = ioctlsocket (select_wakeup_socket, FIONBIO, &p);
1643 LOG (GNUNET_ERROR_TYPE_DEBUG,
1644 "Select thread initialization: ioctlsocket() returns %d\n",
1647 alen = sizeof (s_in);
1648 s_in.sin_family = AF_INET;
1650 s_in.sin_addr.S_un.S_un_b.s_b1 = 127;
1651 s_in.sin_addr.S_un.S_un_b.s_b2 = 0;
1652 s_in.sin_addr.S_un.S_un_b.s_b3 = 0;
1653 s_in.sin_addr.S_un.S_un_b.s_b4 = 1;
1654 res = bind (select_listening_socket,
1655 (const struct sockaddr *) &s_in,
1657 LOG (GNUNET_ERROR_TYPE_DEBUG,
1658 "Select thread initialization: bind() returns %d\n",
1661 res = getsockname (select_listening_socket,
1662 (struct sockaddr *) &s_in,
1664 LOG (GNUNET_ERROR_TYPE_DEBUG,
1665 "Select thread initialization: getsockname() returns %d\n",
1668 res = listen (select_listening_socket,
1670 LOG (GNUNET_ERROR_TYPE_DEBUG,
1671 "Select thread initialization: listen() returns %d\n",
1673 res = connect (select_wakeup_socket,
1674 (const struct sockaddr *) &s_in,
1676 LOG (GNUNET_ERROR_TYPE_DEBUG,
1677 "Select thread initialization: connect() returns %d\n",
1680 select_send_socket = accept (select_listening_socket,
1681 (struct sockaddr *) &s_in,
1684 closesocket (select_listening_socket);
1686 sp.wakeup = select_finished_event;
1687 sp.standby = select_standby_event;
1688 sp.wakeup_socket = select_wakeup_socket;
1690 select_thread = CreateThread (NULL,
1703 * Check if sockets or pipes meet certain conditions
1705 * @param rfds set of sockets or pipes to be checked for readability
1706 * @param wfds set of sockets or pipes to be checked for writability
1707 * @param efds set of sockets or pipes to be checked for exceptions
1708 * @param timeout relative value when to return
1709 * @return number of selected sockets or pipes, #GNUNET_SYSERR on error
1712 GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1713 struct GNUNET_NETWORK_FDSet *wfds,
1714 struct GNUNET_NETWORK_FDSet *efds,
1715 const struct GNUNET_TIME_Relative timeout)
1725 nfds = GNUNET_MAX (nfds,
1728 nfds = GNUNET_MAX (nfds,
1731 (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us))
1734 LOG (GNUNET_ERROR_TYPE_ERROR,
1735 _("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1738 tv.tv_sec = timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us;
1740 (timeout.rel_value_us -
1741 (tv.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value_us));
1742 return select (nfds,
1743 (NULL != rfds) ? &rfds->sds : NULL,
1744 (NULL != wfds) ? &wfds->sds : NULL,
1745 (NULL != efds) ? &efds->sds : NULL,
1746 (timeout.rel_value_us ==
1747 GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) ? NULL : &tv);
1756 * Non-blocking test if a pipe is ready for reading.
1758 * @param fh pipe handle
1759 * @return #GNUNET_YES if the pipe is ready for reading
1762 pipe_read_ready (const struct GNUNET_DISK_FileHandle *fh)
1766 DWORD waitstatus = 0;
1769 bret = PeekNamedPipe (fh->h, NULL, 0, NULL, &waitstatus, NULL);
1770 error = GetLastError ();
1773 /* TODO: either add more errors to this condition, or eliminate it
1774 * entirely (failed to peek -> pipe is in serious trouble, should
1775 * be selected as readable).
1777 if ( (error != ERROR_BROKEN_PIPE) &&
1778 (error != ERROR_INVALID_HANDLE) )
1781 else if (waitstatus <= 0)
1788 * Non-blocking test if a pipe is having an IO exception.
1790 * @param fh pipe handle
1791 * @return #GNUNET_YES if the pipe is having an IO exception.
1794 pipe_except_ready (const struct GNUNET_DISK_FileHandle *fh)
1798 if (PeekNamedPipe (fh->h, NULL, 0, NULL, &dwBytes, NULL))
1805 * Iterate over handles in fds, destructively rewrite the
1806 * handles array contents of fds so that it starts with the
1807 * handles that are ready, and update handles_pos accordingly.
1809 * @param fds set of handles (usually pipes) to be checked for readiness
1810 * @param except GNUNET_NO if fds should be checked for readiness to read,
1811 * GNUNET_YES if fds should be checked for exceptions
1812 * (there is no way to check for write-readiness - pipes are always write-ready)
1813 * @param set_for_sure a HANDLE that is known to be set already,
1814 * because WaitForMultipleObjects() returned its index.
1815 * @return number of ready handles
1818 check_handles_status (struct GNUNET_NETWORK_FDSet *fds,
1820 HANDLE set_for_sure)
1822 const struct GNUNET_DISK_FileHandle *fh;
1826 for (woff = 0, roff = 0; roff < fds->handles_pos; roff++)
1828 fh = fds->handles[roff];
1829 if (fh == set_for_sure)
1831 fds->handles[woff++] = fh;
1833 else if (fh->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
1835 if ((except && pipe_except_ready (fh)) ||
1836 (!except && pipe_read_ready (fh)))
1837 fds->handles[woff++] = fh;
1839 else if (fh->type == GNUNET_DISK_HANLDE_TYPE_FILE)
1842 fds->handles[woff++] = fh;
1846 if (WAIT_OBJECT_0 == WaitForSingleObject (fh->h, 0))
1847 fds->handles[woff++] = fh;
1850 fds->handles_pos = woff;
1856 * Check if sockets or pipes meet certain conditions, version for W32.
1858 * @param rfds set of sockets or pipes to be checked for readability
1859 * @param wfds set of sockets or pipes to be checked for writability
1860 * @param efds set of sockets or pipes to be checked for exceptions
1861 * @param timeout relative value when to return
1862 * @return number of selected sockets or pipes, #GNUNET_SYSERR on error
1865 GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1866 struct GNUNET_NETWORK_FDSet *wfds,
1867 struct GNUNET_NETWORK_FDSet *efds,
1868 const struct GNUNET_TIME_Relative timeout)
1870 const struct GNUNET_DISK_FileHandle *fh;
1879 HANDLE handle_array[FD_SETSIZE + 2];
1881 int returnedpos = 0;
1891 nfds = GNUNET_MAX (nfds, rfds->nsds);
1892 handles += rfds->handles_pos;
1896 nfds = GNUNET_MAX (nfds, wfds->nsds);
1897 handles += wfds->handles_pos;
1901 nfds = GNUNET_MAX (nfds, efds->nsds);
1902 handles += efds->handles_pos;
1906 (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == timeout.rel_value_us) &&
1910 LOG (GNUNET_ERROR_TYPE_ERROR,
1911 _("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1914 #define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set))
1915 /* calculate how long we need to wait in microseconds */
1916 if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1918 mcs_total = INFINITE;
1919 ms_rounded = INFINITE;
1923 mcs_total = timeout.rel_value_us / GNUNET_TIME_UNIT_MICROSECONDS.rel_value_us;
1924 ms_rounded = (DWORD) (mcs_total / GNUNET_TIME_UNIT_MILLISECONDS.rel_value_us);
1925 if (mcs_total > 0 && ms_rounded == 0)
1928 /* select() may be used as a portable way to sleep */
1929 if (! (rfds || wfds || efds))
1935 if (NULL == select_thread)
1936 initialize_select_thread ();
1942 FD_COPY (&rfds->sds, &aread);
1944 FD_COPY (&wfds->sds, &awrite);
1946 FD_COPY (&efds->sds, &aexcept);
1948 /* Start by doing a fast check on sockets and pipes (without
1949 waiting). It is cheap, and is sufficient most of the time. By
1950 profiling we detected that to be true in 90% of the cases.
1953 /* Do the select now */
1954 select_timeout.tv_sec = 0;
1955 select_timeout.tv_usec = 0;
1957 /* Copy all the writes to the except, so we can detect connect() errors */
1958 for (i = 0; i < awrite.fd_count; i++)
1959 FD_SET (awrite.fd_array[i],
1961 if ( (aread.fd_count > 0) ||
1962 (awrite.fd_count > 0) ||
1963 (aexcept.fd_count > 0) )
1964 selectret = select (1,
1965 (NULL != rfds) ? &aread : NULL,
1966 (NULL != wfds) ? &awrite : NULL,
1971 if (-1 == selectret)
1973 /* Throw an error early on, while we still have the context. */
1974 LOG (GNUNET_ERROR_TYPE_ERROR,
1975 "W32 select(%d, %d, %d) failed: %lu\n",
1976 rfds ? aread.fd_count : 0,
1977 wfds ? awrite.fd_count : 0,
1983 /* Check aexcept, if something is in there and we copied that
1984 FD before to detect connect() errors, add it back to the
1985 write set to report errors. */
1987 for (i = 0; i < aexcept.fd_count; i++)
1988 if (FD_ISSET (aexcept.fd_array[i],
1990 FD_SET (aexcept.fd_array[i],
1994 /* If our select returned something or is a 0-timed request, then
1995 also check the pipes and get out of here! */
1996 /* Sadly, it means code duplication :( */
1997 if ( (selectret > 0) || (0 == mcs_total) )
2002 if (rfds && (rfds->handles_pos > 0))
2003 retcode += check_handles_status (rfds, GNUNET_NO, NULL);
2005 /* wfds handles remain untouched, on W32
2006 we pretend our pipes are "always" write-ready */
2009 if (efds && (efds->handles_pos > 0))
2010 retcode += check_handles_status (efds, GNUNET_YES, NULL);
2014 GNUNET_NETWORK_fdset_zero (rfds);
2015 if (selectret != -1)
2016 GNUNET_NETWORK_fdset_copy_native (rfds, &aread, selectret);
2020 GNUNET_NETWORK_fdset_zero (wfds);
2021 if (selectret != -1)
2022 GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, selectret);
2026 GNUNET_NETWORK_fdset_zero (efds);
2027 if (selectret != -1)
2028 GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, selectret);
2030 if (-1 == selectret)
2032 /* Add our select() FDs to the total return value */
2033 retcode += selectret;
2037 /* If we got this far, use slower implementation that is able to do a waiting select
2038 on both sockets and pipes simultaneously */
2040 /* Events for pipes */
2041 if (! hEventReadReady)
2042 hEventReadReady = CreateEvent (NULL, TRUE, TRUE, NULL);
2043 if (! hEventPipeWrite)
2044 hEventPipeWrite = CreateEvent (NULL, TRUE, TRUE, NULL);
2051 FD_COPY (&rfds->sds, &aread);
2053 FD_COPY (&wfds->sds, &awrite);
2055 FD_COPY (&efds->sds, &aexcept);
2056 /* We will first Add the PIPES to the events */
2057 /* Track how far in `handle_array` the read pipes go,
2058 so we may by-pass them quickly if none of them
2061 if (rfds && (rfds->handles_pos > 0))
2063 for (i = 0; i <rfds->handles_pos; i++)
2065 fh = rfds->handles[i];
2066 if (fh->type == GNUNET_DISK_HANLDE_TYPE_EVENT)
2068 handle_array[nhandles++] = fh->h;
2071 if (fh->type != GNUNET_DISK_HANLDE_TYPE_PIPE)
2073 /* Read zero bytes to check the status of the pipe */
2074 if (! ReadFile (fh->h, NULL, 0, NULL, fh->oOverlapRead))
2076 DWORD error_code = GetLastError ();
2078 if (error_code == ERROR_IO_PENDING)
2080 /* add as unready */
2081 handle_array[nhandles++] = fh->oOverlapRead->hEvent;
2087 handle_array[nhandles++] = hEventReadReady;
2093 /* error also counts as ready */
2094 handle_array[nhandles++] = hEventReadReady;
2100 if (wfds && (wfds->handles_pos > 0))
2102 LOG (GNUNET_ERROR_TYPE_DEBUG,
2103 "Adding the write ready event to the array as %d\n",
2105 handle_array[nhandles++] = hEventPipeWrite;
2111 LOG (GNUNET_ERROR_TYPE_DEBUG,
2112 "Adding the socket event to the array as %d\n",
2114 handle_array[nhandles++] = select_finished_event;
2115 if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
2121 select_timeout.tv_sec = timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us;
2122 select_timeout.tv_usec = (timeout.rel_value_us -
2123 (select_timeout.tv_sec *
2124 GNUNET_TIME_UNIT_SECONDS.rel_value_us));
2125 sp.tv = &select_timeout;
2127 FD_SET (select_wakeup_socket, &aread);
2130 i = recv (select_wakeup_socket,
2131 (char *) &returnedpos,
2138 /* Failed connections cause sockets to be set in errorfds on W32,
2139 * but on POSIX it should set them in writefds.
2140 * First copy all awrite sockets to aexcept, later we'll
2141 * check aexcept and set its contents in awrite as well
2142 * Sockets are also set in errorfds when OOB data is available,
2143 * but we don't use OOB data.
2145 for (i = 0; i < awrite.fd_count; i++)
2146 FD_SET (awrite.fd_array[i],
2148 ResetEvent (select_finished_event);
2149 SetEvent (select_standby_event);
2152 /* NULL-terminate array */
2153 handle_array[nhandles] = NULL;
2154 LOG (GNUNET_ERROR_TYPE_DEBUG,
2155 "nfds: %d, handles: %d, will wait: %llu mcs\n",
2162 = WaitForMultipleObjects (nhandles,
2166 LOG (GNUNET_ERROR_TYPE_DEBUG,
2167 "WaitForMultipleObjects Returned: %d\n",
2172 GNUNET_break (0); /* This branch shouldn't actually be executed...*/
2173 i = (int) WaitForSingleObject (select_finished_event,
2175 returncode = WAIT_TIMEOUT;
2179 /* Shouldn't come this far. If it does - investigate. */
2185 /* Don't wake up select-thread when delay is 0, it should return immediately
2186 * and wake up by itself.
2189 i = send (select_send_socket,
2190 (const char *) &returnedpos,
2193 i = (int) WaitForSingleObject (select_finished_event,
2195 LOG (GNUNET_ERROR_TYPE_DEBUG,
2196 "Finished waiting for the select thread: %d %d\n",
2203 i = recv (select_wakeup_socket,
2204 (char *) &returnedpos,
2208 /* Check aexcept, add its contents to awrite */
2209 for (i = 0; i < aexcept.fd_count; i++)
2210 FD_SET (aexcept.fd_array[i], &awrite);
2213 returnedpos = returncode - WAIT_OBJECT_0;
2214 LOG (GNUNET_ERROR_TYPE_DEBUG,
2215 "return pos is: %d\n",
2220 /* We queued a zero-long read on each pipe to check
2221 * its state, now we must cancel these read operations.
2222 * This must be done while rfds->handles_pos is still
2223 * intact and matches the number of read handles that we
2224 * got from the caller.
2226 for (i = 0; i < rfds->handles_pos; i++)
2228 fh = rfds->handles[i];
2229 if (GNUNET_DISK_HANLDE_TYPE_PIPE == fh->type)
2233 /* We may have some pipes ready for reading. */
2234 if (returnedpos < read_pipes_off)
2235 retcode += check_handles_status (rfds, GNUNET_NO, handle_array[returnedpos]);
2237 rfds->handles_pos = 0;
2239 if (-1 != sp.status)
2240 GNUNET_NETWORK_fdset_copy_native (rfds, &aread, retcode);
2244 retcode += wfds->handles_pos;
2245 /* wfds handles remain untouched */
2246 if (-1 != sp.status)
2247 GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, retcode);
2251 retcode += check_handles_status (rfds,
2253 returnedpos < nhandles ? handle_array[returnedpos] : NULL);
2254 if (-1 != sp.status)
2255 GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, retcode);
2259 retcode += sp.status;
2267 /* end of network.c */