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