include/hyperman/hm_win.h

filter: Statementstmt 100% 16 / 16 Branchbran 75.0% 2 / 4 (1 uncoverable) Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 95.0% 18 / 20 (1 uncoverable) CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/hyperman/backend_epoll.c ↑ Summary include/hyperman/hyperman.h »
1 #ifndef HM_WIN_H
2 #define HM_WIN_H
3  
4 /* hm_win.h - the platform shim for the socket/IO surface.
5 *
6 * On a POSIX host every entry point below is a macro expanding to the bare
7 * system call, so the Unix build is byte-for-byte what it was before this
8 * header existed: no wrapper frame, no branch, nothing for the optimiser to
9 * undo. On native Windows they map onto Winsock, with every SOCKET wrapped
10 * in a C-runtime fd by _open_osfhandle() so the rest of Hyperman keeps its
11 * dense "int fd" model - loop->conns[HM_MAXFD], the io watcher arrays and
12 * every backend's fd->index table stay exactly as written - and the real
13 * SOCKET is recovered with _get_osfhandle() only at the Winsock boundary.
14 * That is the same trick Fetch uses (fetch/ft_win.h); it is what makes the
15 * port a shim rather than a rewrite.
16 *
17 * Everything here is prefixed hm_ / HM_ on purpose. perl.h has already
18 * pulled the platform headers by the time this is included, and reusing an
19 * ambient name it may have defined is how Eshu spent three releases.
20 *
21 * Included first from hm_core.h, before hm_parse.h / hm_tls.h / the backends.
22 */
23  
24 #ifdef _WIN32
25  
26 /* select()'s descriptor set is sized at winsock2.h include time; raise it
27 * before the first one wins. Nothing here uses select(), but a backend or a
28 * consumer might, and the define is free. */
29 #ifndef FD_SETSIZE
30 #define FD_SETSIZE 4096
31 #endif
32  
33 #include <winsock2.h>
34 #include <ws2tcpip.h>
35 #include <mswsock.h>
36 #include <io.h>
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <stdint.h>
42  
43 /* An older mingw-w64 (Strawberry 5.24's gcc 4.9) leaves _WIN32_WINNT at XP,
44 * and its headers then hide what Vista added: WSAPoll and its struct,
45 * AI_NUMERICSERV, inet_ntop and inet_pton. ws2_32 has exported them all
46 * since Vista, so they are declared here when the headers did not. Raising
47 * _WIN32_WINNT instead is too late: perl.h has included them already. */
48 #ifndef POLLRDNORM
49 typedef struct hm_wsapollfd {
50 SOCKET fd;
51 SHORT events;
52 SHORT revents;
53 } WSAPOLLFD, *LPWSAPOLLFD;
54 #define POLLRDNORM 0x0100
55 #define POLLRDBAND 0x0200
56 #define POLLPRI 0x0400
57 #define POLLWRNORM 0x0010
58 #define POLLWRBAND 0x0020
59 #define POLLERR 0x0001
60 #define POLLHUP 0x0002
61 #define POLLNVAL 0x0004
62 #define POLLIN (POLLRDNORM | POLLRDBAND)
63 #define POLLOUT POLLWRNORM
64 WINSOCK_API_LINKAGE int WSAAPI WSAPoll(LPWSAPOLLFD fdArray, ULONG fds, INT timeout);
65 #endif
66 #ifndef AI_NUMERICSERV
67 #define AI_NUMERICSERV 0x00000008
68 #endif
69 #if defined(__MINGW32__) && defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0600 \
70 && !defined(inet_ntop)
71 WINSOCK_API_LINKAGE const char * WSAAPI inet_ntop(INT af, const void *src,
72 char *dst, size_t size);
73 WINSOCK_API_LINKAGE INT WSAAPI inet_pton(INT af, const char *src, void *dst);
74 #endif
75  
76 #ifndef EINPROGRESS
77 #define EINPROGRESS WSAEINPROGRESS
78 #endif
79 #ifndef EWOULDBLOCK
80 #define EWOULDBLOCK WSAEWOULDBLOCK
81 #endif
82  
83 /* Winsock needs an explicit startup, once per process. Lazily from the
84 * first socket we make: a process that never listens never pays it, and
85 * there is no teardown - the process exiting is the teardown, and a
86 * WSACleanup at unload races anything still holding a socket. */
87 static int hm_win_started = 0;
88 static void hm_os_init(void) {
89 if (!hm_win_started) {
90 WSADATA wsa;
91 WSAStartup(MAKEWORD(2, 2), &wsa);
92 hm_win_started = 1;
93 }
94 }
95  
96 /* Winsock keeps its error out of errno; the core reads errno everywhere
97 * (EAGAIN drives the whole backpressure path), so translate at each call. */
98 static void hm_os_seterrno(void) {
99 switch (WSAGetLastError()) {
100 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
101 case WSAEINPROGRESS:
102 case WSAEALREADY: errno = EINPROGRESS; break;
103 case WSAEINTR: errno = EINTR; break;
104 case WSAECONNRESET: errno = ECONNRESET; break;
105 case WSAECONNABORTED: errno = ECONNABORTED; break;
106 case WSAECONNREFUSED: errno = ECONNREFUSED; break;
107 case WSAETIMEDOUT: errno = ETIMEDOUT; break;
108 case WSAEMFILE: errno = EMFILE; break;
109 case WSAENOTSOCK: errno = EBADF; break;
110 default: errno = EIO; break;
111 }
112 }
113  
114 /* the SOCKET behind one of our fds */
115 #define HM_SOCK(fd) ((SOCKET)_get_osfhandle(fd))
116  
117 /* OpenSSL on Windows wants the SOCKET, not the CRT fd. Socket handle
118 * values fit in an int in practice, which is the assumption OpenSSL's own
119 * API makes. */
120 #define HM_SSL_FD(fd) ((int)HM_SOCK(fd))
121  
122 /* wrap a fresh SOCKET in a CRT fd, or -1 */
123 static int hm_os_wrap(SOCKET s) {
124 int fd;
125 if (s == INVALID_SOCKET) { hm_os_seterrno(); return -1; }
126 fd = _open_osfhandle((intptr_t)s, O_RDWR | O_BINARY);
127 if (fd < 0) { closesocket(s); errno = EMFILE; return -1; }
128 return fd;
129 }
130  
131 static int hm_os_socket(int af, int type, int proto) {
132 hm_os_init();
133 return hm_os_wrap(socket(af, type, proto));
134 }
135  
136 static int hm_os_accept(int fd, struct sockaddr *sa, socklen_t *len) {
137 return hm_os_wrap(accept(HM_SOCK(fd), sa, len));
138 }
139  
140 static int hm_os_bind(int fd, const struct sockaddr *sa, socklen_t len) {
141 if (bind(HM_SOCK(fd), sa, len) == 0) return 0;
142 hm_os_seterrno();
143 return -1;
144 }
145  
146 static int hm_os_listen(int fd, int backlog) {
147 if (listen(HM_SOCK(fd), backlog) == 0) return 0;
148 hm_os_seterrno();
149 return -1;
150 }
151  
152 static int hm_os_setsockopt(int fd, int lvl, int opt, const void *v, socklen_t len) {
153 if (setsockopt(HM_SOCK(fd), lvl, opt, (const char *)v, (int)len) == 0) return 0;
154 hm_os_seterrno();
155 return -1;
156 }
157  
158 static int hm_os_getsockname(int fd, struct sockaddr *sa, socklen_t *len) {
159 if (getsockname(HM_SOCK(fd), sa, len) == 0) return 0;
160 hm_os_seterrno();
161 return -1;
162 }
163  
164 /* _close releases the CRT fd slot and, through it, the socket handle */
165 static int hm_os_close(int fd) { return _close(fd); }
166  
167 static void hm_os_set_nonblock(int fd) {
168 u_long on = 1;
169 ioctlsocket(HM_SOCK(fd), FIONBIO, &on);
170 }
171  
172 /* read/write on a CRT-wrapped socket is not portable - the CRT would go
173 * through ReadFile/WriteFile, which is not the socket path we want (and
174 * not what non-blocking sockets answer to). Always recv/send. */
175 static ssize_t hm_os_recv(int fd, void *buf, size_t n) {
176 int r = recv(HM_SOCK(fd), (char *)buf, (int)n, 0);
177 if (r == SOCKET_ERROR) { hm_os_seterrno(); return -1; }
178 return r;
179 }
180  
181 static ssize_t hm_os_recv_peek(int fd, void *buf, size_t n) {
182 int r = recv(HM_SOCK(fd), (char *)buf, (int)n, MSG_PEEK);
183 if (r == SOCKET_ERROR) { hm_os_seterrno(); return -1; }
184 return r;
185 }
186  
187 static ssize_t hm_os_send(int fd, const void *buf, size_t n) {
188 int r = send(HM_SOCK(fd), (const char *)buf, (int)n, 0);
189 if (r == SOCKET_ERROR) { hm_os_seterrno(); return -1; }
190 return r;
191 }
192  
193 /* Datagrams, for the QUIC listener (hm_quic.h). One packet per call.
194 *
195 * recvmsg/sendmsg would additionally give the LOCAL address (IP_PKTINFO) and
196 * ECN, and recvmmsg/sendmmsg would batch - all of which QUIC eventually
197 * wants and none of which is here yet. Swapping them in does not ripple
198 * because there is exactly one call site each, inside hm_quic.h: keep it
199 * that way rather than reaching for these from anywhere else. */
200 static ssize_t hm_os_recvfrom(int fd, void *buf, size_t n,
201 struct sockaddr *sa, socklen_t *salen) {
202 int r = recvfrom(HM_SOCK(fd), (char *)buf, (int)n, 0, sa, salen);
203 if (r == SOCKET_ERROR) { hm_os_seterrno(); return -1; }
204 return r;
205 }
206  
207 static ssize_t hm_os_sendto(int fd, const void *buf, size_t n,
208 const struct sockaddr *sa, socklen_t salen) {
209 int r = sendto(HM_SOCK(fd), (const char *)buf, (int)n, 0, sa, salen);
210 if (r == SOCKET_ERROR) { hm_os_seterrno(); return -1; }
211 return r;
212 }
213  
214 /* Monotonic nanoseconds. loop->now is time(NULL) - seconds, and wall clock
215 * at that - which ngtcp2 cannot use for a PTO measured in microseconds.
216 * backend_poll.c keeps its own hm_poll_now for its own timer list; it is
217 * deliberately not refactored onto this. */
218 static uint64_t hm_now_ns(void) {
219 static LARGE_INTEGER freq;
220 LARGE_INTEGER c;
221 if (!freq.QuadPart) QueryPerformanceFrequency(&freq);
222 QueryPerformanceCounter(&c);
223 return (uint64_t)((double)c.QuadPart * 1e9 / (double)freq.QuadPart);
224 }
225  
226 #include <process.h>
227 #include <sys/stat.h>
228 #define hm_os_getpid() ((int)_getpid())
229  
230 /* Plain FILE descriptors (the access log), as opposed to sockets. MSVC
231 * spells these with the underscore; the un-prefixed names are deprecated
232 * aliases that a strict build can refuse. */
233 #define hm_os_open_file(path, flags, mode) _open((path), (flags), (mode))
234 #define hm_os_write_file(fd, buf, n) _write((fd), (buf), (unsigned int)(n))
235  
236 /* Positional read (streaming response bodies). Windows has no pread; the
237 * seek-then-read pair is equivalent HERE because a loop owns its fds and
238 * this server is single-threaded per process - there is no other reader
239 * to race the file position with. */
240 static ssize_t hm_os_pread(int fd, void *buf, size_t n, __int64 off) {
241 if (_lseeki64(fd, off, SEEK_SET) < 0) return -1;
242 return (ssize_t)_read(fd, buf, (unsigned int)n);
243 }
244  
245 /* One worker on Windows: there is no fork, and perl's emulation of it is
246 * ithreads - N interpreters in ONE process, sharing the file-scope state
247 * this server keeps per process. So the DEFAULT resolves to a single
248 * worker that works, and an explicit workers => N > 1 is refused at boot
249 * rather than silently downgraded (hm_run_server). */
250 #define hm_os_ncpu() (1)
251  
252 /* Windows has no SIGPIPE (no signal for it to raise) and no SIGUSR1. The
253 * numbers exist only so the same add_signal calls compile; the WSAPoll
254 * backend accepts them and never delivers them, which is what the POD
255 * says. SIGINT/SIGTERM are real there and come from the console handler. */
256 #ifndef SIGPIPE
257 #define SIGPIPE 13
258 #endif
259 #ifndef SIGUSR1
260 #define SIGUSR1 30
261 #endif
262 #ifndef SIGUSR2
263 #define SIGUSR2 31
264 #endif
265 #ifndef SIGHUP
266 #define SIGHUP 1
267 #endif
268 #ifndef O_CLOEXEC
269 #define O_CLOEXEC 0 /* no fork to leak into; nothing to close-on-exec */
270 #endif
271  
272 /* A self-pipe: two connected fds, the write end pokeable from anywhere to
273 * wake a blocked wait. Windows has pipes, but WSAPoll can only poll
274 * SOCKETS, so the pair has to be a loopback TCP connection: listen on
275 * 127.0.0.1:0, connect to it, accept. Both ends non-blocking. 0 or -1. */
276 static int hm_os_selfpipe(int *rfd, int *wfd) {
277 int lst = -1, a = -1, b = -1;
278 struct sockaddr_in addr;
279 socklen_t alen = sizeof(addr);
280  
281 hm_os_init();
282 lst = hm_os_socket(AF_INET, SOCK_STREAM, 0);
283 if (lst < 0) return -1;
284 memset(&addr, 0, sizeof(addr));
285 addr.sin_family = AF_INET;
286 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
287 addr.sin_port = 0;
288 if (hm_os_bind(lst, (struct sockaddr *)&addr, sizeof(addr)) < 0) goto fail;
289 if (hm_os_listen(lst, 1) < 0) goto fail;
290 if (hm_os_getsockname(lst, (struct sockaddr *)&addr, &alen) < 0) goto fail;
291  
292 b = hm_os_socket(AF_INET, SOCK_STREAM, 0);
293 if (b < 0) goto fail;
294 if (connect(HM_SOCK(b), (struct sockaddr *)&addr, sizeof(addr)) != 0) goto fail;
295 a = hm_os_accept(lst, NULL, NULL);
296 if (a < 0) goto fail;
297  
298 hm_os_close(lst);
299 hm_os_set_nonblock(a);
300 hm_os_set_nonblock(b);
301 *rfd = a; *wfd = b;
302 return 0;
303 fail:
304 if (lst >= 0) hm_os_close(lst);
305 if (a >= 0) hm_os_close(a);
306 if (b >= 0) hm_os_close(b);
307 return -1;
308 }
309  
310 /* scatter/gather: WSABUF is struct iovec with the fields swapped */
311 typedef WSABUF hm_iovec;
312 #define HM_IOV_SET(iov, i, base, n) \
313 do { (iov)[i].buf = (char *)(base); (iov)[i].len = (ULONG)(n); } while (0)
314  
315 static ssize_t hm_os_writev(int fd, hm_iovec *iov, int n) {
316 DWORD sent = 0;
317 if (WSASend(HM_SOCK(fd), iov, (DWORD)n, &sent, 0, NULL, NULL) == SOCKET_ERROR) {
318 hm_os_seterrno();
319 return -1;
320 }
321 return (ssize_t)sent;
322 }
323  
324 #else /* ---- POSIX: passthroughs, so the Unix build is unchanged ---- */
325  
326 #include <sys/types.h>
327 #include <sys/socket.h>
328 #include <sys/uio.h>
329 #include <netinet/in.h>
330 #include <netinet/tcp.h>
331 #include <arpa/inet.h>
332 #include <unistd.h>
333 #include <fcntl.h>
334 #include <errno.h>
335 #include <string.h>
336  
337 #define hm_os_init() ((void)0)
338 #define hm_os_seterrno() ((void)0)
339 #define HM_SOCK(fd) (fd)
340 #define HM_SSL_FD(fd) (fd)
341 #define hm_os_socket(af, ty, pr) socket((af), (ty), (pr))
342 #define hm_os_accept(fd, sa, len) accept((fd), (sa), (len))
343 #define hm_os_bind(fd, sa, len) bind((fd), (sa), (len))
344 #define hm_os_listen(fd, backlog) listen((fd), (backlog))
345 #define hm_os_setsockopt(fd, lv, op, v, len) setsockopt((fd), (lv), (op), (v), (len))
346 #define hm_os_getsockname(fd, sa, len) getsockname((fd), (sa), (len))
347 #define hm_os_close(fd) close((fd))
348 #define hm_os_recv(fd, b, n) read((fd), (b), (n))
349 #define hm_os_recv_peek(fd, b, n) recv((fd), (b), (n), MSG_PEEK)
350 #define hm_os_send(fd, b, n) write((fd), (b), (n))
351 #define hm_os_writev(fd, iov, n) writev((fd), (iov), (n))
352 #define hm_os_getpid() ((int)getpid())
353 #define hm_os_open_file(path, flags, mode) open((path), (flags), (mode))
354 #define hm_os_write_file(fd, buf, n) write((fd), (buf), (n))
355 #define hm_os_pread(fd, buf, n, off) pread((fd), (buf), (n), (off))
356  
357 /* Datagrams, for the QUIC listener (hm_quic.h). One packet per call.
358 *
359 * recvmsg/sendmsg would additionally give the LOCAL address (IP_PKTINFO) and
360 * ECN, and recvmmsg/sendmmsg would batch - all of which QUIC eventually
361 * wants and none of which is here yet. Swapping them in does not ripple
362 * because there is exactly one call site each, inside hm_quic.h: keep it
363 * that way rather than reaching for these from anywhere else. */
364 #define hm_os_recvfrom(fd, b, n, sa, len) recvfrom((fd), (b), (n), 0, (sa), (len))
365 #define hm_os_sendto(fd, b, n, sa, len) sendto((fd), (b), (n), 0, (sa), (len))
366  
367 /* Monotonic nanoseconds. loop->now is time(NULL) - seconds, and wall clock
368 * at that - which ngtcp2 cannot use for a PTO measured in microseconds.
369 * clock_gettime needs -lrt on glibc before 2.17; Makefile.PL already probes
370 * for that because backend_poll.c calls it, and backend_poll.c keeps its own
371 * hm_poll_now for its own timer list rather than being refactored onto this. */
372 #include <time.h>
373 31447 static uint64_t hm_now_ns(void) {
374 struct timespec ts;
375 31447 clock_gettime(CLOCK_MONOTONIC, &ts);
376 31447 return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
377 }
378  
379 /* the same self-pipe, where a pipe is pollable */
380 1 static int hm_os_selfpipe(int *rfd, int *wfd) {
381 int fds[2];
382 /*
383 # uncoverable branch true
384 # uncoverable condition left count:1 class:ignore_covered_err */
385 1 ▶ if (pipe(fds) < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (pipe(fds) < 0) return -1; 0 1 1
386 1 fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL, 0) | O_NONBLOCK);
387 1 fcntl(fds[1], F_SETFL, fcntl(fds[1], F_GETFL, 0) | O_NONBLOCK);
388 1 *rfd = fds[0]; *wfd = fds[1];
389 1 return 0;
390 }
391  
392 #include <unistd.h>
393 /* the default worker count: one per CPU */
394 13 static int hm_os_ncpu(void) {
395 13 long n = sysconf(_SC_NPROCESSORS_ONLN);
396 13 ▶ return n > 0 ? (int)n : 1; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
return n > 0 ? (int)n : 1; /* # uncoverable condition right count:1 class:ignore_covered_err */ 13 0 13
397 }
398  
399 typedef struct iovec hm_iovec;
400 #define HM_IOV_SET(iov, i, base, n) \
401 do { (iov)[i].iov_base = (void *)(base); (iov)[i].iov_len = (n); } while (0)
402  
403 92 static void hm_os_set_nonblock(int fd) {
404 92 int fl = fcntl(fd, F_GETFL, 0);
405 92 fcntl(fd, F_SETFL, fl | O_NONBLOCK);
406 92 }
407  
408 #endif /* _WIN32 */
409  
410 /* memmem is a GNU/BSD extension the MinGW and MSVC CRTs lack. The needles
411 * here are the request terminators (\r\n\r\n), so the fallback's O(n*m) is
412 * bounded by a header block, not by a body. */
413 #if defined(_WIN32)
414 static void *hm_memmem(const void *hay, size_t hlen, const void *ndl, size_t nlen) {
415 const unsigned char *h = (const unsigned char *)hay;
416 const unsigned char *n = (const unsigned char *)ndl;
417 size_t i;
418 if (nlen == 0) return (void *)hay;
419 if (hlen < nlen) return NULL;
420 for (i = 0; i + nlen <= hlen; i++)
421 if (h[i] == n[0] && memcmp(h + i, n, nlen) == 0) return (void *)(h + i);
422 return NULL;
423 }
424 #else
425 #define hm_memmem memmem
426 #endif
427  
428 /* localtime_r is POSIX and absent from both Windows CRTs. The Windows
429 * spelling is localtime_s, whose arguments are the other way round and which
430 * MinGW only declares under the secure-API macros - so this uses localtime()
431 * and copies, which needs no feature test. That is safe here for the reason
432 * it is not on POSIX: the Windows CRT keeps its struct tm in thread-local
433 * storage. */
434 #include <time.h>
435 #if defined(_WIN32)
436 static struct tm *hm_localtime_r(const time_t *t, struct tm *out) {
437 struct tm *p = localtime(t);
438 if (!p) return NULL;
439 *out = *p;
440 return out;
441 }
442 static struct tm *hm_gmtime_r(const time_t *t, struct tm *out) {
443 struct tm *p = gmtime(t);
444 if (!p) return NULL;
445 *out = *p;
446 return out;
447 }
448 #else
449 #define hm_localtime_r localtime_r
450 #define hm_gmtime_r gmtime_r
451 #endif
452  
453 #endif /* HM_WIN_H */
« include/hyperman/backend_epoll.c ↑ Summary include/hyperman/hyperman.h »