update debian/copyright
[gnulib.git] / lib / poll.c
1 /* Emulation for poll(2)
2    Contributed by Paolo Bonzini.
3
4    Copyright 2001-2003, 2006-2011 Free Software Foundation, Inc.
5
6    This file is part of gnulib.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2, or (at your option)
11    any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License along
19    with this program; if not, write to the Free Software Foundation,
20    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
21
22 /* Tell gcc not to warn about the (nfd < 0) tests, below.  */
23 #if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
24 # pragma GCC diagnostic ignored "-Wtype-limits"
25 #endif
26
27 #include <config.h>
28 #include <alloca.h>
29
30 #include <sys/types.h>
31
32 /* Specification.  */
33 #include <poll.h>
34
35 #include <errno.h>
36 #include <limits.h>
37 #include <assert.h>
38
39 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
40 # define WIN32_NATIVE
41 # include <winsock2.h>
42 # include <windows.h>
43 # include <io.h>
44 # include <stdio.h>
45 # include <conio.h>
46 # include "msvc-nothrow.h"
47 #else
48 # include <sys/time.h>
49 # include <sys/socket.h>
50 # include <sys/select.h>
51 # include <unistd.h>
52 #endif
53
54 #ifdef HAVE_SYS_IOCTL_H
55 # include <sys/ioctl.h>
56 #endif
57 #ifdef HAVE_SYS_FILIO_H
58 # include <sys/filio.h>
59 #endif
60
61 #include <time.h>
62
63 #ifndef INFTIM
64 # define INFTIM (-1)
65 #endif
66
67 /* BeOS does not have MSG_PEEK.  */
68 #ifndef MSG_PEEK
69 # define MSG_PEEK 0
70 #endif
71
72 #ifdef WIN32_NATIVE
73
74 #define IsConsoleHandle(h) (((long) (h) & 3) == 3)
75
76 static BOOL
77 IsSocketHandle (HANDLE h)
78 {
79   WSANETWORKEVENTS ev;
80
81   if (IsConsoleHandle (h))
82     return FALSE;
83
84   /* Under Wine, it seems that getsockopt returns 0 for pipes too.
85      WSAEnumNetworkEvents instead distinguishes the two correctly.  */
86   ev.lNetworkEvents = 0xDEADBEEF;
87   WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
88   return ev.lNetworkEvents != 0xDEADBEEF;
89 }
90
91 /* Declare data structures for ntdll functions.  */
92 typedef struct _FILE_PIPE_LOCAL_INFORMATION {
93   ULONG NamedPipeType;
94   ULONG NamedPipeConfiguration;
95   ULONG MaximumInstances;
96   ULONG CurrentInstances;
97   ULONG InboundQuota;
98   ULONG ReadDataAvailable;
99   ULONG OutboundQuota;
100   ULONG WriteQuotaAvailable;
101   ULONG NamedPipeState;
102   ULONG NamedPipeEnd;
103 } FILE_PIPE_LOCAL_INFORMATION, *PFILE_PIPE_LOCAL_INFORMATION;
104
105 typedef struct _IO_STATUS_BLOCK
106 {
107   union {
108     DWORD Status;
109     PVOID Pointer;
110   } u;
111   ULONG_PTR Information;
112 } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
113
114 typedef enum _FILE_INFORMATION_CLASS {
115   FilePipeLocalInformation = 24
116 } FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
117
118 typedef DWORD (WINAPI *PNtQueryInformationFile)
119          (HANDLE, IO_STATUS_BLOCK *, VOID *, ULONG, FILE_INFORMATION_CLASS);
120
121 # ifndef PIPE_BUF
122 #  define PIPE_BUF      512
123 # endif
124
125 /* Compute revents values for file handle H.  If some events cannot happen
126    for the handle, eliminate them from *P_SOUGHT.  */
127
128 static int
129 win32_compute_revents (HANDLE h, int *p_sought)
130 {
131   int i, ret, happened;
132   INPUT_RECORD *irbuffer;
133   DWORD avail, nbuffer;
134   BOOL bRet;
135   IO_STATUS_BLOCK iosb;
136   FILE_PIPE_LOCAL_INFORMATION fpli;
137   static PNtQueryInformationFile NtQueryInformationFile;
138   static BOOL once_only;
139
140   switch (GetFileType (h))
141     {
142     case FILE_TYPE_PIPE:
143       if (!once_only)
144         {
145           NtQueryInformationFile = (PNtQueryInformationFile)
146             GetProcAddress (GetModuleHandle ("ntdll.dll"),
147                             "NtQueryInformationFile");
148           once_only = TRUE;
149         }
150
151       happened = 0;
152       if (PeekNamedPipe (h, NULL, 0, NULL, &avail, NULL) != 0)
153         {
154           if (avail)
155             happened |= *p_sought & (POLLIN | POLLRDNORM);
156         }
157       else if (GetLastError () == ERROR_BROKEN_PIPE)
158         happened |= POLLHUP;
159
160       else
161         {
162           /* It was the write-end of the pipe.  Check if it is writable.
163              If NtQueryInformationFile fails, optimistically assume the pipe is
164              writable.  This could happen on Win9x, where NtQueryInformationFile
165              is not available, or if we inherit a pipe that doesn't permit
166              FILE_READ_ATTRIBUTES access on the write end (I think this should
167              not happen since WinXP SP2; WINE seems fine too).  Otherwise,
168              ensure that enough space is available for atomic writes.  */
169           memset (&iosb, 0, sizeof (iosb));
170           memset (&fpli, 0, sizeof (fpli));
171
172           if (!NtQueryInformationFile
173               || NtQueryInformationFile (h, &iosb, &fpli, sizeof (fpli),
174                                          FilePipeLocalInformation)
175               || fpli.WriteQuotaAvailable >= PIPE_BUF
176               || (fpli.OutboundQuota < PIPE_BUF &&
177                   fpli.WriteQuotaAvailable == fpli.OutboundQuota))
178             happened |= *p_sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
179         }
180       return happened;
181
182     case FILE_TYPE_CHAR:
183       ret = WaitForSingleObject (h, 0);
184       if (!IsConsoleHandle (h))
185         return ret == WAIT_OBJECT_0 ? *p_sought & ~(POLLPRI | POLLRDBAND) : 0;
186
187       nbuffer = avail = 0;
188       bRet = GetNumberOfConsoleInputEvents (h, &nbuffer);
189       if (bRet)
190         {
191           /* Input buffer.  */
192           *p_sought &= POLLIN | POLLRDNORM;
193           if (nbuffer == 0)
194             return POLLHUP;
195           if (!*p_sought)
196             return 0;
197
198           irbuffer = (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
199           bRet = PeekConsoleInput (h, irbuffer, nbuffer, &avail);
200           if (!bRet || avail == 0)
201             return POLLHUP;
202
203           for (i = 0; i < avail; i++)
204             if (irbuffer[i].EventType == KEY_EVENT)
205               return *p_sought;
206           return 0;
207         }
208       else
209         {
210           /* Screen buffer.  */
211           *p_sought &= POLLOUT | POLLWRNORM | POLLWRBAND;
212           return *p_sought;
213         }
214
215     default:
216       ret = WaitForSingleObject (h, 0);
217       if (ret == WAIT_OBJECT_0)
218         return *p_sought & ~(POLLPRI | POLLRDBAND);
219
220       return *p_sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
221     }
222 }
223
224 /* Convert fd_sets returned by select into revents values.  */
225
226 static int
227 win32_compute_revents_socket (SOCKET h, int sought, long lNetworkEvents)
228 {
229   int happened = 0;
230
231   if ((lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE)) == FD_ACCEPT)
232     happened |= (POLLIN | POLLRDNORM) & sought;
233
234   else if (lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
235     {
236       int r, error;
237
238       char data[64];
239       WSASetLastError (0);
240       r = recv (h, data, sizeof (data), MSG_PEEK);
241       error = WSAGetLastError ();
242       WSASetLastError (0);
243
244       if (r > 0 || error == WSAENOTCONN)
245         happened |= (POLLIN | POLLRDNORM) & sought;
246
247       /* Distinguish hung-up sockets from other errors.  */
248       else if (r == 0 || error == WSAESHUTDOWN || error == WSAECONNRESET
249                || error == WSAECONNABORTED || error == WSAENETRESET)
250         happened |= POLLHUP;
251
252       else
253         happened |= POLLERR;
254     }
255
256   if (lNetworkEvents & (FD_WRITE | FD_CONNECT))
257     happened |= (POLLOUT | POLLWRNORM | POLLWRBAND) & sought;
258
259   if (lNetworkEvents & FD_OOB)
260     happened |= (POLLPRI | POLLRDBAND) & sought;
261
262   return happened;
263 }
264
265 #else /* !MinGW */
266
267 /* Convert select(2) returned fd_sets into poll(2) revents values.  */
268 static int
269 compute_revents (int fd, int sought, fd_set *rfds, fd_set *wfds, fd_set *efds)
270 {
271   int happened = 0;
272   if (FD_ISSET (fd, rfds))
273     {
274       int r;
275       int socket_errno;
276
277 # if defined __MACH__ && defined __APPLE__
278       /* There is a bug in Mac OS X that causes it to ignore MSG_PEEK
279          for some kinds of descriptors.  Detect if this descriptor is a
280          connected socket, a server socket, or something else using a
281          0-byte recv, and use ioctl(2) to detect POLLHUP.  */
282       r = recv (fd, NULL, 0, MSG_PEEK);
283       socket_errno = (r < 0) ? errno : 0;
284       if (r == 0 || socket_errno == ENOTSOCK)
285         ioctl (fd, FIONREAD, &r);
286 # else
287       char data[64];
288       r = recv (fd, data, sizeof (data), MSG_PEEK);
289       socket_errno = (r < 0) ? errno : 0;
290 # endif
291       if (r == 0)
292         happened |= POLLHUP;
293
294       /* If the event happened on an unconnected server socket,
295          that's fine. */
296       else if (r > 0 || ( /* (r == -1) && */ socket_errno == ENOTCONN))
297         happened |= (POLLIN | POLLRDNORM) & sought;
298
299       /* Distinguish hung-up sockets from other errors.  */
300       else if (socket_errno == ESHUTDOWN || socket_errno == ECONNRESET
301                || socket_errno == ECONNABORTED || socket_errno == ENETRESET)
302         happened |= POLLHUP;
303
304       else
305         happened |= POLLERR;
306     }
307
308   if (FD_ISSET (fd, wfds))
309     happened |= (POLLOUT | POLLWRNORM | POLLWRBAND) & sought;
310
311   if (FD_ISSET (fd, efds))
312     happened |= (POLLPRI | POLLRDBAND) & sought;
313
314   return happened;
315 }
316 #endif /* !MinGW */
317
318 int
319 poll (struct pollfd *pfd, nfds_t nfd, int timeout)
320 {
321 #ifndef WIN32_NATIVE
322   fd_set rfds, wfds, efds;
323   struct timeval tv;
324   struct timeval *ptv;
325   int maxfd, rc;
326   nfds_t i;
327
328 # ifdef _SC_OPEN_MAX
329   static int sc_open_max = -1;
330
331   if (nfd < 0
332       || (nfd > sc_open_max
333           && (sc_open_max != -1
334               || nfd > (sc_open_max = sysconf (_SC_OPEN_MAX)))))
335     {
336       errno = EINVAL;
337       return -1;
338     }
339 # else /* !_SC_OPEN_MAX */
340 #  ifdef OPEN_MAX
341   if (nfd < 0 || nfd > OPEN_MAX)
342     {
343       errno = EINVAL;
344       return -1;
345     }
346 #  endif /* OPEN_MAX -- else, no check is needed */
347 # endif /* !_SC_OPEN_MAX */
348
349   /* EFAULT is not necessary to implement, but let's do it in the
350      simplest case. */
351   if (!pfd)
352     {
353       errno = EFAULT;
354       return -1;
355     }
356
357   /* convert timeout number into a timeval structure */
358   if (timeout == 0)
359     {
360       ptv = &tv;
361       ptv->tv_sec = 0;
362       ptv->tv_usec = 0;
363     }
364   else if (timeout > 0)
365     {
366       ptv = &tv;
367       ptv->tv_sec = timeout / 1000;
368       ptv->tv_usec = (timeout % 1000) * 1000;
369     }
370   else if (timeout == INFTIM)
371     /* wait forever */
372     ptv = NULL;
373   else
374     {
375       errno = EINVAL;
376       return -1;
377     }
378
379   /* create fd sets and determine max fd */
380   maxfd = -1;
381   FD_ZERO (&rfds);
382   FD_ZERO (&wfds);
383   FD_ZERO (&efds);
384   for (i = 0; i < nfd; i++)
385     {
386       if (pfd[i].fd < 0)
387         continue;
388
389       if (pfd[i].events & (POLLIN | POLLRDNORM))
390         FD_SET (pfd[i].fd, &rfds);
391
392       /* see select(2): "the only exceptional condition detectable
393          is out-of-band data received on a socket", hence we push
394          POLLWRBAND events onto wfds instead of efds. */
395       if (pfd[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND))
396         FD_SET (pfd[i].fd, &wfds);
397       if (pfd[i].events & (POLLPRI | POLLRDBAND))
398         FD_SET (pfd[i].fd, &efds);
399       if (pfd[i].fd >= maxfd
400           && (pfd[i].events & (POLLIN | POLLOUT | POLLPRI
401                                | POLLRDNORM | POLLRDBAND
402                                | POLLWRNORM | POLLWRBAND)))
403         {
404           maxfd = pfd[i].fd;
405           if (maxfd > FD_SETSIZE)
406             {
407               errno = EOVERFLOW;
408               return -1;
409             }
410         }
411     }
412
413   /* examine fd sets */
414   rc = select (maxfd + 1, &rfds, &wfds, &efds, ptv);
415   if (rc < 0)
416     return rc;
417
418   /* establish results */
419   rc = 0;
420   for (i = 0; i < nfd; i++)
421     if (pfd[i].fd < 0)
422       pfd[i].revents = 0;
423     else
424       {
425         int happened = compute_revents (pfd[i].fd, pfd[i].events,
426                                         &rfds, &wfds, &efds);
427         if (happened)
428           {
429             pfd[i].revents = happened;
430             rc++;
431           }
432       }
433
434   return rc;
435 #else
436   static struct timeval tv0;
437   static HANDLE hEvent;
438   WSANETWORKEVENTS ev;
439   HANDLE h, handle_array[FD_SETSIZE + 2];
440   DWORD ret, wait_timeout, nhandles;
441   fd_set rfds, wfds, xfds;
442   BOOL poll_again;
443   MSG msg;
444   int rc = 0;
445   nfds_t i;
446
447   if (nfd < 0 || timeout < -1)
448     {
449       errno = EINVAL;
450       return -1;
451     }
452
453   if (!hEvent)
454     hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
455
456 restart:
457   handle_array[0] = hEvent;
458   nhandles = 1;
459   FD_ZERO (&rfds);
460   FD_ZERO (&wfds);
461   FD_ZERO (&xfds);
462
463   /* Classify socket handles and create fd sets. */
464   for (i = 0; i < nfd; i++)
465     {
466       int sought = pfd[i].events;
467       pfd[i].revents = 0;
468       if (pfd[i].fd < 0)
469         continue;
470       if (!(sought & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM | POLLWRBAND
471                       | POLLPRI | POLLRDBAND)))
472         continue;
473
474       h = (HANDLE) _get_osfhandle (pfd[i].fd);
475       assert (h != NULL);
476       if (IsSocketHandle (h))
477         {
478           int requested = FD_CLOSE;
479
480           /* see above; socket handles are mapped onto select.  */
481           if (sought & (POLLIN | POLLRDNORM))
482             {
483               requested |= FD_READ | FD_ACCEPT;
484               FD_SET ((SOCKET) h, &rfds);
485             }
486           if (sought & (POLLOUT | POLLWRNORM | POLLWRBAND))
487             {
488               requested |= FD_WRITE | FD_CONNECT;
489               FD_SET ((SOCKET) h, &wfds);
490             }
491           if (sought & (POLLPRI | POLLRDBAND))
492             {
493               requested |= FD_OOB;
494               FD_SET ((SOCKET) h, &xfds);
495             }
496
497           if (requested)
498             WSAEventSelect ((SOCKET) h, hEvent, requested);
499         }
500       else
501         {
502           /* Poll now.  If we get an event, do not poll again.  Also,
503              screen buffer handles are waitable, and they'll block until
504              a character is available.  win32_compute_revents eliminates
505              bits for the "wrong" direction. */
506           pfd[i].revents = win32_compute_revents (h, &sought);
507           if (sought)
508             handle_array[nhandles++] = h;
509           if (pfd[i].revents)
510             timeout = 0;
511         }
512     }
513
514   if (select (0, &rfds, &wfds, &xfds, &tv0) > 0)
515     {
516       /* Do MsgWaitForMultipleObjects anyway to dispatch messages, but
517          no need to call select again.  */
518       poll_again = FALSE;
519       wait_timeout = 0;
520     }
521   else
522     {
523       poll_again = TRUE;
524       if (timeout == INFTIM)
525         wait_timeout = INFINITE;
526       else
527         wait_timeout = timeout;
528     }
529
530   for (;;)
531     {
532       ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
533                                        wait_timeout, QS_ALLINPUT);
534
535       if (ret == WAIT_OBJECT_0 + nhandles)
536         {
537           /* new input of some other kind */
538           BOOL bRet;
539           while ((bRet = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0)
540             {
541               TranslateMessage (&msg);
542               DispatchMessage (&msg);
543             }
544         }
545       else
546         break;
547     }
548
549   if (poll_again)
550     select (0, &rfds, &wfds, &xfds, &tv0);
551
552   /* Place a sentinel at the end of the array.  */
553   handle_array[nhandles] = NULL;
554   nhandles = 1;
555   for (i = 0; i < nfd; i++)
556     {
557       int happened;
558
559       if (pfd[i].fd < 0)
560         continue;
561       if (!(pfd[i].events & (POLLIN | POLLRDNORM |
562                              POLLOUT | POLLWRNORM | POLLWRBAND)))
563         continue;
564
565       h = (HANDLE) _get_osfhandle (pfd[i].fd);
566       if (h != handle_array[nhandles])
567         {
568           /* It's a socket.  */
569           WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
570           WSAEventSelect ((SOCKET) h, 0, 0);
571
572           /* If we're lucky, WSAEnumNetworkEvents already provided a way
573              to distinguish FD_READ and FD_ACCEPT; this saves a recv later.  */
574           if (FD_ISSET ((SOCKET) h, &rfds)
575               && !(ev.lNetworkEvents & (FD_READ | FD_ACCEPT)))
576             ev.lNetworkEvents |= FD_READ | FD_ACCEPT;
577           if (FD_ISSET ((SOCKET) h, &wfds))
578             ev.lNetworkEvents |= FD_WRITE | FD_CONNECT;
579           if (FD_ISSET ((SOCKET) h, &xfds))
580             ev.lNetworkEvents |= FD_OOB;
581
582           happened = win32_compute_revents_socket ((SOCKET) h, pfd[i].events,
583                                                    ev.lNetworkEvents);
584         }
585       else
586         {
587           /* Not a socket.  */
588           int sought = pfd[i].events;
589           happened = win32_compute_revents (h, &sought);
590           nhandles++;
591         }
592
593        if ((pfd[i].revents |= happened) != 0)
594         rc++;
595     }
596
597   if (!rc && timeout == INFTIM)
598     {
599       SwitchToThread();
600       goto restart;
601     }
602
603   return rc;
604 #endif
605 }