66a468e455a8f314eb5c56bb488d497f63d0681d
[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
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.
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      General Public License for more details.
14
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.
19 */
20
21 /**
22  * @file util/network.c
23  * @brief basic, low-level networking interface
24  * @author Nils Durner
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "disk.h"
30
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)
34
35 #define DEBUG_NETWORK GNUNET_EXTRA_LOGGING
36
37
38 #ifndef INVALID_SOCKET
39 #define INVALID_SOCKET -1
40 #endif
41
42
43 /**
44  * @brief handle to a socket
45  */
46 struct GNUNET_NETWORK_Handle
47 {
48 #ifndef MINGW
49   int fd;
50 #else
51   SOCKET fd;
52 #endif
53
54   /**
55    * Address family / domain.
56    */
57   int af;
58
59   /**
60    * Type of the socket
61    */
62   int type;
63
64   /**
65    * Number of bytes in addr.
66    */
67   socklen_t addrlen;
68
69   /**
70    * Address we were bound to, or NULL.
71    */
72   struct sockaddr *addr;
73
74 };
75
76
77 /**
78  * Test if the given protocol family is supported by this system.
79  *
80  * @param pf protocol family to test (PF_INET, PF_INET6, PF_UNIX)
81  * @return #GNUNET_OK if the PF is supported
82  */
83 int
84 GNUNET_NETWORK_test_pf (int pf)
85 {
86   int s;
87
88   s = socket (pf, SOCK_STREAM, 0);
89   if (-1 == s)
90   {
91     if (EAFNOSUPPORT == errno)
92       return GNUNET_NO;
93     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
94                 "Failed to create test socket: %s\n",
95                 STRERROR (errno));
96     return GNUNET_SYSERR;
97   }
98 #if WINDOWS
99   closesocket (s);
100 #else
101   close (s);
102 #endif
103   return GNUNET_OK;
104 }
105
106
107 /**
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).
111  *
112  * @param unixpath long path, will be freed (or same pointer returned
113  *        with moved 0-termination).
114  * @return shortened unixpath, NULL on error
115  */
116 char *
117 GNUNET_NETWORK_shorten_unixpath (char *unixpath)
118 {
119   struct sockaddr_un dummy;
120   size_t slen;
121   char *end;
122   struct GNUNET_HashCode sh;
123   struct GNUNET_CRYPTO_HashAsciiEncoded ae;
124   size_t upm;
125
126   upm = sizeof (dummy.sun_path);
127   slen = strlen (unixpath);
128   if (slen < upm)
129     return unixpath; /* no shortening required */
130   GNUNET_CRYPTO_hash (unixpath, slen, &sh);
131   while (16 +
132          strlen (unixpath) >= upm)
133   {
134     if (NULL == (end = strrchr (unixpath, '/')))
135     {
136       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
137                   _("Unable to shorten unix path `%s' while keeping name unique\n"),
138                   unixpath);
139       GNUNET_free (unixpath);
140       return NULL;
141     }
142     *end = '\0';
143   }
144   GNUNET_CRYPTO_hash_to_enc (&sh, &ae);
145   strncat (unixpath, (char*) ae.encoding, 16);
146   return unixpath;
147 }
148
149
150 #ifndef WINDOWS
151 /**
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).
157  *
158  * @param un unix domain socket address to check
159  */
160 void
161 GNUNET_NETWORK_unix_precheck (const struct sockaddr_un *un)
162 {
163   int s;
164   int eno;
165   struct stat sbuf;
166   int ret;
167
168   s = socket (AF_UNIX, SOCK_STREAM, 0);
169   if (-1 == s)
170   {
171     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
172                          "Failed to open AF_UNIX socket");
173     return;
174   }
175   ret = connect (s,
176                  (struct sockaddr *) un,
177                  sizeof (struct sockaddr_un));
178   eno = errno;
179   GNUNET_break (0 == close (s));
180   if (0 == ret)
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,
186                  &sbuf))
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",
193               un->sun_path);
194   if (0 != unlink (un->sun_path))
195     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
196                               "unlink",
197                               un->sun_path);
198 }
199 #endif
200
201
202
203 #ifndef FD_COPY
204 #define FD_COPY(s, d) do { GNUNET_memcpy ((d), (s), sizeof (fd_set)); } while (0)
205 #endif
206
207
208 /**
209  * Set if a socket should use blocking or non-blocking IO.
210  *
211  * @param fd socket
212  * @param doBlock blocking mode
213  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
214  */
215 int
216 GNUNET_NETWORK_socket_set_blocking (struct GNUNET_NETWORK_Handle *fd,
217                                     int doBlock)
218 {
219
220 #if MINGW
221   u_long mode;
222
223   mode = !doBlock;
224   if (SOCKET_ERROR ==
225       ioctlsocket (fd->fd,
226                    FIONBIO,
227                    &mode))
228
229   {
230     SetErrnoFromWinsockError (WSAGetLastError ());
231     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
232                   "ioctlsocket");
233     return GNUNET_SYSERR;
234   }
235   return GNUNET_OK;
236
237 #else
238   /* not MINGW */
239   int flags = fcntl (fd->fd, F_GETFL);
240
241   if (flags == -1)
242
243   {
244     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
245                   "fcntl");
246     return GNUNET_SYSERR;
247   }
248   if (doBlock)
249     flags &= ~O_NONBLOCK;
250
251   else
252     flags |= O_NONBLOCK;
253   if (0 != fcntl (fd->fd,
254                   F_SETFL,
255                   flags))
256
257   {
258     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
259                   "fcntl");
260     return GNUNET_SYSERR;
261   }
262   return GNUNET_OK;
263 #endif
264 }
265
266
267 /**
268  * Make a socket non-inheritable to child processes
269  *
270  * @param h the socket to make non-inheritable
271  * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
272  * @warning Not implemented on Windows
273  */
274 static int
275 socket_set_inheritable (const struct GNUNET_NETWORK_Handle *h)
276 {
277 #ifndef MINGW
278   int i;
279   i = fcntl (h->fd, F_GETFD);
280   if (i < 0)
281     return GNUNET_SYSERR;
282   if (i == (i | FD_CLOEXEC))
283     return GNUNET_OK;
284   i |= FD_CLOEXEC;
285   if (fcntl (h->fd, F_SETFD, i) < 0)
286     return GNUNET_SYSERR;
287 #else
288   BOOL b;
289   SetLastError (0);
290   b = SetHandleInformation ((HANDLE) h->fd, HANDLE_FLAG_INHERIT, 0);
291   if (!b)
292   {
293     SetErrnoFromWinsockError (WSAGetLastError ());
294     return GNUNET_SYSERR;
295   }
296 #endif
297   return GNUNET_OK;
298 }
299
300
301 #ifdef DARWIN
302 /**
303  * The MSG_NOSIGNAL equivalent on Mac OS X
304  *
305  * @param h the socket to make non-delaying
306  */
307 static void
308 socket_set_nosigpipe (const struct GNUNET_NETWORK_Handle *h)
309 {
310   int abs_value = 1;
311
312   if (0 !=
313       setsockopt (h->fd, SOL_SOCKET, SO_NOSIGPIPE,
314                   (const void *) &abs_value,
315                   sizeof (abs_value)))
316     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
317 }
318 #endif
319
320
321 /**
322  * Disable delays when sending data via the socket.
323  * (GNUnet makes sure that messages are as big as
324  * possible already).
325  *
326  * @param h the socket to make non-delaying
327  */
328 static void
329 socket_set_nodelay (const struct GNUNET_NETWORK_Handle *h)
330 {
331 #ifndef WINDOWS
332   int value = 1;
333
334   if (0 !=
335       setsockopt (h->fd,
336                   IPPROTO_TCP,
337                   TCP_NODELAY,
338                   &value, sizeof (value)))
339     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
340                   "setsockopt");
341 #else
342   const char *abs_value = "1";
343
344   if (0 !=
345       setsockopt (h->fd, IPPROTO_TCP, TCP_NODELAY,
346                   (const void *) abs_value,
347                   sizeof (abs_value)))
348     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
349                   "setsockopt");
350 #endif
351 }
352
353
354 /**
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.
359  *
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
365  */
366 static int
367 initialize_network_handle (struct GNUNET_NETWORK_Handle *h,
368                            int af,
369                            int type)
370 {
371   int eno;
372
373   h->af = af;
374   h->type = type;
375   if (h->fd == INVALID_SOCKET)
376   {
377 #ifdef MINGW
378     SetErrnoFromWinsockError (WSAGetLastError ());
379 #endif
380     eno = errno;
381     GNUNET_free (h);
382     errno = eno;
383     return GNUNET_SYSERR;
384   }
385 #ifndef MINGW
386   if (h->fd >= FD_SETSIZE)
387   {
388     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
389     errno = EMFILE;
390     return GNUNET_SYSERR;
391   }
392 #endif
393   if (GNUNET_OK != socket_set_inheritable (h))
394     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
395                   "socket_set_inheritable");
396
397   if (GNUNET_SYSERR == GNUNET_NETWORK_socket_set_blocking (h, GNUNET_NO))
398   {
399     eno = errno;
400     GNUNET_break (0);
401     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h));
402     errno = eno;
403     return GNUNET_SYSERR;
404   }
405 #ifdef DARWIN
406   socket_set_nosigpipe (h);
407 #endif
408   if ( (type == SOCK_STREAM)
409 #ifdef AF_UNIX
410        && (af != AF_UNIX)
411 #endif
412        )
413     socket_set_nodelay (h);
414   return GNUNET_OK;
415 }
416
417
418 /**
419  * accept a new connection on a socket
420  *
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
425  */
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)
430 {
431   struct GNUNET_NETWORK_Handle *ret;
432   int eno;
433
434   ret = GNUNET_new (struct GNUNET_NETWORK_Handle);
435 #if DEBUG_NETWORK
436   {
437     struct sockaddr_storage name;
438     socklen_t namelen = sizeof (name);
439
440     int gsn = getsockname (desc->fd,
441                            (struct sockaddr *) &name,
442                            &namelen);
443
444     if (0 == gsn)
445       LOG (GNUNET_ERROR_TYPE_DEBUG,
446            "Accepting connection on `%s'\n",
447            GNUNET_a2s ((const struct sockaddr *) &name,
448                        namelen));
449   }
450 #endif
451   ret->fd = accept (desc->fd,
452                     address,
453                     address_len);
454   if (-1 == ret->fd)
455   {
456     eno = errno;
457     GNUNET_free (ret);
458     errno = eno;
459     return NULL;
460   }
461   if (GNUNET_OK !=
462       initialize_network_handle (ret,
463                                  (NULL != address) ? address->sa_family : desc->af,
464                                  SOCK_STREAM))
465   {
466
467     return NULL;
468   }
469   return ret;
470 }
471
472
473 /**
474  * Bind a socket to a particular address.
475  *
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
480  */
481 int
482 GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc,
483                             const struct sockaddr *address,
484                             socklen_t address_len)
485 {
486   int ret;
487
488 #ifdef IPV6_V6ONLY
489 #ifdef IPPROTO_IPV6
490   {
491     const int on = 1;
492
493     if (AF_INET6 == desc->af)
494       if (setsockopt (desc->fd, IPPROTO_IPV6, 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 (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 (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 (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_DISK_internal_file_handle_ (h,
1330                                      &fd,
1331                                      sizeof (int));
1332   FD_SET (fd,
1333           &fds->sds);
1334   fds->nsds = GNUNET_MAX (fd + 1,
1335                           fds->nsds);
1336 #endif
1337 }
1338
1339
1340 /**
1341  * Add a file handle to the fd set
1342  * @param fds fd set
1343  * @param h the file handle to add
1344  */
1345 void
1346 GNUNET_NETWORK_fdset_handle_set_first (struct GNUNET_NETWORK_FDSet *fds,
1347                                        const struct GNUNET_DISK_FileHandle *h)
1348 {
1349 #ifdef MINGW
1350   if (fds->handles_pos == fds->handles_size)
1351     GNUNET_array_grow (fds->handles,
1352                        fds->handles_size,
1353                        fds->handles_size * 2 + 2);
1354   fds->handles[fds->handles_pos] = h;
1355   if (fds->handles[0] != h)
1356   {
1357     const struct GNUNET_DISK_FileHandle *bak = fds->handles[0];
1358     fds->handles[0] = h;
1359     fds->handles[fds->handles_pos] = bak;
1360   }
1361   fds->handles_pos++;
1362 #else
1363   GNUNET_NETWORK_fdset_handle_set (fds, h);
1364 #endif
1365 }
1366
1367
1368 /**
1369  * Check if a file handle is part of an fd set
1370  *
1371  * @param fds fd set
1372  * @param h file handle
1373  * @return #GNUNET_YES if the file handle is part of the set
1374  */
1375 int
1376 GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds,
1377                                    const struct GNUNET_DISK_FileHandle *h)
1378 {
1379 #ifdef MINGW
1380   unsigned int i;
1381
1382   for (i=0;i<fds->handles_pos;i++)
1383     if (fds->handles[i] == h)
1384       return GNUNET_YES;
1385   return GNUNET_NO;
1386 #else
1387   return FD_ISSET (h->fd,
1388                    &fds->sds);
1389 #endif
1390 }
1391
1392
1393 #ifdef MINGW
1394 /**
1395  * Numerically compare pointers to sort them.
1396  * Used to test for overlap in the arrays.
1397  *
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.
1401  */
1402 static int
1403 ptr_cmp (const void *p1,
1404          const void *p2)
1405 {
1406   if (p1 == p2)
1407     return 0;
1408   if ((intptr_t) p1 < (intptr_t) p2)
1409     return -1;
1410   return 1;
1411 }
1412 #endif
1413
1414
1415 /**
1416  * Checks if two fd sets overlap
1417  *
1418  * @param fds1 first fd set
1419  * @param fds2 second fd set
1420  * @return #GNUNET_YES if they do overlap, #GNUNET_NO otherwise
1421  */
1422 int
1423 GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1,
1424                               const struct GNUNET_NETWORK_FDSet *fds2)
1425 {
1426 #ifndef MINGW
1427   int nfds;
1428
1429   nfds = GNUNET_MIN (fds1->nsds,
1430                      fds2->nsds);
1431   while (nfds > 0)
1432   {
1433     nfds--;
1434     if ( (FD_ISSET (nfds,
1435                     &fds1->sds)) &&
1436          (FD_ISSET (nfds,
1437                     &fds2->sds)) )
1438       return GNUNET_YES;
1439   }
1440   return GNUNET_NO;
1441 #else
1442   unsigned int i;
1443   unsigned int j;
1444
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])
1450         return GNUNET_YES;
1451
1452   /* take a short cut if possible */
1453   if ( (0 == fds1->handles_pos) ||
1454        (0 == fds2->handles_pos) )
1455     return GNUNET_NO;
1456
1457   /* Sort file handles array to avoid quadratic complexity when
1458      checking for overlap */
1459   qsort (fds1->handles,
1460          fds1->handles_pos,
1461          sizeof (void *),
1462          &ptr_cmp);
1463   qsort (fds2->handles,
1464          fds2->handles_pos,
1465          sizeof (void *),
1466          &ptr_cmp);
1467   i = 0;
1468   j = 0;
1469   while ( (i < fds1->handles_pos) &&
1470           (j < fds2->handles_pos) )
1471   {
1472     switch (ptr_cmp (fds1->handles[i],
1473                      fds2->handles[j]))
1474     {
1475     case -1:
1476       i++;
1477       break;
1478     case 0:
1479       return GNUNET_YES;
1480     case 1:
1481       j++;
1482     }
1483   }
1484   return GNUNET_NO;
1485 #endif
1486 }
1487
1488
1489 /**
1490  * Creates an fd set
1491  *
1492  * @return a new fd set
1493  */
1494 struct GNUNET_NETWORK_FDSet *
1495 GNUNET_NETWORK_fdset_create ()
1496 {
1497   struct GNUNET_NETWORK_FDSet *fds;
1498
1499   fds = GNUNET_new (struct GNUNET_NETWORK_FDSet);
1500   GNUNET_NETWORK_fdset_zero (fds);
1501   return fds;
1502 }
1503
1504
1505 /**
1506  * Releases the associated memory of an fd set
1507  *
1508  * @param fds fd set
1509  */
1510 void
1511 GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds)
1512 {
1513 #ifdef MINGW
1514   GNUNET_array_grow (fds->handles,
1515                      fds->handles_size,
1516                      0);
1517 #endif
1518   GNUNET_free (fds);
1519 }
1520
1521
1522 #if MINGW
1523 /**
1524  * FIXME.
1525  */
1526 struct _select_params
1527 {
1528   /**
1529    * Read set.
1530    */
1531   fd_set *r;
1532
1533   /**
1534    * Write set.
1535    */
1536   fd_set *w;
1537
1538   /**
1539    * Except set.
1540    */
1541   fd_set *e;
1542
1543   /**
1544    * Timeout for select().
1545    */
1546   struct timeval *tv;
1547
1548   /**
1549    * FIXME.
1550    */
1551   HANDLE wakeup;
1552
1553   /**
1554    * FIXME.
1555    */
1556   HANDLE standby;
1557
1558   /**
1559    * FIXME.
1560    */
1561   SOCKET wakeup_socket;
1562
1563   /**
1564    * Set to return value from select.
1565    */
1566   int status;
1567 };
1568
1569
1570 /**
1571  * FIXME.
1572  */
1573 static DWORD WINAPI
1574 _selector (LPVOID p)
1575 {
1576   struct _select_params *sp = p;
1577
1578   while (1)
1579   {
1580     WaitForSingleObject (sp->standby,
1581                          INFINITE);
1582     ResetEvent (sp->standby);
1583     sp->status = select (1,
1584                          sp->r,
1585                          sp->w,
1586                          sp->e,
1587                          sp->tv);
1588     if (FD_ISSET (sp->wakeup_socket,
1589                   sp->r))
1590     {
1591       FD_CLR (sp->wakeup_socket,
1592               sp->r);
1593       sp->status -= 1;
1594     }
1595     SetEvent (sp->wakeup);
1596   }
1597   return 0;
1598 }
1599
1600
1601 static HANDLE hEventPipeWrite;
1602
1603 static HANDLE hEventReadReady;
1604
1605 static struct _select_params sp;
1606
1607 static HANDLE select_thread;
1608
1609 static HANDLE select_finished_event;
1610
1611 static HANDLE select_standby_event;
1612
1613 static SOCKET select_wakeup_socket = -1;
1614
1615 static SOCKET select_send_socket = -1;
1616
1617 static struct timeval select_timeout;
1618
1619
1620 /**
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.
1624  */
1625 static void
1626 initialize_select_thread ()
1627 {
1628   SOCKET select_listening_socket = -1;
1629   struct sockaddr_in s_in;
1630   int alen;
1631   int res;
1632   unsigned long p;
1633
1634   select_standby_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1635   select_finished_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1636
1637   select_wakeup_socket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1638
1639   select_listening_socket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1640
1641   p = 1;
1642   res = ioctlsocket (select_wakeup_socket, FIONBIO, &p);
1643   LOG (GNUNET_ERROR_TYPE_DEBUG,
1644        "Select thread initialization: ioctlsocket() returns %d\n",
1645        res);
1646
1647   alen = sizeof (s_in);
1648   s_in.sin_family = AF_INET;
1649   s_in.sin_port = 0;
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,
1656               sizeof (s_in));
1657   LOG (GNUNET_ERROR_TYPE_DEBUG,
1658        "Select thread initialization: bind() returns %d\n",
1659        res);
1660
1661   res = getsockname (select_listening_socket,
1662                      (struct sockaddr *) &s_in,
1663                      &alen);
1664   LOG (GNUNET_ERROR_TYPE_DEBUG,
1665        "Select thread initialization: getsockname() returns %d\n",
1666        res);
1667
1668   res = listen (select_listening_socket,
1669                 SOMAXCONN);
1670   LOG (GNUNET_ERROR_TYPE_DEBUG,
1671        "Select thread initialization: listen() returns %d\n",
1672        res);
1673   res = connect (select_wakeup_socket,
1674                  (const struct sockaddr *) &s_in,
1675                  sizeof (s_in));
1676   LOG (GNUNET_ERROR_TYPE_DEBUG,
1677        "Select thread initialization: connect() returns %d\n",
1678        res);
1679
1680   select_send_socket = accept (select_listening_socket,
1681                                (struct sockaddr *) &s_in,
1682                                &alen);
1683
1684   closesocket (select_listening_socket);
1685
1686   sp.wakeup = select_finished_event;
1687   sp.standby = select_standby_event;
1688   sp.wakeup_socket = select_wakeup_socket;
1689
1690   select_thread = CreateThread (NULL,
1691                                 0,
1692                                 _selector,
1693                                 &sp,
1694                                 0, NULL);
1695 }
1696
1697
1698 #endif
1699
1700 /**
1701  * Test if the given @a port is available.
1702  *
1703  * @param ipproto transport protocol to test (i.e. IPPROTO_TCP)
1704  * @param port port number to test
1705  * @return #GNUNET_OK if the port is available, #GNUNET_NO if not
1706  */
1707 int
1708 GNUNET_NETWORK_test_port_free (int ipproto,
1709                                uint16_t port)
1710 {
1711   struct GNUNET_NETWORK_Handle *socket;
1712   int bind_status;
1713   int socktype;
1714   char open_port_str[6];
1715   struct addrinfo hint;
1716   struct addrinfo *ret;
1717   struct addrinfo *ai;
1718
1719   GNUNET_snprintf (open_port_str,
1720                    sizeof (open_port_str),
1721                    "%u",
1722                    (unsigned int) port);
1723   socktype = (IPPROTO_TCP == ipproto)
1724     ? SOCK_STREAM
1725     : SOCK_DGRAM;
1726   ret = NULL;
1727   memset (&hint, 0, sizeof (hint));
1728   hint.ai_family = AF_UNSPEC;   /* IPv4 and IPv6 */
1729   hint.ai_socktype = socktype;
1730   hint.ai_protocol = ipproto;
1731   hint.ai_addrlen = 0;
1732   hint.ai_addr = NULL;
1733   hint.ai_canonname = NULL;
1734   hint.ai_next = NULL;
1735   hint.ai_flags = AI_PASSIVE | AI_NUMERICSERV;  /* Wild card address */
1736   GNUNET_assert (0 == getaddrinfo (NULL,
1737                                    open_port_str,
1738                                    &hint,
1739                                    &ret));
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   tv.tv_sec = timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us;
1797   tv.tv_usec =
1798     (timeout.rel_value_us -
1799      (tv.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value_us));
1800   return select (nfds,
1801                  (NULL != rfds) ? &rfds->sds : NULL,
1802                  (NULL != wfds) ? &wfds->sds : NULL,
1803                  (NULL != efds) ? &efds->sds : NULL,
1804                  (timeout.rel_value_us ==
1805                   GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) ? NULL : &tv);
1806 }
1807
1808
1809 #else
1810 /* MINGW */
1811
1812
1813 /**
1814  * Non-blocking test if a pipe is ready for reading.
1815  *
1816  * @param fh pipe handle
1817  * @return #GNUNET_YES if the pipe is ready for reading
1818  */
1819 static int
1820 pipe_read_ready (const struct GNUNET_DISK_FileHandle *fh)
1821 {
1822   DWORD error;
1823   BOOL bret;
1824   DWORD waitstatus = 0;
1825
1826   SetLastError (0);
1827   bret = PeekNamedPipe (fh->h, NULL, 0, NULL, &waitstatus, NULL);
1828   error = GetLastError ();
1829   if (0 == bret)
1830   {
1831     /* TODO: either add more errors to this condition, or eliminate it
1832      * entirely (failed to peek -> pipe is in serious trouble, should
1833      * be selected as readable).
1834      */
1835     if ( (error != ERROR_BROKEN_PIPE) &&
1836          (error != ERROR_INVALID_HANDLE) )
1837       return GNUNET_NO;
1838   }
1839   else if (waitstatus <= 0)
1840     return GNUNET_NO;
1841   return GNUNET_YES;
1842 }
1843
1844
1845 /**
1846  * Non-blocking test if a pipe is having an IO exception.
1847  *
1848  * @param fh pipe handle
1849  * @return #GNUNET_YES if the pipe is having an IO exception.
1850  */
1851 static int
1852 pipe_except_ready (const struct GNUNET_DISK_FileHandle *fh)
1853 {
1854   DWORD dwBytes;
1855
1856   if (PeekNamedPipe (fh->h, NULL, 0, NULL, &dwBytes, NULL))
1857     return GNUNET_NO;
1858   return GNUNET_YES;
1859 }
1860
1861
1862 /**
1863  * Iterate over handles in fds, destructively rewrite the
1864  * handles array contents of fds so that it starts with the
1865  * handles that are ready, and update handles_pos accordingly.
1866  *
1867  * @param fds set of handles (usually pipes) to be checked for readiness
1868  * @param except GNUNET_NO if fds should be checked for readiness to read,
1869  * GNUNET_YES if fds should be checked for exceptions
1870  * (there is no way to check for write-readiness - pipes are always write-ready)
1871  * @param set_for_sure a HANDLE that is known to be set already,
1872  * because WaitForMultipleObjects() returned its index.
1873  * @return number of ready handles
1874  */
1875 static int
1876 check_handles_status (struct GNUNET_NETWORK_FDSet *fds,
1877                       int except,
1878                       HANDLE set_for_sure)
1879 {
1880   const struct GNUNET_DISK_FileHandle *fh;
1881   unsigned int roff;
1882   unsigned int woff;
1883
1884   for (woff = 0, roff = 0; roff < fds->handles_pos; roff++)
1885   {
1886     fh = fds->handles[roff];
1887     if (fh == set_for_sure)
1888     {
1889       fds->handles[woff++] = fh;
1890     }
1891     else if (fh->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
1892     {
1893       if ((except && pipe_except_ready (fh)) ||
1894           (!except && pipe_read_ready (fh)))
1895         fds->handles[woff++] = fh;
1896     }
1897     else if (fh->type == GNUNET_DISK_HANLDE_TYPE_FILE)
1898     {
1899       if (!except)
1900         fds->handles[woff++] = fh;
1901     }
1902     else
1903     {
1904       if (WAIT_OBJECT_0 == WaitForSingleObject (fh->h, 0))
1905         fds->handles[woff++] = fh;
1906     }
1907   }
1908   fds->handles_pos = woff;
1909   return woff;
1910 }
1911
1912
1913 /**
1914  * Check if sockets or pipes meet certain conditions, version for W32.
1915  *
1916  * @param rfds set of sockets or pipes to be checked for readability
1917  * @param wfds set of sockets or pipes to be checked for writability
1918  * @param efds set of sockets or pipes to be checked for exceptions
1919  * @param timeout relative value when to return
1920  * @return number of selected sockets or pipes, #GNUNET_SYSERR on error
1921  */
1922 int
1923 GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1924                               struct GNUNET_NETWORK_FDSet *wfds,
1925                               struct GNUNET_NETWORK_FDSet *efds,
1926                               const struct GNUNET_TIME_Relative timeout)
1927 {
1928   const struct GNUNET_DISK_FileHandle *fh;
1929   int nfds;
1930   int handles;
1931   unsigned int i;
1932   int retcode;
1933   uint64_t mcs_total;
1934   DWORD ms_rounded;
1935   int nhandles = 0;
1936   int read_pipes_off;
1937   HANDLE handle_array[FD_SETSIZE + 2];
1938   int returncode;
1939   int returnedpos = 0;
1940   int selectret;
1941   fd_set aread;
1942   fd_set awrite;
1943   fd_set aexcept;
1944
1945   nfds = 0;
1946   handles = 0;
1947   if (NULL != rfds)
1948   {
1949     nfds = GNUNET_MAX (nfds, rfds->nsds);
1950     handles += rfds->handles_pos;
1951   }
1952   if (NULL != wfds)
1953   {
1954     nfds = GNUNET_MAX (nfds, wfds->nsds);
1955     handles += wfds->handles_pos;
1956   }
1957   if (NULL != efds)
1958   {
1959     nfds = GNUNET_MAX (nfds, efds->nsds);
1960     handles += efds->handles_pos;
1961   }
1962
1963   if ((0 == nfds) &&
1964       (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == timeout.rel_value_us) &&
1965       (0 == handles) )
1966   {
1967     GNUNET_break (0);
1968     LOG (GNUNET_ERROR_TYPE_ERROR,
1969          _("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1970          "select");
1971   }
1972 #define SAFE_FD_ISSET(fd, set)  (set != NULL && FD_ISSET(fd, set))
1973   /* calculate how long we need to wait in microseconds */
1974   if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1975   {
1976     mcs_total = INFINITE;
1977     ms_rounded = INFINITE;
1978   }
1979   else
1980   {
1981     mcs_total = timeout.rel_value_us / GNUNET_TIME_UNIT_MICROSECONDS.rel_value_us;
1982     ms_rounded = (DWORD) (mcs_total / GNUNET_TIME_UNIT_MILLISECONDS.rel_value_us);
1983     if (mcs_total > 0 && ms_rounded == 0)
1984       ms_rounded = 1;
1985   }
1986   /* select() may be used as a portable way to sleep */
1987   if (! (rfds || wfds || efds))
1988   {
1989     Sleep (ms_rounded);
1990     return 0;
1991   }
1992
1993   if (NULL == select_thread)
1994     initialize_select_thread ();
1995
1996   FD_ZERO (&aread);
1997   FD_ZERO (&awrite);
1998   FD_ZERO (&aexcept);
1999   if (rfds)
2000     FD_COPY (&rfds->sds, &aread);
2001   if (wfds)
2002     FD_COPY (&wfds->sds, &awrite);
2003   if (efds)
2004     FD_COPY (&efds->sds, &aexcept);
2005
2006   /* Start by doing a fast check on sockets and pipes (without
2007      waiting). It is cheap, and is sufficient most of the time.  By
2008      profiling we detected that to be true in 90% of the cases.
2009   */
2010
2011   /* Do the select now */
2012   select_timeout.tv_sec = 0;
2013   select_timeout.tv_usec = 0;
2014
2015   /* Copy all the writes to the except, so we can detect connect() errors */
2016   for (i = 0; i < awrite.fd_count; i++)
2017     FD_SET (awrite.fd_array[i],
2018             &aexcept);
2019   if ( (aread.fd_count > 0) ||
2020        (awrite.fd_count > 0) ||
2021        (aexcept.fd_count > 0) )
2022     selectret = select (1,
2023                         (NULL != rfds) ? &aread : NULL,
2024                         (NULL != wfds) ? &awrite : NULL,
2025                         &aexcept,
2026                         &select_timeout);
2027   else
2028     selectret = 0;
2029   if (-1 == selectret)
2030   {
2031     /* Throw an error early on, while we still have the context. */
2032     LOG (GNUNET_ERROR_TYPE_ERROR,
2033          "W32 select(%d, %d, %d) failed: %lu\n",
2034          rfds ? aread.fd_count : 0,
2035          wfds ? awrite.fd_count : 0,
2036          aexcept.fd_count,
2037          GetLastError ());
2038     GNUNET_assert (0);
2039   }
2040
2041   /* Check aexcept, if something is in there and we copied that
2042      FD before to detect connect() errors, add it back to the
2043      write set to report errors. */
2044   if (NULL != wfds)
2045     for (i = 0; i < aexcept.fd_count; i++)
2046       if (FD_ISSET (aexcept.fd_array[i],
2047                     &wfds->sds))
2048         FD_SET (aexcept.fd_array[i],
2049                 &awrite);
2050
2051
2052   /* If our select returned something or is a 0-timed request, then
2053      also check the pipes and get out of here! */
2054   /* Sadly, it means code duplication :( */
2055   if ( (selectret > 0) || (0 == mcs_total) )
2056   {
2057     retcode = 0;
2058
2059     /* Read Pipes */
2060     if (rfds && (rfds->handles_pos > 0))
2061       retcode += check_handles_status (rfds, GNUNET_NO, NULL);
2062
2063     /* wfds handles remain untouched, on W32
2064        we pretend our pipes are "always" write-ready */
2065
2066     /* except pipes */
2067     if (efds && (efds->handles_pos > 0))
2068       retcode += check_handles_status (efds, GNUNET_YES, NULL);
2069
2070     if (rfds)
2071     {
2072       GNUNET_NETWORK_fdset_zero (rfds);
2073       if (selectret != -1)
2074         GNUNET_NETWORK_fdset_copy_native (rfds, &aread, selectret);
2075     }
2076     if (wfds)
2077     {
2078       GNUNET_NETWORK_fdset_zero (wfds);
2079       if (selectret != -1)
2080         GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, selectret);
2081     }
2082     if (efds)
2083     {
2084       GNUNET_NETWORK_fdset_zero (efds);
2085       if (selectret != -1)
2086         GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, selectret);
2087     }
2088     if (-1 == selectret)
2089       return -1;
2090     /* Add our select() FDs to the total return value */
2091     retcode += selectret;
2092     return retcode;
2093   }
2094
2095   /* If we got this far, use slower implementation that is able to do a waiting select
2096      on both sockets and pipes simultaneously */
2097
2098   /* Events for pipes */
2099   if (! hEventReadReady)
2100     hEventReadReady = CreateEvent (NULL, TRUE, TRUE, NULL);
2101   if (! hEventPipeWrite)
2102     hEventPipeWrite = CreateEvent (NULL, TRUE, TRUE, NULL);
2103   retcode = 0;
2104
2105   FD_ZERO (&aread);
2106   FD_ZERO (&awrite);
2107   FD_ZERO (&aexcept);
2108   if (rfds)
2109     FD_COPY (&rfds->sds, &aread);
2110   if (wfds)
2111     FD_COPY (&wfds->sds, &awrite);
2112   if (efds)
2113     FD_COPY (&efds->sds, &aexcept);
2114   /* We will first Add the PIPES to the events */
2115   /* Track how far in `handle_array` the read pipes go,
2116      so we may by-pass them quickly if none of them
2117      are selected. */
2118   read_pipes_off = 0;
2119   if (rfds && (rfds->handles_pos > 0))
2120   {
2121     for (i = 0; i <rfds->handles_pos; i++)
2122     {
2123       fh = rfds->handles[i];
2124       if (fh->type == GNUNET_DISK_HANLDE_TYPE_EVENT)
2125       {
2126         handle_array[nhandles++] = fh->h;
2127         continue;
2128       }
2129       if (fh->type != GNUNET_DISK_HANLDE_TYPE_PIPE)
2130         continue;
2131       /* Read zero bytes to check the status of the pipe */
2132       if (! ReadFile (fh->h, NULL, 0, NULL, fh->oOverlapRead))
2133       {
2134         DWORD error_code = GetLastError ();
2135
2136         if (error_code == ERROR_IO_PENDING)
2137         {
2138           /* add as unready */
2139           handle_array[nhandles++] = fh->oOverlapRead->hEvent;
2140           read_pipes_off++;
2141         }
2142         else
2143         {
2144           /* add as ready */
2145           handle_array[nhandles++] = hEventReadReady;
2146           read_pipes_off++;
2147         }
2148       }
2149       else
2150       {
2151         /* error also counts as ready */
2152         handle_array[nhandles++] = hEventReadReady;
2153         read_pipes_off++;
2154       }
2155     }
2156   }
2157
2158   if (wfds && (wfds->handles_pos > 0))
2159   {
2160     LOG (GNUNET_ERROR_TYPE_DEBUG,
2161          "Adding the write ready event to the array as %d\n",
2162          nhandles);
2163     handle_array[nhandles++] = hEventPipeWrite;
2164   }
2165
2166   sp.status = 0;
2167   if (nfds > 0)
2168   {
2169     LOG (GNUNET_ERROR_TYPE_DEBUG,
2170          "Adding the socket event to the array as %d\n",
2171          nhandles);
2172     handle_array[nhandles++] = select_finished_event;
2173     if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
2174     {
2175       sp.tv = NULL;
2176     }
2177     else
2178     {
2179       select_timeout.tv_sec = timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us;
2180       select_timeout.tv_usec = (timeout.rel_value_us -
2181                                 (select_timeout.tv_sec *
2182                                  GNUNET_TIME_UNIT_SECONDS.rel_value_us));
2183       sp.tv = &select_timeout;
2184     }
2185     FD_SET (select_wakeup_socket, &aread);
2186     do
2187     {
2188       i = recv (select_wakeup_socket,
2189                 (char *) &returnedpos,
2190                 1,
2191                 0);
2192     } while (i == 1);
2193     sp.r = &aread;
2194     sp.w = &awrite;
2195     sp.e = &aexcept;
2196     /* Failed connections cause sockets to be set in errorfds on W32,
2197      * but on POSIX it should set them in writefds.
2198      * First copy all awrite sockets to aexcept, later we'll
2199      * check aexcept and set its contents in awrite as well
2200      * Sockets are also set in errorfds when OOB data is available,
2201      * but we don't use OOB data.
2202      */
2203     for (i = 0; i < awrite.fd_count; i++)
2204       FD_SET (awrite.fd_array[i],
2205               &aexcept);
2206     ResetEvent (select_finished_event);
2207     SetEvent (select_standby_event);
2208   }
2209
2210   /* NULL-terminate array */
2211   handle_array[nhandles] = NULL;
2212   LOG (GNUNET_ERROR_TYPE_DEBUG,
2213        "nfds: %d, handles: %d, will wait: %llu mcs\n",
2214        nfds,
2215        nhandles,
2216        mcs_total);
2217   if (nhandles)
2218   {
2219     returncode
2220       = WaitForMultipleObjects (nhandles,
2221                                 handle_array,
2222                                 FALSE,
2223                                 ms_rounded);
2224     LOG (GNUNET_ERROR_TYPE_DEBUG,
2225          "WaitForMultipleObjects Returned: %d\n",
2226          returncode);
2227   }
2228   else if (nfds > 0)
2229   {
2230     GNUNET_break (0); /* This branch shouldn't actually be executed...*/
2231     i = (int) WaitForSingleObject (select_finished_event,
2232                                    INFINITE);
2233     returncode = WAIT_TIMEOUT;
2234   }
2235   else
2236   {
2237     /* Shouldn't come this far. If it does - investigate. */
2238     GNUNET_assert (0);
2239   }
2240
2241   if (nfds > 0)
2242   {
2243     /* Don't wake up select-thread when delay is 0, it should return immediately
2244      * and wake up by itself.
2245      */
2246     if (0 != mcs_total)
2247       i = send (select_send_socket,
2248                 (const char *) &returnedpos,
2249                 1,
2250                 0);
2251     i = (int) WaitForSingleObject (select_finished_event,
2252                                    INFINITE);
2253     LOG (GNUNET_ERROR_TYPE_DEBUG,
2254          "Finished waiting for the select thread: %d %d\n",
2255          i,
2256          sp.status);
2257     if (0 != mcs_total)
2258     {
2259       do
2260       {
2261         i = recv (select_wakeup_socket,
2262                   (char *) &returnedpos,
2263                   1, 0);
2264       } while (1 == i);
2265     }
2266     /* Check aexcept, add its contents to awrite */
2267     for (i = 0; i < aexcept.fd_count; i++)
2268       FD_SET (aexcept.fd_array[i], &awrite);
2269   }
2270
2271   returnedpos = returncode - WAIT_OBJECT_0;
2272   LOG (GNUNET_ERROR_TYPE_DEBUG,
2273        "return pos is: %d\n",
2274        returnedpos);
2275
2276   if (rfds)
2277   {
2278     /* We queued a zero-long read on each pipe to check
2279      * its state, now we must cancel these read operations.
2280      * This must be done while rfds->handles_pos is still
2281      * intact and matches the number of read handles that we
2282      * got from the caller.
2283      */
2284     for (i = 0; i < rfds->handles_pos; i++)
2285     {
2286       fh = rfds->handles[i];
2287       if (GNUNET_DISK_HANLDE_TYPE_PIPE == fh->type)
2288         CancelIo (fh->h);
2289     }
2290
2291     /* We may have some pipes ready for reading. */
2292     if (returnedpos < read_pipes_off)
2293       retcode += check_handles_status (rfds, GNUNET_NO, handle_array[returnedpos]);
2294     else
2295       rfds->handles_pos = 0;
2296
2297     if (-1 != sp.status)
2298       GNUNET_NETWORK_fdset_copy_native (rfds, &aread, retcode);
2299   }
2300   if (wfds)
2301   {
2302     retcode += wfds->handles_pos;
2303     /* wfds handles remain untouched */
2304     if (-1 != sp.status)
2305       GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, retcode);
2306   }
2307   if (efds)
2308   {
2309     retcode += check_handles_status (rfds,
2310                                      GNUNET_YES,
2311                                      returnedpos < nhandles ? handle_array[returnedpos] : NULL);
2312     if (-1 != sp.status)
2313       GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, retcode);
2314   }
2315
2316   if (sp.status > 0)
2317     retcode += sp.status;
2318
2319   return retcode;
2320 }
2321
2322 /* MINGW */
2323 #endif
2324
2325 /* end of network.c */