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