Merge branch 'master' of ssh://bonzini@git.sv.gnu.org/srv/git/gnulib
[pspp] / lib / poll.c
1 /* Emulation for poll(2)
2    Contributed by Paolo Bonzini.
3
4    Copyright 2001, 2002, 2003, 2006, 2007, 2008 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 #include <config.h>
23
24 #include <sys/types.h>
25 #include "poll.h"
26 #include <errno.h>
27 #include <limits.h>
28
29 #ifdef __MSVCRT__
30 #include <windows.h>
31 #include <winsock2.h>
32 #include <io.h>
33 #include <stdio.h>
34 #include <conio.h>
35 #else
36 #include <sys/socket.h>
37 #include <sys/select.h>
38 #include <unistd.h>
39 #endif
40
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
43 #endif
44 #ifdef HAVE_SYS_FILIO_H
45 #include <sys/filio.h>
46 #endif
47
48 #include <sys/time.h>
49 #include <time.h>
50
51 #ifndef INFTIM
52 #define INFTIM (-1)
53 #endif
54
55 /* BeOS does not have MSG_PEEK.  */
56 #ifndef MSG_PEEK
57 #define MSG_PEEK 0
58 #endif
59
60 #ifdef __MSVCRT__
61
62 /* Declare data structures for ntdll functions.  */
63 typedef struct _FILE_PIPE_LOCAL_INFORMATION {
64   ULONG NamedPipeType;
65   ULONG NamedPipeConfiguration;
66   ULONG MaximumInstances;
67   ULONG CurrentInstances;
68   ULONG InboundQuota;
69   ULONG ReadDataAvailable;
70   ULONG OutboundQuota;
71   ULONG WriteQuotaAvailable;
72   ULONG NamedPipeState;
73   ULONG NamedPipeEnd;
74 } FILE_PIPE_LOCAL_INFORMATION, *PFILE_PIPE_LOCAL_INFORMATION;
75
76 typedef struct _IO_STATUS_BLOCK
77 {
78   union u {
79     NTSTATUS Status;
80     PVOID Pointer;
81   };
82   ULONG_PTR Information;
83 } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
84
85 #define FilePipeLocalInformation 24
86
87 typedef NTSTATUS (NTAPI *PNtQueryInformationFile)
88          (HANDLE, IO_STATUS_BLOCK *, VOID *, ULONG, FILE_INFORMATION_CLASS);
89
90 #ifndef PIPE_BUF
91 #define PIPE_BUF        512
92 #endif
93
94 /* Compute revents values for file handle H.  */
95
96 static int
97 win32_compute_revents (HANDLE h, int sought)
98 {
99   int i, ret, happened;
100   INPUT_RECORD *irbuffer;
101   DWORD avail, nbuffer;
102   IO_STATUS_BLOCK iosb;
103   FILE_PIPE_LOCAL_INFORMATION fpli;
104   static PNtQueryInformationFile NtQueryInformationFile;
105
106   ret = WaitForSingleObject (h, 0);
107   if (ret != WAIT_OBJECT_0)
108     return sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
109
110   switch (GetFileType (h))
111     {
112     case FILE_TYPE_PIPE:
113       if (!NtQueryInformationFile)
114         NtQueryInformationFile = (PNtQueryInformationFile)
115           GetProcAddress (GetModuleHandle ("ntdll.dll"),
116                           "NtQueryInformationFile");
117
118       happened = 0;
119       if (!PeekNamedPipe (h, NULL, 0, NULL, &avail, NULL))
120         return POLLERR;
121
122       if (avail)
123         happened |= sought & (POLLIN | POLLRDNORM);
124
125       memset (&iosb, 0, sizeof (iosb));
126       memset (&fpli, 0, sizeof (fpli));
127
128       /* If NtQueryInformationFile fails, optimistically assume the pipe is
129          writable.  This could happen on Win9x, because NtQueryInformationFile
130          is not available, or if we inherit a pipe that doesn't permit
131          FILE_READ_ATTRIBUTES access on the write end (I think this should
132          not happen since WinXP SP2; WINE seems fine too).  Otherwise,
133          ensure that enough space is available for atomic writes.  */
134       if (NtQueryInformationFile (h, &iosb, &fpli, sizeof (fpli),
135                                   FilePipeLocalInformation)
136           || fpli.WriteQuotaAvailable >= PIPE_BUF
137           || (fpli.OutboundQuota < PIPE_BUF &&
138               fpli.WriteQuotaAvailable == fpli.OutboundQuota))
139         happened |= sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
140
141       return happened;
142
143     case FILE_TYPE_CHAR:
144       nbuffer = avail = 0;
145       bRet = GetNumberOfConsoleInputEvents (h, &nbuffer);
146       if (!bRet || nbuffer == 0)
147         return POLLHUP;
148
149       irbuffer = (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
150       bRet = PeekConsoleInput (h, irbuffer, nbuffer, &avail);
151       if (!bRet || avail == 0)
152         return POLLHUP;
153
154       for (i = 0; i < avail; i++)
155         if (irbuffer[i].EventType == KEY_EVENT)
156           return sought & ~(POLLPRI | POLLRDBAND);
157
158       return sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
159
160     default:
161       return sought & ~(POLLPRI | POLLRDBAND);
162     }
163 }
164
165 /* Convert fd_sets returned by select into revents values.  */
166
167 static int
168 win32_compute_revents_socket (SOCKET h, int sought,
169                               fd_set *rfds, fd_set *wfds, fd_set *efds)
170 {
171   int happened = 0;
172
173   if (FD_ISSET (h, rfds))
174     {
175       int r, error;
176
177       char data[64];
178       WSASetLastError (0);
179       r = recv (h, data, sizeof (data), MSG_PEEK);
180       error = WSAGetLastError ();
181       WSASetLastError (0);
182
183       if (r == 0)
184         happened |= POLLHUP;
185
186       /* If the event happened on an unconnected server socket,
187          that's fine. */
188       else if (r > 0 || ( /* (r == -1) && */ error == ENOTCONN))
189         happened |= (POLLIN | POLLRDNORM) & sought;
190
191       /* Distinguish hung-up sockets from other errors.  */
192       else if (error == WSAESHUTDOWN || error == WSAECONNRESET
193                || error == WSAECONNABORTED || error == WSAENETRESET)
194         happened |= POLLHUP;
195
196       else
197         happened |= POLLERR;
198     }
199
200   if (FD_ISSET (h, wfds))
201     happened |= (POLLOUT | POLLWRNORM | POLLWRBAND) & sought;
202
203   if (FD_ISSET (h, efds))
204     happened |= (POLLPRI | POLLRDBAND) & sought;
205
206   return happened;
207 }
208
209 #else /* !MinGW */
210
211 /* Convert select(2) returned fd_sets into poll(2) revents values.  */
212 static int
213 compute_revents (int fd, int sought, fd_set *rfds, fd_set *wfds, fd_set *efds)
214 {
215   int happened;
216   if (FD_ISSET (fd, rfds))
217     {
218       int r;
219       int socket_errno;
220
221 #if defined __MACH__ && defined __APPLE__
222       /* There is a bug in Mac OS X that causes it to ignore MSG_PEEK
223          for some kinds of descriptors.  Detect if this descriptor is a
224          connected socket, a server socket, or something else using a
225          0-byte recv, and use ioctl(2) to detect POLLHUP.  */
226       r = recv (fd, NULL, 0, MSG_PEEK);
227       socket_errno = (r < 0) ? errno : 0;
228       if (r == 0 || socket_errno == ENOTSOCK)
229         ioctl (fd, FIONREAD, &r);
230 #else
231       char data[64];
232       r = recv (fd, data, sizeof (data), MSG_PEEK);
233       socket_errno = (r < 0) ? errno : 0;
234 #endif
235       if (r == 0)
236         happened |= POLLHUP;
237
238       /* If the event happened on an unconnected server socket,
239          that's fine. */
240       else if (r > 0 || ( /* (r == -1) && */ socket_errno == ENOTCONN))
241         happened |= (POLLIN | POLLRDNORM) & sought;
242
243       /* Distinguish hung-up sockets from other errors.  */
244       else if (socket_errno == ESHUTDOWN || socket_errno == ECONNRESET
245                || socket_errno == ECONNABORTED || socket_errno == ENETRESET)
246         happened |= POLLHUP;
247
248       else
249         happened |= POLLERR;
250     }
251
252   if (FD_ISSET (fd, wfds))
253     happened |= (POLLOUT | POLLWRNORM | POLLWRBAND) & sought;
254
255   if (FD_ISSET (fd, efds))
256     happened |= (POLLPRI | POLLRDBAND) & sought;
257
258   return happened;
259 }
260 #endif /* !MinGW */
261
262 int
263 poll (pfd, nfd, timeout)
264      struct pollfd *pfd;
265      nfds_t nfd;
266      int timeout;
267 {
268 #ifndef __MSVCRT__
269   fd_set rfds, wfds, efds;
270   struct timeval tv;
271   struct timeval *ptv;
272   int maxfd, rc;
273   nfds_t i;
274
275 #ifdef _SC_OPEN_MAX
276   static int sc_open_max = -1;
277
278   if (nfd < 0
279       || (nfd > sc_open_max
280           && (sc_open_max != -1
281               || nfd > (sc_open_max = sysconf (_SC_OPEN_MAX)))))
282     {
283       errno = EINVAL;
284       return -1;
285     }
286 #else /* !_SC_OPEN_MAX */
287 #ifdef OPEN_MAX
288   if (nfd < 0 || nfd > OPEN_MAX)
289     {
290       errno = EINVAL;
291       return -1;
292     }
293 #endif /* OPEN_MAX -- else, no check is needed */
294 #endif /* !_SC_OPEN_MAX */
295
296   /* EFAULT is not necessary to implement, but let's do it in the
297      simplest case. */
298   if (!pfd)
299     {
300       errno = EFAULT;
301       return -1;
302     }
303
304   /* convert timeout number into a timeval structure */
305   if (timeout == 0)
306     {
307       ptv = &tv;
308       ptv->tv_sec = 0;
309       ptv->tv_usec = 0;
310     }
311   else if (timeout > 0)
312     {
313       ptv = &tv;
314       ptv->tv_sec = timeout / 1000;
315       ptv->tv_usec = (timeout % 1000) * 1000;
316     }
317   else if (timeout == INFTIM)
318     /* wait forever */
319     ptv = NULL;
320   else
321     {
322       errno = EINVAL;
323       return -1;
324     }
325
326   /* create fd sets and determine max fd */
327   maxfd = -1;
328   FD_ZERO (&rfds);
329   FD_ZERO (&wfds);
330   FD_ZERO (&efds);
331   for (i = 0; i < nfd; i++)
332     {
333       if (pfd[i].fd < 0)
334         continue;
335
336       if (pfd[i].events & (POLLIN | POLLRDNORM))
337         FD_SET (pfd[i].fd, &rfds);
338
339       /* see select(2): "the only exceptional condition detectable
340          is out-of-band data received on a socket", hence we push
341          POLLWRBAND events onto wfds instead of efds. */
342       if (pfd[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND))
343         FD_SET (pfd[i].fd, &wfds);
344       if (pfd[i].events & (POLLPRI | POLLRDBAND))
345         FD_SET (pfd[i].fd, &efds);
346       if (pfd[i].fd >= maxfd
347           && (pfd[i].events & (POLLIN | POLLOUT | POLLPRI
348                                | POLLRDNORM | POLLRDBAND
349                                | POLLWRNORM | POLLWRBAND)))
350         {
351           maxfd = pfd[i].fd;
352
353           /* Windows use a linear array of sockets (of size FD_SETSIZE). The
354              descriptor value is not used to address the array.  */
355 #if defined __CYGWIN__ || (!defined _WIN32 && !defined __WIN32__)
356           if (maxfd > FD_SETSIZE)
357             {
358               errno = EOVERFLOW;
359               return -1;
360             }
361 #endif
362         }
363     }
364
365   /* examine fd sets */
366   rc = select (maxfd + 1, &rfds, &wfds, &efds, ptv);
367   if (rc < 0)
368     return rc;
369
370   /* establish results */
371   rc = 0;
372   for (i = 0; i < nfd; i++)
373     if (pfd[i].fd < 0)
374       pfd[i].revents = 0;
375     else
376       {
377         int happened = compute_revents (pfd[i].fd, pfd[i].events,
378                                         &rfds, &wfds, &efds);
379         if (happened)
380           {
381             pfd[i].revents = happened;
382             rc++;
383           }
384       }
385
386   return rc;
387 #else
388   fd_set rfds, wfds, efds;
389   static struct timeval tv0;
390   struct timeval tv = { 0, 0 };
391   struct timeval *ptv;
392   static HANDLE hEvent;
393   HANDLE handle_array[FD_SET_SIZE + 2];
394   DWORD ret, wait_timeout, nhandles;
395   int nsock;
396   BOOL bRet;
397   MSG msg;
398   char sockbuf[256];
399   int rc;
400   nfds_t i;
401
402   if (nfd < 0 || nfd > FD_SET_SIZE || timeout < 0)
403     {
404       errno = EINVAL;
405       return -1;
406     }
407
408   if (!hEvent)
409     hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
410
411   handle_array[0] = hEvent;
412   nhandles = 1;
413   nsock = 0;
414
415   /* Classify socket handles and create fd sets. */
416   FD_ZERO (&rfds);
417   FD_ZERO (&wfds);
418   FD_ZERO (&efds);
419   for (i = 0; i < nfd; i++)
420     {
421       if (pfd[i].fd < 0)
422         continue;
423
424       h = (HANDLE) _get_osfhandle (i);
425       assert (h != NULL);
426       optlen = sizeof(sockbuf);
427       if ((getsockopt ((SOCKET) h, SOL_SOCKET, SO_TYPE, sockbuf, &optlen)
428            != SOCKET_ERROR)
429           || WSAGetLastError() != WSAENOTSOCK)
430         {
431           int ev = 0;
432
433           /* see above; socket handles are mapped onto select.  */
434           if (pfd[i].events & (POLLIN | POLLRDNORM))
435             {
436               FD_SET (pfd[i].fd, &rfds);
437               ev |= FD_READ | FD_ACCEPT;
438             }
439           if (pfd[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND))
440             {
441               FD_SET (pfd[i].fd, &wfds);
442               ev |= FD_WRITE | FD_CONNECT;
443             }
444           if (pfd[i].events & (POLLPRI | POLLRDBAND))
445             {
446               FD_SET (pfd[i].fd, &efds);
447               ev |= FD_OOB;
448             }
449           if (ev)
450             {
451               WSAEventSelect ((SOCKET) h, hEvent, ev);
452               nsock++;
453             }
454         }
455       else
456         {
457           if (pfd[i].events & (POLLIN | POLLRDNORM |
458                                POLLOUT | POLLWRNORM | POLLWRBAND))
459             handle_array[nhandles++] = h;
460         }
461     }
462
463   if (timeout == INFTIM)
464     wait_timeout = INFINITE;
465   else
466     wait_timeout = timeout;
467
468   for (;;)
469     {
470       ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
471                                        wait_timeout, QS_ALLINPUT);
472
473       if (ret == WAIT_OBJECT_0 + nhandles)
474         {
475           /* new input of some other kind */
476           while ((bRet = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0)
477             {
478               TranslateMessage (&msg);
479               DispatchMessage (&msg);
480             }
481         }
482       else
483         break;
484     }
485
486   /* Now check if the sockets have some event set.  */
487   select (nsock + 1, rfds, wfds, efds, &tv0);
488
489   /* Place a sentinel at the end of the array.  */
490   handle_array[nhandles] = NULL;
491   nhandles = 1;
492   for (i = 0; i < nfd; i++)
493     {
494       int happened;
495
496       if (pfd[i].fd < 0)
497         {
498           pfd[i].revents = 0;
499           continue;
500         }
501
502       h = (HANDLE) _get_osfhandle (i);
503       if (h != handle_array[nhandles])
504         {
505           /* It's a socket.  */
506           WSAEventSelect (h, 0, 0);
507           happened = win32_compute_revents_socket ((SOCKET) h, pfd[i].events,
508                                                    &rfds, &wfds, &efds);
509         }
510       else
511         {
512           /* Not a socket.  */
513           nhandles++;
514           happened = win32_compute_revents (h, pfd[i].events);
515         }
516
517        if (happened)
518         {
519           pfd[i].revents = happened;
520           rc++;
521         }
522     }
523
524   return rc;
525 #endif
526 }