fixfix
[oweals/gnunet.git] / src / util / network.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 Christian Grothoff (and other contributing authors)
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 2, 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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/network.c
23  * @brief basic, low-level networking interface
24  * @author Nils Durner
25  */
26
27 #include "platform.h"
28 #include "gnunet_disk_lib.h"
29 #include "disk.h"
30 #include "gnunet_container_lib.h"
31
32 #define DEBUG_NETWORK GNUNET_NO
33
34 #define DEBUG_W32_CYCLES GNUNET_NO
35
36 #ifndef INVALID_SOCKET
37 #define INVALID_SOCKET -1
38 #endif
39
40
41 struct GNUNET_NETWORK_Handle
42 {
43 #ifndef MINGW
44   int fd;
45
46 #else
47   SOCKET fd;
48 #endif
49
50   /**
51    * Address family / domain.
52    */
53   int af;
54
55   /**
56    * Number of bytes in addr.
57    */
58   socklen_t addrlen;
59
60   /**
61    * Address we were bound to, or NULL.
62    */
63   struct sockaddr *addr;
64
65 };
66
67
68 struct GNUNET_NETWORK_FDSet
69 {
70
71   /**
72    * Maximum number of any socket socket descriptor in the set (plus one)
73    */
74   int nsds;
75
76   /**
77    * Bitset with the descriptors.
78    */
79   fd_set sds;
80
81 #ifdef WINDOWS
82   /**
83    * Linked list of handles
84    */
85   struct GNUNET_CONTAINER_SList *handles;
86 #endif
87
88 };
89
90 #ifndef FD_COPY
91 #define FD_COPY(s, d) (memcpy ((d), (s), sizeof (fd_set)))
92 #endif
93
94
95 /**
96  * Set if a socket should use blocking or non-blocking IO.
97  * @param fd socket
98  * @param doBlock blocking mode
99  * @return GNUNET_OK on success, GNUNET_SYSERR on error
100  */
101 static int
102 socket_set_blocking (struct GNUNET_NETWORK_Handle *fd, int doBlock)
103 {
104
105 #if MINGW
106   u_long mode;
107   mode = !doBlock;
108   if (ioctlsocket (fd->fd, FIONBIO, &mode) == SOCKET_ERROR)
109
110     {
111       SetErrnoFromWinsockError (WSAGetLastError ());
112       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "ioctlsocket");
113       return GNUNET_SYSERR;
114     }
115   return GNUNET_OK;
116
117 #else
118   /* not MINGW */
119   int flags = fcntl (fd->fd, F_GETFL);
120   if (flags == -1)
121
122     {
123       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fcntl");
124       return GNUNET_SYSERR;
125     }
126   if (doBlock)
127     flags &= ~O_NONBLOCK;
128
129   else
130     flags |= O_NONBLOCK;
131   if (0 != fcntl (fd->fd, F_SETFL, flags))
132
133     {
134       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fcntl");
135       return GNUNET_SYSERR;
136     }
137   return GNUNET_OK;
138 #endif
139 }
140
141
142 #ifndef MINGW
143 /**
144  * Make a socket non-inheritable to child processes
145  *
146  * @param h the socket to make non-inheritable
147  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
148  * @warning Not implemented on Windows
149  */
150 static int
151 socket_set_inheritable (const struct GNUNET_NETWORK_Handle *h)
152 {
153   int i;
154
155   i = fcntl (h->fd, F_GETFD);  
156   if (i < 0)
157     return GNUNET_SYSERR;
158   if (i == (i | FD_CLOEXEC))
159     return GNUNET_OK;
160   i |= FD_CLOEXEC;
161   if (fcntl (h->fd, F_SETFD, i) < 0)
162     return GNUNET_SYSERR;
163   return GNUNET_OK;
164 }
165 #endif
166
167
168 #ifdef DARWIN
169 /**
170  * The MSG_NOSIGNAL equivalent on Mac OS X
171  *
172  * @param h the socket to make non-delaying
173  */
174 static void
175 socket_set_nosigpipe (const struct GNUNET_NETWORK_Handle *h)
176 {
177   int abs_value = 1;
178   if (0 !=
179       setsockopt (h->fd, SOL_SOCKET, SO_NOSIGPIPE, &abs_value, sizeof (abs_value)))
180     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
181 }
182 #endif
183
184
185 /**
186  * Disable delays when sending data via the socket.
187  * (GNUnet makes sure that messages are as big as
188  * possible already).
189  *
190  * @param h the socket to make non-delaying
191  */
192 static void
193 socket_set_nodelay (const struct GNUNET_NETWORK_Handle *h)
194 {
195 #ifndef WINDOWS  
196   int value = 1;
197   if (0 != setsockopt (h->fd, IPPROTO_TCP, TCP_NODELAY, &value, sizeof (value)))
198     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
199 #else
200   const char * abs_value = "1";
201   if (0 != setsockopt (h->fd, IPPROTO_TCP, TCP_NODELAY, abs_value, sizeof (abs_value)))
202     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
203 #endif  
204 }
205
206
207 /**
208  * accept a new connection on a socket
209  *
210  * @param desc bound socket
211  * @param address address of the connecting peer, may be NULL
212  * @param address_len length of address
213  * @return client socket
214  */
215 struct GNUNET_NETWORK_Handle *
216 GNUNET_NETWORK_socket_accept (const struct GNUNET_NETWORK_Handle *desc,
217                               struct sockaddr *address,
218                               socklen_t * address_len)
219 {
220   struct GNUNET_NETWORK_Handle *ret;
221
222   ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
223 #if DEBUG_NETWORK
224   {
225     struct sockaddr name;
226     int namelen = sizeof (name);
227     int gsn = getsockname (desc->fd, &name, &namelen);
228     if (gsn == 0)
229       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
230           "Accepting connection on `%s'\n",
231           GNUNET_a2s (&name, namelen));
232   }
233 #endif
234   ret->fd = accept (desc->fd, address, address_len);
235   if (address != NULL)
236     ret->af = address->sa_family;
237   else
238     ret->af = desc->af;
239   if (ret->fd == INVALID_SOCKET)
240     {
241 #ifdef MINGW
242       SetErrnoFromWinsockError (WSAGetLastError ());
243 #endif
244       GNUNET_free (ret);
245       return NULL;
246     }
247 #ifndef MINGW
248   if (ret->fd >= FD_SETSIZE)
249     {
250       GNUNET_break (0 == close (ret->fd));
251       GNUNET_free (ret);
252       errno = EMFILE;
253       return NULL;
254     }
255 #endif
256   if (GNUNET_SYSERR == socket_set_blocking (ret, GNUNET_NO))
257
258     {
259
260       /* we might want to treat this one as fatal... */
261       GNUNET_break (0);
262       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ret));
263       return NULL;
264     }
265
266 #ifndef MINGW
267   if (GNUNET_OK != socket_set_inheritable (ret))
268     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
269                          "socket_set_inheritable");
270 #endif
271 #ifdef DARWIN
272   socket_set_nosigpipe (ret);
273 #endif
274 #ifdef AF_UNIX
275   if (ret->af != AF_UNIX)
276 #endif
277     socket_set_nodelay (ret);
278   return ret;
279 }
280
281
282 /**
283  * Bind to a connected socket
284  * @param desc socket
285  * @param address address to be bound
286  * @param address_len length of address
287  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
288  */
289 int
290 GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc,
291                             const struct sockaddr *address,
292                             socklen_t address_len)
293 {
294   int ret;
295   
296 #ifdef IPV6_V6ONLY 
297 #ifdef IPPROTO_IPV6
298   const int on = 1;
299   if (desc->af == AF_INET6)
300     if (0 != setsockopt (desc->fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
301       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "setsockopt");
302 #if 0
303   /* is this needed or desired? or done elsewhere? */
304   if (0 != setsockopt (desc->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)))
305     GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "setsockopt");
306 #endif
307 #endif
308 #endif
309 #ifndef LINUX
310 #ifndef MINGW
311   if (address->sa_family == AF_UNIX)
312     {
313       const struct sockaddr_un *un = (const struct sockaddr_un*) address;
314       (void) unlink (un->sun_path);
315     }
316 #endif
317 #endif
318   ret = bind (desc->fd, address, address_len);
319 #ifdef MINGW
320   if (SOCKET_ERROR == ret)
321     SetErrnoFromWinsockError (WSAGetLastError ());
322 #endif
323   if (ret != 0)
324           return GNUNET_SYSERR;
325 #ifndef MINGW
326 #ifndef LINUX
327   desc->addr = GNUNET_malloc (address_len);
328   memcpy (desc->addr, address, address_len);
329   desc->addrlen = address_len;
330 #endif
331 #endif
332   return GNUNET_OK;
333 }
334
335
336 /**
337  * Close a socket
338  * @param desc socket
339  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
340  */
341 int
342 GNUNET_NETWORK_socket_close (struct GNUNET_NETWORK_Handle *desc)
343 {
344   int ret;
345
346 #ifdef MINGW
347   DWORD error = 0;
348 #if DEBUG_NETWORK
349   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_NETWORK_socket_close", "Closing 0x%x\n", desc->fd);
350 #endif
351   SetLastError (0);
352   ret = closesocket (desc->fd);
353   error = WSAGetLastError ();
354   SetErrnoFromWinsockError (error);
355 #if DEBUG_NETWORK
356   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_NETWORK_socket_close", "Closed 0x%x, closesocket() returned %d, GLE is %u\n", desc->fd, ret, error);
357 #endif
358 #else
359   ret = close (desc->fd);
360 #endif
361 #ifndef LINUX
362 #ifndef MINGW
363   if ( (desc->af == AF_UNIX) && (NULL != desc->addr) )
364     {
365       const struct sockaddr_un *un = (const struct sockaddr_un*) desc->addr;
366       if (0 != unlink (un->sun_path))
367           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
368                                   "unlink",
369                                   un->sun_path);
370     }
371 #endif
372 #endif
373   GNUNET_free_non_null (desc->addr);
374   GNUNET_free (desc);
375   return (ret == 0) ? GNUNET_OK : GNUNET_SYSERR;
376 }
377
378
379 /**
380  * Box a native socket (and check that it is a socket).
381  *
382  * @param fd socket to box
383  * @return NULL on error (including not supported on target platform)
384  */
385 struct GNUNET_NETWORK_Handle *
386 GNUNET_NETWORK_socket_box_native (int fd)
387 {
388 #if MINGW
389   return NULL;
390 #else
391   struct GNUNET_NETWORK_Handle *ret;
392
393   if (fcntl (fd, F_GETFD) < 0)
394     return NULL; /* invalid FD */
395   ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle)); 
396   ret->fd = fd;
397   ret->af = AF_UNSPEC;
398   return ret;
399 #endif
400 }
401
402
403 /**
404  * Connect a socket
405  * @param desc socket
406  * @param address peer address
407  * @param address_len length of address
408  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
409  */
410 int
411 GNUNET_NETWORK_socket_connect (const struct GNUNET_NETWORK_Handle *desc,
412                                const struct sockaddr *address,
413                                socklen_t address_len)
414 {
415   int ret;
416   ret = connect (desc->fd, address, address_len);
417
418 #ifdef MINGW
419   if (SOCKET_ERROR == ret)
420     {
421       SetErrnoFromWinsockError (WSAGetLastError ());
422       if (errno == EWOULDBLOCK)
423         errno = EINPROGRESS;
424     }
425 #endif
426   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
427 }
428
429
430 /**
431  * Get socket options
432  *
433  * @param desc socket
434  * @param level protocol level of the option
435  * @param optname identifier of the option
436  * @param optval options
437  * @param optlen length of optval
438  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
439  */
440 int
441 GNUNET_NETWORK_socket_getsockopt (const struct GNUNET_NETWORK_Handle *desc,
442                                   int level, int optname, void *optval,
443                                   socklen_t * optlen)
444 {
445   int ret;
446   ret = getsockopt (desc->fd, level, optname, optval, optlen);
447
448 #ifdef MINGW
449   if (ret == 0 && level == SOL_SOCKET && optname == SO_ERROR)
450     *((int *) optval) = GetErrnoFromWinsockError (*((int *) optval));
451
452   else if (SOCKET_ERROR == ret)
453     SetErrnoFromWinsockError (WSAGetLastError ());
454 #endif
455   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
456 }
457
458
459 /**
460  * Listen on a socket
461  * @param desc socket
462  * @param backlog length of the listen queue
463  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
464  */
465 int
466 GNUNET_NETWORK_socket_listen (const struct GNUNET_NETWORK_Handle *desc,
467                               int backlog)
468 {
469   int ret;
470   ret = listen (desc->fd, backlog);
471
472 #ifdef MINGW
473   if (SOCKET_ERROR == ret)
474     SetErrnoFromWinsockError (WSAGetLastError ());
475
476 #endif
477   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
478 }
479
480
481 /**
482  * How much data is available to be read on this descriptor?
483  *
484  * Returns GNUNET_NO if no data is available, or on error!
485  * @param desc socket
486  */
487 ssize_t
488 GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle
489                                        *desc)
490 {
491   int error;
492
493   /* How much is there to be read? */
494 #ifndef WINDOWS
495   int pending;
496   error = ioctl (desc->fd, FIONREAD, &pending);
497   if (error == 0)
498 #else
499   u_long pending;
500   error = ioctlsocket (desc->fd, FIONREAD, &pending);
501   if (error != SOCKET_ERROR)
502 #endif
503     return pending;
504   else
505     return GNUNET_NO;
506 }
507
508
509 /**
510  * Read data from a connected socket (always non-blocking).
511  * @param desc socket
512  * @param buffer buffer
513  * @param length length of buffer
514  * @param src_addr either the source to recv from, or all zeroes
515  *        to be filled in by recvfrom
516  * @param addrlen length of the addr
517  */
518 ssize_t
519 GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle * desc,
520                                 void *buffer, size_t length,
521                                 struct sockaddr * src_addr,
522                                 socklen_t * addrlen)
523 {
524   int ret;
525   int flags;
526   flags = 0;
527
528 #ifdef MSG_DONTWAIT
529   flags |= MSG_DONTWAIT;
530
531 #endif
532   ret = recvfrom (desc->fd, buffer, length, flags, src_addr, addrlen);
533 #ifdef MINGW
534   if (SOCKET_ERROR == ret)
535     SetErrnoFromWinsockError (WSAGetLastError ());
536 #endif 
537   return ret;
538 }
539
540
541 /**
542  * Read data from a connected socket (always non-blocking).
543  * @param desc socket
544  * @param buffer buffer
545  * @param length length of buffer
546  */
547 ssize_t
548 GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle * desc,
549                             void *buffer, size_t length)
550 {
551   int ret;
552   int flags;
553   flags = 0;
554
555 #ifdef MSG_DONTWAIT
556   flags |= MSG_DONTWAIT;
557 #endif
558   ret = recv (desc->fd, buffer, length, flags);
559 #ifdef MINGW
560   if (SOCKET_ERROR == ret)
561     SetErrnoFromWinsockError (WSAGetLastError ());
562 #endif
563   return ret;
564 }
565
566
567 /**
568  * Send data (always non-blocking).
569  *
570  * @param desc socket
571  * @param buffer data to send
572  * @param length size of the buffer
573  * @return number of bytes sent, GNUNET_SYSERR on error
574  */
575 ssize_t
576 GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle * desc,
577                             const void *buffer, size_t length)
578 {
579   int ret;
580   int flags;
581   flags = 0;
582
583 #ifdef MSG_DONTWAIT
584   flags |= MSG_DONTWAIT;
585
586 #endif
587 #ifdef MSG_NOSIGNAL
588   flags |= MSG_NOSIGNAL;
589
590 #endif
591   ret = send (desc->fd, buffer, length, flags);
592
593 #ifdef MINGW
594   if (SOCKET_ERROR == ret)
595     SetErrnoFromWinsockError (WSAGetLastError ());
596
597 #endif
598   return ret;
599 }
600
601
602 /**
603  * Send data to a particular destination (always non-blocking).
604  * This function only works for UDP sockets.
605  *
606  * @param desc socket
607  * @param message data to send
608  * @param length size of the data
609  * @param dest_addr destination address
610  * @param dest_len length of address
611  * @return number of bytes sent, GNUNET_SYSERR on error
612  */
613 ssize_t
614 GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle * desc,
615                               const void *message, size_t length,
616                               const struct sockaddr * dest_addr,
617                               socklen_t dest_len)
618 {
619   int ret;
620   int flags;
621   flags = 0;
622
623 #ifdef MSG_DONTWAIT
624   flags |= MSG_DONTWAIT;
625 #endif
626 #ifdef MSG_NOSIGNAL
627   flags |= MSG_NOSIGNAL;
628 #endif
629   ret = sendto (desc->fd, message, length, flags, dest_addr, dest_len);
630 #ifdef MINGW
631   if (SOCKET_ERROR == ret)
632     SetErrnoFromWinsockError (WSAGetLastError ());
633 #endif
634   return ret;
635 }
636
637
638 /**
639  * Set socket option
640  * @param fd socket
641  * @param level protocol level of the option
642  * @param option_name option identifier
643  * @param option_value value to set
644  * @param option_len size of option_value
645  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
646  */
647 int
648 GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd,
649                                   int level, int option_name,
650                                   const void *option_value,
651                                   socklen_t option_len)
652 {
653   int ret;
654
655   ret = setsockopt (fd->fd, level, option_name, option_value, option_len);
656 #ifdef MINGW
657   if (SOCKET_ERROR == ret)
658     SetErrnoFromWinsockError (WSAGetLastError ());
659 #endif
660   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
661 }
662
663
664 /**
665  * Create a new socket.  Configure it for non-blocking IO and
666  * mark it as non-inheritable to child processes (set the
667  * close-on-exec flag).
668  *
669  * @param domain domain of the socket
670  * @param type socket type
671  * @param protocol network protocol
672  * @return new socket, NULL on error
673  */
674 struct GNUNET_NETWORK_Handle *
675 GNUNET_NETWORK_socket_create (int domain, int type, int protocol)
676 {
677   struct GNUNET_NETWORK_Handle *ret;
678
679   ret = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle));
680   ret->af = domain;
681   ret->fd = socket (domain, type, protocol);
682   if (INVALID_SOCKET == ret->fd)
683     {
684 #ifdef MINGW
685       SetErrnoFromWinsockError (WSAGetLastError ());
686 #endif
687       GNUNET_free (ret);
688       return NULL;
689     }
690
691 #ifndef MINGW
692   if (ret->fd >= FD_SETSIZE)
693     {
694       GNUNET_break (0 == close (ret->fd));
695       GNUNET_free (ret);
696       errno = EMFILE;
697       return NULL;
698     }
699
700 #endif
701   if (GNUNET_SYSERR == socket_set_blocking (ret, GNUNET_NO))
702     {
703       /* we might want to treat this one as fatal... */
704       GNUNET_break (0);
705       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ret));
706       return NULL;
707     }
708
709 #ifndef MINGW
710   if (GNUNET_OK != socket_set_inheritable (ret))
711     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
712                          "socket_set_inheritable");
713 #endif
714 #ifdef DARWIN
715   socket_set_nosigpipe (ret);
716 #endif
717   if ( (type == SOCK_STREAM) 
718 #ifdef AF_UNIX
719        && (domain != AF_UNIX) 
720 #endif
721        )
722     socket_set_nodelay (ret);
723   return ret;
724 }
725
726
727 /**
728  * Shut down socket operations
729  * @param desc socket
730  * @param how type of shutdown
731  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
732  */
733 int
734 GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc, int how)
735 {
736   int ret;
737
738   ret = shutdown (desc->fd, how);
739 #ifdef MINGW
740   if (ret != 0)
741     SetErrnoFromWinsockError (WSAGetLastError ());
742 #endif
743   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
744 }
745
746
747 /**
748  * Disable the "CORK" feature for communication with the given socket,
749  * forcing the OS to immediately flush the buffer on transmission
750  * instead of potentially buffering multiple messages.  Essentially
751  * reduces the OS send buffers to zero.
752  *
753  * @param desc socket
754  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
755  */
756 int
757 GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc)
758 {
759   int value = 0;
760   int ret = 0;
761 #if WINDOWS
762   if (0 != (ret = setsockopt (desc->fd, SOL_SOCKET, SO_SNDBUF, (char *) &value, sizeof (value))))
763     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
764   if (0 != (ret = setsockopt (desc->fd, SOL_SOCKET, SO_RCVBUF, (char *) &value, sizeof (value))))
765     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
766 #else
767   if (0 != (ret = setsockopt (desc->fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof (value))))
768     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
769   if (0 != (ret = setsockopt (desc->fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof (value))))
770     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
771 #endif
772
773   return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
774 }
775
776
777 /**
778  * Reset FD set
779  * @param fds fd set
780  */
781 void
782 GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds)
783 {
784   FD_ZERO (&fds->sds);
785   fds->nsds = 0;
786 #ifdef MINGW
787   GNUNET_CONTAINER_slist_clear (fds->handles);
788 #endif
789 }
790
791 /**
792  * Add a socket to the FD set
793  * @param fds fd set
794  * @param desc socket to add
795  */
796 void
797 GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds,
798                           const struct GNUNET_NETWORK_Handle *desc)
799 {
800   FD_SET (desc->fd, &fds->sds);
801   if (desc->fd + 1 > fds->nsds)
802     fds->nsds = desc->fd + 1;
803 }
804
805
806 /**
807  * Check whether a socket is part of the fd set
808  * @param fds fd set
809  * @param desc socket
810  * @return 0 if the FD is not set
811  */
812 int
813 GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds,
814                             const struct GNUNET_NETWORK_Handle *desc)
815 {
816   return FD_ISSET (desc->fd, &fds->sds);
817 }
818
819
820 /**
821  * Add one fd set to another
822  * @param dst the fd set to add to
823  * @param src the fd set to add from
824  */
825 void
826 GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst,
827                           const struct GNUNET_NETWORK_FDSet *src)
828 {
829   int nfds;
830   for (nfds = src->nsds; nfds > 0; nfds--)
831     if (FD_ISSET (nfds, &src->sds))
832
833       {
834         FD_SET (nfds, &dst->sds);
835         if (nfds + 1 > dst->nsds)
836           dst->nsds = nfds + 1;
837       }
838 #ifdef MINGW
839   GNUNET_CONTAINER_slist_append (dst->handles, src->handles);
840 #endif
841 }
842
843
844 /**
845  * Copy one fd set to another
846  *
847  * @param to destination
848  * @param from source
849  */
850 void
851 GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to,
852                            const struct GNUNET_NETWORK_FDSet *from)
853 {
854   FD_COPY (&from->sds, &to->sds);
855   to->nsds = from->nsds;
856
857 #ifdef MINGW
858   GNUNET_CONTAINER_slist_clear (to->handles);
859   GNUNET_CONTAINER_slist_append (to->handles, from->handles);
860 #endif
861 }
862
863
864 /**
865  * Return file descriptor for this network handle
866  *
867  * @param desc wrapper to process
868  * @return POSIX file descriptor
869  */
870 int
871 GNUNET_NETWORK_get_fd (struct GNUNET_NETWORK_Handle *desc)
872 {
873   return desc->fd;
874 }
875
876
877 /**
878  * Copy a native fd set
879  *
880  * @param to destination
881  * @param from native source set
882  * @param nfds the biggest socket number in from + 1
883  */
884 void
885 GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to,
886                                   const fd_set * from, int nfds)
887 {
888   FD_COPY (from, &to->sds);
889   to->nsds = nfds;
890 }
891
892
893 /**
894  * Set a native fd in a set
895  *
896  * @param to destination
897  * @param nfd native FD to set
898  */
899 void GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to,
900                                       int nfd)
901 {
902   GNUNET_assert((nfd >= 0) && (nfd < FD_SETSIZE));
903   FD_SET (nfd, &to->sds);
904   to->nsds = GNUNET_MAX (nfd + 1, to->nsds);
905 }
906
907
908 /**
909  * Test native fd in a set
910  *
911  * @param to set to test, NULL for empty set
912  * @param nfd native FD to test, or -1 for none
913  * @return GNUNET_YES if FD is set in the set
914  */
915 int 
916 GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to,
917                                   int nfd)
918 {
919   if ( (nfd == -1) || (to == NULL) )
920     return GNUNET_NO;
921   return FD_ISSET (nfd, &to->sds) ? GNUNET_YES : GNUNET_NO;
922 }
923
924
925 /**
926  * Add a file handle to the fd set
927  * @param fds fd set
928  * @param h the file handle to add
929  */
930 void
931 GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds,
932                                  const struct GNUNET_DISK_FileHandle *h)
933 {
934 #ifdef MINGW
935   GNUNET_CONTAINER_slist_add (fds->handles,
936                               GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
937                               h, sizeof (struct GNUNET_DISK_FileHandle));
938
939 #else
940   int fd;
941   GNUNET_DISK_internal_file_handle_ (h, &fd, sizeof (int));
942   FD_SET (fd, &fds->sds);
943   if (fd + 1 > fds->nsds)
944     fds->nsds = fd + 1;
945
946 #endif
947 }
948
949
950 /**
951  * Check if a file handle is part of an fd set
952  * @param fds fd set
953  * @param h file handle
954  * @return GNUNET_YES if the file handle is part of the set
955  */
956 int
957 GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds,
958                                    const struct GNUNET_DISK_FileHandle *h)
959 {
960
961 #ifdef MINGW
962   return GNUNET_CONTAINER_slist_contains (fds->handles, h,
963                                           sizeof (struct GNUNET_DISK_FileHandle));
964 #else
965   return FD_ISSET (h->fd, &fds->sds);
966 #endif
967 }
968
969
970 /**
971  * Checks if two fd sets overlap
972  * @param fds1 first fd set
973  * @param fds2 second fd set
974  * @return GNUNET_YES if they do overlap, GNUNET_NO otherwise
975  */
976 int
977 GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1,
978                               const struct GNUNET_NETWORK_FDSet *fds2)
979 {
980 #ifndef MINGW
981   int nfds;
982
983   nfds = fds1->nsds;
984   if (nfds > fds2->nsds)
985     nfds = fds2->nsds;
986   while (nfds > 0)
987     {
988       nfds--;
989       if (FD_ISSET (nfds, &fds1->sds) && FD_ISSET (nfds, &fds2->sds))
990         return GNUNET_YES;
991     }
992 #else
993   struct GNUNET_CONTAINER_SList_Iterator *it;
994   struct GNUNET_DISK_FileHandle *h;
995   int i;
996   int j;
997
998   /*This code is somewhat hacky, we are not supposed to know what's
999     inside of fd_set; also the O(n^2) is really bad... */
1000
1001   for (i = 0; i < fds1->sds.fd_count; i++)
1002   {
1003     for (j = 0; j < fds2->sds.fd_count; j++)
1004     {
1005       if (fds1->sds.fd_array[i] == fds2->sds.fd_array[j])
1006         return GNUNET_YES;
1007     }
1008   }
1009   it = GNUNET_CONTAINER_slist_begin (fds1->handles);
1010   while (GNUNET_CONTAINER_slist_end (it) != GNUNET_YES)
1011     {
1012 #if DEBUG_NETWORK
1013       struct GNUNET_CONTAINER_SList_Iterator *t;
1014 #endif
1015       h = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (it, NULL);
1016 #if DEBUG_NETWORK
1017       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Checking that FD 0x%x is in another set:\n", h->h);
1018       for (t = GNUNET_CONTAINER_slist_begin (fds2->handles);
1019           GNUNET_CONTAINER_slist_end (t) != GNUNET_YES;
1020           GNUNET_CONTAINER_slist_next (t))
1021       {
1022         struct GNUNET_DISK_FileHandle *fh;
1023         fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (t, NULL);
1024         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "0x%x\n", fh->h);
1025       }
1026 #endif
1027       if (GNUNET_CONTAINER_slist_contains
1028           (fds2->handles, h, sizeof (struct GNUNET_DISK_FileHandle)))
1029         {
1030 #if DEBUG_NETWORK
1031           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Match!\n");
1032 #endif
1033           GNUNET_CONTAINER_slist_iter_destroy (it);
1034           return GNUNET_YES;
1035         }
1036       GNUNET_CONTAINER_slist_next (it);
1037     }
1038   GNUNET_CONTAINER_slist_iter_destroy (it);
1039 #endif
1040   return GNUNET_NO;
1041 }
1042
1043
1044 /**
1045  * Creates an fd set
1046  * @return a new fd set
1047  */
1048 struct GNUNET_NETWORK_FDSet *
1049 GNUNET_NETWORK_fdset_create ()
1050 {
1051   struct GNUNET_NETWORK_FDSet *fds;
1052   fds = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_FDSet));
1053 #ifdef MINGW
1054   fds->handles = GNUNET_CONTAINER_slist_create ();
1055 #endif
1056   GNUNET_NETWORK_fdset_zero (fds);
1057   return fds;
1058 }
1059
1060
1061 /**
1062  * Releases the associated memory of an fd set
1063  * @param fds fd set
1064  */
1065 void
1066 GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds)
1067 {
1068 #ifdef MINGW
1069   GNUNET_CONTAINER_slist_destroy (fds->handles);
1070 #endif
1071   GNUNET_free (fds);
1072 }
1073
1074 /**
1075  * Check if sockets meet certain conditions
1076  * @param rfds set of sockets to be checked for readability
1077  * @param wfds set of sockets to be checked for writability
1078  * @param efds set of sockets to be checked for exceptions
1079  * @param timeout relative value when to return
1080  * @return number of selected sockets, GNUNET_SYSERR on error
1081  */
1082 int
1083 GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1084                               struct GNUNET_NETWORK_FDSet *wfds,
1085                               struct GNUNET_NETWORK_FDSet *efds,
1086                               const struct GNUNET_TIME_Relative timeout)
1087 {
1088   int nfds = 0;
1089 #ifdef MINGW
1090   int handles = 0;
1091   int ex_handles = 0;
1092   int read_handles = 0;
1093   int write_handles = 0;
1094
1095   int i = 0;
1096   int retcode = 0;
1097   DWORD ms_total = 0;
1098
1099   int nsock = 0, nhandles = 0, nSockEvents = 0;
1100
1101   static HANDLE hEventRead = 0;
1102   static HANDLE hEventWrite = 0;
1103   static HANDLE hEventException = 0;
1104   static HANDLE hEventPipeWrite = 0;
1105   static HANDLE hEventReadReady = 0;
1106
1107   int readPipes = 0;
1108   int writePipePos = 0;
1109
1110   HANDLE handle_array[FD_SETSIZE + 2];
1111   int returncode = -1;
1112   DWORD newretcode = 0;
1113   int returnedpos = 0;
1114
1115   struct GNUNET_CONTAINER_SList *handles_read, *handles_write, *handles_except;
1116
1117   fd_set aread, awrite, aexcept;
1118 #if DEBUG_NETWORK
1119   fd_set bread, bwrite, bexcept;
1120 #endif
1121
1122   /* TODO: Make this growable */
1123   struct GNUNET_DISK_FileHandle *readArray[50];
1124 #else
1125   struct timeval tv;
1126 #endif
1127   if (NULL != rfds)
1128     {
1129       nfds = rfds->nsds;
1130 #ifdef MINGW
1131       handles += read_handles = GNUNET_CONTAINER_slist_count (rfds->handles);
1132 #if DEBUG_NETWORK
1133       {
1134         struct GNUNET_CONTAINER_SList_Iterator *t;
1135         for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1136             GNUNET_CONTAINER_slist_end (t) != GNUNET_YES;
1137             GNUNET_CONTAINER_slist_next (t))
1138         {
1139           struct GNUNET_DISK_FileHandle *fh;
1140           fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (t, NULL);
1141           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x (0x%x) is SET in rfds\n", fh->h, fh);
1142         }
1143       }
1144 #endif
1145 #endif
1146     }
1147   if (NULL != wfds)
1148     {
1149       nfds = GNUNET_MAX (nfds, wfds->nsds);
1150 #ifdef MINGW
1151       handles += write_handles = GNUNET_CONTAINER_slist_count (wfds->handles);
1152 #endif
1153     }
1154   if (NULL != efds)
1155     {
1156       nfds = GNUNET_MAX (nfds, efds->nsds);
1157 #ifdef MINGW
1158       handles += ex_handles = GNUNET_CONTAINER_slist_count (efds->handles);
1159 #endif
1160     }
1161
1162   if ((nfds == 0) && (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1163 #ifdef MINGW
1164       && handles == 0
1165 #endif
1166     )
1167     {
1168       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1169                   _
1170                   ("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1171                   "select");
1172       GNUNET_break (0);
1173     }
1174 #ifndef MINGW
1175   tv.tv_sec = timeout.rel_value / GNUNET_TIME_UNIT_SECONDS.rel_value;
1176   tv.tv_usec =
1177     1000 * (timeout.rel_value - (tv.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value));
1178   return select (nfds,
1179                  (rfds != NULL) ? &rfds->sds : NULL,
1180                  (wfds != NULL) ? &wfds->sds : NULL,
1181                  (efds != NULL) ? &efds->sds : NULL,
1182                  (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1183                  ? NULL : &tv);
1184
1185 #else
1186 #define SAFE_FD_ISSET(fd, set)  (set != NULL && FD_ISSET(fd, set))
1187   /* calculate how long we need to wait in milliseconds */
1188   if (timeout.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
1189     ms_total = INFINITE;
1190   else
1191     ms_total = timeout.rel_value / GNUNET_TIME_UNIT_MILLISECONDS.rel_value;
1192   /* select() may be used as a portable way to sleep */
1193   if (!(rfds || wfds || efds))
1194     {
1195       Sleep (ms_total);
1196       return 0;
1197     }
1198
1199   /* Events for sockets */
1200   if (!hEventRead)
1201     hEventRead = CreateEvent (NULL, TRUE, FALSE, NULL);
1202   else
1203     ResetEvent (hEventRead);
1204   if (!hEventReadReady)
1205     hEventReadReady = CreateEvent (NULL, TRUE, TRUE, NULL);
1206   if (!hEventWrite)
1207     hEventWrite = CreateEvent (NULL, TRUE, FALSE, NULL);
1208   else
1209     ResetEvent (hEventWrite);
1210   if (!hEventException)
1211     hEventException = CreateEvent (NULL, TRUE, FALSE, NULL);
1212   else
1213     ResetEvent (hEventException);
1214
1215   /* Event for pipes */
1216   if (!hEventPipeWrite)
1217     hEventPipeWrite = CreateEvent (NULL, TRUE, TRUE, NULL);
1218   readPipes = 0;
1219   writePipePos = -1;
1220   
1221   handles_read = GNUNET_CONTAINER_slist_create ();
1222   handles_write = GNUNET_CONTAINER_slist_create ();
1223   handles_except = GNUNET_CONTAINER_slist_create ();
1224   FD_ZERO (&aread);
1225   FD_ZERO (&awrite);
1226   FD_ZERO (&aexcept);
1227 #if DEBUG_NETWORK
1228   FD_ZERO (&bread);
1229   FD_ZERO (&bwrite);
1230   FD_ZERO (&bexcept);
1231 #endif
1232   if (rfds)
1233   {
1234     FD_COPY (&rfds->sds, &aread);
1235 #if DEBUG_NETWORK
1236     FD_COPY (&rfds->sds, &bread);
1237 #endif
1238   }
1239   if (wfds)
1240   {
1241     FD_COPY (&wfds->sds, &awrite);
1242 #if DEBUG_NETWORK
1243     FD_COPY (&wfds->sds, &bwrite);
1244 #endif
1245   }
1246   if (efds)
1247   {
1248     FD_COPY (&efds->sds, &aexcept);
1249 #if DEBUG_NETWORK
1250     FD_COPY (&efds->sds, &bexcept);
1251 #endif
1252   }
1253   /* We will first Add the PIPES to the events */
1254   /* Read Pipes */
1255   if (rfds && read_handles)
1256   {
1257     struct GNUNET_CONTAINER_SList_Iterator *i;
1258     for (i = GNUNET_CONTAINER_slist_begin (rfds->handles);
1259         GNUNET_CONTAINER_slist_end (i) != GNUNET_YES;
1260         GNUNET_CONTAINER_slist_next (i))
1261     {
1262       struct GNUNET_DISK_FileHandle *fh;
1263       fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (i, NULL);
1264       if (fh->type == GNUNET_PIPE)
1265       {
1266         /* Read zero bytes to check the status of the pipe */
1267 #if DEBUG_NETWORK
1268         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Reading 0 bytes from the pipe 0x%x\n", fh->h);
1269 #endif
1270         if (!ReadFile (fh->h, NULL, 0, NULL, fh->oOverlapRead))
1271         {
1272           DWORD error_code = GetLastError();
1273           if (error_code == ERROR_IO_PENDING)
1274           {
1275 #if DEBUG_NETWORK
1276             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding the pipe's 0x%x overlapped event to the array as %d\n", fh->h, nhandles);
1277 #endif
1278             handle_array[nhandles++] = fh->oOverlapRead->hEvent;
1279             readArray[readPipes++] = fh;
1280           }
1281           /*
1282           else
1283           {
1284             SetErrnoFromWinError (error_code);
1285           }
1286           */
1287         }
1288         else
1289         {
1290 #if DEBUG_NETWORK
1291           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding the read ready event to the array as %d\n", nhandles);
1292 #endif
1293           handle_array[nhandles++] = hEventReadReady;
1294           readArray[readPipes++] = fh;
1295         }
1296       }
1297       else
1298       {
1299         GNUNET_CONTAINER_slist_add (handles_read,
1300             GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1301             fh, sizeof (struct GNUNET_DISK_FileHandle));
1302       }
1303     }
1304     GNUNET_CONTAINER_slist_iter_destroy (i);
1305   }
1306   if (wfds && write_handles)
1307   {
1308 #if DEBUG_NETWORK
1309     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding the write ready event to the array as %d\n", nhandles);
1310 #endif
1311     handle_array[nhandles++] = hEventPipeWrite;
1312     writePipePos = nhandles;
1313   }
1314   if (efds && ex_handles)
1315   {
1316     struct GNUNET_CONTAINER_SList_Iterator *i;
1317     for (i = GNUNET_CONTAINER_slist_begin (efds->handles);
1318         GNUNET_CONTAINER_slist_end (i) != GNUNET_YES;
1319         GNUNET_CONTAINER_slist_next (i))
1320     {
1321       struct GNUNET_DISK_FileHandle *fh;
1322       DWORD dwBytes;
1323
1324       fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (i, NULL);
1325       if (fh->type == GNUNET_PIPE)
1326       {
1327         if (!PeekNamedPipe (fh->h, NULL, 0, NULL, &dwBytes, NULL))
1328         {
1329           GNUNET_CONTAINER_slist_add (handles_except,
1330               GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1331               fh, sizeof (struct GNUNET_DISK_FileHandle));
1332           newretcode++;
1333         }
1334       }
1335     }
1336     GNUNET_CONTAINER_slist_iter_destroy (i);
1337   }
1338   if (nfds > 0)
1339   {
1340     if (rfds)
1341     {
1342 #if DEBUG_NETWORK
1343       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding the socket read event to the array as %d\n", nhandles);
1344 #endif
1345       handle_array[nhandles++] = hEventRead;
1346       nSockEvents++;
1347       for (i = 0; i < rfds->sds.fd_count; i++)
1348       {
1349         WSAEventSelect (rfds->sds.fd_array[i], hEventRead, FD_ACCEPT | FD_READ | FD_CLOSE);
1350         nsock++;
1351       }
1352     }
1353     if (wfds)
1354     {
1355       int wakeup = 0;
1356 #if DEBUG_NETWORK
1357       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding the socket write event to the array as %d\n", nhandles);
1358 #endif
1359       handle_array[nhandles++] = hEventWrite;
1360       nSockEvents++;
1361       for (i = 0; i < wfds->sds.fd_count; i++)
1362       {
1363         DWORD error;
1364         int status;
1365         status = send (wfds->sds.fd_array[i], NULL, 0, 0);
1366         error = GetLastError ();
1367 #if DEBUG_NETWORK
1368         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pre-send to the socket %d returned %d (%u)\n", i, status, error);
1369 #endif
1370         if (status == 0 || (error != WSAEWOULDBLOCK && error != WSAENOTCONN))
1371           wakeup = 1;
1372         WSAEventSelect (wfds->sds.fd_array[i], hEventWrite, FD_WRITE | FD_CONNECT | FD_CLOSE);
1373         nsock++;
1374       }
1375       if (wakeup)
1376         SetEvent (hEventWrite);
1377     }
1378     if (efds)
1379     {
1380 #if DEBUG_NETWORK
1381       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding the socket error event to the array as %d\n", nhandles);
1382 #endif
1383       handle_array[nhandles++] = hEventException;
1384       nSockEvents++;
1385       for (i = 0; i < efds->sds.fd_count; i++)
1386       {
1387         WSAEventSelect (efds->sds.fd_array[i], hEventException, FD_OOB | FD_CLOSE);
1388         nsock++;
1389       }
1390     }
1391   }
1392
1393   handle_array[nhandles] = NULL;
1394
1395 #if DEBUG_NETWORK
1396   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Number nfds : %d\n", nfds);
1397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Number of handles : %d\n", nhandles);
1398   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "retcode : %d\n", newretcode);
1399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Will wait : %d\n", ms_total);
1400 #endif
1401
1402   if (nhandles)
1403     returncode = WaitForMultipleObjects (nhandles, handle_array, FALSE, ms_total); 
1404 #if DEBUG_NETWORK
1405   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WaitForMultipleObjects Returned : %d\n", returncode);
1406 #endif
1407   
1408   returnedpos = returncode - WAIT_OBJECT_0;
1409 #if DEBUG_NETWORK
1410   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return pos is : %d\n", returnedpos);
1411 #endif
1412
1413   /* FIXME: THIS LINE IS WRONG !! We should add to handles only handles that fired the events, not all ! */
1414   /*
1415   if(rfds)
1416     GNUNET_CONTAINER_slist_append (handles_read, rfds->handles);
1417   */
1418   if (nhandles && (returnedpos < nhandles))
1419   {
1420     DWORD waitstatus;
1421     /* Do the select */
1422     if (nfds)
1423     {
1424       struct timeval tvslice;
1425       tvslice.tv_sec = 0;
1426       tvslice.tv_usec = 10;
1427       retcode = select (nfds, &aread, &awrite, &aexcept, &tvslice);
1428       if (retcode == -1)
1429         retcode = 0;
1430 #if DEBUG_NETWORK
1431       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Select retcode : %d\n", retcode);
1432 #endif
1433     }
1434     /* FIXME: <= writePipePos? Really? */
1435     if ((writePipePos != -1) && (returnedpos <= writePipePos))
1436     {
1437       GNUNET_CONTAINER_slist_append (handles_write, wfds->handles);
1438       retcode += write_handles;
1439 #if DEBUG_NETWORK
1440       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Added write pipe\n");
1441 #endif
1442     }
1443 #if DEBUG_NETWORK
1444     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ReadPipes is : %d\n", readPipes);
1445 #endif
1446     /* We have some pipes ready for read. */
1447     /* FIXME: it is supposed to work !! Only choose the Pipes who fired the event, but it is not working */
1448     
1449     if (returnedpos < readPipes)
1450     {
1451       /*
1452       for (i = 0; i < readPipes; i++)
1453       {
1454         waitstatus = WaitForSingleObject (handle_array[i], 0);
1455         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Read pipe %d wait status is : %d\n", i, waitstatus);
1456         if (waitstatus != WAIT_OBJECT_0)
1457           continue;
1458         GNUNET_CONTAINER_slist_add (handles_read,
1459             GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1460             readArray[i], sizeof (struct GNUNET_DISK_FileHandle));
1461         retcode++;
1462         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Added read Pipe\n");
1463       }
1464       */
1465       for (i = 0; i < readPipes; i++)
1466       {
1467         DWORD error;
1468         BOOL bret;
1469         SetLastError (0);
1470         waitstatus = 0;
1471         bret = PeekNamedPipe (readArray[i]->h, NULL, 0, NULL, &waitstatus, NULL);
1472         error = GetLastError ();
1473 #if DEBUG_NETWORK
1474         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peek at read pipe %d (0x%x) returned %d (%d bytes available) GLE %u\n", i, readArray[i]->h, bret, waitstatus, error);
1475 #endif
1476         if (bret == 0 || waitstatus <= 0)
1477           continue;
1478         GNUNET_CONTAINER_slist_add (handles_read,
1479             GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1480             readArray[i], sizeof (struct GNUNET_DISK_FileHandle));
1481         retcode++;
1482 #if DEBUG_NETWORK
1483         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Added read Pipe 0x%x (0x%x)\n", readArray[i], readArray[i]->h);
1484 #endif
1485       }
1486     }
1487     waitstatus = WaitForSingleObject (hEventWrite, 0);
1488 #if DEBUG_NETWORK
1489     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Wait for the write event returned %d\n", waitstatus);
1490 #endif
1491     if (waitstatus == WAIT_OBJECT_0)
1492     {
1493       for (i = 0; i < wfds->sds.fd_count; i++)
1494       {
1495         DWORD error;
1496         int status;
1497         int so_error = 0;
1498         int sizeof_so_error = sizeof (so_error);
1499         int gso_result = getsockopt (wfds->sds.fd_array[i], SOL_SOCKET, SO_ERROR, (char *) &so_error, &sizeof_so_error);
1500         status = send (wfds->sds.fd_array[i], NULL, 0, 0);
1501         error = GetLastError ();
1502 #if DEBUG_NETWORK
1503         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send to the socket %d returned %d (%u)\n", i, status, error);
1504 #endif
1505         if (status == 0
1506             || (error != WSAEWOULDBLOCK && error != WSAENOTCONN)
1507             || (status == -1 && gso_result == 0 && error == WSAENOTCONN && so_error == WSAECONNREFUSED))
1508         {
1509           FD_SET (wfds->sds.fd_array[i], &awrite);
1510           retcode += 1;
1511         }
1512       }
1513     }
1514   }
1515 #if DEBUG_NETWORK
1516   if (!nhandles || (returnedpos >= nhandles))
1517     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Returning from _select() with nothing!\n");
1518 #endif
1519   if (rfds)
1520   {
1521     struct GNUNET_CONTAINER_SList_Iterator *t;
1522     for (i = 0; i < rfds->sds.fd_count; i++)
1523     {
1524       WSAEventSelect (rfds->sds.fd_array[i], hEventRead, 0);
1525       nsock++;
1526     }
1527     for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1528         GNUNET_CONTAINER_slist_end (t) != GNUNET_YES;
1529         GNUNET_CONTAINER_slist_next (t))
1530     {
1531       struct GNUNET_DISK_FileHandle *fh;
1532       fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (t, NULL);
1533       if (fh->type == GNUNET_PIPE)
1534       {
1535         CancelIo (fh->h);
1536       }
1537     }
1538     GNUNET_CONTAINER_slist_iter_destroy (t);
1539 #if DEBUG_NETWORK
1540     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Zeroing rfds\n");
1541 #endif
1542     GNUNET_NETWORK_fdset_zero (rfds);
1543     if (retcode != -1 && nhandles && (returnedpos < nhandles))
1544       GNUNET_NETWORK_fdset_copy_native (rfds, &aread, retcode);
1545     GNUNET_CONTAINER_slist_append (rfds->handles, handles_read);
1546   }
1547   if (wfds)
1548   {
1549     for (i = 0; i < wfds->sds.fd_count; i++)
1550     {
1551       WSAEventSelect (wfds->sds.fd_array[i], hEventWrite, 0);
1552       nsock++;
1553     }
1554 #if DEBUG_NETWORK
1555     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Zeroing wfds\n");
1556 #endif
1557     GNUNET_NETWORK_fdset_zero (wfds);
1558     if (retcode != -1 && nhandles && (returnedpos < nhandles))
1559       GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, retcode);
1560     GNUNET_CONTAINER_slist_append (wfds->handles, handles_write);
1561   }
1562   if (efds)
1563   {
1564     for (i = 0; i < efds->sds.fd_count; i++)
1565     {
1566       WSAEventSelect (efds->sds.fd_array[i], hEventException, 0);
1567       nsock++;
1568     }
1569 #if DEBUG_NETWORK
1570     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Zeroing efds\n");
1571 #endif
1572     GNUNET_NETWORK_fdset_zero (efds);
1573     if (retcode != -1 && nhandles && (returnedpos < nhandles))
1574       GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, retcode);
1575     GNUNET_CONTAINER_slist_append (efds->handles, handles_except);
1576   }
1577   GNUNET_CONTAINER_slist_destroy (handles_read);
1578   GNUNET_CONTAINER_slist_destroy (handles_write);
1579   GNUNET_CONTAINER_slist_destroy (handles_except);
1580 #if DEBUG_NETWORK
1581   if (rfds)
1582   {
1583     struct GNUNET_CONTAINER_SList_Iterator *t;
1584     for (i = 0; i < bread.fd_count; i++)
1585     {
1586       if (bread.fd_array[i] != 0)
1587         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x is %s in rfds\n", bread.fd_array[i], (SAFE_FD_ISSET (bread.fd_array[i], rfds)) ? "SET" : "NOT SET");
1588     }
1589     for (t = GNUNET_CONTAINER_slist_begin (rfds->handles);
1590         GNUNET_CONTAINER_slist_end (t) != GNUNET_YES;
1591         GNUNET_CONTAINER_slist_next (t))
1592     {
1593       struct GNUNET_DISK_FileHandle *fh;
1594       fh = (struct GNUNET_DISK_FileHandle *) GNUNET_CONTAINER_slist_get (t, NULL);
1595       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x is SET in rfds\n", fh->h);
1596     }
1597   }
1598   if (wfds)
1599   {
1600     for (i = 0; i < bwrite.fd_count; i++)
1601     {
1602       if (bwrite.fd_array[i] != 0)
1603         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x is %s in wfds\n", bwrite.fd_array[i], (SAFE_FD_ISSET (bwrite.fd_array[i], rfds)) ? "SET" : "NOT SET");
1604     }
1605   }
1606   if (efds)
1607   {
1608     for (i = 0; i < bexcept.fd_count; i++)
1609     {
1610       if (bexcept.fd_array[i] != 0)
1611         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "FD 0x%x is %s in efds\n", bexcept.fd_array[i], (SAFE_FD_ISSET (bexcept.fd_array[i], rfds)) ? "SET" : "NOT SET");
1612     }
1613   }
1614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Returning %d or 0\n", retcode);
1615 #endif
1616   if (nhandles && (returnedpos < nhandles))
1617     return retcode;
1618   else
1619 #endif
1620     return 0;
1621 }
1622
1623
1624 /* end of network.c */