moonbridge

view moonbridge_io.c @ 311:930a43a0099a

Bugfix/workaround: Do not call getpeername() when opening TCP connections in non-blocking mode
author jbe
date Sat Jan 27 17:48:15 2018 +0100 (2018-01-27)
parents e4e1ad8d5ab8
children 334ea1f13b0b
line source
2 #ifndef __has_include
3 #define __has_include(x) 0
4 #endif
6 #include <stdlib.h>
7 #include <stdint.h>
8 #include <string.h>
9 #include <errno.h>
10 #include <unistd.h>
11 #include <signal.h>
12 #include <fcntl.h>
13 #include <sys/stat.h>
14 #include <sys/socket.h>
15 #include <sys/un.h>
16 #include <netinet/in.h>
17 #include <netinet/tcp.h>
18 #include <sys/select.h>
19 #include <time.h>
20 #include <netdb.h>
21 #include <arpa/inet.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #if defined(__linux__) || __has_include(<bsd/unistd.h>)
25 #include <bsd/unistd.h>
26 #endif
28 #ifdef MOONBR_IO_USE_TLS
29 #include <tls.h>
30 #endif
32 #include <lua.h>
33 #include <lauxlib.h>
34 #include <lualib.h>
36 #include <assert.h>
38 #define MOONBR_IO_MAXSTRERRORLEN 80
39 #define MOONBR_IO_READBUFLEN 4096
40 #define MOONBR_IO_WRITEBUFLEN 4096
42 #define MOONBR_IO_LISTEN_BACKLOG 1024
44 #define MOONBR_IO_STRERROR_R_MSG "Error detail unavailable due to noncompliant strerror_r() implementation"
45 #define moonbr_io_prepare_errmsg() \
46 char errmsg[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG; \
47 strerror_r(errno, errmsg, MOONBR_IO_MAXSTRERRORLEN)
48 #define moonbr_io_return_prepared_errmsg() \
49 lua_pushnil(L); \
50 lua_pushstring(L, errmsg); \
51 return 2
52 #define moonbr_io_return_errmsg() \
53 do { \
54 moonbr_io_prepare_errmsg(); \
55 moonbr_io_return_prepared_errmsg(); \
56 } while (0)
58 #define MOONBR_IO_HANDLE_MT_REGKEY "moonbridge_io_handle"
59 #define MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY "moonbridge_io_handle_public"
60 #define MOONBR_IO_LISTENER_MT_REGKEY "moonbridge_io_listener"
61 #define MOONBR_IO_CHILD_MT_REGKEY "moonbridge_io_child"
62 #define MOONBR_IO_CHILD_PT_REGKEY "moonbridge_io_child_pt"
64 #ifdef MOONBR_IO_USE_TLS
66 #define MOONBR_IO_TLSCONF_MT_REGKEY "moonbridge_io_tlsconf"
68 typedef struct {
69 struct tls_config *config;
70 int server;
71 } moonbr_io_tlsconf_t;
73 #endif /* MOONBR_IO_USE_TLS */
75 typedef struct {
76 int fd;
77 int issock;
78 sa_family_t addrfam;
79 int finished;
80 int closed;
81 int nonblocking;
82 int nopush;
83 int readerr;
84 int readbufin;
85 int readbufout;
86 int writeerr;
87 size_t writeleft;
88 size_t flushedleft;
89 #if LUA_VERSION_NUM >= 503
90 lua_Integer writeqin;
91 lua_Integer writeqout;
92 #else
93 int writeqin;
94 int writeqout;
95 #endif
96 size_t writeqoff;
97 int writebufin;
98 int writebufout;
99 char readbuf[MOONBR_IO_READBUFLEN];
100 char writebuf[MOONBR_IO_WRITEBUFLEN];
101 #ifdef MOONBR_IO_USE_TLS
102 struct tls *tls;
103 struct tls *servertls;
104 int tlshandshake;
105 int tlsclosing;
106 #endif
107 } moonbr_io_handle_t;
109 typedef struct {
110 int fd;
111 sa_family_t addrfam;
112 int nonblocking;
113 } moonbr_io_listener_t;
115 typedef struct {
116 pid_t pid;
117 int status;
118 int status_valid;
119 } moonbr_io_child_t;
121 volatile sig_atomic_t moonbr_io_sigterm_flag = 0;
122 volatile sig_atomic_t moonbr_io_sigchld_flag = 0;
124 static int moonbr_io_yield(lua_State *L) {
125 return lua_yield(L, lua_gettop(L));
126 }
128 #if LUA_VERSION_NUM >= 503
129 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
130 #else
131 static int moonbr_io_cont_returnall(lua_State *L) {
132 #endif
133 return lua_gettop(L);
134 }
136 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
137 static int yieldfunc(lua_State *L) { \
138 int args; \
139 lua_pushcfunction(L, callfunc); \
140 lua_insert(L, 1); \
141 args = lua_gettop(L); \
142 lua_pushcfunction(L, moonbr_io_yield); \
143 lua_insert(L, 3); \
144 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
145 return lua_gettop(L); \
146 }
148 static int moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
149 int flags;
150 if (handle->nonblocking == nonblocking) return 0;
151 flags = fcntl(handle->fd, F_GETFL, 0);
152 if (flags == -1) return -1;
153 if (nonblocking) flags |= O_NONBLOCK;
154 else flags &= ~O_NONBLOCK;
155 if (fcntl(handle->fd, F_SETFL, flags) == -1) return -1;
156 handle->nonblocking = nonblocking;
157 return 0;
158 }
160 static int moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
161 struct linger lingerval = { 0, };
162 if (!handle->issock) return 0;
163 if (timeout >= 0) {
164 lingerval.l_onoff = 1;
165 lingerval.l_linger = timeout;
166 }
167 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) return -1;
168 return 0;
169 }
171 static inline int moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
172 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
173 if (
174 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
175 handle->nopush == nopush
176 ) return 0;
177 #if defined(TCP_NOPUSH)
178 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) return -1;
179 #elif defined(TCP_CORK)
180 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) return -1;
181 #endif
182 handle->nopush = nopush;
183 #else
184 #warning Neither TCP_NOPUSH nor TCP_CORK is available
185 #endif
186 return 0;
187 }
189 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
190 moonbr_io_handle_t *handle;
191 lua_Integer maxread;
192 const char *terminatorstr;
193 size_t terminatorlen;
194 char terminator = 0; /* initialize to avoid compiler warning */
195 luaL_Buffer luabuf;
196 size_t luabufcnt = 0;
197 int remaining;
198 char *terminatorpos;
199 ssize_t bytesread;
200 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
201 maxread = luaL_optinteger(L, 2, -1);
202 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
203 if (terminatorlen) {
204 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
205 terminator = terminatorstr[0];
206 }
207 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
208 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
209 if (handle->readerr) {
210 lua_pushnil(L);
211 lua_pushliteral(L, "Previous read error");
212 return 2;
213 }
214 if (handle->fd < 0) {
215 /* fake EOF to simulate shutdown */
216 if (!drain) lua_pushliteral(L, "");
217 else lua_pushinteger(L, 0);
218 lua_pushliteral(L, "eof");
219 return 2;
220 }
221 handle->readerr = 1;
222 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
223 if (!drain) luaL_buffinit(L, &luabuf);
224 while (1) {
225 remaining = -1;
226 terminatorpos = NULL;
227 if (
228 maxread >= 0 &&
229 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
230 ) {
231 remaining = (size_t)maxread - luabufcnt;
232 if (terminatorlen) {
233 terminatorpos = memchr(
234 handle->readbuf + handle->readbufout,
235 terminator,
236 remaining
237 );
238 }
239 } else if (terminatorlen) {
240 terminatorpos = memchr(
241 handle->readbuf + handle->readbufout,
242 terminator,
243 handle->readbufin - handle->readbufout
244 );
245 }
246 if (terminatorpos) remaining = 1 + (
247 terminatorpos - (handle->readbuf + handle->readbufout)
248 );
249 if (remaining >= 0) {
250 if (!drain) {
251 luaL_addlstring(
252 &luabuf,
253 handle->readbuf + handle->readbufout,
254 remaining
255 );
256 luaL_pushresult(&luabuf);
257 } else {
258 lua_pushinteger(L, luabufcnt + remaining);
259 }
260 if (terminatorpos) lua_pushliteral(L, "term");
261 else lua_pushliteral(L, "maxlen");
262 handle->readbufout += remaining;
263 if (handle->readbufout == handle->readbufin) {
264 handle->readbufin = 0;
265 handle->readbufout = 0;
266 }
267 handle->readerr = 0;
268 return 2;
269 }
270 if (!drain) luaL_addlstring(
271 &luabuf,
272 handle->readbuf + handle->readbufout,
273 handle->readbufin - handle->readbufout
274 );
275 luabufcnt += handle->readbufin - handle->readbufout;
276 handle->readbufout = 0;
277 #ifdef MOONBR_IO_USE_TLS
278 if (handle->tls) {
279 do {
280 if (!handle->tlshandshake) {
281 do bytesread = tls_handshake(handle->tls);
282 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
283 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
284 handle->tlshandshake = bytesread;
285 errno = EAGAIN;
286 break;
287 }
288 if (bytesread < 0) {
289 lua_pushnil(L);
290 lua_pushstring(L, tls_error(handle->tls));
291 return 2;
292 }
293 handle->tlshandshake = 1;
294 }
295 do bytesread = tls_read(handle->tls, handle->readbuf, MOONBR_IO_READBUFLEN);
296 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
297 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
298 errno = EAGAIN;
299 break;
300 }
301 if (bytesread < 0) {
302 lua_pushnil(L);
303 lua_pushstring(L, tls_error(handle->tls));
304 return 2;
305 }
306 } while (0);
307 }
308 else
309 #endif
310 do bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
311 while (bytesread < 0 && (errno == EINTR));
312 if (
313 bytesread == 0 || (
314 nonblocking &&
315 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
316 )
317 ) {
318 handle->readbufin = 0;
319 if (!drain) luaL_pushresult(&luabuf);
320 else lua_pushinteger(L, luabufcnt);
321 if (bytesread == 0) lua_pushliteral(L, "eof");
322 else lua_pushliteral(L, "block");
323 handle->readerr = 0;
324 return 2;
325 }
326 if (bytesread < 0) moonbr_io_return_errmsg();
327 handle->readbufin = bytesread;
328 }
329 }
331 static int moonbr_io_read(lua_State *L) {
332 return moonbr_io_read_impl(L, 0, 0);
333 }
335 static int moonbr_io_read_nb(lua_State *L) {
336 return moonbr_io_read_impl(L, 1, 0);
337 }
339 static int moonbr_io_drain(lua_State *L) {
340 return moonbr_io_read_impl(L, 0, 1);
341 }
343 static int moonbr_io_drain_nb(lua_State *L) {
344 return moonbr_io_read_impl(L, 1, 1);
345 }
347 #if LUA_VERSION_NUM >= 503
348 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
349 #else
350 static int moonbr_io_read_cont(lua_State *L) {
351 #endif
352 lua_Integer remaining;
353 size_t len;
354 #if !(LUA_VERSION_NUM >= 503)
355 int ctx = 0;
356 lua_getctx(L, &ctx);
357 #endif
358 remaining = lua_tointeger(L, 3);
359 while (1) {
360 lua_pushcfunction(L, moonbr_io_read_nb);
361 lua_pushvalue(L, 1);
362 lua_pushvalue(L, 3);
363 lua_pushvalue(L, 4);
364 lua_call(L, 3, 2);
365 if (lua_isnil(L, -2)) return 2;
366 lua_insert(L, -2);
367 len = lua_rawlen(L, -1);
368 if (ctx == 0) {
369 lua_replace(L, 5);
370 ctx = 1;
371 } else if (ctx == 1) {
372 lua_pushvalue(L, 5);
373 lua_newtable(L);
374 lua_replace(L, 5);
375 lua_rawseti(L, 5, 1);
376 lua_rawseti(L, 5, 2);
377 ctx = 2;
378 } else {
379 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
380 }
381 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
382 lua_pop(L, 1);
383 if (remaining >= 0 && len) {
384 remaining -= len;
385 lua_pushinteger(L, remaining);
386 lua_replace(L, 3);
387 }
388 lua_pushvalue(L, 2);
389 lua_callk(L, 0, 0, ctx, moonbr_io_read_cont);
390 }
391 if (ctx != 1) {
392 luaL_Buffer buf;
393 lua_Integer i, chunkcount;
394 chunkcount = lua_rawlen(L, 5);
395 luaL_buffinit(L, &buf);
396 for (i=1; i<=chunkcount && i>0; i++) {
397 lua_rawgeti(L, 5, i);
398 luaL_addvalue(&buf);
399 }
400 luaL_pushresult(&buf);
401 lua_pushvalue(L, -2);
402 }
403 return 2;
404 }
406 static int moonbr_io_read_call(lua_State *L) {
407 lua_settop(L, 4);
408 lua_pushnil(L);
409 #if LUA_VERSION_NUM >= 503
410 return moonbr_io_read_cont(L, 0, 0);
411 #else
412 return moonbr_io_read_cont(L);
413 #endif
414 }
416 moonbr_io_yield_wrapper(moonbr_io_read_yield, moonbr_io_read_call);
418 #if LUA_VERSION_NUM >= 503
419 static int moonbr_io_drain_cont(lua_State *L, int status, lua_KContext ctx) {
420 #else
421 static int moonbr_io_drain_cont(lua_State *L) {
422 #endif
423 lua_Integer remaining, len;
424 size_t totallen = 0;
425 #if !(LUA_VERSION_NUM >= 503)
426 int ctx = 0;
427 lua_getctx(L, &ctx);
428 #endif
429 remaining = lua_tointeger(L, 3);
430 while (1) {
431 lua_pushcfunction(L, moonbr_io_drain_nb);
432 lua_pushvalue(L, 1);
433 lua_pushvalue(L, 3);
434 lua_pushvalue(L, 4);
435 lua_call(L, 3, 2);
436 if (lua_isnil(L, -2)) return 2;
437 lua_insert(L, -2);
438 len = lua_tointeger(L, -1);
439 lua_pop(L, 1);
440 totallen += len;
441 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
442 lua_pop(L, 1);
443 if (remaining >= 0 && len) {
444 remaining -= len;
445 lua_pushinteger(L, remaining);
446 lua_replace(L, 3);
447 }
448 lua_pushvalue(L, 2);
449 lua_callk(L, 0, 0, ctx, moonbr_io_drain_cont);
450 }
451 lua_pushinteger(L, totallen);
452 lua_pushvalue(L, -2);
453 return 2;
454 }
456 static int moonbr_io_drain_call(lua_State *L) {
457 #if LUA_VERSION_NUM >= 503
458 return moonbr_io_drain_cont(L, 0, 0);
459 #else
460 return moonbr_io_drain_cont(L);
461 #endif
462 }
464 moonbr_io_yield_wrapper(moonbr_io_drain_yield, moonbr_io_drain_call);
466 #ifdef MOONBR_IO_USE_TLS
468 #define moonbr_io_write_tls(buf, buflen) \
469 if (handle->tls) { \
470 do { \
471 if (!handle->tlshandshake) { \
472 do written = tls_handshake(handle->tls); \
473 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
474 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
475 handle->tlshandshake = written; \
476 errno = EAGAIN; \
477 break; \
478 } \
479 if (written < 0) { \
480 lua_pushnil(L); \
481 lua_pushstring(L, tls_error(handle->tls)); \
482 return 2; \
483 } \
484 handle->tlshandshake = 1; \
485 } \
486 do written = tls_write(handle->tls, (buf), (buflen)); \
487 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
488 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
489 errno = EAGAIN; \
490 break; \
491 } \
492 if (written < 0) { \
493 lua_pushnil(L); \
494 lua_pushstring(L, tls_error(handle->tls)); \
495 return 2; \
496 } \
497 } while (0); \
498 } \
499 else
501 #endif /* MOONBR_IO_USE_TLS */
503 static int moonbr_io_write_impl(lua_State *L, int nonblocking, int flush) {
504 moonbr_io_handle_t *handle;
505 int i, top;
506 const char *str;
507 size_t strlen;
508 ssize_t written;
509 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
510 if (handle->closed) luaL_error(L, "Attempt to write to a closed I/O handle");
511 if (handle->finished) luaL_error(L, "Attempt to write to a finished I/O handle");
512 if (handle->writeerr) {
513 lua_pushnil(L);
514 lua_pushliteral(L, "Previous write error");
515 return 2;
516 }
517 handle->writeerr = 1;
518 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
519 top = lua_gettop(L);
520 lua_getuservalue(L, 1);
521 lua_getfield(L, -1, "writequeue");
522 for (i=2; i<=top; i++) {
523 luaL_checklstring(L, i, &strlen);
524 lua_pushvalue(L, i);
525 lua_rawseti(L, -2, handle->writeqin++);
526 handle->writeleft += strlen;
527 }
528 if (flush) handle->flushedleft = handle->writeleft;
529 while (handle->writeqout != handle->writeqin) {
530 lua_rawgeti(L, -1, handle->writeqout);
531 str = lua_tolstring(L, -1, &strlen);
532 while (handle->writeqoff < strlen) {
533 if (
534 strlen - handle->writeqoff <
535 MOONBR_IO_WRITEBUFLEN - handle->writebufin
536 ) {
537 memcpy(
538 handle->writebuf + handle->writebufin,
539 str + handle->writeqoff,
540 strlen - handle->writeqoff
541 );
542 handle->writebufin += strlen - handle->writeqoff;
543 break;
544 } else {
545 memcpy(
546 handle->writebuf + handle->writebufin,
547 str + handle->writeqoff,
548 MOONBR_IO_WRITEBUFLEN - handle->writebufin
549 );
550 handle->writeqoff += MOONBR_IO_WRITEBUFLEN - handle->writebufin;
551 handle->writebufin = MOONBR_IO_WRITEBUFLEN;
552 while (handle->writebufout < MOONBR_IO_WRITEBUFLEN) {
553 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
554 #ifdef MOONBR_IO_USE_TLS
555 moonbr_io_write_tls(
556 handle->writebuf + handle->writebufout,
557 MOONBR_IO_WRITEBUFLEN - handle->writebufout
558 )
559 #endif
560 written = write(
561 handle->fd,
562 handle->writebuf + handle->writebufout,
563 MOONBR_IO_WRITEBUFLEN - handle->writebufout
564 );
565 if (written < 0) {
566 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
567 goto moonbr_io_write_impl_block;
568 } else if (errno != EINTR) moonbr_io_return_errmsg();
569 } else {
570 handle->writebufout += written;
571 handle->writeleft -= written;
572 if (handle->flushedleft) {
573 if (written >= handle->flushedleft) {
574 handle->flushedleft = 0;
575 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
576 } else {
577 handle->flushedleft -= written;
578 }
579 }
580 }
581 }
582 handle->writebufin = 0;
583 handle->writebufout = 0;
584 }
585 }
586 handle->writeqoff = 0;
587 lua_pop(L, 1);
588 lua_pushnil(L);
589 lua_rawseti(L, -2, handle->writeqout++);
590 }
591 while (handle->flushedleft) {
592 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
593 #ifdef MOONBR_IO_USE_TLS
594 moonbr_io_write_tls(
595 handle->writebuf + handle->writebufout,
596 handle->writebufin - handle->writebufout
597 )
598 #endif
599 written = write(
600 handle->fd,
601 handle->writebuf + handle->writebufout,
602 handle->writebufin - handle->writebufout
603 );
604 if (written < 0) {
605 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
606 goto moonbr_io_write_impl_block;
607 } else if (errno != EINTR) moonbr_io_return_errmsg();
608 } else {
609 handle->writebufout += written;
610 handle->writeleft -= written;
611 if (handle->flushedleft) {
612 if (written >= handle->flushedleft) {
613 handle->flushedleft = 0;
614 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
615 } else {
616 handle->flushedleft -= written;
617 }
618 }
619 }
620 }
621 if (handle->writebufout == handle->writebufin) {
622 handle->writebufin = 0;
623 handle->writebufout = 0;
624 }
625 if (nonblocking) lua_pushinteger(L, 0);
626 else lua_pushvalue(L, 1);
627 handle->writeerr = 0;
628 return 1;
629 moonbr_io_write_impl_block:
630 lua_pushinteger(L, handle->writeleft);
631 handle->writeerr = 0;
632 return 1;
633 }
635 static int moonbr_io_write(lua_State *L) {
636 return moonbr_io_write_impl(L, 0, 0);
637 }
639 static int moonbr_io_write_nb(lua_State *L) {
640 return moonbr_io_write_impl(L, 1, 0);
641 }
643 static int moonbr_io_flush(lua_State *L) {
644 return moonbr_io_write_impl(L, 0, 1);
645 }
647 static int moonbr_io_flush_nb(lua_State *L) {
648 return moonbr_io_write_impl(L, 1, 1);
649 }
651 #if LUA_VERSION_NUM >= 503
652 static int moonbr_io_write_cont(lua_State *L, int status, lua_KContext ctx) {
653 #else
654 static int moonbr_io_write_cont(lua_State *L) {
655 #endif
656 while (1) {
657 lua_pushcfunction(L, moonbr_io_write_nb);
658 lua_pushvalue(L, 1);
659 lua_call(L, 1, 2);
660 if (lua_isnil(L, -2)) return 2;
661 if (!lua_tointeger(L, -2)) {
662 lua_pushvalue(L, 1);
663 return 1;
664 }
665 lua_pop(L, 2);
666 lua_pushvalue(L, 2);
667 lua_callk(L, 0, 0, 0, moonbr_io_write_cont);
668 }
669 }
671 static int moonbr_io_write_call(lua_State *L) {
672 lua_pushcfunction(L, moonbr_io_write_nb);
673 lua_insert(L, 3);
674 lua_pushvalue(L, 1);
675 lua_insert(L, 4);
676 lua_call(L, lua_gettop(L) - 3, 2);
677 if (lua_isnil(L, -2)) return 2;
678 if (!lua_tointeger(L, -2)) {
679 lua_pushvalue(L, 1);
680 return 1;
681 }
682 #if LUA_VERSION_NUM >= 503
683 return moonbr_io_write_cont(L, 0, 0);
684 #else
685 return moonbr_io_write_cont(L);
686 #endif
687 }
689 moonbr_io_yield_wrapper(moonbr_io_write_yield, moonbr_io_write_call);
691 static int moonbr_io_flush_call(lua_State *L) {
692 lua_pushcfunction(L, moonbr_io_flush_nb);
693 lua_insert(L, 3);
694 lua_pushvalue(L, 1);
695 lua_insert(L, 4);
696 lua_call(L, lua_gettop(L) - 3, 2);
697 if (lua_isnil(L, -2)) return 2;
698 if (!lua_tointeger(L, -2)) {
699 lua_pushvalue(L, 1);
700 return 1;
701 }
702 #if LUA_VERSION_NUM >= 503
703 return moonbr_io_write_cont(L, 0, 0);
704 #else
705 return moonbr_io_write_cont(L);
706 #endif
707 }
709 moonbr_io_yield_wrapper(moonbr_io_flush_yield, moonbr_io_flush_call);
711 static int moonbr_io_finish(lua_State *L) {
712 moonbr_io_handle_t *handle;
713 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
714 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
715 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
716 if (handle->writeleft) {
717 lua_pushcfunction(L, moonbr_io_flush);
718 lua_pushvalue(L, 1);
719 if (lua_pcall(L, 1, 2, 0)) {
720 handle->finished = 1;
721 lua_error(L);
722 }
723 if (!lua_toboolean(L, -2)) {
724 handle->finished = 1;
725 return 2;
726 }
727 }
728 handle->finished = 1;
729 #ifdef MOONBR_IO_USE_TLS
730 if ((handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) && !handle->tls) {
731 #else
732 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
733 #endif
734 if (shutdown(handle->fd, SHUT_WR)) moonbr_io_return_errmsg();
735 } else {
736 #ifdef MOONBR_IO_USE_TLS
737 if (handle->tls) {
738 int status;
739 if (moonbr_io_handle_set_nonblocking(L, handle, 1)) moonbr_io_return_errmsg();
740 do status = tls_close(handle->tls);
741 while (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT);
742 if (status) {
743 close(handle->fd);
744 handle->fd = -1;
745 lua_pushnil(L);
746 lua_pushstring(L, tls_error(handle->tls));
747 return 2;
748 }
749 }
750 #endif
751 if (close(handle->fd)) {
752 handle->fd = -1;
753 moonbr_io_return_errmsg();
754 }
755 handle->fd = -1; /* fake EOF on read */
756 }
757 lua_pushboolean(L, 1);
758 return 1;
759 }
761 static int moonbr_io_close_impl(lua_State *L, int nonblocking, int reset) {
762 moonbr_io_handle_t *handle;
763 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
764 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
765 if (!reset && handle->fd >= 0) {
766 if (handle->writeleft) {
767 lua_pushcfunction(L, nonblocking ? moonbr_io_flush_nb : moonbr_io_flush);
768 lua_pushvalue(L, 1);
769 if (lua_pcall(L, 1, 2, 0)) {
770 handle->closed = 1;
771 close(handle->fd);
772 handle->fd = -1;
773 lua_error(L);
774 }
775 if (!nonblocking) handle->closed = 1; /* TODO: handle nonblocking case */
776 if (!lua_toboolean(L, -2)) {
777 close(handle->fd);
778 handle->fd = -1;
779 return 2;
780 }
781 #if LUA_VERSION_NUM >= 503
782 if (nonblocking && lua_tointeger(L, -2)) {
783 #else
784 if (nonblocking && lua_tonumber(L, -2)) {
785 #endif
786 lua_pushliteral(L, "flush");
787 lua_pushvalue(L, -3);
788 return 2;
789 }
790 } else {
791 handle->closed = 1;
792 }
793 #ifdef MOONBR_IO_USE_TLS
794 if (handle->tls) {
795 int status;
796 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
797 do status = tls_close(handle->tls);
798 while (!nonblocking && (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT));
799 if (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT) {
800 handle->tlsclosing = status; /* TODO: handle polling */
801 lua_pushliteral(L, "close");
802 return 1;
803 }
804 if (status) {
805 close(handle->fd);
806 handle->fd = -1;
807 lua_pushnil(L);
808 lua_pushstring(L, tls_error(handle->tls));
809 return 2;
810 }
811 }
812 #endif
813 if (moonbr_io_handle_set_linger(L, handle, -1)) {
814 moonbr_io_prepare_errmsg();
815 close(handle->fd);
816 handle->fd = -1;
817 moonbr_io_return_prepared_errmsg();
818 }
819 } else {
820 handle->closed = 1;
821 }
822 if (handle->fd >= 0) {
823 if (close(handle->fd)) {
824 handle->fd = -1;
825 moonbr_io_return_errmsg();
826 }
827 handle->fd = -1;
828 }
829 lua_pushboolean(L, 1);
830 return 1;
832 }
834 static int moonbr_io_close(lua_State *L) {
835 return moonbr_io_close_impl(L, 0, 0);
836 }
838 static int moonbr_io_reset(lua_State *L) {
839 return moonbr_io_close_impl(L, 0, 1);
840 }
842 static int moonbr_io_handlegc(lua_State *L) {
843 moonbr_io_handle_t *handle;
844 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
845 if (handle->fd >= 0) {
846 lua_pushcfunction(L, moonbr_io_reset);
847 lua_pushvalue(L, 1);
848 lua_pushinteger(L, 0);
849 lua_call(L, 2, 0);
850 }
851 #ifdef MOONBR_IO_USE_TLS
852 if (handle->tls) {
853 tls_free(handle->tls);
854 handle->tls = NULL;
855 }
856 if (handle->servertls) {
857 tls_free(handle->servertls);
858 handle->servertls = NULL;
859 }
860 #endif
861 return 0;
862 }
864 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
865 moonbr_io_handle_t *handle;
866 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
867 if (!handle->closed) {
868 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
869 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
870 lua_call(L, 1, 0);
871 }
872 }
874 static int moonbr_io_pushhandle_impl(lua_State *L) {
875 int *fd;
876 int skip_peeraddr;
877 moonbr_io_handle_t *handle;
878 struct sockaddr addr;
879 socklen_t addrlen;
880 fd = lua_touserdata(L, 1);
881 skip_peeraddr = lua_toboolean(L, 2);
882 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
883 handle->fd = -1; /* avoid closing incomplete handle */
884 addrlen = sizeof(addr);
885 if (getsockname(*fd, &addr, &addrlen)) {
886 if (errno != ENOTSOCK) {
887 moonbr_io_prepare_errmsg();
888 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
889 }
890 handle->issock = 0;
891 } else {
892 handle->issock = 1;
893 handle->addrfam = addr.sa_family;
894 }
895 handle->finished = 0;
896 handle->closed = 0;
897 handle->nonblocking = -1;
898 handle->nopush = -1;
899 handle->readerr = 0;
900 handle->readbufin = 0;
901 handle->readbufout = 0;
902 handle->writeerr = 0;
903 handle->writeleft = 0;
904 handle->flushedleft = 0;
905 handle->writeqin = 0;
906 handle->writeqout = 0;
907 handle->writeqoff = 0;
908 handle->writebufin = 0;
909 handle->writebufout = 0;
910 #ifdef MOONBR_IO_USE_TLS
911 handle->tls = NULL;
912 handle->servertls = NULL;
913 handle->tlshandshake = 0;
914 handle->tlsclosing = 0;
915 #endif
916 handle->fd = *fd; /* required for set_linger call */
917 if (moonbr_io_handle_set_linger(L, handle, 0)) {
918 moonbr_io_prepare_errmsg();
919 handle->fd = -1;
920 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
921 }
922 handle->fd = -1; /* avoid closing incomplete handle */
923 luaL_setmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
924 lua_newtable(L); // uservalue
925 lua_newtable(L);
926 lua_setfield(L, -2, "writequeue");
927 lua_newtable(L); // public
928 if (handle->addrfam == AF_INET6) {
929 struct sockaddr_in6 addr_in6;
930 char addrstrbuf[INET6_ADDRSTRLEN];
931 const char *addrstr;
932 addrlen = sizeof(addr_in6);
933 /* NOTE: According to documentation, getsockname() may fail if connection
934 * was reset. There seems to be no problem in practice though. */
935 if (getsockname(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
936 moonbr_io_prepare_errmsg();
937 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
938 }
939 if (addrlen > sizeof(addr_in6)) {
940 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
941 }
942 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
943 if (!addrstr) {
944 moonbr_io_prepare_errmsg();
945 luaL_error(L, "Could not format local IP address: %s", errmsg);
946 } else {
947 lua_pushstring(L, addrstr);
948 lua_setfield(L, -2, "local_ip6");
949 }
950 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
951 lua_setfield(L, -2, "local_tcpport");
952 if (!skip_peeraddr) {
953 /* NOTE: According to documentation, getpeername() may fail if connection
954 * was reset. There seems to be no problem in practice though. */
955 if (getpeername(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
956 moonbr_io_prepare_errmsg();
957 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
958 }
959 if (addrlen > sizeof(addr_in6)) {
960 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
961 }
962 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
963 if (!addrstr) {
964 moonbr_io_prepare_errmsg();
965 luaL_error(L, "Could not format remote IP address: %s", errmsg);
966 } else {
967 lua_pushstring(L, addrstr);
968 lua_setfield(L, -2, "remote_ip6");
969 }
970 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
971 lua_setfield(L, -2, "remote_tcpport");
972 }
973 } else if (handle->addrfam == AF_INET) {
974 struct sockaddr_in addr_in;
975 char addrstrbuf[INET_ADDRSTRLEN];
976 const char *addrstr;
977 addrlen = sizeof(addr_in);
978 /* NOTE: According to documentation, getsockname() may fail if connection
979 * was reset. There seems to be no problem in practice though. */
980 if (getsockname(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
981 moonbr_io_prepare_errmsg();
982 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
983 }
984 if (addrlen > sizeof(addr_in)) {
985 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
986 }
987 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
988 if (!addrstr) {
989 moonbr_io_prepare_errmsg();
990 luaL_error(L, "Could not format local IP address: %s", errmsg);
991 } else {
992 lua_pushstring(L, addrstr);
993 lua_setfield(L, -2, "local_ip4");
994 }
995 lua_pushinteger(L, ntohs(addr_in.sin_port));
996 lua_setfield(L, -2, "local_tcpport");
997 if (!skip_peeraddr) {
998 /* NOTE: According to documentation, getpeername() may fail if connection
999 * was reset. There seems to be no problem in practice though. */
1000 if (getpeername(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
1001 moonbr_io_prepare_errmsg();
1002 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
1004 if (addrlen > sizeof(addr_in)) {
1005 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
1007 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
1008 if (!addrstr) {
1009 moonbr_io_prepare_errmsg();
1010 luaL_error(L, "Could not format remote IP address: %s", errmsg);
1011 } else {
1012 lua_pushstring(L, addrstr);
1013 lua_setfield(L, -2, "remote_ip4");
1015 lua_pushinteger(L, ntohs(addr_in.sin_port));
1016 lua_setfield(L, -2, "remote_tcpport");
1019 luaL_setmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1020 lua_setfield(L, -2, "public");
1021 lua_setuservalue(L, -2);
1022 handle->fd = *fd;
1023 *fd = -1; /* closing is now handled by garbage collection */
1024 return 1;
1027 void moonbr_io_pushhandle(lua_State *L, int fd) {
1028 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1029 lua_pushlightuserdata(L, &fd);
1030 if (lua_pcall(L, 1, 1, 0)) {
1031 if (fd != -1) close(fd); // TODO: correct to close file descriptor here?
1032 lua_error(L);
1036 void moonbr_io_pushhandle_skip_peeraddr(lua_State *L, int fd) {
1037 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1038 lua_pushlightuserdata(L, &fd);
1039 lua_pushboolean(L, 1);
1040 if (lua_pcall(L, 2, 1, 0)) {
1041 if (fd != -1) close(fd); // TODO: correct to close file descriptor here?
1042 lua_error(L);
1046 static int moonbr_io_handleindex(lua_State *L) {
1047 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1048 luaL_checkany(L, 2);
1049 lua_getuservalue(L, 1);
1050 lua_getfield(L, -1, "public");
1051 lua_pushvalue(L, 2);
1052 lua_gettable(L, -2);
1053 return 1;
1056 static int moonbr_io_handlenewindex(lua_State *L) {
1057 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1058 luaL_checkany(L, 2);
1059 luaL_checkany(L, 3);
1060 lua_getuservalue(L, 1);
1061 lua_getfield(L, -1, "public");
1062 lua_pushvalue(L, 2);
1063 lua_pushvalue(L, 3);
1064 lua_settable(L, -3);
1065 return 0;
1068 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
1069 const char *path;
1070 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1071 const int path_maxlen = sizeof(struct sockaddr_un) - (
1072 (void *)sockaddr.sun_path - (void *)&sockaddr
1073 ) - 1; /* one byte for termination */
1074 int sock;
1075 path = luaL_checkstring(L, 1);
1076 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1077 strcpy(sockaddr.sun_path, path);
1078 sock = socket(
1079 PF_LOCAL,
1080 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1082 );
1083 if (sock < 0) moonbr_io_return_errmsg();
1084 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1085 if (!nonblocking && errno == EINTR) {
1086 moonbr_io_prepare_errmsg();
1087 close(sock);
1088 moonbr_io_return_prepared_errmsg();
1089 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1091 moonbr_io_pushhandle(L, sock);
1092 return 1;
1095 static int moonbr_io_localconnect(lua_State *L) {
1096 return moonbr_io_localconnect_impl(L, 0);
1099 static int moonbr_io_localconnect_nb(lua_State *L) {
1100 return moonbr_io_localconnect_impl(L, 1);
1103 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
1104 const char *host, *port;
1105 struct addrinfo hints = { 0, };
1106 struct addrinfo *res, *addrinfo;
1107 int errcode;
1108 int sock;
1109 host = luaL_checkstring(L, 1);
1110 port = luaL_checkstring(L, 2);
1111 hints.ai_family = AF_UNSPEC;
1112 hints.ai_socktype = SOCK_STREAM;
1113 hints.ai_protocol = IPPROTO_TCP;
1114 hints.ai_flags = AI_ADDRCONFIG;
1115 errcode = getaddrinfo(host, port, &hints, &res);
1116 if (errcode) {
1117 freeaddrinfo(res);
1118 if (errcode == EAI_SYSTEM) {
1119 moonbr_io_prepare_errmsg();
1120 lua_pushnil(L);
1121 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1122 } else {
1123 lua_pushnil(L);
1124 lua_pushstring(L, gai_strerror(errcode));
1126 return 2;
1128 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1129 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1131 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1132 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1134 addrinfo = res;
1135 moonbr_io_tcpconnect_found:
1136 sock = socket(
1137 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1138 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1139 addrinfo->ai_protocol
1140 );
1141 if (sock < 0) {
1142 moonbr_io_prepare_errmsg();
1143 freeaddrinfo(res);
1144 moonbr_io_return_prepared_errmsg();
1146 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1147 freeaddrinfo(res);
1148 if (!nonblocking && errno == EINTR) {
1149 moonbr_io_prepare_errmsg();
1150 close(sock);
1151 moonbr_io_return_prepared_errmsg();
1152 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1153 } else {
1154 freeaddrinfo(res);
1156 if (nonblocking) {
1157 moonbr_io_pushhandle_skip_peeraddr(L, sock);
1158 if (addrinfo->ai_family == AF_INET6) {
1159 // TODO: fill remote_ip6 and remote_tcpport
1160 } else if (addrinfo->ai_family == AF_INET) {
1161 // TODO: fill remote_ip4 and remote_tcpport
1163 } else {
1164 moonbr_io_pushhandle(L, sock);
1166 return 1;
1169 static int moonbr_io_tcpconnect(lua_State *L) {
1170 return moonbr_io_tcpconnect_impl(L, 0);
1173 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1174 return moonbr_io_tcpconnect_impl(L, 1);
1177 static int moonbr_io_locallisten(lua_State *L) {
1178 moonbr_io_listener_t *listener;
1179 const char *path;
1180 struct stat sb;
1181 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1182 const int path_maxlen = sizeof(struct sockaddr_un) - (
1183 (void *)sockaddr.sun_path - (void *)&sockaddr
1184 ) - 1; /* one byte for termination */
1185 int sock;
1186 path = luaL_checkstring(L, 1);
1187 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1188 strcpy(sockaddr.sun_path, path);
1189 if (stat(path, &sb) == 0) {
1190 if (S_ISSOCK(sb.st_mode)) unlink(path);
1192 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1193 listener->fd = -1;
1194 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1195 sock = socket(
1196 PF_LOCAL,
1197 SOCK_STREAM | SOCK_CLOEXEC,
1199 );
1200 if (sock < 0) moonbr_io_return_errmsg();
1201 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1202 moonbr_io_prepare_errmsg();
1203 close(sock);
1204 moonbr_io_return_prepared_errmsg();
1206 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1207 moonbr_io_prepare_errmsg();
1208 close(sock);
1209 moonbr_io_return_prepared_errmsg();
1211 listener->fd = sock;
1212 listener->addrfam = AF_LOCAL;
1213 listener->nonblocking = -1;
1214 return 1;
1217 static int moonbr_io_tcplisten(lua_State *L) {
1218 moonbr_io_listener_t *listener;
1219 const char *host, *port;
1220 struct addrinfo hints = { 0, };
1221 struct addrinfo *res, *addrinfo;
1222 int errcode;
1223 int sock;
1224 host = luaL_optstring(L, 1, NULL);
1225 port = luaL_checkstring(L, 2);
1226 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1227 listener->fd = -1;
1228 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1229 hints.ai_family = AF_UNSPEC;
1230 hints.ai_socktype = SOCK_STREAM;
1231 hints.ai_protocol = IPPROTO_TCP;
1232 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1233 errcode = getaddrinfo(host, port, &hints, &res);
1234 if (errcode) {
1235 freeaddrinfo(res);
1236 if (errcode == EAI_SYSTEM) {
1237 moonbr_io_prepare_errmsg();
1238 lua_pushnil(L);
1239 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1240 } else {
1241 lua_pushnil(L);
1242 lua_pushstring(L, gai_strerror(errcode));
1244 return 2;
1246 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1247 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1249 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1250 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1252 addrinfo = res;
1253 moonbr_io_tcpconnect_found:
1254 listener->addrfam = addrinfo->ai_family;
1255 sock = socket(
1256 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1257 addrinfo->ai_socktype | SOCK_CLOEXEC,
1258 addrinfo->ai_protocol
1259 );
1260 if (sock < 0) {
1261 moonbr_io_prepare_errmsg();
1262 freeaddrinfo(res);
1263 moonbr_io_return_prepared_errmsg();
1266 static const int reuseval = 1;
1267 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1268 moonbr_io_prepare_errmsg();
1269 freeaddrinfo(res);
1270 close(sock);
1271 lua_pushnil(L);
1272 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1273 return 2;
1276 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1277 moonbr_io_prepare_errmsg();
1278 freeaddrinfo(res);
1279 close(sock);
1280 moonbr_io_return_prepared_errmsg();
1282 freeaddrinfo(res);
1283 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1284 moonbr_io_prepare_errmsg();
1285 close(sock);
1286 moonbr_io_return_prepared_errmsg();
1288 listener->fd = sock;
1289 listener->nonblocking = -1;
1290 return 1;
1293 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1294 moonbr_io_listener_t *listener;
1295 int fd;
1296 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1297 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1298 if (listener->nonblocking != nonblocking) {
1299 int flags;
1300 flags = fcntl(listener->fd, F_GETFL, 0);
1301 if (flags == -1) {
1302 moonbr_io_prepare_errmsg();
1303 close(listener->fd);
1304 listener->fd = -1;
1305 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1307 if (nonblocking) flags |= O_NONBLOCK;
1308 else flags &= ~O_NONBLOCK;
1309 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1310 moonbr_io_prepare_errmsg();
1311 close(listener->fd);
1312 listener->fd = -1;
1313 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1315 listener->nonblocking = nonblocking;
1317 while (1) {
1318 #if defined(__linux__) && !defined(_GNU_SOURCE)
1319 fd = accept(listener->fd, NULL, NULL);
1320 if (fd != -1) {
1321 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
1322 moonbr_io_prepare_errmsg();
1323 close(listener->fd);
1324 listener->fd = -1;
1325 close(fd);
1326 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1329 #else
1330 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1331 #endif
1332 if (fd < 0) {
1333 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1334 lua_pushboolean(L, 0);
1335 lua_pushliteral(L, "No incoming connection pending");
1336 return 2;
1337 } else if (errno != EINTR) moonbr_io_return_errmsg();
1338 } else {
1339 moonbr_io_pushhandle(L, fd);
1340 return 1;
1345 static int moonbr_io_accept(lua_State *L) {
1346 return moonbr_io_accept_impl(L, 0);
1349 static int moonbr_io_accept_nb(lua_State *L) {
1350 return moonbr_io_accept_impl(L, 1);
1353 static int moonbr_io_unlisten(lua_State *L) {
1354 moonbr_io_listener_t *listener;
1355 struct sockaddr_un addr;
1356 socklen_t addrlen;
1357 struct stat sb;
1358 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1359 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1360 addrlen = sizeof(addr);
1361 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1362 if (close(listener->fd)) {
1363 moonbr_io_prepare_errmsg();
1364 listener->fd = -1;
1365 if (addrlen && addrlen <= sizeof(addr)) {
1366 if (stat(addr.sun_path, &sb) == 0) {
1367 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1370 moonbr_io_return_prepared_errmsg();
1372 listener->fd = -1;
1373 if (addrlen && addrlen <= sizeof(addr)) {
1374 if (stat(addr.sun_path, &sb) == 0) {
1375 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1378 lua_pushboolean(L, 1);
1379 return 1;
1382 static int moonbr_io_listenergc(lua_State *L) {
1383 moonbr_io_listener_t *listener;
1384 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1385 if (listener->fd >= 0) close(listener->fd);
1386 listener->fd = -1;
1387 return 0;
1390 static int moonbr_io_exec(lua_State *L) {
1391 char **argv;
1392 int i, argc;
1393 int sockin[2], sockout[2], sockerr[2];
1394 volatile int errorcond = 0;
1395 volatile char errmsgbuf[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG;
1396 moonbr_io_child_t *child;
1397 argc = lua_gettop(L);
1398 argv = lua_newuserdata(L, (argc + 1) * sizeof(char *));
1399 for (i=0; i<argc; i++) argv[i] = (char *)luaL_checkstring(L, i+1);
1400 argv[argc] = NULL;
1401 child = lua_newuserdata(L, sizeof(moonbr_io_child_t));
1402 child->pid = 0;
1403 child->status_valid = 0;
1404 lua_newtable(L);
1405 lua_setuservalue(L, -2);
1406 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1407 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1408 moonbr_io_prepare_errmsg();
1409 lua_pushnil(L);
1410 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1411 return 2;
1413 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1414 moonbr_io_prepare_errmsg();
1415 close(sockin[0]);
1416 close(sockin[1]);
1417 lua_pushnil(L);
1418 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1419 return 2;
1421 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1422 moonbr_io_prepare_errmsg();
1423 close(sockin[0]);
1424 close(sockin[1]);
1425 close(sockout[0]);
1426 close(sockout[1]);
1427 lua_pushnil(L);
1428 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1429 return 2;
1431 child->pid = vfork();
1432 if (child->pid == -1) {
1433 moonbr_io_prepare_errmsg();
1434 close(sockin[0]);
1435 close(sockin[1]);
1436 close(sockout[0]);
1437 close(sockout[1]);
1438 close(sockerr[0]);
1439 close(sockerr[1]);
1440 lua_pushnil(L);
1441 lua_pushfstring(L, "Could not fork: %s", errmsg);
1442 return 2;
1444 if (!child->pid) {
1445 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1446 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1447 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1448 closefrom(3);
1449 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1450 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1451 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1452 if (execvp(argv[0], argv)) {
1453 errorcond = 2;
1454 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1455 _exit(0);
1457 moonbr_io_exec_error1:
1458 errorcond = 1;
1459 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1460 _exit(0);
1462 close(sockin[1]);
1463 close(sockout[1]);
1464 close(sockerr[1]);
1465 if (errorcond) {
1466 int status;
1467 close(sockin[0]);
1468 close(sockout[0]);
1469 close(sockerr[0]);
1470 while (waitpid(child->pid, &status, 0) == -1) {
1471 if (errno != EINTR) {
1472 moonbr_io_prepare_errmsg();
1473 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1476 child->pid = 0;
1477 lua_pushnil(L);
1478 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1479 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1480 return 2;
1482 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1483 lua_pushlightuserdata(L, &sockin[0]);
1484 if (lua_pcall(L, 1, 1, 0)) {
1485 if (sockin[0] != -1) close(sockin[0]);
1486 close(sockout[0]);
1487 close(sockerr[0]);
1488 goto moonbr_io_exec_error2;
1490 lua_setfield(L, -2, "stdin");
1491 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1492 lua_pushlightuserdata(L, &sockout[0]);
1493 if (lua_pcall(L, 1, 1, 0)) {
1494 if (sockout[0] != -1) close(sockout[0]);
1495 close(sockerr[0]);
1496 goto moonbr_io_exec_error2;
1498 lua_setfield(L, -2, "stdout");
1499 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1500 lua_pushlightuserdata(L, &sockerr[0]);
1501 if (lua_pcall(L, 1, 1, 0)) {
1502 if (sockerr[0] != -1) close(sockerr[0]);
1503 goto moonbr_io_exec_error2;
1505 lua_setfield(L, -2, "stderr");
1506 return 1;
1507 moonbr_io_exec_error2:
1509 int status;
1510 while (waitpid(child->pid, &status, 0) == -1) {
1511 if (errno != EINTR) {
1512 moonbr_io_prepare_errmsg();
1513 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1517 child->pid = 0;
1518 return lua_error(L);
1521 static int moonbr_io_childindex(lua_State *L) {
1522 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1523 luaL_checkany(L, 2);
1524 lua_getuservalue(L, 1);
1525 lua_pushvalue(L, 2);
1526 lua_gettable(L, -2);
1527 if (lua_isnil(L, -1)) {
1528 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1529 lua_pushvalue(L, 2);
1530 lua_gettable(L, -2);
1532 return 1;
1535 static int moonbr_io_childnewindex(lua_State *L) {
1536 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1537 luaL_checkany(L, 2);
1538 luaL_checkany(L, 3);
1539 lua_getuservalue(L, 1);
1540 lua_pushvalue(L, 2);
1541 lua_pushvalue(L, 3);
1542 lua_settable(L, -3);
1543 return 0;
1546 static int moonbr_io_childgc(lua_State *L) {
1547 moonbr_io_child_t *child;
1548 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1549 if (child->pid) {
1550 int status;
1551 int pid = child->pid;
1552 child->pid = 0;
1553 if (kill(pid, SIGKILL)) {
1554 moonbr_io_prepare_errmsg();
1555 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1557 while (waitpid(pid, &status, 0) == -1) {
1558 if (errno != EINTR) {
1559 moonbr_io_prepare_errmsg();
1560 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1564 return 0;
1567 static int moonbr_io_kill(lua_State *L) {
1568 moonbr_io_child_t *child;
1569 int sig;
1570 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1571 sig = luaL_optinteger(L, 2, SIGKILL);
1572 if (!child->pid) {
1573 if (!child->status_valid) luaL_error(L, "Attempt to kill an already collected child process");
1574 } else {
1575 if (kill(child->pid, sig)) {
1576 moonbr_io_prepare_errmsg();
1577 luaL_error(L, "Error in kill call: %s", errmsg);
1580 lua_settop(L, 1);
1581 return 1;
1584 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1585 moonbr_io_child_t *child;
1586 int status;
1587 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1588 if (!child->pid) {
1589 if (!child->status_valid) luaL_error(L, "Attempt to wait for an already collected child process");
1590 status = child->status;
1591 child->status_valid = 0;
1592 } else {
1593 pid_t waitedpid;
1594 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1595 if (errno != EINTR) {
1596 moonbr_io_prepare_errmsg();
1597 luaL_error(L, "Error in waitpid call: %s", errmsg);
1600 if (!waitedpid) {
1601 lua_pushboolean(L, 0);
1602 lua_pushliteral(L, "Process is still running");
1603 return 2;
1605 child->pid = 0;
1607 if (WIFEXITED(status)) {
1608 lua_pushinteger(L, WEXITSTATUS(status));
1609 } else if (WIFSIGNALED(status)) {
1610 lua_pushinteger(L, -WTERMSIG(status));
1611 } else {
1612 luaL_error(L, "Unexpected status value returned by waitpid call");
1614 return 1;
1617 static int moonbr_io_wait(lua_State *L) {
1618 return moonbr_io_wait_impl(L, 0);
1621 static int moonbr_io_wait_nb(lua_State *L) {
1622 return moonbr_io_wait_impl(L, 1);
1625 #if LUA_VERSION_NUM >= 503
1626 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1627 #else
1628 static int moonbr_io_wait_cont(lua_State *L) {
1629 #endif
1630 #if !(LUA_VERSION_NUM >= 503)
1631 int ctx = 0;
1632 lua_getctx(L, &ctx);
1633 #endif
1634 while (1) {
1635 lua_pushcfunction(L, moonbr_io_wait_nb);
1636 lua_pushvalue(L, 1);
1637 lua_call(L, 1, 1);
1638 if (!lua_isnil(L, -1)) break;
1639 lua_pushvalue(L, 2);
1640 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1642 return 1;
1645 static int moonbr_io_wait_call(lua_State *L) {
1646 lua_settop(L, 2);
1647 #if LUA_VERSION_NUM >= 503
1648 return moonbr_io_wait_cont(L, 0, 0);
1649 #else
1650 return moonbr_io_wait_cont(L);
1651 #endif
1654 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1656 static void moonbr_io_sigterm_handler(int sig) {
1657 moonbr_io_sigterm_flag = 1;
1660 static void moonbr_io_sigchld_handler(int sig) {
1661 moonbr_io_sigchld_flag = 1;
1664 int moonbr_io_catch_sigterm(lua_State *L) {
1665 signal(SIGTERM, moonbr_io_sigterm_handler);
1666 return 0;
1669 static int moonbr_io_getpid(lua_State *L) {
1670 lua_pushinteger(L, getpid());
1671 return 1;
1674 #ifdef MOONBR_IO_USE_TLS
1676 #define moonbr_io_poll_tls() \
1677 if (!handle->tlshandshake) { \
1678 force_wakeup = 1; \
1679 continue; \
1680 } \
1681 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1682 if (fd < 0) { \
1683 force_wakeup = 1; \
1684 continue; \
1685 } \
1686 FD_SET(fd, &readfds); \
1687 if (fd+1 > nfds) nfds = fd+1; \
1688 continue; \
1689 } \
1690 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1691 if (fd < 0) { \
1692 force_wakeup = 1; \
1693 continue; \
1694 } \
1695 FD_SET(fd, &writefds); \
1696 if (fd+1 > nfds) nfds = fd+1; \
1697 continue; \
1698 } \
1699 while (0)
1701 #endif /* MOONBR_IO_USE_TLS */
1703 static int moonbr_io_poll(lua_State *L) {
1704 moonbr_io_handle_t *handle;
1705 moonbr_io_listener_t *listener;
1706 moonbr_io_child_t *child;
1707 int fd, isnum;
1708 int nfds = 0;
1709 fd_set readfds, writefds, exceptfds;
1710 struct timespec timeout = {0, };
1711 int force_wakeup = 0;
1712 int use_timeout = 0; // negative for negative timeout
1713 int check_sigterm = 0;
1714 int check_sigchld = 0;
1715 pid_t waitedpid;
1716 sigset_t mask, orig_mask;
1717 int status;
1718 FD_ZERO(&readfds);
1719 FD_ZERO(&writefds);
1720 FD_ZERO(&exceptfds);
1721 if (!lua_isnoneornil(L, 1)) {
1722 luaL_checktype(L, 1, LUA_TTABLE);
1723 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1724 if (lua_toboolean(L, -1)) {
1725 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1726 if (handle) {
1727 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1728 fd = handle->fd;
1729 #if MOONBR_IO_USE_TLS
1730 moonbr_io_poll_tls();
1731 #endif
1732 if (
1733 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1734 handle->readbufin != handle->readbufout /* data pending in buffer */
1735 ) {
1736 force_wakeup = 1;
1737 continue;
1739 } else {
1740 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1741 if (listener) {
1742 fd = listener->fd;
1743 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1744 } else {
1745 child = luaL_testudata(L, -2, MOONBR_IO_CHILD_MT_REGKEY);
1746 if (child) {
1747 if (!child->pid) luaL_error(L, "Attemt to poll an already collected child process");
1748 if (!check_sigchld) {
1749 check_sigchld = 1;
1750 moonbr_io_sigchld_flag = 0;
1751 signal(SIGCHLD, moonbr_io_sigchld_handler);
1753 if (child->status_valid) {
1754 force_wakeup = 1;
1755 } else {
1756 while ((waitedpid = waitpid(child->pid, &status, WNOHANG)) == -1) {
1757 if (errno != EINTR) {
1758 moonbr_io_prepare_errmsg();
1759 luaL_error(L, "Error in waitpid call: %s", errmsg);
1762 if (waitedpid) {
1763 child->pid = 0;
1764 child->status = status;
1765 child->status_valid = 1;
1766 force_wakeup = 1;
1769 continue;
1770 } else {
1771 fd = lua_tointegerx(L, -2, &isnum);
1772 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1776 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1777 FD_SET(fd, &readfds);
1778 if (fd+1 > nfds) nfds = fd+1;
1782 if (!lua_isnoneornil(L, 2)) {
1783 luaL_checktype(L, 2, LUA_TTABLE);
1784 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1785 if (lua_toboolean(L, -1)) {
1786 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1787 if (handle) {
1788 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1789 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1790 fd = handle->fd;
1791 #if MOONBR_IO_USE_TLS
1792 moonbr_io_poll_tls();
1793 #endif
1794 } else {
1795 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1796 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1797 fd = lua_tointegerx(L, -2, &isnum);
1798 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1800 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1801 FD_SET(fd, &writefds);
1802 if (fd+1 > nfds) nfds = fd+1;
1806 if (!lua_isnoneornil(L, 3)) {
1807 lua_Number n;
1808 n = lua_tonumberx(L, 3, &isnum);
1809 if (isnum && n<0) {
1810 use_timeout = -1;
1811 } else if (isnum && n>=0 && n<100000000) {
1812 use_timeout = 1;
1813 timeout.tv_sec = n;
1814 timeout.tv_nsec = 1e9 * (n - timeout.tv_sec);
1815 } else {
1816 luaL_argcheck(L, 0, 3, "not a valid timeout");
1819 if (use_timeout < 0) force_wakeup = 1;
1820 if (!lua_isnoneornil(L, 4)) luaL_checktype(L, 4, LUA_TBOOLEAN);
1821 check_sigterm = lua_toboolean(L, 4);
1822 if ((check_sigterm || check_sigchld) && !force_wakeup) {
1823 sigemptyset(&mask);
1824 if (check_sigterm) sigaddset(&mask, SIGTERM);
1825 if (check_sigchld) sigaddset(&mask, SIGCHLD);
1826 if (sigprocmask(SIG_BLOCK, &mask, &orig_mask)) abort();
1828 if (check_sigterm && moonbr_io_sigterm_flag) {
1829 if (!force_wakeup) {
1830 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1832 lua_pushboolean(L, 0);
1833 lua_pushliteral(L, "SIGTERM received");
1834 lua_pushboolean(L, 1);
1835 return 3;
1837 if (check_sigchld && !force_wakeup && moonbr_io_sigchld_flag) {
1838 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1839 force_wakeup = 1;
1841 if (use_timeout < 0) {
1842 lua_pushboolean(L, 0);
1843 lua_pushliteral(L, "Timeout");
1844 if (check_sigterm) {
1845 lua_pushboolean(L, 0);
1846 return 3;
1847 } else {
1848 return 2;
1851 if (!force_wakeup) {
1852 status = pselect(
1853 nfds, &readfds, &writefds, &exceptfds,
1854 use_timeout ? &timeout : NULL,
1855 (check_sigterm || check_sigchld) ? &orig_mask : NULL
1856 );
1857 if (check_sigterm || check_sigchld) {
1858 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1859 if (check_sigterm && moonbr_io_sigterm_flag) {
1860 lua_pushboolean(L, 0);
1861 lua_pushliteral(L, "SIGTERM received");
1862 lua_pushboolean(L, 1);
1863 return 3;
1866 if (status == -1) {
1867 if (errno == EINTR) {
1868 lua_pushboolean(L, 1);
1869 return 1;
1870 } else {
1871 moonbr_io_prepare_errmsg();
1872 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1874 } else if (status == 0) {
1875 lua_pushboolean(L, 0);
1876 lua_pushliteral(L, "Timeout");
1877 if (check_sigterm) {
1878 lua_pushboolean(L, 0);
1879 return 3;
1880 } else {
1881 return 2;
1885 lua_pushboolean(L, 1);
1886 return 1;
1889 static int moonbr_io_timeref(lua_State *L) {
1890 lua_Number sub;
1891 struct timespec tp;
1892 sub = luaL_optnumber(L, 1, 0);
1893 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1894 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1896 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1897 return 1;
1900 #ifdef MOONBR_IO_USE_TLS
1902 #define moonbr_io_tlsconf_string(name, field, func) \
1903 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1904 lua_getfield(L, 1, (field)); \
1905 valuetype = lua_type(L, -1); \
1906 if (valuetype != LUA_TNIL) { \
1907 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1908 value = lua_tostring(L, -1); \
1909 if (func(tlsconf->config, value)) { \
1910 lua_pushnil(L); \
1911 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1912 return 2; \
1913 } \
1914 } \
1915 lua_pop(L, 1);
1917 #define moonbr_io_tlsconf_binary(name, field, func) \
1918 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1919 lua_getfield(L, 1, (field)); \
1920 valuetype = lua_type(L, -1); \
1921 if (valuetype != LUA_TNIL) { \
1922 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1923 value = lua_tolstring(L, -1, &valuelen); \
1924 if (func(tlsconf->config, (void *)value, valuelen)) { \
1925 lua_pushnil(L); \
1926 lua_pushliteral(L, "Could not set " name); \
1927 return 2; \
1928 } \
1929 } \
1930 lua_pop(L, 1);
1932 static int moonbr_io_tlsconf(lua_State *L) {
1933 moonbr_io_tlsconf_t *tlsconf;
1934 int valuetype;
1935 const char *value;
1936 size_t valuelen;
1937 luaL_checktype(L, 1, LUA_TTABLE);
1938 tlsconf = lua_newuserdata(L, sizeof(moonbr_io_tlsconf_t));
1939 tlsconf->config = tls_config_new();
1940 if (!tlsconf->config) {
1941 return luaL_error(L, "Could not allocate memory for TLS configuration");
1943 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
1944 lua_getfield(L, 1, "mode");
1945 value = lua_tostring(L, -1);
1946 if (value && !strcmp(value, "server")) tlsconf->server = 1;
1947 else if (value && !strcmp(value, "client")) tlsconf->server = 0;
1948 else luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
1949 lua_pop(L, 1);
1950 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
1951 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
1952 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
1953 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
1954 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
1955 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
1956 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
1957 #if LUA_VERSION_NUM >= 503
1958 valuetype = lua_getfield(L, 1, "verify_client");
1959 #else
1960 lua_getfield(L, 1, "verify_client");
1961 #endif
1962 if (lua_toboolean(L, -1)) {
1963 value = lua_tostring(L, -1);
1964 if (value && !strcmp(value, "required")) {
1965 tls_config_verify_client(tlsconf->config);
1966 } else if (value && !strcmp(value, "optional")) {
1967 tls_config_verify_client_optional(tlsconf->config);
1968 } else {
1969 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
1972 lua_pop(L, 1);
1973 // TODO: configurable legacy support
1974 // tls_config_set_protocols(tlsconf->config, TLS_PROTOCOLS_ALL);
1975 // tls_config_set_ciphers(tlsconf->config, "legacy");
1976 return 1;
1979 static int moonbr_io_tlsconfgc(lua_State *L) {
1980 moonbr_io_tlsconf_t *tlsconf;
1981 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
1982 if (tlsconf->config) tls_config_free(tlsconf->config);
1983 tlsconf->config = NULL;
1984 return 0;
1987 static int moonbr_io_starttls(lua_State *L) {
1988 moonbr_io_handle_t *handle;
1989 moonbr_io_tlsconf_t *tlsconf;
1990 const char *servername;
1991 struct tls *tls, *tls2;
1992 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1993 if (lua_type(L, 2) == LUA_TTABLE) {
1994 lua_pushcfunction(L, moonbr_io_tlsconf);
1995 lua_pushvalue(L, 2);
1996 lua_call(L, 1, 2);
1997 if (lua_isnil(L, -2)) return 2;
1998 lua_pop(L, 1);
1999 lua_replace(L, 2);
2001 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
2002 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
2003 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
2004 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
2005 if (handle->readbufin || handle->writebufin) {
2006 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
2008 if (tlsconf->server) tls = tls_server();
2009 else {
2010 servername = luaL_checkstring(L, 3);
2011 tls = tls_client();
2013 if (!tls) {
2014 return luaL_error(L, "Could not allocate memory for TLS context");
2016 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
2017 if (tlsconf->server) {
2018 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
2019 handle->servertls = tls;
2020 handle->tls = tls2;
2021 } else {
2022 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
2023 handle->tls = tls;
2025 lua_settop(L, 1);
2026 return 1;
2027 moonbr_io_starttls_error:
2028 lua_pushnil(L);
2029 lua_pushstring(L, tls_error(tls));
2030 tls_free(tls);
2031 return 2;
2034 #endif /* MOONBR_IO_USE_TLS */
2036 static const struct luaL_Reg moonbr_io_handle_methods[] = {
2037 {"read", moonbr_io_read},
2038 {"read_nb", moonbr_io_read_nb},
2039 {"read_call", moonbr_io_read_call},
2040 {"read_yield", moonbr_io_read_yield},
2041 {"drain", moonbr_io_drain},
2042 {"drain_nb", moonbr_io_drain_nb},
2043 {"drain_call", moonbr_io_drain_call},
2044 {"drain_yield", moonbr_io_drain_yield},
2045 {"write", moonbr_io_write},
2046 {"write_nb", moonbr_io_write_nb},
2047 {"write_call", moonbr_io_write_call},
2048 {"write_yield", moonbr_io_write_yield},
2049 {"flush", moonbr_io_flush},
2050 {"flush_nb", moonbr_io_flush_nb},
2051 {"flush_call", moonbr_io_flush_call},
2052 {"flush_yield", moonbr_io_flush_yield},
2053 {"finish", moonbr_io_finish},
2054 {"close", moonbr_io_close},
2055 {"reset", moonbr_io_reset},
2056 #ifdef MOONBR_IO_USE_TLS
2057 {"starttls", moonbr_io_starttls},
2058 #endif
2059 {NULL, NULL}
2060 };
2062 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
2063 {"__index", moonbr_io_handleindex},
2064 {"__newindex", moonbr_io_handlenewindex},
2065 {"__gc", moonbr_io_handlegc},
2066 {NULL, NULL}
2067 };
2069 static const struct luaL_Reg moonbr_io_listener_methods[] = {
2070 {"accept", moonbr_io_accept},
2071 {"accept_nb", moonbr_io_accept_nb},
2072 {"close", moonbr_io_unlisten},
2073 {NULL, NULL}
2074 };
2076 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
2077 {"__gc", moonbr_io_listenergc},
2078 {NULL, NULL}
2079 };
2081 static const struct luaL_Reg moonbr_io_child_methods[] = {
2082 {"kill", moonbr_io_kill},
2083 {"wait", moonbr_io_wait},
2084 {"wait_nb", moonbr_io_wait_nb},
2085 {"wait_call", moonbr_io_wait_call},
2086 {"wait_yield", moonbr_io_wait_yield},
2087 {NULL, NULL}
2088 };
2090 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
2091 {"__index", moonbr_io_childindex},
2092 {"__newindex", moonbr_io_childnewindex},
2093 {"__gc", moonbr_io_childgc},
2094 {NULL, NULL}
2095 };
2097 static const struct luaL_Reg moonbr_io_module_funcs[] = {
2098 {"localconnect", moonbr_io_localconnect},
2099 {"localconnect_nb", moonbr_io_localconnect_nb},
2100 {"tcpconnect", moonbr_io_tcpconnect},
2101 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2102 {"locallisten", moonbr_io_locallisten},
2103 {"tcplisten", moonbr_io_tcplisten},
2104 {"exec", moonbr_io_exec},
2105 {"catch_sigterm", moonbr_io_catch_sigterm},
2106 {"getpid", moonbr_io_getpid},
2107 {"poll", moonbr_io_poll},
2108 {"timeref", moonbr_io_timeref},
2109 #ifdef MOONBR_IO_USE_TLS
2110 {"tlsconf", moonbr_io_tlsconf},
2111 #endif
2112 {NULL, NULL}
2113 };
2115 #ifdef MOONBR_IO_USE_TLS
2117 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2118 {"__gc", moonbr_io_tlsconfgc},
2119 {NULL, NULL}
2120 };
2122 #endif /* MOONBR_IO_USE_TLS */
2124 int luaopen_moonbridge_io(lua_State *L) {
2126 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2128 lua_newtable(L); // module
2130 lua_newtable(L); // public metatable
2131 lua_newtable(L); // handle methods
2132 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2133 lua_pushvalue(L, -1);
2134 lua_setfield(L, -4, "handle_pt");
2135 lua_setfield(L, -2, "__index");
2136 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2138 lua_newtable(L); // handle metatable
2139 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2140 lua_pushvalue(L, -1);
2141 lua_setfield(L, -3, "handle_mt");
2142 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2144 lua_newtable(L); // listener metatable
2145 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2146 lua_newtable(L); // listener methods
2147 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2148 lua_pushvalue(L, -1);
2149 lua_setfield(L, -4, "listener_pt");
2150 lua_setfield(L, -2, "__index");
2151 lua_pushvalue(L, -1);
2152 lua_setfield(L, -3, "listener_mt");
2153 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2155 lua_newtable(L); // child methods
2156 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2157 lua_pushvalue(L, -1);
2158 lua_setfield(L, -3, "child_pt");
2159 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2160 lua_newtable(L); // child metatable
2161 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2162 lua_pushvalue(L, -1);
2163 lua_setfield(L, -3, "child_mt");
2164 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2166 #ifdef MOONBR_IO_USE_TLS
2167 if(tls_init()) {
2168 return luaL_error(L, "Could not initialize TLS library");
2170 lua_newtable(L); // tlsconf metatable
2171 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2172 lua_pushvalue(L, -1);
2173 lua_setfield(L, -3, "tlsconf_mt");
2174 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2175 #endif
2177 moonbr_io_pushhandle(L, 0);
2178 lua_setfield(L, -2, "stdin");
2179 moonbr_io_pushhandle(L, 1);
2180 lua_setfield(L, -2, "stdout");
2181 moonbr_io_pushhandle(L, 2);
2182 lua_setfield(L, -2, "stderr");
2184 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2185 return 1;

Impressum / About Us