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