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