moonbridge

view moonbridge_io.c @ 302:b2282fb8553b

Do not shutdown due to main thread termination when shutdown is already in progress
author jbe
date Fri Jun 23 15:49:43 2017 +0200 (2017-06-23)
parents 06f0b9280e77
children 477456cea361
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 } moonbr_io_child_t;
119 volatile sig_atomic_t moonbr_io_sigterm_flag = 0;
120 volatile sig_atomic_t moonbr_io_sigchld_flag = 0;
122 static int moonbr_io_yield(lua_State *L) {
123 return lua_yield(L, lua_gettop(L));
124 }
126 #if LUA_VERSION_NUM >= 503
127 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
128 #else
129 static int moonbr_io_cont_returnall(lua_State *L) {
130 #endif
131 return lua_gettop(L);
132 }
134 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
135 static int yieldfunc(lua_State *L) { \
136 int args; \
137 lua_pushcfunction(L, callfunc); \
138 lua_insert(L, 1); \
139 args = lua_gettop(L); \
140 lua_pushcfunction(L, moonbr_io_yield); \
141 lua_insert(L, 3); \
142 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
143 return lua_gettop(L); \
144 }
146 static int moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
147 int flags;
148 if (handle->nonblocking == nonblocking) return 0;
149 flags = fcntl(handle->fd, F_GETFL, 0);
150 if (flags == -1) return -1;
151 if (nonblocking) flags |= O_NONBLOCK;
152 else flags &= ~O_NONBLOCK;
153 if (fcntl(handle->fd, F_SETFL, flags) == -1) return -1;
154 handle->nonblocking = nonblocking;
155 return 0;
156 }
158 static int moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
159 struct linger lingerval = { 0, };
160 if (!handle->issock) return 0;
161 if (timeout >= 0) {
162 lingerval.l_onoff = 1;
163 lingerval.l_linger = timeout;
164 }
165 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) return -1;
166 return 0;
167 }
169 static inline int moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
170 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
171 if (
172 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
173 handle->nopush == nopush
174 ) return 0;
175 #if defined(TCP_NOPUSH)
176 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) return -1;
177 #elif defined(TCP_CORK)
178 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) return -1;
179 #endif
180 handle->nopush = nopush;
181 #else
182 #warning Neither TCP_NOPUSH nor TCP_CORK is available
183 #endif
184 return 0;
185 }
187 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
188 moonbr_io_handle_t *handle;
189 lua_Integer maxread;
190 const char *terminatorstr;
191 size_t terminatorlen;
192 char terminator = 0; /* initialize to avoid compiler warning */
193 luaL_Buffer luabuf;
194 size_t luabufcnt = 0;
195 int remaining;
196 char *terminatorpos;
197 ssize_t bytesread;
198 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
199 maxread = luaL_optinteger(L, 2, -1);
200 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
201 if (terminatorlen) {
202 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
203 terminator = terminatorstr[0];
204 }
205 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
206 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
207 if (handle->readerr) {
208 lua_pushnil(L);
209 lua_pushliteral(L, "Previous read error");
210 return 2;
211 }
212 if (handle->fd < 0) {
213 /* fake EOF to simulate shutdown */
214 if (!drain) lua_pushliteral(L, "");
215 else lua_pushinteger(L, 0);
216 lua_pushliteral(L, "eof");
217 return 2;
218 }
219 handle->readerr = 1;
220 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
221 if (!drain) luaL_buffinit(L, &luabuf);
222 while (1) {
223 remaining = -1;
224 terminatorpos = NULL;
225 if (
226 maxread >= 0 &&
227 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
228 ) {
229 remaining = (size_t)maxread - luabufcnt;
230 if (terminatorlen) {
231 terminatorpos = memchr(
232 handle->readbuf + handle->readbufout,
233 terminator,
234 remaining
235 );
236 }
237 } else if (terminatorlen) {
238 terminatorpos = memchr(
239 handle->readbuf + handle->readbufout,
240 terminator,
241 handle->readbufin - handle->readbufout
242 );
243 }
244 if (terminatorpos) remaining = 1 + (
245 terminatorpos - (handle->readbuf + handle->readbufout)
246 );
247 if (remaining >= 0) {
248 if (!drain) {
249 luaL_addlstring(
250 &luabuf,
251 handle->readbuf + handle->readbufout,
252 remaining
253 );
254 luaL_pushresult(&luabuf);
255 } else {
256 lua_pushinteger(L, luabufcnt + remaining);
257 }
258 if (terminatorpos) lua_pushliteral(L, "term");
259 else lua_pushliteral(L, "maxlen");
260 handle->readbufout += remaining;
261 if (handle->readbufout == handle->readbufin) {
262 handle->readbufin = 0;
263 handle->readbufout = 0;
264 }
265 handle->readerr = 0;
266 return 2;
267 }
268 if (!drain) luaL_addlstring(
269 &luabuf,
270 handle->readbuf + handle->readbufout,
271 handle->readbufin - handle->readbufout
272 );
273 luabufcnt += handle->readbufin - handle->readbufout;
274 handle->readbufout = 0;
275 #ifdef MOONBR_IO_USE_TLS
276 if (handle->tls) {
277 do {
278 if (!handle->tlshandshake) {
279 do bytesread = tls_handshake(handle->tls);
280 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
281 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
282 handle->tlshandshake = bytesread;
283 errno = EAGAIN;
284 break;
285 }
286 if (bytesread < 0) {
287 lua_pushnil(L);
288 lua_pushstring(L, tls_error(handle->tls));
289 return 2;
290 }
291 handle->tlshandshake = 1;
292 }
293 do bytesread = tls_read(handle->tls, handle->readbuf, MOONBR_IO_READBUFLEN);
294 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
295 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
296 errno = EAGAIN;
297 break;
298 }
299 if (bytesread < 0) {
300 lua_pushnil(L);
301 lua_pushstring(L, tls_error(handle->tls));
302 return 2;
303 }
304 } while (0);
305 }
306 else
307 #endif
308 do bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
309 while (bytesread < 0 && (errno == EINTR));
310 if (
311 bytesread == 0 || (
312 nonblocking &&
313 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
314 )
315 ) {
316 handle->readbufin = 0;
317 if (!drain) luaL_pushresult(&luabuf);
318 else lua_pushinteger(L, luabufcnt);
319 if (bytesread == 0) lua_pushliteral(L, "eof");
320 else lua_pushliteral(L, "block");
321 handle->readerr = 0;
322 return 2;
323 }
324 if (bytesread < 0) moonbr_io_return_errmsg();
325 handle->readbufin = bytesread;
326 }
327 }
329 static int moonbr_io_read(lua_State *L) {
330 return moonbr_io_read_impl(L, 0, 0);
331 }
333 static int moonbr_io_read_nb(lua_State *L) {
334 return moonbr_io_read_impl(L, 1, 0);
335 }
337 static int moonbr_io_drain(lua_State *L) {
338 return moonbr_io_read_impl(L, 0, 1);
339 }
341 static int moonbr_io_drain_nb(lua_State *L) {
342 return moonbr_io_read_impl(L, 1, 1);
343 }
345 #if LUA_VERSION_NUM >= 503
346 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
347 #else
348 static int moonbr_io_read_cont(lua_State *L) {
349 #endif
350 lua_Integer remaining;
351 size_t len;
352 #if !(LUA_VERSION_NUM >= 503)
353 int ctx = 0;
354 lua_getctx(L, &ctx);
355 #endif
356 remaining = lua_tointeger(L, 3);
357 while (1) {
358 lua_pushcfunction(L, moonbr_io_read_nb);
359 lua_pushvalue(L, 1);
360 lua_pushvalue(L, 3);
361 lua_pushvalue(L, 4);
362 lua_call(L, 3, 2);
363 if (lua_isnil(L, -2)) return 2;
364 lua_insert(L, -2);
365 len = lua_rawlen(L, -1);
366 if (ctx == 0) {
367 lua_replace(L, 5);
368 ctx = 1;
369 } else if (ctx == 1) {
370 lua_pushvalue(L, 5);
371 lua_newtable(L);
372 lua_replace(L, 5);
373 lua_rawseti(L, 5, 2);
374 lua_rawseti(L, 5, 1);
375 ctx = 2;
376 } else {
377 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
378 }
379 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
380 lua_pop(L, 1);
381 if (remaining >= 0 && len) {
382 remaining -= len;
383 lua_pushinteger(L, remaining);
384 lua_replace(L, 3);
385 }
386 lua_pushvalue(L, 2);
387 lua_callk(L, 0, 0, ctx, moonbr_io_read_cont);
388 }
389 if (ctx == 1) {
390 lua_pushvalue(L, 5);
391 } else {
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 }
402 lua_pushvalue(L, -2);
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 moonbr_io_handle_t *handle;
877 struct sockaddr addr;
878 socklen_t addrlen;
879 fd = lua_touserdata(L, 1);
880 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
881 handle->fd = -1; /* avoid closing incomplete handle */
882 addrlen = sizeof(addr);
883 if (getsockname(*fd, &addr, &addrlen)) {
884 if (errno != ENOTSOCK) {
885 moonbr_io_prepare_errmsg();
886 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
887 }
888 handle->issock = 0;
889 } else {
890 handle->issock = 1;
891 handle->addrfam = addr.sa_family;
892 }
893 handle->finished = 0;
894 handle->closed = 0;
895 handle->nonblocking = -1;
896 handle->nopush = -1;
897 handle->readerr = 0;
898 handle->readbufin = 0;
899 handle->readbufout = 0;
900 handle->writeerr = 0;
901 handle->writeleft = 0;
902 handle->flushedleft = 0;
903 handle->writeqin = 0;
904 handle->writeqout = 0;
905 handle->writeqoff = 0;
906 handle->writebufin = 0;
907 handle->writebufout = 0;
908 #ifdef MOONBR_IO_USE_TLS
909 handle->tls = NULL;
910 handle->servertls = NULL;
911 handle->tlshandshake = 0;
912 handle->tlsclosing = 0;
913 #endif
914 handle->fd = *fd; /* required for set_linger call */
915 if (moonbr_io_handle_set_linger(L, handle, 0)) {
916 moonbr_io_prepare_errmsg();
917 handle->fd = -1;
918 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
919 }
920 handle->fd = -1; /* avoid closing incomplete handle */
921 luaL_setmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
922 lua_newtable(L); // uservalue
923 lua_newtable(L);
924 lua_setfield(L, -2, "writequeue");
925 lua_newtable(L); // public
926 if (handle->addrfam == AF_INET6) {
927 struct sockaddr_in6 addr_in6;
928 char addrstrbuf[INET6_ADDRSTRLEN];
929 const char *addrstr;
930 addrlen = sizeof(addr_in6);
931 if (getsockname(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
932 moonbr_io_prepare_errmsg();
933 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
934 }
935 if (addrlen > sizeof(addr_in6)) {
936 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
937 }
938 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
939 if (!addrstr) {
940 moonbr_io_prepare_errmsg();
941 luaL_error(L, "Could not format local IP address: %s", errmsg);
942 } else {
943 lua_pushstring(L, addrstr);
944 lua_setfield(L, -2, "local_ip6");
945 }
946 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
947 lua_setfield(L, -2, "local_tcpport");
948 if (getpeername(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
949 moonbr_io_prepare_errmsg();
950 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
951 }
952 if (addrlen > sizeof(addr_in6)) {
953 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
954 }
955 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
956 if (!addrstr) {
957 moonbr_io_prepare_errmsg();
958 luaL_error(L, "Could not format remote IP address: %s", errmsg);
959 } else {
960 lua_pushstring(L, addrstr);
961 lua_setfield(L, -2, "remote_ip6");
962 }
963 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
964 lua_setfield(L, -2, "remote_tcpport");
965 } else if (handle->addrfam == AF_INET) {
966 struct sockaddr_in addr_in;
967 char addrstrbuf[INET_ADDRSTRLEN];
968 const char *addrstr;
969 addrlen = sizeof(addr_in);
970 if (getsockname(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
971 moonbr_io_prepare_errmsg();
972 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
973 }
974 if (addrlen > sizeof(addr_in)) {
975 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
976 }
977 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
978 if (!addrstr) {
979 moonbr_io_prepare_errmsg();
980 luaL_error(L, "Could not format local IP address: %s", errmsg);
981 } else {
982 lua_pushstring(L, addrstr);
983 lua_setfield(L, -2, "local_ip4");
984 }
985 lua_pushinteger(L, ntohs(addr_in.sin_port));
986 lua_setfield(L, -2, "local_tcpport");
987 if (getpeername(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
988 moonbr_io_prepare_errmsg();
989 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
990 }
991 if (addrlen > sizeof(addr_in)) {
992 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
993 }
994 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
995 if (!addrstr) {
996 moonbr_io_prepare_errmsg();
997 luaL_error(L, "Could not format remote IP address: %s", errmsg);
998 } else {
999 lua_pushstring(L, addrstr);
1000 lua_setfield(L, -2, "remote_ip4");
1002 lua_pushinteger(L, ntohs(addr_in.sin_port));
1003 lua_setfield(L, -2, "remote_tcpport");
1005 luaL_setmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1006 lua_setfield(L, -2, "public");
1007 lua_setuservalue(L, -2);
1008 handle->fd = *fd;
1009 *fd = -1; /* closing is now handled by garbage collection */
1010 return 1;
1013 void moonbr_io_pushhandle(lua_State *L, int fd) {
1014 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1015 lua_pushlightuserdata(L, &fd);
1016 if (lua_pcall(L, 1, 1, 0)) {
1017 if (fd != -1) close(fd); // TODO: correct to close file descriptor here?
1018 lua_error(L);
1022 static int moonbr_io_handleindex(lua_State *L) {
1023 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1024 luaL_checkany(L, 2);
1025 lua_getuservalue(L, 1);
1026 lua_getfield(L, -1, "public");
1027 lua_pushvalue(L, 2);
1028 lua_gettable(L, -2);
1029 return 1;
1032 static int moonbr_io_handlenewindex(lua_State *L) {
1033 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1034 luaL_checkany(L, 2);
1035 luaL_checkany(L, 3);
1036 lua_getuservalue(L, 1);
1037 lua_getfield(L, -1, "public");
1038 lua_pushvalue(L, 2);
1039 lua_pushvalue(L, 3);
1040 lua_settable(L, -3);
1041 return 0;
1044 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
1045 const char *path;
1046 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1047 const int path_maxlen = sizeof(struct sockaddr_un) - (
1048 (void *)sockaddr.sun_path - (void *)&sockaddr
1049 ) - 1; /* one byte for termination */
1050 int sock;
1051 path = luaL_checkstring(L, 1);
1052 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1053 strcpy(sockaddr.sun_path, path);
1054 sock = socket(
1055 PF_LOCAL,
1056 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1058 );
1059 if (sock < 0) moonbr_io_return_errmsg();
1060 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1061 if (!nonblocking && errno == EINTR) {
1062 moonbr_io_prepare_errmsg();
1063 close(sock);
1064 moonbr_io_return_prepared_errmsg();
1065 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1067 moonbr_io_pushhandle(L, sock);
1068 return 1;
1071 static int moonbr_io_localconnect(lua_State *L) {
1072 return moonbr_io_localconnect_impl(L, 0);
1075 static int moonbr_io_localconnect_nb(lua_State *L) {
1076 return moonbr_io_localconnect_impl(L, 1);
1079 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
1080 const char *host, *port;
1081 struct addrinfo hints = { 0, };
1082 struct addrinfo *res, *addrinfo;
1083 int errcode;
1084 int sock;
1085 host = luaL_checkstring(L, 1);
1086 port = luaL_checkstring(L, 2);
1087 hints.ai_family = AF_UNSPEC;
1088 hints.ai_socktype = SOCK_STREAM;
1089 hints.ai_protocol = IPPROTO_TCP;
1090 hints.ai_flags = AI_ADDRCONFIG;
1091 errcode = getaddrinfo(host, port, &hints, &res);
1092 if (errcode) {
1093 freeaddrinfo(res);
1094 if (errcode == EAI_SYSTEM) {
1095 moonbr_io_prepare_errmsg();
1096 lua_pushnil(L);
1097 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1098 } else {
1099 lua_pushnil(L);
1100 lua_pushstring(L, gai_strerror(errcode));
1102 return 2;
1104 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1105 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1107 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1108 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1110 addrinfo = res;
1111 moonbr_io_tcpconnect_found:
1112 sock = socket(
1113 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1114 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1115 addrinfo->ai_protocol
1116 );
1117 if (sock < 0) {
1118 moonbr_io_prepare_errmsg();
1119 freeaddrinfo(res);
1120 moonbr_io_return_prepared_errmsg();
1122 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1123 freeaddrinfo(res);
1124 if (!nonblocking && errno == EINTR) {
1125 moonbr_io_prepare_errmsg();
1126 close(sock);
1127 moonbr_io_return_prepared_errmsg();
1128 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1129 } else {
1130 freeaddrinfo(res);
1132 moonbr_io_pushhandle(L, sock);
1133 return 1;
1136 static int moonbr_io_tcpconnect(lua_State *L) {
1137 return moonbr_io_tcpconnect_impl(L, 0);
1140 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1141 return moonbr_io_tcpconnect_impl(L, 1);
1144 static int moonbr_io_locallisten(lua_State *L) {
1145 moonbr_io_listener_t *listener;
1146 const char *path;
1147 struct stat sb;
1148 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1149 const int path_maxlen = sizeof(struct sockaddr_un) - (
1150 (void *)sockaddr.sun_path - (void *)&sockaddr
1151 ) - 1; /* one byte for termination */
1152 int sock;
1153 path = luaL_checkstring(L, 1);
1154 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1155 strcpy(sockaddr.sun_path, path);
1156 if (stat(path, &sb) == 0) {
1157 if (S_ISSOCK(sb.st_mode)) unlink(path);
1159 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1160 listener->fd = -1;
1161 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1162 sock = socket(
1163 PF_LOCAL,
1164 SOCK_STREAM | SOCK_CLOEXEC,
1166 );
1167 if (sock < 0) moonbr_io_return_errmsg();
1168 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1169 moonbr_io_prepare_errmsg();
1170 close(sock);
1171 moonbr_io_return_prepared_errmsg();
1173 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1174 moonbr_io_prepare_errmsg();
1175 close(sock);
1176 moonbr_io_return_prepared_errmsg();
1178 listener->fd = sock;
1179 listener->addrfam = AF_LOCAL;
1180 listener->nonblocking = -1;
1181 return 1;
1184 static int moonbr_io_tcplisten(lua_State *L) {
1185 moonbr_io_listener_t *listener;
1186 const char *host, *port;
1187 struct addrinfo hints = { 0, };
1188 struct addrinfo *res, *addrinfo;
1189 int errcode;
1190 int sock;
1191 host = luaL_optstring(L, 1, NULL);
1192 port = luaL_checkstring(L, 2);
1193 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1194 listener->fd = -1;
1195 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1196 hints.ai_family = AF_UNSPEC;
1197 hints.ai_socktype = SOCK_STREAM;
1198 hints.ai_protocol = IPPROTO_TCP;
1199 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1200 errcode = getaddrinfo(host, port, &hints, &res);
1201 if (errcode) {
1202 freeaddrinfo(res);
1203 if (errcode == EAI_SYSTEM) {
1204 moonbr_io_prepare_errmsg();
1205 lua_pushnil(L);
1206 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1207 } else {
1208 lua_pushnil(L);
1209 lua_pushstring(L, gai_strerror(errcode));
1211 return 2;
1213 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1214 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1216 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1217 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1219 addrinfo = res;
1220 moonbr_io_tcpconnect_found:
1221 listener->addrfam = addrinfo->ai_family;
1222 sock = socket(
1223 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1224 addrinfo->ai_socktype | SOCK_CLOEXEC,
1225 addrinfo->ai_protocol
1226 );
1227 if (sock < 0) {
1228 moonbr_io_prepare_errmsg();
1229 freeaddrinfo(res);
1230 moonbr_io_return_prepared_errmsg();
1233 static const int reuseval = 1;
1234 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1235 moonbr_io_prepare_errmsg();
1236 freeaddrinfo(res);
1237 close(sock);
1238 lua_pushnil(L);
1239 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1240 return 2;
1243 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1244 moonbr_io_prepare_errmsg();
1245 freeaddrinfo(res);
1246 close(sock);
1247 moonbr_io_return_prepared_errmsg();
1249 freeaddrinfo(res);
1250 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1251 moonbr_io_prepare_errmsg();
1252 close(sock);
1253 moonbr_io_return_prepared_errmsg();
1255 listener->fd = sock;
1256 listener->nonblocking = -1;
1257 return 1;
1260 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1261 moonbr_io_listener_t *listener;
1262 int fd;
1263 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1264 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1265 if (listener->nonblocking != nonblocking) {
1266 int flags;
1267 flags = fcntl(listener->fd, F_GETFL, 0);
1268 if (flags == -1) {
1269 moonbr_io_prepare_errmsg();
1270 close(listener->fd);
1271 listener->fd = -1;
1272 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1274 if (nonblocking) flags |= O_NONBLOCK;
1275 else flags &= ~O_NONBLOCK;
1276 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1277 moonbr_io_prepare_errmsg();
1278 close(listener->fd);
1279 listener->fd = -1;
1280 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1282 listener->nonblocking = nonblocking;
1284 while (1) {
1285 #if defined(__linux__) && !defined(_GNU_SOURCE)
1286 fd = accept(listener->fd, NULL, NULL);
1287 if (fd != -1) {
1288 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
1289 moonbr_io_prepare_errmsg();
1290 close(listener->fd);
1291 listener->fd = -1;
1292 close(fd);
1293 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1296 #else
1297 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1298 #endif
1299 if (fd < 0) {
1300 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1301 lua_pushboolean(L, 0);
1302 lua_pushliteral(L, "No incoming connection pending");
1303 return 2;
1304 } else if (errno != EINTR) moonbr_io_return_errmsg();
1305 } else {
1306 moonbr_io_pushhandle(L, fd);
1307 return 1;
1312 static int moonbr_io_accept(lua_State *L) {
1313 return moonbr_io_accept_impl(L, 0);
1316 static int moonbr_io_accept_nb(lua_State *L) {
1317 return moonbr_io_accept_impl(L, 1);
1320 static int moonbr_io_unlisten(lua_State *L) {
1321 moonbr_io_listener_t *listener;
1322 struct sockaddr_un addr;
1323 socklen_t addrlen;
1324 struct stat sb;
1325 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1326 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1327 addrlen = sizeof(addr);
1328 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1329 if (close(listener->fd)) {
1330 moonbr_io_prepare_errmsg();
1331 listener->fd = -1;
1332 if (addrlen && addrlen <= sizeof(addr)) {
1333 if (stat(addr.sun_path, &sb) == 0) {
1334 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1337 moonbr_io_return_prepared_errmsg();
1339 listener->fd = -1;
1340 if (addrlen && addrlen <= sizeof(addr)) {
1341 if (stat(addr.sun_path, &sb) == 0) {
1342 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1345 lua_pushboolean(L, 1);
1346 return 1;
1349 static int moonbr_io_listenergc(lua_State *L) {
1350 moonbr_io_listener_t *listener;
1351 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1352 if (listener->fd >= 0) close(listener->fd);
1353 listener->fd = -1;
1354 return 0;
1357 static int moonbr_io_exec(lua_State *L) {
1358 char **argv;
1359 int i, argc;
1360 int sockin[2], sockout[2], sockerr[2];
1361 volatile int errorcond = 0;
1362 volatile char errmsgbuf[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG;
1363 moonbr_io_child_t *child;
1364 argc = lua_gettop(L);
1365 argv = lua_newuserdata(L, (argc + 1) * sizeof(char *));
1366 for (i=0; i<argc; i++) argv[i] = (char *)luaL_checkstring(L, i+1);
1367 argv[argc] = NULL;
1368 child = lua_newuserdata(L, sizeof(moonbr_io_child_t));
1369 child->pid = 0;
1370 lua_newtable(L);
1371 lua_setuservalue(L, -2);
1372 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1373 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1374 moonbr_io_prepare_errmsg();
1375 lua_pushnil(L);
1376 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1377 return 2;
1379 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1380 moonbr_io_prepare_errmsg();
1381 close(sockin[0]);
1382 close(sockin[1]);
1383 lua_pushnil(L);
1384 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1385 return 2;
1387 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1388 moonbr_io_prepare_errmsg();
1389 close(sockin[0]);
1390 close(sockin[1]);
1391 close(sockout[0]);
1392 close(sockout[1]);
1393 lua_pushnil(L);
1394 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1395 return 2;
1397 child->pid = vfork();
1398 if (child->pid == -1) {
1399 moonbr_io_prepare_errmsg();
1400 close(sockin[0]);
1401 close(sockin[1]);
1402 close(sockout[0]);
1403 close(sockout[1]);
1404 close(sockerr[0]);
1405 close(sockerr[1]);
1406 lua_pushnil(L);
1407 lua_pushfstring(L, "Could not fork: %s", errmsg);
1408 return 2;
1410 if (!child->pid) {
1411 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1412 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1413 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1414 closefrom(3);
1415 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1416 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1417 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1418 if (execvp(argv[0], argv)) {
1419 errorcond = 2;
1420 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1421 _exit(0);
1423 moonbr_io_exec_error1:
1424 errorcond = 1;
1425 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1426 _exit(0);
1428 close(sockin[1]);
1429 close(sockout[1]);
1430 close(sockerr[1]);
1431 if (errorcond) {
1432 int status;
1433 close(sockin[0]);
1434 close(sockout[0]);
1435 close(sockerr[0]);
1436 while (waitpid(child->pid, &status, 0) == -1) {
1437 if (errno != EINTR) {
1438 moonbr_io_prepare_errmsg();
1439 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1442 child->pid = 0;
1443 lua_pushnil(L);
1444 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1445 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1446 return 2;
1448 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1449 lua_pushlightuserdata(L, &sockin[0]);
1450 if (lua_pcall(L, 1, 1, 0)) {
1451 if (sockin[0] != -1) close(sockin[0]);
1452 close(sockout[0]);
1453 close(sockerr[0]);
1454 goto moonbr_io_exec_error2;
1456 lua_setfield(L, -2, "stdin");
1457 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1458 lua_pushlightuserdata(L, &sockout[0]);
1459 if (lua_pcall(L, 1, 1, 0)) {
1460 if (sockout[0] != -1) close(sockout[0]);
1461 close(sockerr[0]);
1462 goto moonbr_io_exec_error2;
1464 lua_setfield(L, -2, "stdout");
1465 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1466 lua_pushlightuserdata(L, &sockerr[0]);
1467 if (lua_pcall(L, 1, 1, 0)) {
1468 if (sockerr[0] != -1) close(sockerr[0]);
1469 goto moonbr_io_exec_error2;
1471 lua_setfield(L, -2, "stderr");
1472 return 1;
1473 moonbr_io_exec_error2:
1475 int status;
1476 while (waitpid(child->pid, &status, 0) == -1) {
1477 if (errno != EINTR) {
1478 moonbr_io_prepare_errmsg();
1479 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1483 child->pid = 0;
1484 return lua_error(L);
1487 static int moonbr_io_childindex(lua_State *L) {
1488 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1489 luaL_checkany(L, 2);
1490 lua_getuservalue(L, 1);
1491 lua_pushvalue(L, 2);
1492 lua_gettable(L, -2);
1493 if (lua_isnil(L, -1)) {
1494 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1495 lua_pushvalue(L, 2);
1496 lua_gettable(L, -2);
1498 return 1;
1501 static int moonbr_io_childnewindex(lua_State *L) {
1502 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1503 luaL_checkany(L, 2);
1504 luaL_checkany(L, 3);
1505 lua_getuservalue(L, 1);
1506 lua_pushvalue(L, 2);
1507 lua_pushvalue(L, 3);
1508 lua_settable(L, -3);
1509 return 0;
1512 static int moonbr_io_childgc(lua_State *L) {
1513 moonbr_io_child_t *child;
1514 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1515 if (child->pid) {
1516 int status;
1517 int pid = child->pid;
1518 child->pid = 0;
1519 if (kill(pid, SIGKILL)) {
1520 moonbr_io_prepare_errmsg();
1521 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1523 while (waitpid(pid, &status, 0) == -1) {
1524 if (errno != EINTR) {
1525 moonbr_io_prepare_errmsg();
1526 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1530 return 0;
1533 static int moonbr_io_kill(lua_State *L) {
1534 moonbr_io_child_t *child;
1535 int sig;
1536 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1537 sig = luaL_optinteger(L, 2, SIGKILL);
1538 if (!child->pid) luaL_error(L, "Attempt to kill an already collected child process");
1539 if (kill(child->pid, sig)) {
1540 moonbr_io_prepare_errmsg();
1541 luaL_error(L, "Error in kill call: %s", errmsg);
1543 lua_settop(L, 1);
1544 return 1;
1547 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1548 moonbr_io_child_t *child;
1549 pid_t waitedpid;
1550 int status;
1551 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1552 if (!child->pid) luaL_error(L, "Attempt to wait for an already collected child process");
1553 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1554 if (errno != EINTR) {
1555 moonbr_io_prepare_errmsg();
1556 luaL_error(L, "Error in waitpid call: %s", errmsg);
1559 if (!waitedpid) {
1560 lua_pushboolean(L, 0);
1561 lua_pushliteral(L, "Process is still running");
1562 return 2;
1563 } else {
1564 child->pid = 0;
1565 if (WIFEXITED(status)) {
1566 lua_pushinteger(L, WEXITSTATUS(status));
1567 } else if (WIFSIGNALED(status)) {
1568 lua_pushinteger(L, -WTERMSIG(status));
1569 } else {
1570 luaL_error(L, "Unexpected status value returned by waitpid call");
1572 return 1;
1576 static int moonbr_io_wait(lua_State *L) {
1577 return moonbr_io_wait_impl(L, 0);
1580 static int moonbr_io_wait_nb(lua_State *L) {
1581 return moonbr_io_wait_impl(L, 1);
1584 #if LUA_VERSION_NUM >= 503
1585 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1586 #else
1587 static int moonbr_io_wait_cont(lua_State *L) {
1588 #endif
1589 #if !(LUA_VERSION_NUM >= 503)
1590 int ctx = 0;
1591 lua_getctx(L, &ctx);
1592 #endif
1593 while (1) {
1594 lua_pushcfunction(L, moonbr_io_wait_nb);
1595 lua_pushvalue(L, 1);
1596 lua_call(L, 1, 1);
1597 if (!lua_isnil(L, -1)) break;
1598 lua_pushvalue(L, 2);
1599 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1601 return 1;
1604 static int moonbr_io_wait_call(lua_State *L) {
1605 lua_settop(L, 2);
1606 #if LUA_VERSION_NUM >= 503
1607 return moonbr_io_wait_cont(L, 0, 0);
1608 #else
1609 return moonbr_io_wait_cont(L);
1610 #endif
1613 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1615 static void moonbr_io_sigterm_handler(int sig) {
1616 moonbr_io_sigterm_flag = 1;
1619 static void moonbr_io_sigchld_handler(int sig) {
1620 moonbr_io_sigchld_flag = 1;
1623 int moonbr_io_catch_sigterm(lua_State *L) {
1624 signal(SIGTERM, moonbr_io_sigterm_handler);
1625 return 0;
1628 static int moonbr_io_getpid(lua_State *L) {
1629 lua_pushinteger(L, getpid());
1630 return 1;
1633 #ifdef MOONBR_IO_USE_TLS
1635 #define moonbr_io_poll_tls() \
1636 if (!handle->tlshandshake) { \
1637 force_wakeup = 1; \
1638 continue; \
1639 } \
1640 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1641 if (fd < 0) { \
1642 force_wakeup = 1; \
1643 continue; \
1644 } \
1645 FD_SET(fd, &readfds); \
1646 if (fd+1 > nfds) nfds = fd+1; \
1647 continue; \
1648 } \
1649 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1650 if (fd < 0) { \
1651 force_wakeup = 1; \
1652 continue; \
1653 } \
1654 FD_SET(fd, &writefds); \
1655 if (fd+1 > nfds) nfds = fd+1; \
1656 continue; \
1657 } \
1658 while (0)
1660 #endif /* MOONBR_IO_USE_TLS */
1662 static int moonbr_io_poll(lua_State *L) {
1663 moonbr_io_handle_t *handle;
1664 moonbr_io_listener_t *listener;
1665 moonbr_io_child_t *child;
1666 int fd, isnum;
1667 int nfds = 0;
1668 fd_set readfds, writefds, exceptfds;
1669 struct timespec timeout = {0, };
1670 int force_wakeup = 0;
1671 int use_timeout = 0; // negative for negative timeout
1672 int check_sigterm = 0;
1673 int check_sigchld = 0;
1674 pid_t waitedpid;
1675 sigset_t mask, orig_mask;
1676 int status;
1677 FD_ZERO(&readfds);
1678 FD_ZERO(&writefds);
1679 FD_ZERO(&exceptfds);
1680 if (!lua_isnoneornil(L, 1)) {
1681 luaL_checktype(L, 1, LUA_TTABLE);
1682 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1683 if (lua_toboolean(L, -1)) {
1684 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1685 if (handle) {
1686 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1687 fd = handle->fd;
1688 #if MOONBR_IO_USE_TLS
1689 moonbr_io_poll_tls();
1690 #endif
1691 if (
1692 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1693 handle->readbufin != handle->readbufout /* data pending in buffer */
1694 ) {
1695 force_wakeup = 1;
1696 continue;
1698 } else {
1699 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1700 if (listener) {
1701 fd = listener->fd;
1702 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1703 } else {
1704 child = luaL_testudata(L, -2, MOONBR_IO_CHILD_MT_REGKEY);
1705 if (child) {
1706 if (!child->pid) luaL_error(L, "Attemt to poll an already collected child process");
1707 if (!check_sigchld) {
1708 check_sigchld = 1;
1709 moonbr_io_sigchld_flag = 0;
1710 signal(SIGCHLD, moonbr_io_sigchld_handler);
1712 while ((waitedpid = waitpid(child->pid, &status, WNOHANG|WNOWAIT)) == -1) {
1713 if (errno != EINTR) {
1714 moonbr_io_prepare_errmsg();
1715 luaL_error(L, "Error in waitpid call: %s", errmsg);
1718 if (waitedpid) force_wakeup = 1;
1719 continue;
1720 } else {
1721 fd = lua_tointegerx(L, -2, &isnum);
1722 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1726 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1727 FD_SET(fd, &readfds);
1728 if (fd+1 > nfds) nfds = fd+1;
1732 if (!lua_isnoneornil(L, 2)) {
1733 luaL_checktype(L, 2, LUA_TTABLE);
1734 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1735 if (lua_toboolean(L, -1)) {
1736 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1737 if (handle) {
1738 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1739 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1740 fd = handle->fd;
1741 #if MOONBR_IO_USE_TLS
1742 moonbr_io_poll_tls();
1743 #endif
1744 } else {
1745 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1746 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1747 fd = lua_tointegerx(L, -2, &isnum);
1748 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1750 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1751 FD_SET(fd, &writefds);
1752 if (fd+1 > nfds) nfds = fd+1;
1756 if (!lua_isnoneornil(L, 3)) {
1757 lua_Number n;
1758 n = lua_tonumberx(L, 3, &isnum);
1759 if (isnum && n<0) {
1760 use_timeout = -1;
1761 } else if (isnum && n>=0 && n<100000000) {
1762 use_timeout = 1;
1763 timeout.tv_sec = n;
1764 timeout.tv_nsec = 1e9 * (n - timeout.tv_sec);
1765 } else {
1766 luaL_argcheck(L, 0, 3, "not a valid timeout");
1769 if (use_timeout < 0) force_wakeup = 1;
1770 if (!lua_isnoneornil(L, 4)) luaL_checktype(L, 4, LUA_TBOOLEAN);
1771 check_sigterm = lua_toboolean(L, 4);
1772 if ((check_sigterm || check_sigchld) && !force_wakeup) {
1773 sigemptyset(&mask);
1774 if (check_sigterm) sigaddset(&mask, SIGTERM);
1775 if (check_sigchld) sigaddset(&mask, SIGCHLD);
1776 if (sigprocmask(SIG_BLOCK, &mask, &orig_mask)) abort();
1778 if (check_sigterm && moonbr_io_sigterm_flag) {
1779 if (!force_wakeup) {
1780 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1782 lua_pushboolean(L, 0);
1783 lua_pushliteral(L, "SIGTERM received");
1784 lua_pushboolean(L, 1);
1785 return 3;
1787 if (check_sigchld && !force_wakeup && moonbr_io_sigchld_flag) {
1788 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1789 force_wakeup = 1;
1791 if (use_timeout < 0) {
1792 lua_pushboolean(L, 0);
1793 lua_pushliteral(L, "Timeout");
1794 if (check_sigterm) {
1795 lua_pushboolean(L, 0);
1796 return 3;
1797 } else {
1798 return 2;
1801 if (!force_wakeup) {
1802 status = pselect(
1803 nfds, &readfds, &writefds, &exceptfds,
1804 use_timeout ? &timeout : NULL,
1805 (check_sigterm || check_sigchld) ? &orig_mask : NULL
1806 );
1807 if (check_sigterm || check_sigchld) {
1808 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1809 if (check_sigterm && moonbr_io_sigterm_flag) {
1810 lua_pushboolean(L, 0);
1811 lua_pushliteral(L, "SIGTERM received");
1812 lua_pushboolean(L, 1);
1813 return 3;
1816 if (status == -1) {
1817 if (errno == EINTR) {
1818 lua_pushboolean(L, 1);
1819 return 1;
1820 } else {
1821 moonbr_io_prepare_errmsg();
1822 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1824 } else if (status == 0) {
1825 lua_pushboolean(L, 0);
1826 lua_pushliteral(L, "Timeout");
1827 if (check_sigterm) {
1828 lua_pushboolean(L, 0);
1829 return 3;
1830 } else {
1831 return 2;
1835 lua_pushboolean(L, 1);
1836 return 1;
1839 static int moonbr_io_timeref(lua_State *L) {
1840 lua_Number sub;
1841 struct timespec tp;
1842 sub = luaL_optnumber(L, 1, 0);
1843 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1844 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1846 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1847 return 1;
1850 #ifdef MOONBR_IO_USE_TLS
1852 #define moonbr_io_tlsconf_string(name, field, func) \
1853 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1854 lua_getfield(L, 1, (field)); \
1855 valuetype = lua_type(L, -1); \
1856 if (valuetype != LUA_TNIL) { \
1857 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1858 value = lua_tostring(L, -1); \
1859 if (func(tlsconf->config, value)) { \
1860 lua_pushnil(L); \
1861 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1862 return 2; \
1863 } \
1864 } \
1865 lua_pop(L, 1);
1867 #define moonbr_io_tlsconf_binary(name, field, func) \
1868 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1869 lua_getfield(L, 1, (field)); \
1870 valuetype = lua_type(L, -1); \
1871 if (valuetype != LUA_TNIL) { \
1872 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1873 value = lua_tolstring(L, -1, &valuelen); \
1874 if (func(tlsconf->config, (void *)value, valuelen)) { \
1875 lua_pushnil(L); \
1876 lua_pushliteral(L, "Could not set " name); \
1877 return 2; \
1878 } \
1879 } \
1880 lua_pop(L, 1);
1882 static int moonbr_io_tlsconf(lua_State *L) {
1883 moonbr_io_tlsconf_t *tlsconf;
1884 int valuetype;
1885 const char *value;
1886 size_t valuelen;
1887 luaL_checktype(L, 1, LUA_TTABLE);
1888 tlsconf = lua_newuserdata(L, sizeof(moonbr_io_tlsconf_t));
1889 tlsconf->config = tls_config_new();
1890 if (!tlsconf->config) {
1891 return luaL_error(L, "Could not allocate memory for TLS configuration");
1893 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
1894 lua_getfield(L, 1, "mode");
1895 value = lua_tostring(L, -1);
1896 if (value && !strcmp(value, "server")) tlsconf->server = 1;
1897 else if (value && !strcmp(value, "client")) tlsconf->server = 0;
1898 else luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
1899 lua_pop(L, 1);
1900 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
1901 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
1902 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
1903 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
1904 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
1905 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
1906 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
1907 #if LUA_VERSION_NUM >= 503
1908 valuetype = lua_getfield(L, 1, "verify_client");
1909 #else
1910 lua_getfield(L, 1, "verify_client");
1911 #endif
1912 if (lua_toboolean(L, -1)) {
1913 value = lua_tostring(L, -1);
1914 if (value && !strcmp(value, "required")) {
1915 tls_config_verify_client(tlsconf->config);
1916 } else if (value && !strcmp(value, "optional")) {
1917 tls_config_verify_client_optional(tlsconf->config);
1918 } else {
1919 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
1922 lua_pop(L, 1);
1923 // TODO: configurable legacy support
1924 // tls_config_set_protocols(tlsconf->config, TLS_PROTOCOLS_ALL);
1925 // tls_config_set_ciphers(tlsconf->config, "legacy");
1926 return 1;
1929 static int moonbr_io_tlsconfgc(lua_State *L) {
1930 moonbr_io_tlsconf_t *tlsconf;
1931 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
1932 if (tlsconf->config) tls_config_free(tlsconf->config);
1933 tlsconf->config = NULL;
1934 return 0;
1937 static int moonbr_io_starttls(lua_State *L) {
1938 moonbr_io_handle_t *handle;
1939 moonbr_io_tlsconf_t *tlsconf;
1940 const char *servername;
1941 struct tls *tls, *tls2;
1942 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1943 if (lua_type(L, 2) == LUA_TTABLE) {
1944 lua_pushcfunction(L, moonbr_io_tlsconf);
1945 lua_pushvalue(L, 2);
1946 lua_call(L, 1, 2);
1947 if (lua_isnil(L, -2)) return 2;
1948 lua_pop(L, 1);
1949 lua_replace(L, 2);
1951 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
1952 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
1953 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
1954 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
1955 if (handle->readbufin || handle->writebufin) {
1956 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
1958 if (tlsconf->server) tls = tls_server();
1959 else {
1960 servername = luaL_checkstring(L, 3);
1961 tls = tls_client();
1963 if (!tls) {
1964 return luaL_error(L, "Could not allocate memory for TLS context");
1966 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
1967 if (tlsconf->server) {
1968 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
1969 handle->servertls = tls;
1970 handle->tls = tls2;
1971 } else {
1972 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
1973 handle->tls = tls;
1975 lua_settop(L, 1);
1976 return 1;
1977 moonbr_io_starttls_error:
1978 lua_pushnil(L);
1979 lua_pushstring(L, tls_error(tls));
1980 tls_free(tls);
1981 return 2;
1984 #endif /* MOONBR_IO_USE_TLS */
1986 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1987 {"read", moonbr_io_read},
1988 {"read_nb", moonbr_io_read_nb},
1989 {"read_call", moonbr_io_read_call},
1990 {"read_yield", moonbr_io_read_yield},
1991 {"drain", moonbr_io_drain},
1992 {"drain_nb", moonbr_io_drain_nb},
1993 {"drain_call", moonbr_io_drain_call},
1994 {"drain_yield", moonbr_io_drain_yield},
1995 {"write", moonbr_io_write},
1996 {"write_nb", moonbr_io_write_nb},
1997 {"write_call", moonbr_io_write_call},
1998 {"write_yield", moonbr_io_write_yield},
1999 {"flush", moonbr_io_flush},
2000 {"flush_nb", moonbr_io_flush_nb},
2001 {"flush_call", moonbr_io_flush_call},
2002 {"flush_yield", moonbr_io_flush_yield},
2003 {"finish", moonbr_io_finish},
2004 {"close", moonbr_io_close},
2005 {"reset", moonbr_io_reset},
2006 #ifdef MOONBR_IO_USE_TLS
2007 {"starttls", moonbr_io_starttls},
2008 #endif
2009 {NULL, NULL}
2010 };
2012 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
2013 {"__index", moonbr_io_handleindex},
2014 {"__newindex", moonbr_io_handlenewindex},
2015 {"__gc", moonbr_io_handlegc},
2016 {NULL, NULL}
2017 };
2019 static const struct luaL_Reg moonbr_io_listener_methods[] = {
2020 {"accept", moonbr_io_accept},
2021 {"accept_nb", moonbr_io_accept_nb},
2022 {"close", moonbr_io_unlisten},
2023 {NULL, NULL}
2024 };
2026 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
2027 {"__gc", moonbr_io_listenergc},
2028 {NULL, NULL}
2029 };
2031 static const struct luaL_Reg moonbr_io_child_methods[] = {
2032 {"kill", moonbr_io_kill},
2033 {"wait", moonbr_io_wait},
2034 {"wait_nb", moonbr_io_wait_nb},
2035 {"wait_call", moonbr_io_wait_call},
2036 {"wait_yield", moonbr_io_wait_yield},
2037 {NULL, NULL}
2038 };
2040 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
2041 {"__index", moonbr_io_childindex},
2042 {"__newindex", moonbr_io_childnewindex},
2043 {"__gc", moonbr_io_childgc},
2044 {NULL, NULL}
2045 };
2047 static const struct luaL_Reg moonbr_io_module_funcs[] = {
2048 {"localconnect", moonbr_io_localconnect},
2049 {"localconnect_nb", moonbr_io_localconnect_nb},
2050 {"tcpconnect", moonbr_io_tcpconnect},
2051 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2052 {"locallisten", moonbr_io_locallisten},
2053 {"tcplisten", moonbr_io_tcplisten},
2054 {"exec", moonbr_io_exec},
2055 {"catch_sigterm", moonbr_io_catch_sigterm},
2056 {"getpid", moonbr_io_getpid},
2057 {"poll", moonbr_io_poll},
2058 {"timeref", moonbr_io_timeref},
2059 #ifdef MOONBR_IO_USE_TLS
2060 {"tlsconf", moonbr_io_tlsconf},
2061 #endif
2062 {NULL, NULL}
2063 };
2065 #ifdef MOONBR_IO_USE_TLS
2067 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2068 {"__gc", moonbr_io_tlsconfgc},
2069 {NULL, NULL}
2070 };
2072 #endif /* MOONBR_IO_USE_TLS */
2074 int luaopen_moonbridge_io(lua_State *L) {
2076 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2078 lua_newtable(L); // module
2080 lua_newtable(L); // public metatable
2081 lua_newtable(L); // handle methods
2082 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2083 lua_pushvalue(L, -1);
2084 lua_setfield(L, -4, "handle_pt");
2085 lua_setfield(L, -2, "__index");
2086 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2088 lua_newtable(L); // handle metatable
2089 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2090 lua_pushvalue(L, -1);
2091 lua_setfield(L, -3, "handle_mt");
2092 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2094 lua_newtable(L); // listener metatable
2095 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2096 lua_newtable(L); // listener methods
2097 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2098 lua_pushvalue(L, -1);
2099 lua_setfield(L, -4, "listener_pt");
2100 lua_setfield(L, -2, "__index");
2101 lua_pushvalue(L, -1);
2102 lua_setfield(L, -3, "listener_mt");
2103 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2105 lua_newtable(L); // child methods
2106 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2107 lua_pushvalue(L, -1);
2108 lua_setfield(L, -3, "child_pt");
2109 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2110 lua_newtable(L); // child metatable
2111 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2112 lua_pushvalue(L, -1);
2113 lua_setfield(L, -3, "child_mt");
2114 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2116 #ifdef MOONBR_IO_USE_TLS
2117 if(tls_init()) {
2118 return luaL_error(L, "Could not initialize TLS library");
2120 lua_newtable(L); // tlsconf metatable
2121 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2122 lua_pushvalue(L, -1);
2123 lua_setfield(L, -3, "tlsconf_mt");
2124 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2125 #endif
2127 moonbr_io_pushhandle(L, 0);
2128 lua_setfield(L, -2, "stdin");
2129 moonbr_io_pushhandle(L, 1);
2130 lua_setfield(L, -2, "stdout");
2131 moonbr_io_pushhandle(L, 2);
2132 lua_setfield(L, -2, "stderr");
2134 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2135 return 1;

Impressum / About Us