paragraph for gnunet devs that don't know how to use the web
[oweals/gnunet.git] / src / util / network.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2013 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your option) any later version.
9
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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /**
20  * @file util/network.c
21  * @brief basic, low-level networking interface
22  * @author Nils Durner
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "disk.h"
28
29 #define LOG(kind,...) GNUNET_log_from (kind, "util-network", __VA_ARGS__)
30 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-network", syscall, filename)
31 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-network", syscall)
32
33 #define DEBUG_NETWORK GNUNET_EXTRA_LOGGING
34
35
36 #ifndef INVALID_SOCKET
37 #define INVALID_SOCKET -1
38 #endif
39
40
41 /**
42  * @brief handle to a socket
43  */
44 struct GNUNET_NETWORK_Handle
45 {
46 #ifndef MINGW
47   int fd;
48 #else
49   SOCKET fd;
50 #endif
51
52   /**
53    * Address family / domain.
54    */
55   int af;
56
57   /**
58    * Type of the socket
59    */
60   int type;
61
62   /**
63    * Number of bytes in addr.
64    */
65   socklen_t addrlen;
66
67   /**
68    * Address we were bound to, or NULL.
69    */
70   struct sockaddr *addr;
71
72 };
73
74
75 /**
76  * Test if the given protocol family is supported by this system.
77  *
78  * @param pf protocol family to test (PF_INET, PF_INET6, PF_UNIX)
79  * @return #GNUNET_OK if the PF is supported
80  */
81 int
82 GNUNET_NETWORK_test_pf (int pf)
83 {
84   int s;
85
86   s = socket (pf, SOCK_STREAM, 0);
87   if (-1 == s)
88   {
89     if (EAFNOSUPPORT == errno)
90       return GNUNET_NO;
91     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
92                 "Failed to create test socket: %s\n",
93                 STRERROR (errno));
94     return GNUNET_SYSERR;
95   }
96 #if WINDOWS
97   closesocket (s);
98 #else
99   close (s);
100 #endif
101   return GNUNET_OK;
102 }
103
104
105 /**
106  * Given a unixpath that is too long (larger than UNIX_PATH_MAX),
107  * shorten it to an acceptable length while keeping it unique
108  * and making sure it remains a valid filename (if possible).
109  *
110  * @param unixpath long path, will be freed (or same pointer returned
111  *        with moved 0-termination).
112  * @return shortened unixpath, NULL on error
113  */
114 char *
115 GNUNET_NETWORK_shorten_unixpath (char *unixpath)
116 {
117   struct sockaddr_un dummy;
118   size_t slen;
119   char *end;
120   struct GNUNET_HashCode sh;
121   struct GNUNET_CRYPTO_HashAsciiEncoded ae;
122   size_t upm;
123
124   upm = sizeof (dummy.sun_path);
125   slen = strlen (unixpath);
126   if (slen < upm)
127     return unixpath; /* no shortening required */
128   GNUNET_CRYPTO_hash (unixpath, slen, &sh);
129   while (16 + strlen (unixpath) >= upm)
130   {
131     if (NULL == (end = strrchr (unixpath, '/')))
132     {
133       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
134                   _("Unable to shorten unix path `%s' while keeping name unique\n"),
135                   unixpath);
136       GNUNET_free (unixpath);
137       return NULL;
138     }
139     *end = '\0';
140   }
141   GNUNET_CRYPTO_hash_to_enc (&sh, &ae);
142   strncat (unixpath, (char *) ae.encoding, 16);
143   return unixpath;
144 }
145
146
147 #ifndef WINDOWS
148 /**
149  * If services crash, they can leave a unix domain socket file on the
150  * disk. This needs to be manually removed, because otherwise both
151  * bind() and connect() for the respective address will fail.  In this
152  * function, we test if such a left-over file exists, and if so,
153  * remove it (unless there is a listening service at the address).
154  *
155  * @param un unix domain socket address to check
156  */
157 void
158 GNUNET_NETWORK_unix_precheck (const struct sockaddr_un *un)
159 {
160   int s;
161   int eno;
162   struct stat sbuf;
163   int ret;
164
165   s = socket (AF_UNIX, SOCK_STREAM, 0);
166   if (-1 == s)
167   {
168     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
169                          "Failed to open AF_UNIX socket");
170     return;
171   }
172   ret = connect (s,
173                  (struct sockaddr *) un,
174                  sizeof (struct sockaddr_un));
175   eno = errno;
176   GNUNET_break (0 == close (s));
177   if (0 == ret)
178     return; /* another process is listening, do not remove! */
179   if (ECONNREFUSED != eno)
180     return; /* some other error, likely "no such file or directory" -- all well */
181   /* should unlink, but sanity checks first */
182   if (0 != stat (un->sun_path,
183                  &sbuf))
184     return; /* failed to 'stat', likely does not exist after all */
185   if (S_IFSOCK != (S_IFMT & sbuf.st_mode))
186     return; /* refuse to unlink anything except sockets */
187   /* finally, really unlink */
188   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
189               "Removing left-over `%s' from previous exeuction\n",
190               un->sun_path);
191   if (0 != unlink (un->sun_path))
192     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
193                               "unlink",
194                               un->sun_path);
195 }
196 #endif
197
198
199
200 #ifndef FD_COPY
201 #define FD_COPY(s, d) do { GNUNET_memcpy ((d), (s), sizeof (fd_set)); } while (0)
202 #endif
203
204
205 /**
206  * Set if a socket should use blocking or non-blocking IO.
207  *
208  * @param fd socket
209  * @param doBlock blocking mode
210  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
211  */
212 int
213 GNUNET_NETWORK_socket_set_blocking (struct GNUNET_NETWORK_Handle *fd,
214                                     int doBlock)
215 {
216
217 #if MINGW
218   u_long mode;
219
220   mode = !doBlock;
221   if (SOCKET_ERROR ==
222       ioctlsocket (fd->fd,
223                    FIONBIO,
224                    &mode))
225
226   {
227     SetErrnoFromWinsockError (WSAGetLastError ());
228     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
229                   "ioctlsocket");
230     return GNUNET_SYSERR;
231   }
232   return GNUNET_OK;
233
234 #else
235   /* not MINGW */
236   int flags = fcntl (fd->fd, F_GETFL);
237
238   if (flags == -1)
239   {
240     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
241                   "fcntl");
242     return GNUNET_SYSERR;
243   }
244   if (doBlock)
245     flags &= ~O_NONBLOCK;
246
247   else
248     flags |= O_NONBLOCK;
249   if (0 != fcntl (fd->fd,
250                   F_SETFL,
251                   flags))
252
253   {
254     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
255                   "fcntl");
256     return GNUNET_SYSERR;
257   }
258   return GNUNET_OK;
259 #endif
260 }
261
262
263 /**
264  * Make a socket non-inheritable to child processes
265  *
266  * @param h the socket to make non-inheritable
267  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
268  * @warning Not implemented on Windows
269  */
270 static int
271 socket_set_inheritable (const struct GNUNET_NETWORK_Handle *h)
272 {
273 #ifndef MINGW
274   int i;
275   i = fcntl (h->fd, F_GETFD);
276   if (i < 0)
277     return GNUNET_SYSERR;
278   if (i == (i | FD_CLOEXEC))
279     return GNUNET_OK;
280   i |= FD_CLOEXEC;
281   if (fcntl (h->fd, F_SETFD, i) < 0)
282     return GNUNET_SYSERR;
283 #else
284   BOOL b;
285   SetLastError (0);
286   b = SetHandleInformation ((HANDLE) h->fd, HANDLE_FLAG_INHERIT, 0);
287   if (!b)
288   {
289     SetErrnoFromWinsockError (WSAGetLastError ());
290     return GNUNET_SYSERR;
291   }
292 #endif
293   return GNUNET_OK;
294 }
295
296
297 #ifdef DARWIN
298 /**
299  * The MSG_NOSIGNAL equivalent on Mac OS X
300  *
301  * @param h the socket to make non-delaying
302  */
303 static void
304 socket_set_nosigpipe (const struct GNUNET_NETWORK_Handle *h)
305 {
306   int abs_value = 1;
307
308   if (0 !=
309       setsockopt (h->fd, SOL_SOCKET, SO_NOSIGPIPE,
310                   (const void *) &abs_value,
311                   sizeof (abs_value)))
312     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
313 }
314 #endif
315
316
317 /**
318  * Disable delays when sending data via the socket.
319  * (GNUnet makes sure that messages are as big as
320  * possible already).
321  *
322  * @param h the socket to make non-delaying
323  */
324 static void
325 socket_set_nodelay (const struct GNUNET_NETWORK_Handle *h)
326 {
327 #ifndef WINDOWS
328   int value = 1;
329
330   if (0 !=
331       setsockopt (h->fd,
332                   IPPROTO_TCP,
333                   TCP_NODELAY,
334                   &value, sizeof (value)))
335     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
336                   "setsockopt");
337 #else
338   const char *abs_value = "1";
339
340   if (0 !=
341       setsockopt (h->fd,
342                   IPPROTO_TCP,
343                   TCP_NODELAY,
344                   (const void *) abs_value,
345                   sizeof (abs_value)))
346     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
347                   "setsockopt");
348 #endif
349 }
350
351
352 /**
353  * Perform proper canonical initialization for a network handle.
354  * Set it to non-blocking, make it non-inheritable to child
355  * processes, disable SIGPIPE, enable "nodelay" (if non-UNIX
356  * stream socket) and check that it is smaller than FD_SETSIZE.
357  *
358  * @param h socket to initialize
359  * @param af address family of the socket
360  * @param type socket type
361  * @return #GNUNET_OK on success, #GNUNET_SYSERR if initialization
362  *         failed and the handle was destroyed
363  */
364 static int
365 initialize_network_handle (struct GNUNET_NETWORK_Handle *h,
366                            int af,
367                            int type)
368 {
369   int eno;
370
371   h->af = af;
372   h->type = type;
373   if (h->fd == INVALID_SOCKET)
374   {
375 #ifdef MINGW
376     SetErrnoFromWinsockError (WSAGetLastError ());
377 #endif
378     eno = errno;
379     GNUNET_free (h);
380     errno = eno;
381     return GNUNET_SYSERR;
382   }
383 #ifndef MINGW
384   if (h->fd >= FD_SETSIZE)
385   {
386     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
387     errno = EMFILE;
388     return GNUNET_SYSERR;
389   }
390 #endif
391   if (GNUNET_OK != socket_set_inheritable (h))
392     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
393                   "socket_set_inheritable");
394
395   if (GNUNET_SYSERR == GNUNET_NETWORK_socket_set_blocking (h, GNUNET_NO))
396   {
397     eno = errno;
398     GNUNET_break (0);
399     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
400     errno = eno;
401     return GNUNET_SYSERR;
402   }
403 #ifdef DARWIN
404   socket_set_nosigpipe (h);
405 #endif
406   if ( (type == SOCK_STREAM)
407 #ifdef AF_UNIX
408        && (af != AF_UNIX)
409 #endif
410       )
411     socket_set_nodelay (h);
412   return GNUNET_OK;
413 }
414
415
416 /**
417  * accept a new connection on a socket
418  *
419  * @param desc bound socket
420  * @param address address of the connecting peer, may be NULL
421  * @param address_len length of @a address
422  * @return client socket
423  */
424 struct GNUNET_NETWORK_Handle *
425 GNUNET_NETWORK_socket_accept (const struct GNUNET_NETWORK_Handle *desc,
426                               struct sockaddr *address,
427                               socklen_t *address_len)
428 {
429   struct GNUNET_NETWORK_Handle *ret;
430   int eno;
431
432   ret = GNUNET_new (struct GNUNET_NETWORK_Handle);
433 #if DEBUG_NETWORK
434   {
435     struct sockaddr_storage name;
436     socklen_t namelen = sizeof (name);
437
438     int gsn = getsockname (desc->fd,
439                            (struct sockaddr *) &name,
440                            &namelen);
441
442     if (0 == gsn)
443       LOG (GNUNET_ERROR_TYPE_DEBUG,
444            "Accepting connection on `%s'\n",
445            GNUNET_a2s ((const struct sockaddr *) &name,
446                        namelen));
447   }
448 #endif
449   ret->fd = accept (desc->fd,
450                     address,
451                     address_len);
452   if (-1 == ret->fd)
453   {
454     eno = errno;
455     GNUNET_free (ret);
456     errno = eno;
457     return NULL;
458   }
459   if (GNUNET_OK !=
460       initialize_network_handle (ret,
461                                  (NULL != address) ? address->sa_family : desc->af,
462                                  SOCK_STREAM))
463   {
464
465     return NULL;
466   }
467   return ret;
468 }
469
470
471 /**
472  * Bind a socket to a particular address.
473  *
474  * @param desc socket to bind
475  * @param address address to be bound
476  * @param address_len length of @a address
477  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
478  */
479 int
480 GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc,
481                             const struct sockaddr *address,
482                             socklen_t address_len)
483 {
484   int ret;
485
486 #ifdef IPV6_V6ONLY
487 #ifdef IPPROTO_IPV6
488   {
489     const int on = 1;
490
491     if (AF_INET6 == desc->af)
492       if (setsockopt (desc->fd,
493                       IPPROTO_IPV6,
494                       IPV6_V6ONLY,
495                       (const void *) &on,
496                       sizeof (on)))
497         LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
498                       "setsockopt");
499   }
500 #endif
501 #endif
502 #ifndef WINDOWS
503   if (AF_UNIX == address->sa_family)
504     GNUNET_NETWORK_unix_precheck ((const struct sockaddr_un *) address);
505   {
506     const int on = 1;
507
508     /* This is required here for TCP sockets, but only on UNIX */
509     if ( (SOCK_STREAM == desc->type) &&
510          (0 != setsockopt (desc->fd,
511                            SOL_SOCKET,
512                            SO_REUSEADDR,
513                            &on, sizeof (on))))
514       LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
515                     "setsockopt");
516   }
517   {
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;
523
524     if ((AF_UNIX == address->sa_family)
525         && ('\0' != un->sun_path[0]) ) /* Not an abstract socket */
526       not_abstract = 1;
527     if (not_abstract)
528       old_mask = umask (S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IROTH | S_IXOTH);
529 #endif
530
531     ret = bind (desc->fd,
532                 address,
533                 address_len);
534
535 #ifndef WINDOWS
536     if (not_abstract)
537       (void) umask (old_mask);
538   }
539 #endif
540 #ifdef MINGW
541   if (SOCKET_ERROR == ret)
542     SetErrnoFromWinsockError (WSAGetLastError ());
543 #endif
544   if (0 != ret)
545     return GNUNET_SYSERR;
546 #ifndef MINGW
547   desc->addr = GNUNET_malloc (address_len);
548   GNUNET_memcpy (desc->addr, address, address_len);
549   desc->addrlen = address_len;
550 #endif
551   return GNUNET_OK;
552 }
553
554
555 /**
556  * Close a socket
557  *
558  * @param desc socket
559  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
560  */
561 int
562 GNUNET_NETWORK_socket_close (struct GNUNET_NETWORK_Handle *desc)
563 {
564   int ret;
565
566 #ifdef WINDOWS
567   DWORD error = 0;
568
569   SetLastError (0);
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",
575        desc->fd,
576        ret,
577        error);
578 #else
579   ret = close (desc->fd);
580 #endif
581 #ifndef WINDOWS
582   const struct sockaddr_un *un = (const struct sockaddr_un *) desc->addr;
583
584   /* Cleanup the UNIX domain socket and its parent directories in case of non
585      abstract sockets */
586   if ( (AF_UNIX == desc->af) &&
587        (NULL != desc->addr) &&
588        ('\0' != un->sun_path[0]) )
589   {
590     char *dirname = GNUNET_strndup (un->sun_path,
591                                     sizeof (un->sun_path));
592
593     if (0 != unlink (dirname))
594     {
595       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
596                          "unlink",
597                          dirname);
598     }
599     else
600     {
601       size_t len;
602
603       len = strlen (dirname);
604       while ((len > 0) && (dirname[len] != DIR_SEPARATOR))
605         len--;
606       dirname[len] = '\0';
607       if ((0 != len) && (0 != rmdir (dirname)))
608       {
609         switch (errno)
610         {
611         case EACCES:
612         case ENOTEMPTY:
613         case EPERM:
614           /* these are normal and can just be ignored */
615           break;
616         default:
617           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
618                                     "rmdir",
619                                     dirname);
620           break;
621         }
622       }
623     }
624     GNUNET_free (dirname);
625   }
626 #endif
627   GNUNET_NETWORK_socket_free_memory_only_ (desc);
628   return (ret == 0) ? GNUNET_OK : GNUNET_SYSERR;
629 }
630
631
632 /**
633  * Only free memory of a socket, keep the file descriptor untouched.
634  *
635  * @param desc socket
636  */
637 void
638 GNUNET_NETWORK_socket_free_memory_only_ (struct GNUNET_NETWORK_Handle *desc)
639 {
640   GNUNET_free_non_null (desc->addr);
641   GNUNET_free (desc);
642 }
643
644
645 /**
646  * Box a native socket (and check that it is a socket).
647  *
648  * @param fd socket to box
649  * @return NULL on error (including not supported on target platform)
650  */
651 struct GNUNET_NETWORK_Handle *
652 GNUNET_NETWORK_socket_box_native (SOCKTYPE fd)
653 {
654   struct GNUNET_NETWORK_Handle *ret;
655 #if MINGW
656   unsigned long i;
657   DWORD d;
658   /* FIXME: Find a better call to check that FD is valid */
659   if (0 !=
660       WSAIoctl (fd, FIONBIO,
661                 (void *) &i, sizeof (i),
662                 NULL, 0, &d,
663                 NULL, NULL))
664     return NULL;                /* invalid FD */
665   ret = GNUNET_new (struct GNUNET_NETWORK_Handle);
666   ret->fd = fd;
667   ret->af = AF_UNSPEC;
668   return ret;
669 #else
670   if (fcntl (fd, F_GETFD) < 0)
671     return NULL;                /* invalid FD */
672   ret = GNUNET_new (struct GNUNET_NETWORK_Handle);
673   ret->fd = fd;
674   ret->af = AF_UNSPEC;
675   return ret;
676 #endif
677 }
678
679
680 /**
681  * Connect a socket to some remote address.
682  *
683  * @param desc socket
684  * @param address peer address
685  * @param address_len length of @a address
686  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
687  */
688 int
689 GNUNET_NETWORK_socket_connect (const struct GNUNET_NETWORK_Handle *desc,
690                                const struct sockaddr *address,
691                                socklen_t address_len)
692 {
693   int ret;
694
695   ret = connect (desc->fd,
696                  address,
697                  address_len);
698 #ifdef MINGW
699   if (SOCKET_ERROR == ret)
700   {
701     SetErrnoFromWinsockError (WSAGetLastError ());
702     if (errno == EWOULDBLOCK)
703       errno = EINPROGRESS;
704   }
705 #endif
706   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
707 }
708
709
710 /**
711  * Get socket options
712  *
713  * @param desc socket
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
719  */
720 int
721 GNUNET_NETWORK_socket_getsockopt (const struct GNUNET_NETWORK_Handle *desc,
722                                   int level,
723                                   int optname,
724                                   void *optval,
725                                   socklen_t *optlen)
726 {
727   int ret;
728
729   ret = getsockopt (desc->fd,
730                     level,
731                     optname,
732                     optval, optlen);
733
734 #ifdef MINGW
735   if ( (0 == ret) &&
736        (SOL_SOCKET == level) &&
737        (SO_ERROR == optname) )
738     *((int *) optval) = GetErrnoFromWinsockError (*((int *) optval));
739   else if (SOCKET_ERROR == ret)
740     SetErrnoFromWinsockError (WSAGetLastError ());
741 #endif
742   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
743 }
744
745
746 /**
747  * Listen on a socket
748  *
749  * @param desc socket
750  * @param backlog length of the listen queue
751  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
752  */
753 int
754 GNUNET_NETWORK_socket_listen (const struct GNUNET_NETWORK_Handle *desc,
755                               int backlog)
756 {
757   int ret;
758
759   ret = listen (desc->fd,
760                 backlog);
761 #ifdef MINGW
762   if (SOCKET_ERROR == ret)
763     SetErrnoFromWinsockError (WSAGetLastError ());
764 #endif
765   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
766 }
767
768
769 /**
770  * How much data is available to be read on this descriptor?
771  *
772  * @param desc socket
773  * @returns #GNUNET_SYSERR if no data is available, or on error!
774  */
775 ssize_t
776 GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle *desc)
777 {
778   int error;
779
780   /* How much is there to be read? */
781 #ifndef WINDOWS
782   int pending;
783
784   error = ioctl (desc->fd,
785                  FIONREAD,
786                  &pending);
787   if (0 == error)
788     return (ssize_t) pending;
789   return GNUNET_SYSERR;
790 #else
791   u_long pending;
792
793   error = ioctlsocket (desc->fd,
794                        FIONREAD,
795                        &pending);
796   if (error != SOCKET_ERROR)
797     return (ssize_t) pending;
798   return GNUNET_SYSERR;
799 #endif
800 }
801
802
803 /**
804  * Read data from a socket (always non-blocking).
805  *
806  * @param desc socket
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
812  */
813 ssize_t
814 GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle *desc,
815                                 void *buffer,
816                                 size_t length,
817                                 struct sockaddr *src_addr,
818                                 socklen_t *addrlen)
819 {
820   int ret;
821   int flags;
822
823   flags = 0;
824
825 #ifdef MSG_DONTWAIT
826   flags |= MSG_DONTWAIT;
827
828 #endif
829   ret = recvfrom (desc->fd,
830                   buffer,
831                   length,
832                   flags,
833                   src_addr,
834                   addrlen);
835 #ifdef MINGW
836   if (SOCKET_ERROR == ret)
837     SetErrnoFromWinsockError (WSAGetLastError ());
838 #endif
839   return ret;
840 }
841
842
843 /**
844  * Read data from a connected socket (always non-blocking).
845  *
846  * @param desc socket
847  * @param buffer buffer
848  * @param length length of @a buffer
849  * @return number of bytes received, -1 on error
850  */
851 ssize_t
852 GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle *desc,
853                             void *buffer,
854                             size_t length)
855 {
856   int ret;
857   int flags;
858
859   flags = 0;
860
861 #ifdef MSG_DONTWAIT
862   flags |= MSG_DONTWAIT;
863 #endif
864   ret = recv (desc->fd,
865               buffer,
866               length,
867               flags);
868 #ifdef MINGW
869   if (SOCKET_ERROR == ret)
870     SetErrnoFromWinsockError (WSAGetLastError ());
871 #endif
872   return ret;
873 }
874
875
876 /**
877  * Send data (always non-blocking).
878  *
879  * @param desc socket
880  * @param buffer data to send
881  * @param length size of the @a buffer
882  * @return number of bytes sent, #GNUNET_SYSERR on error
883  */
884 ssize_t
885 GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle *desc,
886                             const void *buffer,
887                             size_t length)
888 {
889   int ret;
890   int flags;
891
892   flags = 0;
893 #ifdef MSG_DONTWAIT
894   flags |= MSG_DONTWAIT;
895
896 #endif
897 #ifdef MSG_NOSIGNAL
898   flags |= MSG_NOSIGNAL;
899
900 #endif
901   ret = send (desc->fd,
902               buffer,
903               length,
904               flags);
905 #ifdef MINGW
906   if (SOCKET_ERROR == ret)
907     SetErrnoFromWinsockError (WSAGetLastError ());
908
909 #endif
910   return ret;
911 }
912
913
914 /**
915  * Send data to a particular destination (always non-blocking).
916  * This function only works for UDP sockets.
917  *
918  * @param desc socket
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
924  */
925 ssize_t
926 GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle *desc,
927                               const void *message,
928                               size_t length,
929                               const struct sockaddr *dest_addr,
930                               socklen_t dest_len)
931 {
932   int ret;
933   int flags;
934
935   flags = 0;
936
937 #ifdef MSG_DONTWAIT
938   flags |= MSG_DONTWAIT;
939 #endif
940 #ifdef MSG_NOSIGNAL
941   flags |= MSG_NOSIGNAL;
942 #endif
943   ret = sendto (desc->fd, message, length, flags, dest_addr, dest_len);
944 #ifdef MINGW
945   if (SOCKET_ERROR == ret)
946     SetErrnoFromWinsockError (WSAGetLastError ());
947 #endif
948   return ret;
949 }
950
951
952 /**
953  * Set socket option
954  *
955  * @param fd socket
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
961  */
962 int
963 GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd,
964                                   int level,
965                                   int option_name,
966                                   const void *option_value,
967                                   socklen_t option_len)
968 {
969   int ret;
970
971   ret = setsockopt (fd->fd,
972                     level,
973                     option_name,
974                     option_value,
975                     option_len);
976 #ifdef MINGW
977   if (SOCKET_ERROR == ret)
978     SetErrnoFromWinsockError (WSAGetLastError ());
979 #endif
980   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
981 }
982
983
984 /**
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).
988  *
989  * @param domain domain of the socket
990  * @param type socket type
991  * @param protocol network protocol
992  * @return new socket, NULL on error
993  */
994 struct GNUNET_NETWORK_Handle *
995 GNUNET_NETWORK_socket_create (int domain,
996                               int type,
997                               int protocol)
998 {
999   struct GNUNET_NETWORK_Handle *ret;
1000   int fd;
1001
1002   fd = socket (domain, type, protocol);
1003   if (-1 == fd)
1004     return NULL;
1005   ret = GNUNET_new (struct GNUNET_NETWORK_Handle);
1006   ret->fd = fd;
1007   if (GNUNET_OK !=
1008       initialize_network_handle (ret,
1009                                  domain,
1010                                  type))
1011     return NULL;
1012   return ret;
1013 }
1014
1015
1016 /**
1017  * Shut down socket operations
1018  * @param desc socket
1019  * @param how type of shutdown
1020  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1021  */
1022 int
1023 GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc,
1024                                 int how)
1025 {
1026   int ret;
1027
1028   ret = shutdown (desc->fd, how);
1029 #ifdef MINGW
1030   if (0 != ret)
1031     SetErrnoFromWinsockError (WSAGetLastError ());
1032 #endif
1033   return (0 == ret) ? GNUNET_OK : GNUNET_SYSERR;
1034 }
1035
1036
1037 /**
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.
1042  *
1043  * @param desc socket
1044  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1045  */
1046 int
1047 GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc)
1048 {
1049   int ret = 0;
1050
1051 #if WINDOWS
1052   int value = 0;
1053
1054   if (0 !=
1055       (ret =
1056        setsockopt (desc->fd,
1057                    SOL_SOCKET,
1058                    SO_SNDBUF,
1059                    (char *) &value,
1060                    sizeof (value))))
1061     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1062                   "setsockopt");
1063   if (0 !=
1064       (ret =
1065        setsockopt (desc->fd,
1066                    SOL_SOCKET,
1067                    SO_RCVBUF,
1068                    (char *) &value,
1069                    sizeof (value))))
1070     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1071                   "setsockopt");
1072 #elif LINUX
1073   int value = 0;
1074
1075   if (0 !=
1076       (ret =
1077        setsockopt (desc->fd,
1078                    SOL_SOCKET,
1079                    SO_SNDBUF,
1080                    &value,
1081                    sizeof (value))))
1082     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1083                   "setsockopt");
1084   if (0 !=
1085       (ret =
1086        setsockopt (desc->fd,
1087                    SOL_SOCKET,
1088                    SO_RCVBUF,
1089                    &value,
1090                    sizeof (value))))
1091     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1092                   "setsockopt");
1093 #endif
1094   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
1095 }
1096
1097
1098 /**
1099  * Reset FD set
1100  *
1101  * @param fds fd set
1102  */
1103 void
1104 GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds)
1105 {
1106   FD_ZERO (&fds->sds);
1107   fds->nsds = 0;
1108 #ifdef MINGW
1109   fds->handles_pos = 0;
1110 #endif
1111 }
1112
1113
1114 /**
1115  * Add a socket to the FD set
1116  *
1117  * @param fds fd set
1118  * @param desc socket to add
1119  */
1120 void
1121 GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds,
1122                           const struct GNUNET_NETWORK_Handle *desc)
1123 {
1124   FD_SET (desc->fd,
1125           &fds->sds);
1126   fds->nsds = GNUNET_MAX (fds->nsds,
1127                           desc->fd + 1);
1128 }
1129
1130
1131 /**
1132  * Check whether a socket is part of the fd set
1133  *
1134  * @param fds fd set
1135  * @param desc socket
1136  * @return 0 if the FD is not set
1137  */
1138 int
1139 GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds,
1140                             const struct GNUNET_NETWORK_Handle *desc)
1141 {
1142   return FD_ISSET (desc->fd,
1143                    &fds->sds);
1144 }
1145
1146
1147 /**
1148  * Add one fd set to another
1149  *
1150  * @param dst the fd set to add to
1151  * @param src the fd set to add from
1152  */
1153 void
1154 GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst,
1155                           const struct GNUNET_NETWORK_FDSet *src)
1156 {
1157 #ifndef MINGW
1158   int nfds;
1159
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,
1164                           src->nsds);
1165 #else
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).
1170    *
1171    * NOTE: I don't understand why the UNIX-logic wouldn't work
1172    * for the first part here as well. -CG
1173    */
1174   unsigned int i;
1175
1176   for (i = 0; i < src->sds.fd_count; i++)
1177     FD_SET (src->sds.fd_array[i],
1178             &dst->sds);
1179   dst->nsds = GNUNET_MAX (src->nsds,
1180                           dst->nsds);
1181
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,
1185                        dst->handles_size,
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];
1189 #endif
1190 }
1191
1192
1193 /**
1194  * Copy one fd set to another
1195  *
1196  * @param to destination
1197  * @param from source
1198  */
1199 void
1200 GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to,
1201                            const struct GNUNET_NETWORK_FDSet *from)
1202 {
1203   FD_COPY (&from->sds,
1204            &to->sds);
1205   to->nsds = from->nsds;
1206 #ifdef MINGW
1207   if (from->handles_pos > to->handles_size)
1208     GNUNET_array_grow (to->handles,
1209                        to->handles_size,
1210                        from->handles_pos * 2);
1211   GNUNET_memcpy (to->handles,
1212                  from->handles,
1213                  from->handles_pos * sizeof (struct GNUNET_NETWORK_Handle *));
1214   to->handles_pos = from->handles_pos;
1215 #endif
1216 }
1217
1218
1219 /**
1220  * Return file descriptor for this network handle
1221  *
1222  * @param desc wrapper to process
1223  * @return POSIX file descriptor
1224  */
1225 int
1226 GNUNET_NETWORK_get_fd (const struct GNUNET_NETWORK_Handle *desc)
1227 {
1228   return desc->fd;
1229 }
1230
1231
1232 /**
1233  * Return sockaddr for this network handle
1234  *
1235  * @param desc wrapper to process
1236  * @return sockaddr
1237  */
1238 struct sockaddr*
1239 GNUNET_NETWORK_get_addr (const struct GNUNET_NETWORK_Handle *desc)
1240 {
1241   return desc->addr;
1242 }
1243
1244
1245 /**
1246  * Return sockaddr length for this network handle
1247  *
1248  * @param desc wrapper to process
1249  * @return socklen_t for sockaddr
1250  */
1251 socklen_t
1252 GNUNET_NETWORK_get_addrlen (const struct GNUNET_NETWORK_Handle *desc)
1253 {
1254   return desc->addrlen;
1255 }
1256
1257
1258 /**
1259  * Copy a native fd set
1260  *
1261  * @param to destination
1262  * @param from native source set
1263  * @param nfds the biggest socket number in from + 1
1264  */
1265 void
1266 GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to,
1267                                   const fd_set *from,
1268                                   int nfds)
1269 {
1270   FD_COPY (from,
1271            &to->sds);
1272   to->nsds = nfds;
1273 }
1274
1275
1276 /**
1277  * Set a native fd in a set
1278  *
1279  * @param to destination
1280  * @param nfd native FD to set
1281  */
1282 void
1283 GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to,
1284                                  int nfd)
1285 {
1286   GNUNET_assert ((nfd >= 0) && (nfd < FD_SETSIZE));
1287   FD_SET (nfd, &to->sds);
1288   to->nsds = GNUNET_MAX (nfd + 1,
1289                          to->nsds);
1290 }
1291
1292
1293 /**
1294  * Test native fd in a set
1295  *
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
1299  */
1300 int
1301 GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to,
1302                                   int nfd)
1303 {
1304   if ( (-1 == nfd) ||
1305        (NULL == to) )
1306     return GNUNET_NO;
1307   return FD_ISSET (nfd, &to->sds) ? GNUNET_YES : GNUNET_NO;
1308 }
1309
1310
1311 /**
1312  * Add a file handle to the fd set
1313  * @param fds fd set
1314  * @param h the file handle to add
1315  */
1316 void
1317 GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds,
1318                                  const struct GNUNET_DISK_FileHandle *h)
1319 {
1320 #ifdef MINGW
1321   if (fds->handles_pos == fds->handles_size)
1322     GNUNET_array_grow (fds->handles,
1323                        fds->handles_size,
1324                        fds->handles_size * 2 + 2);
1325   fds->handles[fds->handles_pos++] = h;
1326 #else
1327   int fd;
1328
1329   GNUNET_assert (GNUNET_OK ==
1330                  GNUNET_DISK_internal_file_handle_ (h,
1331                                                     &fd,
1332                                                     sizeof (int)));
1333   FD_SET (fd,
1334           &fds->sds);
1335   fds->nsds = GNUNET_MAX (fd + 1,
1336                           fds->nsds);
1337 #endif
1338 }
1339
1340
1341 /**
1342  * Add a file handle to the fd set
1343  * @param fds fd set
1344  * @param h the file handle to add
1345  */
1346 void
1347 GNUNET_NETWORK_fdset_handle_set_first (struct GNUNET_NETWORK_FDSet *fds,
1348                                        const struct GNUNET_DISK_FileHandle *h)
1349 {
1350 #ifdef MINGW
1351   if (fds->handles_pos == fds->handles_size)
1352     GNUNET_array_grow (fds->handles,
1353                        fds->handles_size,
1354                        fds->handles_size * 2 + 2);
1355   fds->handles[fds->handles_pos] = h;
1356   if (fds->handles[0] != h)
1357   {
1358     const struct GNUNET_DISK_FileHandle *bak = fds->handles[0];
1359     fds->handles[0] = h;
1360     fds->handles[fds->handles_pos] = bak;
1361   }
1362   fds->handles_pos++;
1363 #else
1364   GNUNET_NETWORK_fdset_handle_set (fds, h);
1365 #endif
1366 }
1367
1368
1369 /**
1370  * Check if a file handle is part of an fd set
1371  *
1372  * @param fds fd set
1373  * @param h file handle
1374  * @return #GNUNET_YES if the file handle is part of the set
1375  */
1376 int
1377 GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds,
1378                                    const struct GNUNET_DISK_FileHandle *h)
1379 {
1380 #ifdef MINGW
1381   unsigned int i;
1382
1383   for (i=0;i<fds->handles_pos;i++)
1384     if (fds->handles[i] == h)
1385       return GNUNET_YES;
1386   return GNUNET_NO;
1387 #else
1388   return FD_ISSET (h->fd,
1389                    &fds->sds);
1390 #endif
1391 }
1392
1393
1394 #ifdef MINGW
1395 /**
1396  * Numerically compare pointers to sort them.
1397  * Used to test for overlap in the arrays.
1398  *
1399  * @param p1 a pointer
1400  * @param p2 a pointer
1401  * @return -1, 0 or 1, if the p1 < p2, p1==p2 or p1 > p2.
1402  */
1403 static int
1404 ptr_cmp (const void *p1,
1405          const void *p2)
1406 {
1407   if (p1 == p2)
1408     return 0;
1409   if ((intptr_t) p1 < (intptr_t) p2)
1410     return -1;
1411   return 1;
1412 }
1413 #endif
1414
1415
1416 /**
1417  * Checks if two fd sets overlap
1418  *
1419  * @param fds1 first fd set
1420  * @param fds2 second fd set
1421  * @return #GNUNET_YES if they do overlap, #GNUNET_NO otherwise
1422  */
1423 int
1424 GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1,
1425                               const struct GNUNET_NETWORK_FDSet *fds2)
1426 {
1427 #ifndef MINGW
1428   int nfds;
1429
1430   nfds = GNUNET_MIN (fds1->nsds,
1431                      fds2->nsds);
1432   while (nfds > 0)
1433   {
1434     nfds--;
1435     if ( (FD_ISSET (nfds,
1436                     &fds1->sds)) &&
1437          (FD_ISSET (nfds,
1438                     &fds2->sds)) )
1439       return GNUNET_YES;
1440   }
1441   return GNUNET_NO;
1442 #else
1443   unsigned int i;
1444   unsigned int j;
1445
1446   /* This code is somewhat hacky, we are not supposed to know what's
1447    * inside of fd_set; also the O(n^2) is really bad... */
1448   for (i = 0; i < fds1->sds.fd_count; i++)
1449     for (j = 0; j < fds2->sds.fd_count; j++)
1450       if (fds1->sds.fd_array[i] == fds2->sds.fd_array[j])
1451         return GNUNET_YES;
1452
1453   /* take a short cut if possible */
1454   if ( (0 == fds1->handles_pos) ||
1455        (0 == fds2->handles_pos) )
1456     return GNUNET_NO;
1457
1458   /* Sort file handles array to avoid quadratic complexity when
1459      checking for overlap */
1460   qsort (fds1->handles,
1461          fds1->handles_pos,
1462          sizeof (void *),
1463          &ptr_cmp);
1464   qsort (fds2->handles,
1465          fds2->handles_pos,
1466          sizeof (void *),
1467          &ptr_cmp);
1468   i = 0;
1469   j = 0;
1470   while ( (i < fds1->handles_pos) &&
1471           (j < fds2->handles_pos) )
1472   {
1473     switch (ptr_cmp (fds1->handles[i],
1474                      fds2->handles[j]))
1475     {
1476     case -1:
1477       i++;
1478       break;
1479     case 0:
1480       return GNUNET_YES;
1481     case 1:
1482       j++;
1483     }
1484   }
1485   return GNUNET_NO;
1486 #endif
1487 }
1488
1489
1490 /**
1491  * Creates an fd set
1492  *
1493  * @return a new fd set
1494  */
1495 struct GNUNET_NETWORK_FDSet *
1496 GNUNET_NETWORK_fdset_create ()
1497 {
1498   struct GNUNET_NETWORK_FDSet *fds;
1499
1500   fds = GNUNET_new (struct GNUNET_NETWORK_FDSet);
1501   GNUNET_NETWORK_fdset_zero (fds);
1502   return fds;
1503 }
1504
1505
1506 /**
1507  * Releases the associated memory of an fd set
1508  *
1509  * @param fds fd set
1510  */
1511 void
1512 GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds)
1513 {
1514 #ifdef MINGW
1515   GNUNET_array_grow (fds->handles,
1516                      fds->handles_size,
1517                      0);
1518 #endif
1519   GNUNET_free (fds);
1520 }
1521
1522
1523 #if MINGW
1524 /**
1525  * FIXME.
1526  */
1527 struct _select_params
1528 {
1529   /**
1530    * Read set.
1531    */
1532   fd_set *r;
1533
1534   /**
1535    * Write set.
1536    */
1537   fd_set *w;
1538
1539   /**
1540    * Except set.
1541    */
1542   fd_set *e;
1543
1544   /**
1545    * Timeout for select().
1546    */
1547   struct timeval *tv;
1548
1549   /**
1550    * FIXME.
1551    */
1552   HANDLE wakeup;
1553
1554   /**
1555    * FIXME.
1556    */
1557   HANDLE standby;
1558
1559   /**
1560    * FIXME.
1561    */
1562   SOCKET wakeup_socket;
1563
1564   /**
1565    * Set to return value from select.
1566    */
1567   int status;
1568 };
1569
1570
1571 /**
1572  * FIXME.
1573  */
1574 static DWORD WINAPI
1575 _selector (LPVOID p)
1576 {
1577   struct _select_params *sp = p;
1578
1579   while (1)
1580   {
1581     WaitForSingleObject (sp->standby,
1582                          INFINITE);
1583     ResetEvent (sp->standby);
1584     sp->status = select (1,
1585                          sp->r,
1586                          sp->w,
1587                          sp->e,
1588                          sp->tv);
1589     if (FD_ISSET (sp->wakeup_socket,
1590                   sp->r))
1591     {
1592       FD_CLR (sp->wakeup_socket,
1593               sp->r);
1594       sp->status -= 1;
1595     }
1596     SetEvent (sp->wakeup);
1597   }
1598   return 0;
1599 }
1600
1601
1602 static HANDLE hEventPipeWrite;
1603
1604 static HANDLE hEventReadReady;
1605
1606 static struct _select_params sp;
1607
1608 static HANDLE select_thread;
1609
1610 static HANDLE select_finished_event;
1611
1612 static HANDLE select_standby_event;
1613
1614 static SOCKET select_wakeup_socket = -1;
1615
1616 static SOCKET select_send_socket = -1;
1617
1618 static struct timeval select_timeout;
1619
1620
1621 /**
1622  * On W32, we actually use a thread to help with the
1623  * event loop due to W32-API limitations.  This function
1624  * initializes that thread.
1625  */
1626 static void
1627 initialize_select_thread ()
1628 {
1629   SOCKET select_listening_socket = -1;
1630   struct sockaddr_in s_in;
1631   int alen;
1632   int res;
1633   unsigned long p;
1634
1635   select_standby_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1636   select_finished_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1637
1638   select_wakeup_socket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1639
1640   select_listening_socket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1641
1642   p = 1;
1643   res = ioctlsocket (select_wakeup_socket, FIONBIO, &p);
1644   LOG (GNUNET_ERROR_TYPE_DEBUG,
1645        "Select thread initialization: ioctlsocket() returns %d\n",
1646        res);
1647
1648   alen = sizeof (s_in);
1649   s_in.sin_family = AF_INET;
1650   s_in.sin_port = 0;
1651   s_in.sin_addr.S_un.S_un_b.s_b1 = 127;
1652   s_in.sin_addr.S_un.S_un_b.s_b2 = 0;
1653   s_in.sin_addr.S_un.S_un_b.s_b3 = 0;
1654   s_in.sin_addr.S_un.S_un_b.s_b4 = 1;
1655   res = bind (select_listening_socket,
1656               (const struct sockaddr *) &s_in,
1657               sizeof (s_in));
1658   LOG (GNUNET_ERROR_TYPE_DEBUG,
1659        "Select thread initialization: bind() returns %d\n",
1660        res);
1661
1662   res = getsockname (select_listening_socket,
1663                      (struct sockaddr *) &s_in,
1664                      &alen);
1665   LOG (GNUNET_ERROR_TYPE_DEBUG,
1666        "Select thread initialization: getsockname() returns %d\n",
1667        res);
1668
1669   res = listen (select_listening_socket,
1670                 SOMAXCONN);
1671   LOG (GNUNET_ERROR_TYPE_DEBUG,
1672        "Select thread initialization: listen() returns %d\n",
1673        res);
1674   res = connect (select_wakeup_socket,
1675                  (const struct sockaddr *) &s_in,
1676                  sizeof (s_in));
1677   LOG (GNUNET_ERROR_TYPE_DEBUG,
1678        "Select thread initialization: connect() returns %d\n",
1679        res);
1680
1681   select_send_socket = accept (select_listening_socket,
1682                                (struct sockaddr *) &s_in,
1683                                &alen);
1684
1685   closesocket (select_listening_socket);
1686
1687   sp.wakeup = select_finished_event;
1688   sp.standby = select_standby_event;
1689   sp.wakeup_socket = select_wakeup_socket;
1690
1691   select_thread = CreateThread (NULL,
1692                                 0,
1693                                 _selector,
1694                                 &sp,
1695                                 0, NULL);
1696 }
1697
1698
1699 #endif
1700
1701 /**
1702  * Test if the given @a port is available.
1703  *
1704  * @param ipproto transport protocol to test (i.e. IPPROTO_TCP)
1705  * @param port port number to test
1706  * @return #GNUNET_OK if the port is available, #GNUNET_NO if not
1707  */
1708 int
1709 GNUNET_NETWORK_test_port_free (int ipproto,
1710                                uint16_t port)
1711 {
1712   struct GNUNET_NETWORK_Handle *socket;
1713   int bind_status;
1714   int socktype;
1715   char open_port_str[6];
1716   struct addrinfo hint;
1717   struct addrinfo *ret;
1718   struct addrinfo *ai;
1719
1720   GNUNET_snprintf (open_port_str,
1721                    sizeof (open_port_str),
1722                    "%u",
1723                    (unsigned int) port);
1724   socktype = (IPPROTO_TCP == ipproto) ? SOCK_STREAM : SOCK_DGRAM;
1725   ret = NULL;
1726   memset (&hint, 0, sizeof (hint));
1727   hint.ai_family = AF_UNSPEC; /* IPv4 and IPv6 */
1728   hint.ai_socktype = socktype;
1729   hint.ai_protocol = ipproto;
1730   hint.ai_addrlen = 0;
1731   hint.ai_addr = NULL;
1732   hint.ai_canonname = NULL;
1733   hint.ai_next = NULL;
1734   hint.ai_flags = AI_PASSIVE | AI_NUMERICSERV; /* Wild card address */
1735   GNUNET_assert (0 == getaddrinfo (NULL,
1736                                    open_port_str,
1737                                    &hint,
1738                                    &ret));
1739   bind_status = GNUNET_NO;
1740   for (ai = ret; NULL != ai; ai = ai->ai_next)
1741   {
1742     socket = GNUNET_NETWORK_socket_create (ai->ai_family,
1743                                            ai->ai_socktype,
1744                                            ai->ai_protocol);
1745     if (NULL == socket)
1746       continue;
1747     bind_status = GNUNET_NETWORK_socket_bind (socket,
1748                                               ai->ai_addr,
1749                                               ai->ai_addrlen);
1750     GNUNET_NETWORK_socket_close (socket);
1751     if (GNUNET_OK != bind_status)
1752       break;
1753   }
1754   freeaddrinfo (ret);
1755   return bind_status;
1756 }
1757
1758
1759 #ifndef MINGW
1760 /**
1761  * Check if sockets or pipes meet certain conditions
1762  *
1763  * @param rfds set of sockets or pipes to be checked for readability
1764  * @param wfds set of sockets or pipes to be checked for writability
1765  * @param efds set of sockets or pipes to be checked for exceptions
1766  * @param timeout relative value when to return
1767  * @return number of selected sockets or pipes, #GNUNET_SYSERR on error
1768  */
1769 int
1770 GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1771                               struct GNUNET_NETWORK_FDSet *wfds,
1772                               struct GNUNET_NETWORK_FDSet *efds,
1773                               const struct GNUNET_TIME_Relative timeout)
1774 {
1775   int nfds;
1776   struct timeval tv;
1777
1778   if (NULL != rfds)
1779     nfds = rfds->nsds;
1780   else
1781     nfds = 0;
1782   if (NULL != wfds)
1783     nfds = GNUNET_MAX (nfds,
1784                        wfds->nsds);
1785   if (NULL != efds)
1786     nfds = GNUNET_MAX (nfds,
1787                        efds->nsds);
1788   if ((0 == nfds) &&
1789       (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us))
1790   {
1791     GNUNET_break (0);
1792     LOG (GNUNET_ERROR_TYPE_ERROR,
1793          _("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1794          "select");
1795   }
1796   if (timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us > (unsigned long long) LONG_MAX)
1797   {
1798     tv.tv_sec = LONG_MAX;
1799     tv.tv_usec = 999999L;
1800   }
1801   else
1802   {
1803     tv.tv_sec = (long) (timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us);
1804     tv.tv_usec =
1805       (timeout.rel_value_us -
1806        (tv.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value_us));
1807   }
1808   return select (nfds,
1809                  (NULL != rfds) ? &rfds->sds : NULL,
1810                  (NULL != wfds) ? &wfds->sds : NULL,
1811                  (NULL != efds) ? &efds->sds : NULL,
1812                  (timeout.rel_value_us ==
1813                   GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) ? NULL : &tv);
1814 }
1815
1816
1817 #else
1818 /* MINGW */
1819
1820
1821 /**
1822  * Non-blocking test if a pipe is ready for reading.
1823  *
1824  * @param fh pipe handle
1825  * @return #GNUNET_YES if the pipe is ready for reading
1826  */
1827 static int
1828 pipe_read_ready (const struct GNUNET_DISK_FileHandle *fh)
1829 {
1830   DWORD error;
1831   BOOL bret;
1832   DWORD waitstatus = 0;
1833
1834   SetLastError (0);
1835   bret = PeekNamedPipe (fh->h, NULL, 0, NULL, &waitstatus, NULL);
1836   error = GetLastError ();
1837   if (0 == bret)
1838   {
1839     /* TODO: either add more errors to this condition, or eliminate it
1840      * entirely (failed to peek -> pipe is in serious trouble, should
1841      * be selected as readable).
1842      */
1843     if ( (error != ERROR_BROKEN_PIPE) &&
1844          (error != ERROR_INVALID_HANDLE) )
1845       return GNUNET_NO;
1846   }
1847   else if (waitstatus <= 0)
1848     return GNUNET_NO;
1849   return GNUNET_YES;
1850 }
1851
1852
1853 /**
1854  * Non-blocking test if a pipe is having an IO exception.
1855  *
1856  * @param fh pipe handle
1857  * @return #GNUNET_YES if the pipe is having an IO exception.
1858  */
1859 static int
1860 pipe_except_ready (const struct GNUNET_DISK_FileHandle *fh)
1861 {
1862   DWORD dwBytes;
1863
1864   if (PeekNamedPipe (fh->h, NULL, 0, NULL, &dwBytes, NULL))
1865     return GNUNET_NO;
1866   return GNUNET_YES;
1867 }
1868
1869
1870 /**
1871  * Iterate over handles in fds, destructively rewrite the
1872  * handles array contents of fds so that it starts with the
1873  * handles that are ready, and update handles_pos accordingly.
1874  *
1875  * @param fds set of handles (usually pipes) to be checked for readiness
1876  * @param except GNUNET_NO if fds should be checked for readiness to read,
1877  * GNUNET_YES if fds should be checked for exceptions
1878  * (there is no way to check for write-readiness - pipes are always write-ready)
1879  * @param set_for_sure a HANDLE that is known to be set already,
1880  * because WaitForMultipleObjects() returned its index.
1881  * @return number of ready handles
1882  */
1883 static int
1884 check_handles_status (struct GNUNET_NETWORK_FDSet *fds,
1885                       int except,
1886                       HANDLE set_for_sure)
1887 {
1888   const struct GNUNET_DISK_FileHandle *fh;
1889   unsigned int roff;
1890   unsigned int woff;
1891
1892   for (woff = 0, roff = 0; roff < fds->handles_pos; roff++)
1893   {
1894     fh = fds->handles[roff];
1895     if (fh == set_for_sure)
1896     {
1897       fds->handles[woff++] = fh;
1898     }
1899     else if (fh->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
1900     {
1901       if ((except && pipe_except_ready (fh)) ||
1902           (!except && pipe_read_ready (fh)))
1903         fds->handles[woff++] = fh;
1904     }
1905     else if (fh->type == GNUNET_DISK_HANLDE_TYPE_FILE)
1906     {
1907       if (!except)
1908         fds->handles[woff++] = fh;
1909     }
1910     else
1911     {
1912       if (WAIT_OBJECT_0 == WaitForSingleObject (fh->h, 0))
1913         fds->handles[woff++] = fh;
1914     }
1915   }
1916   fds->handles_pos = woff;
1917   return woff;
1918 }
1919
1920
1921 /**
1922  * Check if sockets or pipes meet certain conditions, version for W32.
1923  *
1924  * @param rfds set of sockets or pipes to be checked for readability
1925  * @param wfds set of sockets or pipes to be checked for writability
1926  * @param efds set of sockets or pipes to be checked for exceptions
1927  * @param timeout relative value when to return
1928  * @return number of selected sockets or pipes, #GNUNET_SYSERR on error
1929  */
1930 int
1931 GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1932                               struct GNUNET_NETWORK_FDSet *wfds,
1933                               struct GNUNET_NETWORK_FDSet *efds,
1934                               const struct GNUNET_TIME_Relative timeout)
1935 {
1936   const struct GNUNET_DISK_FileHandle *fh;
1937   int nfds;
1938   int handles;
1939   unsigned int i;
1940   int retcode;
1941   uint64_t mcs_total;
1942   DWORD ms_rounded;
1943   int nhandles = 0;
1944   int read_pipes_off;
1945   HANDLE handle_array[FD_SETSIZE + 2];
1946   int returncode;
1947   int returnedpos = 0;
1948   int selectret;
1949   fd_set aread;
1950   fd_set awrite;
1951   fd_set aexcept;
1952
1953   nfds = 0;
1954   handles = 0;
1955   if (NULL != rfds)
1956   {
1957     nfds = GNUNET_MAX (nfds, rfds->nsds);
1958     handles += rfds->handles_pos;
1959   }
1960   if (NULL != wfds)
1961   {
1962     nfds = GNUNET_MAX (nfds, wfds->nsds);
1963     handles += wfds->handles_pos;
1964   }
1965   if (NULL != efds)
1966   {
1967     nfds = GNUNET_MAX (nfds, efds->nsds);
1968     handles += efds->handles_pos;
1969   }
1970
1971   if ((0 == nfds) &&
1972       (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == timeout.rel_value_us) &&
1973       (0 == handles) )
1974   {
1975     GNUNET_break (0);
1976     LOG (GNUNET_ERROR_TYPE_ERROR,
1977          _("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1978          "select");
1979   }
1980 #define SAFE_FD_ISSET(fd, set)  (set != NULL && FD_ISSET(fd, set))
1981   /* calculate how long we need to wait in microseconds */
1982   if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1983   {
1984     mcs_total = INFINITE;
1985     ms_rounded = INFINITE;
1986   }
1987   else
1988   {
1989     mcs_total = timeout.rel_value_us / GNUNET_TIME_UNIT_MICROSECONDS.rel_value_us;
1990     ms_rounded = (DWORD) (mcs_total / GNUNET_TIME_UNIT_MILLISECONDS.rel_value_us);
1991     if (mcs_total > 0 && ms_rounded == 0)
1992       ms_rounded = 1;
1993   }
1994   /* select() may be used as a portable way to sleep */
1995   if (! (rfds || wfds || efds))
1996   {
1997     Sleep (ms_rounded);
1998     return 0;
1999   }
2000
2001   if (NULL == select_thread)
2002     initialize_select_thread ();
2003
2004   FD_ZERO (&aread);
2005   FD_ZERO (&awrite);
2006   FD_ZERO (&aexcept);
2007   if (rfds)
2008     FD_COPY (&rfds->sds, &aread);
2009   if (wfds)
2010     FD_COPY (&wfds->sds, &awrite);
2011   if (efds)
2012     FD_COPY (&efds->sds, &aexcept);
2013
2014   /* Start by doing a fast check on sockets and pipes (without
2015      waiting). It is cheap, and is sufficient most of the time.  By
2016      profiling we detected that to be true in 90% of the cases.
2017   */
2018
2019   /* Do the select now */
2020   select_timeout.tv_sec = 0;
2021   select_timeout.tv_usec = 0;
2022
2023   /* Copy all the writes to the except, so we can detect connect() errors */
2024   for (i = 0; i < awrite.fd_count; i++)
2025     FD_SET (awrite.fd_array[i],
2026             &aexcept);
2027   if ( (aread.fd_count > 0) ||
2028        (awrite.fd_count > 0) ||
2029        (aexcept.fd_count > 0) )
2030     selectret = select (1,
2031                         (NULL != rfds) ? &aread : NULL,
2032                         (NULL != wfds) ? &awrite : NULL,
2033                         &aexcept,
2034                         &select_timeout);
2035   else
2036     selectret = 0;
2037   if (-1 == selectret)
2038   {
2039     /* Throw an error early on, while we still have the context. */
2040     LOG (GNUNET_ERROR_TYPE_ERROR,
2041          "W32 select(%d, %d, %d) failed: %lu\n",
2042          rfds ? aread.fd_count : 0,
2043          wfds ? awrite.fd_count : 0,
2044          aexcept.fd_count,
2045          GetLastError ());
2046     GNUNET_assert (0);
2047   }
2048
2049   /* Check aexcept, if something is in there and we copied that
2050      FD before to detect connect() errors, add it back to the
2051      write set to report errors. */
2052   if (NULL != wfds)
2053     for (i = 0; i < aexcept.fd_count; i++)
2054       if (FD_ISSET (aexcept.fd_array[i],
2055                     &wfds->sds))
2056         FD_SET (aexcept.fd_array[i],
2057                 &awrite);
2058
2059
2060   /* If our select returned something or is a 0-timed request, then
2061      also check the pipes and get out of here! */
2062   /* Sadly, it means code duplication :( */
2063   if ( (selectret > 0) || (0 == mcs_total) )
2064   {
2065     retcode = 0;
2066
2067     /* Read Pipes */
2068     if (rfds && (rfds->handles_pos > 0))
2069       retcode += check_handles_status (rfds, GNUNET_NO, NULL);
2070
2071     /* wfds handles remain untouched, on W32
2072        we pretend our pipes are "always" write-ready */
2073
2074     /* except pipes */
2075     if (efds && (efds->handles_pos > 0))
2076       retcode += check_handles_status (efds, GNUNET_YES, NULL);
2077
2078     if (rfds)
2079     {
2080       GNUNET_NETWORK_fdset_zero (rfds);
2081       if (selectret != -1)
2082         GNUNET_NETWORK_fdset_copy_native (rfds, &aread, selectret);
2083     }
2084     if (wfds)
2085     {
2086       GNUNET_NETWORK_fdset_zero (wfds);
2087       if (selectret != -1)
2088         GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, selectret);
2089     }
2090     if (efds)
2091     {
2092       GNUNET_NETWORK_fdset_zero (efds);
2093       if (selectret != -1)
2094         GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, selectret);
2095     }
2096     if (-1 == selectret)
2097       return -1;
2098     /* Add our select() FDs to the total return value */
2099     retcode += selectret;
2100     return retcode;
2101   }
2102
2103   /* If we got this far, use slower implementation that is able to do a waiting select
2104      on both sockets and pipes simultaneously */
2105
2106   /* Events for pipes */
2107   if (! hEventReadReady)
2108     hEventReadReady = CreateEvent (NULL, TRUE, TRUE, NULL);
2109   if (! hEventPipeWrite)
2110     hEventPipeWrite = CreateEvent (NULL, TRUE, TRUE, NULL);
2111   retcode = 0;
2112
2113   FD_ZERO (&aread);
2114   FD_ZERO (&awrite);
2115   FD_ZERO (&aexcept);
2116   if (rfds)
2117     FD_COPY (&rfds->sds, &aread);
2118   if (wfds)
2119     FD_COPY (&wfds->sds, &awrite);
2120   if (efds)
2121     FD_COPY (&efds->sds, &aexcept);
2122   /* We will first Add the PIPES to the events */
2123   /* Track how far in `handle_array` the read pipes go,
2124      so we may by-pass them quickly if none of them
2125      are selected. */
2126   read_pipes_off = 0;
2127   if (rfds && (rfds->handles_pos > 0))
2128   {
2129     for (i = 0; i <rfds->handles_pos; i++)
2130     {
2131       fh = rfds->handles[i];
2132       if (fh->type == GNUNET_DISK_HANLDE_TYPE_EVENT)
2133       {
2134         handle_array[nhandles++] = fh->h;
2135         continue;
2136       }
2137       if (fh->type != GNUNET_DISK_HANLDE_TYPE_PIPE)
2138         continue;
2139       /* Read zero bytes to check the status of the pipe */
2140       if (! ReadFile (fh->h, NULL, 0, NULL, fh->oOverlapRead))
2141       {
2142         DWORD error_code = GetLastError ();
2143
2144         if (error_code == ERROR_IO_PENDING)
2145         {
2146           /* add as unready */
2147           handle_array[nhandles++] = fh->oOverlapRead->hEvent;
2148           read_pipes_off++;
2149         }
2150         else
2151         {
2152           /* add as ready */
2153           handle_array[nhandles++] = hEventReadReady;
2154           read_pipes_off++;
2155         }
2156       }
2157       else
2158       {
2159         /* error also counts as ready */
2160         handle_array[nhandles++] = hEventReadReady;
2161         read_pipes_off++;
2162       }
2163     }
2164   }
2165
2166   if (wfds && (wfds->handles_pos > 0))
2167   {
2168     LOG (GNUNET_ERROR_TYPE_DEBUG,
2169          "Adding the write ready event to the array as %d\n",
2170          nhandles);
2171     handle_array[nhandles++] = hEventPipeWrite;
2172   }
2173
2174   sp.status = 0;
2175   if (nfds > 0)
2176   {
2177     LOG (GNUNET_ERROR_TYPE_DEBUG,
2178          "Adding the socket event to the array as %d\n",
2179          nhandles);
2180     handle_array[nhandles++] = select_finished_event;
2181     if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
2182     {
2183       sp.tv = NULL;
2184     }
2185     else
2186     {
2187       select_timeout.tv_sec = timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us;
2188       select_timeout.tv_usec = (timeout.rel_value_us -
2189                                 (select_timeout.tv_sec *
2190                                  GNUNET_TIME_UNIT_SECONDS.rel_value_us));
2191       sp.tv = &select_timeout;
2192     }
2193     FD_SET (select_wakeup_socket, &aread);
2194     do
2195     {
2196       i = recv (select_wakeup_socket,
2197                 (char *) &returnedpos,
2198                 1,
2199                 0);
2200     } while (i == 1);
2201     sp.r = &aread;
2202     sp.w = &awrite;
2203     sp.e = &aexcept;
2204     /* Failed connections cause sockets to be set in errorfds on W32,
2205      * but on POSIX it should set them in writefds.
2206      * First copy all awrite sockets to aexcept, later we'll
2207      * check aexcept and set its contents in awrite as well
2208      * Sockets are also set in errorfds when OOB data is available,
2209      * but we don't use OOB data.
2210      */
2211     for (i = 0; i < awrite.fd_count; i++)
2212       FD_SET (awrite.fd_array[i],
2213               &aexcept);
2214     ResetEvent (select_finished_event);
2215     SetEvent (select_standby_event);
2216   }
2217
2218   /* NULL-terminate array */
2219   handle_array[nhandles] = NULL;
2220   LOG (GNUNET_ERROR_TYPE_DEBUG,
2221        "nfds: %d, handles: %d, will wait: %llu mcs\n",
2222        nfds,
2223        nhandles,
2224        mcs_total);
2225   if (nhandles)
2226   {
2227     returncode
2228       = WaitForMultipleObjects (nhandles,
2229                                 handle_array,
2230                                 FALSE,
2231                                 ms_rounded);
2232     LOG (GNUNET_ERROR_TYPE_DEBUG,
2233          "WaitForMultipleObjects Returned: %d\n",
2234          returncode);
2235   }
2236   else if (nfds > 0)
2237   {
2238     GNUNET_break (0); /* This branch shouldn't actually be executed...*/
2239     i = (int) WaitForSingleObject (select_finished_event,
2240                                    INFINITE);
2241     returncode = WAIT_TIMEOUT;
2242   }
2243   else
2244   {
2245     /* Shouldn't come this far. If it does - investigate. */
2246     GNUNET_assert (0);
2247   }
2248
2249   if (nfds > 0)
2250   {
2251     /* Don't wake up select-thread when delay is 0, it should return immediately
2252      * and wake up by itself.
2253      */
2254     if (0 != mcs_total)
2255       i = send (select_send_socket,
2256                 (const char *) &returnedpos,
2257                 1,
2258                 0);
2259     i = (int) WaitForSingleObject (select_finished_event,
2260                                    INFINITE);
2261     LOG (GNUNET_ERROR_TYPE_DEBUG,
2262          "Finished waiting for the select thread: %d %d\n",
2263          i,
2264          sp.status);
2265     if (0 != mcs_total)
2266     {
2267       do
2268       {
2269         i = recv (select_wakeup_socket,
2270                   (char *) &returnedpos,
2271                   1, 0);
2272       } while (1 == i);
2273     }
2274     /* Check aexcept, add its contents to awrite */
2275     for (i = 0; i < aexcept.fd_count; i++)
2276       FD_SET (aexcept.fd_array[i], &awrite);
2277   }
2278
2279   returnedpos = returncode - WAIT_OBJECT_0;
2280   LOG (GNUNET_ERROR_TYPE_DEBUG,
2281        "return pos is: %d\n",
2282        returnedpos);
2283
2284   if (rfds)
2285   {
2286     /* We queued a zero-long read on each pipe to check
2287      * its state, now we must cancel these read operations.
2288      * This must be done while rfds->handles_pos is still
2289      * intact and matches the number of read handles that we
2290      * got from the caller.
2291      */
2292     for (i = 0; i < rfds->handles_pos; i++)
2293     {
2294       fh = rfds->handles[i];
2295       if (GNUNET_DISK_HANLDE_TYPE_PIPE == fh->type)
2296         CancelIo (fh->h);
2297     }
2298
2299     /* We may have some pipes ready for reading. */
2300     if (returnedpos < read_pipes_off)
2301       retcode += check_handles_status (rfds, GNUNET_NO, handle_array[returnedpos]);
2302     else
2303       rfds->handles_pos = 0;
2304
2305     if (-1 != sp.status)
2306       GNUNET_NETWORK_fdset_copy_native (rfds, &aread, retcode);
2307   }
2308   if (wfds)
2309   {
2310     retcode += wfds->handles_pos;
2311     /* wfds handles remain untouched */
2312     if (-1 != sp.status)
2313       GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, retcode);
2314   }
2315   if (efds)
2316   {
2317     retcode += check_handles_status (rfds,
2318                                      GNUNET_YES,
2319                                      returnedpos < nhandles ? handle_array[returnedpos] : NULL);
2320     if (-1 != sp.status)
2321       GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, retcode);
2322   }
2323
2324   if (sp.status > 0)
2325     retcode += sp.status;
2326
2327   return retcode;
2328 }
2329
2330 /* MINGW */
2331 #endif
2332
2333 /* end of network.c */