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