Debian Codegraph @

lib/poll.c

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