moonbridge

view moonbridge_io.c @ 314:1b459e9c12c9

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

Impressum / About Us