moonbridge

view moonbridge_io.c @ 307:707e32177a1e

Fixed use of INET_ADDRSTRLEN constant (for IPv4)
author jbe
date Fri Nov 24 00:41:34 2017 +0100 (2017-11-24)
parents e4e1ad8d5ab8
children 930a43a0099a
line source
2 #ifndef __has_include
3 #define __has_include(x) 0
4 #endif
6 #include <stdlib.h>
7 #include <stdint.h>
8 #include <string.h>
9 #include <errno.h>
10 #include <unistd.h>
11 #include <signal.h>
12 #include <fcntl.h>
13 #include <sys/stat.h>
14 #include <sys/socket.h>
15 #include <sys/un.h>
16 #include <netinet/in.h>
17 #include <netinet/tcp.h>
18 #include <sys/select.h>
19 #include <time.h>
20 #include <netdb.h>
21 #include <arpa/inet.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #if defined(__linux__) || __has_include(<bsd/unistd.h>)
25 #include <bsd/unistd.h>
26 #endif
28 #ifdef MOONBR_IO_USE_TLS
29 #include <tls.h>
30 #endif
32 #include <lua.h>
33 #include <lauxlib.h>
34 #include <lualib.h>
36 #include <assert.h>
38 #define MOONBR_IO_MAXSTRERRORLEN 80
39 #define MOONBR_IO_READBUFLEN 4096
40 #define MOONBR_IO_WRITEBUFLEN 4096
42 #define MOONBR_IO_LISTEN_BACKLOG 1024
44 #define MOONBR_IO_STRERROR_R_MSG "Error detail unavailable due to noncompliant strerror_r() implementation"
45 #define moonbr_io_prepare_errmsg() \
46 char errmsg[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG; \
47 strerror_r(errno, errmsg, MOONBR_IO_MAXSTRERRORLEN)
48 #define moonbr_io_return_prepared_errmsg() \
49 lua_pushnil(L); \
50 lua_pushstring(L, errmsg); \
51 return 2
52 #define moonbr_io_return_errmsg() \
53 do { \
54 moonbr_io_prepare_errmsg(); \
55 moonbr_io_return_prepared_errmsg(); \
56 } while (0)
58 #define MOONBR_IO_HANDLE_MT_REGKEY "moonbridge_io_handle"
59 #define MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY "moonbridge_io_handle_public"
60 #define MOONBR_IO_LISTENER_MT_REGKEY "moonbridge_io_listener"
61 #define MOONBR_IO_CHILD_MT_REGKEY "moonbridge_io_child"
62 #define MOONBR_IO_CHILD_PT_REGKEY "moonbridge_io_child_pt"
64 #ifdef MOONBR_IO_USE_TLS
66 #define MOONBR_IO_TLSCONF_MT_REGKEY "moonbridge_io_tlsconf"
68 typedef struct {
69 struct tls_config *config;
70 int server;
71 } moonbr_io_tlsconf_t;
73 #endif /* MOONBR_IO_USE_TLS */
75 typedef struct {
76 int fd;
77 int issock;
78 sa_family_t addrfam;
79 int finished;
80 int closed;
81 int nonblocking;
82 int nopush;
83 int readerr;
84 int readbufin;
85 int readbufout;
86 int writeerr;
87 size_t writeleft;
88 size_t flushedleft;
89 #if LUA_VERSION_NUM >= 503
90 lua_Integer writeqin;
91 lua_Integer writeqout;
92 #else
93 int writeqin;
94 int writeqout;
95 #endif
96 size_t writeqoff;
97 int writebufin;
98 int writebufout;
99 char readbuf[MOONBR_IO_READBUFLEN];
100 char writebuf[MOONBR_IO_WRITEBUFLEN];
101 #ifdef MOONBR_IO_USE_TLS
102 struct tls *tls;
103 struct tls *servertls;
104 int tlshandshake;
105 int tlsclosing;
106 #endif
107 } moonbr_io_handle_t;
109 typedef struct {
110 int fd;
111 sa_family_t addrfam;
112 int nonblocking;
113 } moonbr_io_listener_t;
115 typedef struct {
116 pid_t pid;
117 int status;
118 int status_valid;
119 } moonbr_io_child_t;
121 volatile sig_atomic_t moonbr_io_sigterm_flag = 0;
122 volatile sig_atomic_t moonbr_io_sigchld_flag = 0;
124 static int moonbr_io_yield(lua_State *L) {
125 return lua_yield(L, lua_gettop(L));
126 }
128 #if LUA_VERSION_NUM >= 503
129 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
130 #else
131 static int moonbr_io_cont_returnall(lua_State *L) {
132 #endif
133 return lua_gettop(L);
134 }
136 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
137 static int yieldfunc(lua_State *L) { \
138 int args; \
139 lua_pushcfunction(L, callfunc); \
140 lua_insert(L, 1); \
141 args = lua_gettop(L); \
142 lua_pushcfunction(L, moonbr_io_yield); \
143 lua_insert(L, 3); \
144 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
145 return lua_gettop(L); \
146 }
148 static int moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
149 int flags;
150 if (handle->nonblocking == nonblocking) return 0;
151 flags = fcntl(handle->fd, F_GETFL, 0);
152 if (flags == -1) return -1;
153 if (nonblocking) flags |= O_NONBLOCK;
154 else flags &= ~O_NONBLOCK;
155 if (fcntl(handle->fd, F_SETFL, flags) == -1) return -1;
156 handle->nonblocking = nonblocking;
157 return 0;
158 }
160 static int moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
161 struct linger lingerval = { 0, };
162 if (!handle->issock) return 0;
163 if (timeout >= 0) {
164 lingerval.l_onoff = 1;
165 lingerval.l_linger = timeout;
166 }
167 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) return -1;
168 return 0;
169 }
171 static inline int moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
172 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
173 if (
174 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
175 handle->nopush == nopush
176 ) return 0;
177 #if defined(TCP_NOPUSH)
178 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) return -1;
179 #elif defined(TCP_CORK)
180 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) return -1;
181 #endif
182 handle->nopush = nopush;
183 #else
184 #warning Neither TCP_NOPUSH nor TCP_CORK is available
185 #endif
186 return 0;
187 }
189 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
190 moonbr_io_handle_t *handle;
191 lua_Integer maxread;
192 const char *terminatorstr;
193 size_t terminatorlen;
194 char terminator = 0; /* initialize to avoid compiler warning */
195 luaL_Buffer luabuf;
196 size_t luabufcnt = 0;
197 int remaining;
198 char *terminatorpos;
199 ssize_t bytesread;
200 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
201 maxread = luaL_optinteger(L, 2, -1);
202 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
203 if (terminatorlen) {
204 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
205 terminator = terminatorstr[0];
206 }
207 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
208 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
209 if (handle->readerr) {
210 lua_pushnil(L);
211 lua_pushliteral(L, "Previous read error");
212 return 2;
213 }
214 if (handle->fd < 0) {
215 /* fake EOF to simulate shutdown */
216 if (!drain) lua_pushliteral(L, "");
217 else lua_pushinteger(L, 0);
218 lua_pushliteral(L, "eof");
219 return 2;
220 }
221 handle->readerr = 1;
222 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
223 if (!drain) luaL_buffinit(L, &luabuf);
224 while (1) {
225 remaining = -1;
226 terminatorpos = NULL;
227 if (
228 maxread >= 0 &&
229 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
230 ) {
231 remaining = (size_t)maxread - luabufcnt;
232 if (terminatorlen) {
233 terminatorpos = memchr(
234 handle->readbuf + handle->readbufout,
235 terminator,
236 remaining
237 );
238 }
239 } else if (terminatorlen) {
240 terminatorpos = memchr(
241 handle->readbuf + handle->readbufout,
242 terminator,
243 handle->readbufin - handle->readbufout
244 );
245 }
246 if (terminatorpos) remaining = 1 + (
247 terminatorpos - (handle->readbuf + handle->readbufout)
248 );
249 if (remaining >= 0) {
250 if (!drain) {
251 luaL_addlstring(
252 &luabuf,
253 handle->readbuf + handle->readbufout,
254 remaining
255 );
256 luaL_pushresult(&luabuf);
257 } else {
258 lua_pushinteger(L, luabufcnt + remaining);
259 }
260 if (terminatorpos) lua_pushliteral(L, "term");
261 else lua_pushliteral(L, "maxlen");
262 handle->readbufout += remaining;
263 if (handle->readbufout == handle->readbufin) {
264 handle->readbufin = 0;
265 handle->readbufout = 0;
266 }
267 handle->readerr = 0;
268 return 2;
269 }
270 if (!drain) luaL_addlstring(
271 &luabuf,
272 handle->readbuf + handle->readbufout,
273 handle->readbufin - handle->readbufout
274 );
275 luabufcnt += handle->readbufin - handle->readbufout;
276 handle->readbufout = 0;
277 #ifdef MOONBR_IO_USE_TLS
278 if (handle->tls) {
279 do {
280 if (!handle->tlshandshake) {
281 do bytesread = tls_handshake(handle->tls);
282 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
283 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
284 handle->tlshandshake = bytesread;
285 errno = EAGAIN;
286 break;
287 }
288 if (bytesread < 0) {
289 lua_pushnil(L);
290 lua_pushstring(L, tls_error(handle->tls));
291 return 2;
292 }
293 handle->tlshandshake = 1;
294 }
295 do bytesread = tls_read(handle->tls, handle->readbuf, MOONBR_IO_READBUFLEN);
296 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
297 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
298 errno = EAGAIN;
299 break;
300 }
301 if (bytesread < 0) {
302 lua_pushnil(L);
303 lua_pushstring(L, tls_error(handle->tls));
304 return 2;
305 }
306 } while (0);
307 }
308 else
309 #endif
310 do bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
311 while (bytesread < 0 && (errno == EINTR));
312 if (
313 bytesread == 0 || (
314 nonblocking &&
315 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
316 )
317 ) {
318 handle->readbufin = 0;
319 if (!drain) luaL_pushresult(&luabuf);
320 else lua_pushinteger(L, luabufcnt);
321 if (bytesread == 0) lua_pushliteral(L, "eof");
322 else lua_pushliteral(L, "block");
323 handle->readerr = 0;
324 return 2;
325 }
326 if (bytesread < 0) moonbr_io_return_errmsg();
327 handle->readbufin = bytesread;
328 }
329 }
331 static int moonbr_io_read(lua_State *L) {
332 return moonbr_io_read_impl(L, 0, 0);
333 }
335 static int moonbr_io_read_nb(lua_State *L) {
336 return moonbr_io_read_impl(L, 1, 0);
337 }
339 static int moonbr_io_drain(lua_State *L) {
340 return moonbr_io_read_impl(L, 0, 1);
341 }
343 static int moonbr_io_drain_nb(lua_State *L) {
344 return moonbr_io_read_impl(L, 1, 1);
345 }
347 #if LUA_VERSION_NUM >= 503
348 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
349 #else
350 static int moonbr_io_read_cont(lua_State *L) {
351 #endif
352 lua_Integer remaining;
353 size_t len;
354 #if !(LUA_VERSION_NUM >= 503)
355 int ctx = 0;
356 lua_getctx(L, &ctx);
357 #endif
358 remaining = lua_tointeger(L, 3);
359 while (1) {
360 lua_pushcfunction(L, moonbr_io_read_nb);
361 lua_pushvalue(L, 1);
362 lua_pushvalue(L, 3);
363 lua_pushvalue(L, 4);
364 lua_call(L, 3, 2);
365 if (lua_isnil(L, -2)) return 2;
366 lua_insert(L, -2);
367 len = lua_rawlen(L, -1);
368 if (ctx == 0) {
369 lua_replace(L, 5);
370 ctx = 1;
371 } else if (ctx == 1) {
372 lua_pushvalue(L, 5);
373 lua_newtable(L);
374 lua_replace(L, 5);
375 lua_rawseti(L, 5, 1);
376 lua_rawseti(L, 5, 2);
377 ctx = 2;
378 } else {
379 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
380 }
381 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
382 lua_pop(L, 1);
383 if (remaining >= 0 && len) {
384 remaining -= len;
385 lua_pushinteger(L, remaining);
386 lua_replace(L, 3);
387 }
388 lua_pushvalue(L, 2);
389 lua_callk(L, 0, 0, ctx, moonbr_io_read_cont);
390 }
391 if (ctx != 1) {
392 luaL_Buffer buf;
393 lua_Integer i, chunkcount;
394 chunkcount = lua_rawlen(L, 5);
395 luaL_buffinit(L, &buf);
396 for (i=1; i<=chunkcount && i>0; i++) {
397 lua_rawgeti(L, 5, i);
398 luaL_addvalue(&buf);
399 }
400 luaL_pushresult(&buf);
401 lua_pushvalue(L, -2);
402 }
403 return 2;
404 }
406 static int moonbr_io_read_call(lua_State *L) {
407 lua_settop(L, 4);
408 lua_pushnil(L);
409 #if LUA_VERSION_NUM >= 503
410 return moonbr_io_read_cont(L, 0, 0);
411 #else
412 return moonbr_io_read_cont(L);
413 #endif
414 }
416 moonbr_io_yield_wrapper(moonbr_io_read_yield, moonbr_io_read_call);
418 #if LUA_VERSION_NUM >= 503
419 static int moonbr_io_drain_cont(lua_State *L, int status, lua_KContext ctx) {
420 #else
421 static int moonbr_io_drain_cont(lua_State *L) {
422 #endif
423 lua_Integer remaining, len;
424 size_t totallen = 0;
425 #if !(LUA_VERSION_NUM >= 503)
426 int ctx = 0;
427 lua_getctx(L, &ctx);
428 #endif
429 remaining = lua_tointeger(L, 3);
430 while (1) {
431 lua_pushcfunction(L, moonbr_io_drain_nb);
432 lua_pushvalue(L, 1);
433 lua_pushvalue(L, 3);
434 lua_pushvalue(L, 4);
435 lua_call(L, 3, 2);
436 if (lua_isnil(L, -2)) return 2;
437 lua_insert(L, -2);
438 len = lua_tointeger(L, -1);
439 lua_pop(L, 1);
440 totallen += len;
441 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
442 lua_pop(L, 1);
443 if (remaining >= 0 && len) {
444 remaining -= len;
445 lua_pushinteger(L, remaining);
446 lua_replace(L, 3);
447 }
448 lua_pushvalue(L, 2);
449 lua_callk(L, 0, 0, ctx, moonbr_io_drain_cont);
450 }
451 lua_pushinteger(L, totallen);
452 lua_pushvalue(L, -2);
453 return 2;
454 }
456 static int moonbr_io_drain_call(lua_State *L) {
457 #if LUA_VERSION_NUM >= 503
458 return moonbr_io_drain_cont(L, 0, 0);
459 #else
460 return moonbr_io_drain_cont(L);
461 #endif
462 }
464 moonbr_io_yield_wrapper(moonbr_io_drain_yield, moonbr_io_drain_call);
466 #ifdef MOONBR_IO_USE_TLS
468 #define moonbr_io_write_tls(buf, buflen) \
469 if (handle->tls) { \
470 do { \
471 if (!handle->tlshandshake) { \
472 do written = tls_handshake(handle->tls); \
473 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
474 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
475 handle->tlshandshake = written; \
476 errno = EAGAIN; \
477 break; \
478 } \
479 if (written < 0) { \
480 lua_pushnil(L); \
481 lua_pushstring(L, tls_error(handle->tls)); \
482 return 2; \
483 } \
484 handle->tlshandshake = 1; \
485 } \
486 do written = tls_write(handle->tls, (buf), (buflen)); \
487 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
488 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
489 errno = EAGAIN; \
490 break; \
491 } \
492 if (written < 0) { \
493 lua_pushnil(L); \
494 lua_pushstring(L, tls_error(handle->tls)); \
495 return 2; \
496 } \
497 } while (0); \
498 } \
499 else
501 #endif /* MOONBR_IO_USE_TLS */
503 static int moonbr_io_write_impl(lua_State *L, int nonblocking, int flush) {
504 moonbr_io_handle_t *handle;
505 int i, top;
506 const char *str;
507 size_t strlen;
508 ssize_t written;
509 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
510 if (handle->closed) luaL_error(L, "Attempt to write to a closed I/O handle");
511 if (handle->finished) luaL_error(L, "Attempt to write to a finished I/O handle");
512 if (handle->writeerr) {
513 lua_pushnil(L);
514 lua_pushliteral(L, "Previous write error");
515 return 2;
516 }
517 handle->writeerr = 1;
518 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
519 top = lua_gettop(L);
520 lua_getuservalue(L, 1);
521 lua_getfield(L, -1, "writequeue");
522 for (i=2; i<=top; i++) {
523 luaL_checklstring(L, i, &strlen);
524 lua_pushvalue(L, i);
525 lua_rawseti(L, -2, handle->writeqin++);
526 handle->writeleft += strlen;
527 }
528 if (flush) handle->flushedleft = handle->writeleft;
529 while (handle->writeqout != handle->writeqin) {
530 lua_rawgeti(L, -1, handle->writeqout);
531 str = lua_tolstring(L, -1, &strlen);
532 while (handle->writeqoff < strlen) {
533 if (
534 strlen - handle->writeqoff <
535 MOONBR_IO_WRITEBUFLEN - handle->writebufin
536 ) {
537 memcpy(
538 handle->writebuf + handle->writebufin,
539 str + handle->writeqoff,
540 strlen - handle->writeqoff
541 );
542 handle->writebufin += strlen - handle->writeqoff;
543 break;
544 } else {
545 memcpy(
546 handle->writebuf + handle->writebufin,
547 str + handle->writeqoff,
548 MOONBR_IO_WRITEBUFLEN - handle->writebufin
549 );
550 handle->writeqoff += MOONBR_IO_WRITEBUFLEN - handle->writebufin;
551 handle->writebufin = MOONBR_IO_WRITEBUFLEN;
552 while (handle->writebufout < MOONBR_IO_WRITEBUFLEN) {
553 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
554 #ifdef MOONBR_IO_USE_TLS
555 moonbr_io_write_tls(
556 handle->writebuf + handle->writebufout,
557 MOONBR_IO_WRITEBUFLEN - handle->writebufout
558 )
559 #endif
560 written = write(
561 handle->fd,
562 handle->writebuf + handle->writebufout,
563 MOONBR_IO_WRITEBUFLEN - handle->writebufout
564 );
565 if (written < 0) {
566 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
567 goto moonbr_io_write_impl_block;
568 } else if (errno != EINTR) moonbr_io_return_errmsg();
569 } else {
570 handle->writebufout += written;
571 handle->writeleft -= written;
572 if (handle->flushedleft) {
573 if (written >= handle->flushedleft) {
574 handle->flushedleft = 0;
575 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
576 } else {
577 handle->flushedleft -= written;
578 }
579 }
580 }
581 }
582 handle->writebufin = 0;
583 handle->writebufout = 0;
584 }
585 }
586 handle->writeqoff = 0;
587 lua_pop(L, 1);
588 lua_pushnil(L);
589 lua_rawseti(L, -2, handle->writeqout++);
590 }
591 while (handle->flushedleft) {
592 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
593 #ifdef MOONBR_IO_USE_TLS
594 moonbr_io_write_tls(
595 handle->writebuf + handle->writebufout,
596 handle->writebufin - handle->writebufout
597 )
598 #endif
599 written = write(
600 handle->fd,
601 handle->writebuf + handle->writebufout,
602 handle->writebufin - handle->writebufout
603 );
604 if (written < 0) {
605 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
606 goto moonbr_io_write_impl_block;
607 } else if (errno != EINTR) moonbr_io_return_errmsg();
608 } else {
609 handle->writebufout += written;
610 handle->writeleft -= written;
611 if (handle->flushedleft) {
612 if (written >= handle->flushedleft) {
613 handle->flushedleft = 0;
614 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
615 } else {
616 handle->flushedleft -= written;
617 }
618 }
619 }
620 }
621 if (handle->writebufout == handle->writebufin) {
622 handle->writebufin = 0;
623 handle->writebufout = 0;
624 }
625 if (nonblocking) lua_pushinteger(L, 0);
626 else lua_pushvalue(L, 1);
627 handle->writeerr = 0;
628 return 1;
629 moonbr_io_write_impl_block:
630 lua_pushinteger(L, handle->writeleft);
631 handle->writeerr = 0;
632 return 1;
633 }
635 static int moonbr_io_write(lua_State *L) {
636 return moonbr_io_write_impl(L, 0, 0);
637 }
639 static int moonbr_io_write_nb(lua_State *L) {
640 return moonbr_io_write_impl(L, 1, 0);
641 }
643 static int moonbr_io_flush(lua_State *L) {
644 return moonbr_io_write_impl(L, 0, 1);
645 }
647 static int moonbr_io_flush_nb(lua_State *L) {
648 return moonbr_io_write_impl(L, 1, 1);
649 }
651 #if LUA_VERSION_NUM >= 503
652 static int moonbr_io_write_cont(lua_State *L, int status, lua_KContext ctx) {
653 #else
654 static int moonbr_io_write_cont(lua_State *L) {
655 #endif
656 while (1) {
657 lua_pushcfunction(L, moonbr_io_write_nb);
658 lua_pushvalue(L, 1);
659 lua_call(L, 1, 2);
660 if (lua_isnil(L, -2)) return 2;
661 if (!lua_tointeger(L, -2)) {
662 lua_pushvalue(L, 1);
663 return 1;
664 }
665 lua_pop(L, 2);
666 lua_pushvalue(L, 2);
667 lua_callk(L, 0, 0, 0, moonbr_io_write_cont);
668 }
669 }
671 static int moonbr_io_write_call(lua_State *L) {
672 lua_pushcfunction(L, moonbr_io_write_nb);
673 lua_insert(L, 3);
674 lua_pushvalue(L, 1);
675 lua_insert(L, 4);
676 lua_call(L, lua_gettop(L) - 3, 2);
677 if (lua_isnil(L, -2)) return 2;
678 if (!lua_tointeger(L, -2)) {
679 lua_pushvalue(L, 1);
680 return 1;
681 }
682 #if LUA_VERSION_NUM >= 503
683 return moonbr_io_write_cont(L, 0, 0);
684 #else
685 return moonbr_io_write_cont(L);
686 #endif
687 }
689 moonbr_io_yield_wrapper(moonbr_io_write_yield, moonbr_io_write_call);
691 static int moonbr_io_flush_call(lua_State *L) {
692 lua_pushcfunction(L, moonbr_io_flush_nb);
693 lua_insert(L, 3);
694 lua_pushvalue(L, 1);
695 lua_insert(L, 4);
696 lua_call(L, lua_gettop(L) - 3, 2);
697 if (lua_isnil(L, -2)) return 2;
698 if (!lua_tointeger(L, -2)) {
699 lua_pushvalue(L, 1);
700 return 1;
701 }
702 #if LUA_VERSION_NUM >= 503
703 return moonbr_io_write_cont(L, 0, 0);
704 #else
705 return moonbr_io_write_cont(L);
706 #endif
707 }
709 moonbr_io_yield_wrapper(moonbr_io_flush_yield, moonbr_io_flush_call);
711 static int moonbr_io_finish(lua_State *L) {
712 moonbr_io_handle_t *handle;
713 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
714 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
715 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
716 if (handle->writeleft) {
717 lua_pushcfunction(L, moonbr_io_flush);
718 lua_pushvalue(L, 1);
719 if (lua_pcall(L, 1, 2, 0)) {
720 handle->finished = 1;
721 lua_error(L);
722 }
723 if (!lua_toboolean(L, -2)) {
724 handle->finished = 1;
725 return 2;
726 }
727 }
728 handle->finished = 1;
729 #ifdef MOONBR_IO_USE_TLS
730 if ((handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) && !handle->tls) {
731 #else
732 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
733 #endif
734 if (shutdown(handle->fd, SHUT_WR)) moonbr_io_return_errmsg();
735 } else {
736 #ifdef MOONBR_IO_USE_TLS
737 if (handle->tls) {
738 int status;
739 if (moonbr_io_handle_set_nonblocking(L, handle, 1)) moonbr_io_return_errmsg();
740 do status = tls_close(handle->tls);
741 while (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT);
742 if (status) {
743 close(handle->fd);
744 handle->fd = -1;
745 lua_pushnil(L);
746 lua_pushstring(L, tls_error(handle->tls));
747 return 2;
748 }
749 }
750 #endif
751 if (close(handle->fd)) {
752 handle->fd = -1;
753 moonbr_io_return_errmsg();
754 }
755 handle->fd = -1; /* fake EOF on read */
756 }
757 lua_pushboolean(L, 1);
758 return 1;
759 }
761 static int moonbr_io_close_impl(lua_State *L, int nonblocking, int reset) {
762 moonbr_io_handle_t *handle;
763 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
764 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
765 if (!reset && handle->fd >= 0) {
766 if (handle->writeleft) {
767 lua_pushcfunction(L, nonblocking ? moonbr_io_flush_nb : moonbr_io_flush);
768 lua_pushvalue(L, 1);
769 if (lua_pcall(L, 1, 2, 0)) {
770 handle->closed = 1;
771 close(handle->fd);
772 handle->fd = -1;
773 lua_error(L);
774 }
775 if (!nonblocking) handle->closed = 1; /* TODO: handle nonblocking case */
776 if (!lua_toboolean(L, -2)) {
777 close(handle->fd);
778 handle->fd = -1;
779 return 2;
780 }
781 #if LUA_VERSION_NUM >= 503
782 if (nonblocking && lua_tointeger(L, -2)) {
783 #else
784 if (nonblocking && lua_tonumber(L, -2)) {
785 #endif
786 lua_pushliteral(L, "flush");
787 lua_pushvalue(L, -3);
788 return 2;
789 }
790 } else {
791 handle->closed = 1;
792 }
793 #ifdef MOONBR_IO_USE_TLS
794 if (handle->tls) {
795 int status;
796 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
797 do status = tls_close(handle->tls);
798 while (!nonblocking && (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT));
799 if (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT) {
800 handle->tlsclosing = status; /* TODO: handle polling */
801 lua_pushliteral(L, "close");
802 return 1;
803 }
804 if (status) {
805 close(handle->fd);
806 handle->fd = -1;
807 lua_pushnil(L);
808 lua_pushstring(L, tls_error(handle->tls));
809 return 2;
810 }
811 }
812 #endif
813 if (moonbr_io_handle_set_linger(L, handle, -1)) {
814 moonbr_io_prepare_errmsg();
815 close(handle->fd);
816 handle->fd = -1;
817 moonbr_io_return_prepared_errmsg();
818 }
819 } else {
820 handle->closed = 1;
821 }
822 if (handle->fd >= 0) {
823 if (close(handle->fd)) {
824 handle->fd = -1;
825 moonbr_io_return_errmsg();
826 }
827 handle->fd = -1;
828 }
829 lua_pushboolean(L, 1);
830 return 1;
832 }
834 static int moonbr_io_close(lua_State *L) {
835 return moonbr_io_close_impl(L, 0, 0);
836 }
838 static int moonbr_io_reset(lua_State *L) {
839 return moonbr_io_close_impl(L, 0, 1);
840 }
842 static int moonbr_io_handlegc(lua_State *L) {
843 moonbr_io_handle_t *handle;
844 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
845 if (handle->fd >= 0) {
846 lua_pushcfunction(L, moonbr_io_reset);
847 lua_pushvalue(L, 1);
848 lua_pushinteger(L, 0);
849 lua_call(L, 2, 0);
850 }
851 #ifdef MOONBR_IO_USE_TLS
852 if (handle->tls) {
853 tls_free(handle->tls);
854 handle->tls = NULL;
855 }
856 if (handle->servertls) {
857 tls_free(handle->servertls);
858 handle->servertls = NULL;
859 }
860 #endif
861 return 0;
862 }
864 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
865 moonbr_io_handle_t *handle;
866 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
867 if (!handle->closed) {
868 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
869 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
870 lua_call(L, 1, 0);
871 }
872 }
874 static int moonbr_io_pushhandle_impl(lua_State *L) {
875 int *fd;
876 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 child->status_valid = 0;
1371 lua_newtable(L);
1372 lua_setuservalue(L, -2);
1373 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1374 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1375 moonbr_io_prepare_errmsg();
1376 lua_pushnil(L);
1377 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1378 return 2;
1380 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1381 moonbr_io_prepare_errmsg();
1382 close(sockin[0]);
1383 close(sockin[1]);
1384 lua_pushnil(L);
1385 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1386 return 2;
1388 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1389 moonbr_io_prepare_errmsg();
1390 close(sockin[0]);
1391 close(sockin[1]);
1392 close(sockout[0]);
1393 close(sockout[1]);
1394 lua_pushnil(L);
1395 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1396 return 2;
1398 child->pid = vfork();
1399 if (child->pid == -1) {
1400 moonbr_io_prepare_errmsg();
1401 close(sockin[0]);
1402 close(sockin[1]);
1403 close(sockout[0]);
1404 close(sockout[1]);
1405 close(sockerr[0]);
1406 close(sockerr[1]);
1407 lua_pushnil(L);
1408 lua_pushfstring(L, "Could not fork: %s", errmsg);
1409 return 2;
1411 if (!child->pid) {
1412 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1413 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1414 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1415 closefrom(3);
1416 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1417 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1418 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1419 if (execvp(argv[0], argv)) {
1420 errorcond = 2;
1421 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1422 _exit(0);
1424 moonbr_io_exec_error1:
1425 errorcond = 1;
1426 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1427 _exit(0);
1429 close(sockin[1]);
1430 close(sockout[1]);
1431 close(sockerr[1]);
1432 if (errorcond) {
1433 int status;
1434 close(sockin[0]);
1435 close(sockout[0]);
1436 close(sockerr[0]);
1437 while (waitpid(child->pid, &status, 0) == -1) {
1438 if (errno != EINTR) {
1439 moonbr_io_prepare_errmsg();
1440 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1443 child->pid = 0;
1444 lua_pushnil(L);
1445 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1446 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1447 return 2;
1449 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1450 lua_pushlightuserdata(L, &sockin[0]);
1451 if (lua_pcall(L, 1, 1, 0)) {
1452 if (sockin[0] != -1) close(sockin[0]);
1453 close(sockout[0]);
1454 close(sockerr[0]);
1455 goto moonbr_io_exec_error2;
1457 lua_setfield(L, -2, "stdin");
1458 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1459 lua_pushlightuserdata(L, &sockout[0]);
1460 if (lua_pcall(L, 1, 1, 0)) {
1461 if (sockout[0] != -1) close(sockout[0]);
1462 close(sockerr[0]);
1463 goto moonbr_io_exec_error2;
1465 lua_setfield(L, -2, "stdout");
1466 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1467 lua_pushlightuserdata(L, &sockerr[0]);
1468 if (lua_pcall(L, 1, 1, 0)) {
1469 if (sockerr[0] != -1) close(sockerr[0]);
1470 goto moonbr_io_exec_error2;
1472 lua_setfield(L, -2, "stderr");
1473 return 1;
1474 moonbr_io_exec_error2:
1476 int status;
1477 while (waitpid(child->pid, &status, 0) == -1) {
1478 if (errno != EINTR) {
1479 moonbr_io_prepare_errmsg();
1480 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1484 child->pid = 0;
1485 return lua_error(L);
1488 static int moonbr_io_childindex(lua_State *L) {
1489 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1490 luaL_checkany(L, 2);
1491 lua_getuservalue(L, 1);
1492 lua_pushvalue(L, 2);
1493 lua_gettable(L, -2);
1494 if (lua_isnil(L, -1)) {
1495 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1496 lua_pushvalue(L, 2);
1497 lua_gettable(L, -2);
1499 return 1;
1502 static int moonbr_io_childnewindex(lua_State *L) {
1503 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1504 luaL_checkany(L, 2);
1505 luaL_checkany(L, 3);
1506 lua_getuservalue(L, 1);
1507 lua_pushvalue(L, 2);
1508 lua_pushvalue(L, 3);
1509 lua_settable(L, -3);
1510 return 0;
1513 static int moonbr_io_childgc(lua_State *L) {
1514 moonbr_io_child_t *child;
1515 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1516 if (child->pid) {
1517 int status;
1518 int pid = child->pid;
1519 child->pid = 0;
1520 if (kill(pid, SIGKILL)) {
1521 moonbr_io_prepare_errmsg();
1522 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1524 while (waitpid(pid, &status, 0) == -1) {
1525 if (errno != EINTR) {
1526 moonbr_io_prepare_errmsg();
1527 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1531 return 0;
1534 static int moonbr_io_kill(lua_State *L) {
1535 moonbr_io_child_t *child;
1536 int sig;
1537 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1538 sig = luaL_optinteger(L, 2, SIGKILL);
1539 if (!child->pid) {
1540 if (!child->status_valid) luaL_error(L, "Attempt to kill an already collected child process");
1541 } else {
1542 if (kill(child->pid, sig)) {
1543 moonbr_io_prepare_errmsg();
1544 luaL_error(L, "Error in kill call: %s", errmsg);
1547 lua_settop(L, 1);
1548 return 1;
1551 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1552 moonbr_io_child_t *child;
1553 int status;
1554 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1555 if (!child->pid) {
1556 if (!child->status_valid) luaL_error(L, "Attempt to wait for an already collected child process");
1557 status = child->status;
1558 child->status_valid = 0;
1559 } else {
1560 pid_t waitedpid;
1561 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1562 if (errno != EINTR) {
1563 moonbr_io_prepare_errmsg();
1564 luaL_error(L, "Error in waitpid call: %s", errmsg);
1567 if (!waitedpid) {
1568 lua_pushboolean(L, 0);
1569 lua_pushliteral(L, "Process is still running");
1570 return 2;
1572 child->pid = 0;
1574 if (WIFEXITED(status)) {
1575 lua_pushinteger(L, WEXITSTATUS(status));
1576 } else if (WIFSIGNALED(status)) {
1577 lua_pushinteger(L, -WTERMSIG(status));
1578 } else {
1579 luaL_error(L, "Unexpected status value returned by waitpid call");
1581 return 1;
1584 static int moonbr_io_wait(lua_State *L) {
1585 return moonbr_io_wait_impl(L, 0);
1588 static int moonbr_io_wait_nb(lua_State *L) {
1589 return moonbr_io_wait_impl(L, 1);
1592 #if LUA_VERSION_NUM >= 503
1593 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1594 #else
1595 static int moonbr_io_wait_cont(lua_State *L) {
1596 #endif
1597 #if !(LUA_VERSION_NUM >= 503)
1598 int ctx = 0;
1599 lua_getctx(L, &ctx);
1600 #endif
1601 while (1) {
1602 lua_pushcfunction(L, moonbr_io_wait_nb);
1603 lua_pushvalue(L, 1);
1604 lua_call(L, 1, 1);
1605 if (!lua_isnil(L, -1)) break;
1606 lua_pushvalue(L, 2);
1607 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1609 return 1;
1612 static int moonbr_io_wait_call(lua_State *L) {
1613 lua_settop(L, 2);
1614 #if LUA_VERSION_NUM >= 503
1615 return moonbr_io_wait_cont(L, 0, 0);
1616 #else
1617 return moonbr_io_wait_cont(L);
1618 #endif
1621 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1623 static void moonbr_io_sigterm_handler(int sig) {
1624 moonbr_io_sigterm_flag = 1;
1627 static void moonbr_io_sigchld_handler(int sig) {
1628 moonbr_io_sigchld_flag = 1;
1631 int moonbr_io_catch_sigterm(lua_State *L) {
1632 signal(SIGTERM, moonbr_io_sigterm_handler);
1633 return 0;
1636 static int moonbr_io_getpid(lua_State *L) {
1637 lua_pushinteger(L, getpid());
1638 return 1;
1641 #ifdef MOONBR_IO_USE_TLS
1643 #define moonbr_io_poll_tls() \
1644 if (!handle->tlshandshake) { \
1645 force_wakeup = 1; \
1646 continue; \
1647 } \
1648 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1649 if (fd < 0) { \
1650 force_wakeup = 1; \
1651 continue; \
1652 } \
1653 FD_SET(fd, &readfds); \
1654 if (fd+1 > nfds) nfds = fd+1; \
1655 continue; \
1656 } \
1657 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1658 if (fd < 0) { \
1659 force_wakeup = 1; \
1660 continue; \
1661 } \
1662 FD_SET(fd, &writefds); \
1663 if (fd+1 > nfds) nfds = fd+1; \
1664 continue; \
1665 } \
1666 while (0)
1668 #endif /* MOONBR_IO_USE_TLS */
1670 static int moonbr_io_poll(lua_State *L) {
1671 moonbr_io_handle_t *handle;
1672 moonbr_io_listener_t *listener;
1673 moonbr_io_child_t *child;
1674 int fd, isnum;
1675 int nfds = 0;
1676 fd_set readfds, writefds, exceptfds;
1677 struct timespec timeout = {0, };
1678 int force_wakeup = 0;
1679 int use_timeout = 0; // negative for negative timeout
1680 int check_sigterm = 0;
1681 int check_sigchld = 0;
1682 pid_t waitedpid;
1683 sigset_t mask, orig_mask;
1684 int status;
1685 FD_ZERO(&readfds);
1686 FD_ZERO(&writefds);
1687 FD_ZERO(&exceptfds);
1688 if (!lua_isnoneornil(L, 1)) {
1689 luaL_checktype(L, 1, LUA_TTABLE);
1690 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1691 if (lua_toboolean(L, -1)) {
1692 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1693 if (handle) {
1694 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1695 fd = handle->fd;
1696 #if MOONBR_IO_USE_TLS
1697 moonbr_io_poll_tls();
1698 #endif
1699 if (
1700 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1701 handle->readbufin != handle->readbufout /* data pending in buffer */
1702 ) {
1703 force_wakeup = 1;
1704 continue;
1706 } else {
1707 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1708 if (listener) {
1709 fd = listener->fd;
1710 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1711 } else {
1712 child = luaL_testudata(L, -2, MOONBR_IO_CHILD_MT_REGKEY);
1713 if (child) {
1714 if (!child->pid) luaL_error(L, "Attemt to poll an already collected child process");
1715 if (!check_sigchld) {
1716 check_sigchld = 1;
1717 moonbr_io_sigchld_flag = 0;
1718 signal(SIGCHLD, moonbr_io_sigchld_handler);
1720 if (child->status_valid) {
1721 force_wakeup = 1;
1722 } else {
1723 while ((waitedpid = waitpid(child->pid, &status, WNOHANG)) == -1) {
1724 if (errno != EINTR) {
1725 moonbr_io_prepare_errmsg();
1726 luaL_error(L, "Error in waitpid call: %s", errmsg);
1729 if (waitedpid) {
1730 child->pid = 0;
1731 child->status = status;
1732 child->status_valid = 1;
1733 force_wakeup = 1;
1736 continue;
1737 } else {
1738 fd = lua_tointegerx(L, -2, &isnum);
1739 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1743 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1744 FD_SET(fd, &readfds);
1745 if (fd+1 > nfds) nfds = fd+1;
1749 if (!lua_isnoneornil(L, 2)) {
1750 luaL_checktype(L, 2, LUA_TTABLE);
1751 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1752 if (lua_toboolean(L, -1)) {
1753 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1754 if (handle) {
1755 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1756 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1757 fd = handle->fd;
1758 #if MOONBR_IO_USE_TLS
1759 moonbr_io_poll_tls();
1760 #endif
1761 } else {
1762 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1763 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1764 fd = lua_tointegerx(L, -2, &isnum);
1765 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1767 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1768 FD_SET(fd, &writefds);
1769 if (fd+1 > nfds) nfds = fd+1;
1773 if (!lua_isnoneornil(L, 3)) {
1774 lua_Number n;
1775 n = lua_tonumberx(L, 3, &isnum);
1776 if (isnum && n<0) {
1777 use_timeout = -1;
1778 } else if (isnum && n>=0 && n<100000000) {
1779 use_timeout = 1;
1780 timeout.tv_sec = n;
1781 timeout.tv_nsec = 1e9 * (n - timeout.tv_sec);
1782 } else {
1783 luaL_argcheck(L, 0, 3, "not a valid timeout");
1786 if (use_timeout < 0) force_wakeup = 1;
1787 if (!lua_isnoneornil(L, 4)) luaL_checktype(L, 4, LUA_TBOOLEAN);
1788 check_sigterm = lua_toboolean(L, 4);
1789 if ((check_sigterm || check_sigchld) && !force_wakeup) {
1790 sigemptyset(&mask);
1791 if (check_sigterm) sigaddset(&mask, SIGTERM);
1792 if (check_sigchld) sigaddset(&mask, SIGCHLD);
1793 if (sigprocmask(SIG_BLOCK, &mask, &orig_mask)) abort();
1795 if (check_sigterm && moonbr_io_sigterm_flag) {
1796 if (!force_wakeup) {
1797 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1799 lua_pushboolean(L, 0);
1800 lua_pushliteral(L, "SIGTERM received");
1801 lua_pushboolean(L, 1);
1802 return 3;
1804 if (check_sigchld && !force_wakeup && moonbr_io_sigchld_flag) {
1805 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1806 force_wakeup = 1;
1808 if (use_timeout < 0) {
1809 lua_pushboolean(L, 0);
1810 lua_pushliteral(L, "Timeout");
1811 if (check_sigterm) {
1812 lua_pushboolean(L, 0);
1813 return 3;
1814 } else {
1815 return 2;
1818 if (!force_wakeup) {
1819 status = pselect(
1820 nfds, &readfds, &writefds, &exceptfds,
1821 use_timeout ? &timeout : NULL,
1822 (check_sigterm || check_sigchld) ? &orig_mask : NULL
1823 );
1824 if (check_sigterm || check_sigchld) {
1825 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1826 if (check_sigterm && moonbr_io_sigterm_flag) {
1827 lua_pushboolean(L, 0);
1828 lua_pushliteral(L, "SIGTERM received");
1829 lua_pushboolean(L, 1);
1830 return 3;
1833 if (status == -1) {
1834 if (errno == EINTR) {
1835 lua_pushboolean(L, 1);
1836 return 1;
1837 } else {
1838 moonbr_io_prepare_errmsg();
1839 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1841 } else if (status == 0) {
1842 lua_pushboolean(L, 0);
1843 lua_pushliteral(L, "Timeout");
1844 if (check_sigterm) {
1845 lua_pushboolean(L, 0);
1846 return 3;
1847 } else {
1848 return 2;
1852 lua_pushboolean(L, 1);
1853 return 1;
1856 static int moonbr_io_timeref(lua_State *L) {
1857 lua_Number sub;
1858 struct timespec tp;
1859 sub = luaL_optnumber(L, 1, 0);
1860 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1861 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1863 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1864 return 1;
1867 #ifdef MOONBR_IO_USE_TLS
1869 #define moonbr_io_tlsconf_string(name, field, func) \
1870 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1871 lua_getfield(L, 1, (field)); \
1872 valuetype = lua_type(L, -1); \
1873 if (valuetype != LUA_TNIL) { \
1874 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1875 value = lua_tostring(L, -1); \
1876 if (func(tlsconf->config, value)) { \
1877 lua_pushnil(L); \
1878 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1879 return 2; \
1880 } \
1881 } \
1882 lua_pop(L, 1);
1884 #define moonbr_io_tlsconf_binary(name, field, func) \
1885 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1886 lua_getfield(L, 1, (field)); \
1887 valuetype = lua_type(L, -1); \
1888 if (valuetype != LUA_TNIL) { \
1889 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1890 value = lua_tolstring(L, -1, &valuelen); \
1891 if (func(tlsconf->config, (void *)value, valuelen)) { \
1892 lua_pushnil(L); \
1893 lua_pushliteral(L, "Could not set " name); \
1894 return 2; \
1895 } \
1896 } \
1897 lua_pop(L, 1);
1899 static int moonbr_io_tlsconf(lua_State *L) {
1900 moonbr_io_tlsconf_t *tlsconf;
1901 int valuetype;
1902 const char *value;
1903 size_t valuelen;
1904 luaL_checktype(L, 1, LUA_TTABLE);
1905 tlsconf = lua_newuserdata(L, sizeof(moonbr_io_tlsconf_t));
1906 tlsconf->config = tls_config_new();
1907 if (!tlsconf->config) {
1908 return luaL_error(L, "Could not allocate memory for TLS configuration");
1910 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
1911 lua_getfield(L, 1, "mode");
1912 value = lua_tostring(L, -1);
1913 if (value && !strcmp(value, "server")) tlsconf->server = 1;
1914 else if (value && !strcmp(value, "client")) tlsconf->server = 0;
1915 else luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
1916 lua_pop(L, 1);
1917 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
1918 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
1919 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
1920 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
1921 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
1922 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
1923 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
1924 #if LUA_VERSION_NUM >= 503
1925 valuetype = lua_getfield(L, 1, "verify_client");
1926 #else
1927 lua_getfield(L, 1, "verify_client");
1928 #endif
1929 if (lua_toboolean(L, -1)) {
1930 value = lua_tostring(L, -1);
1931 if (value && !strcmp(value, "required")) {
1932 tls_config_verify_client(tlsconf->config);
1933 } else if (value && !strcmp(value, "optional")) {
1934 tls_config_verify_client_optional(tlsconf->config);
1935 } else {
1936 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
1939 lua_pop(L, 1);
1940 // TODO: configurable legacy support
1941 // tls_config_set_protocols(tlsconf->config, TLS_PROTOCOLS_ALL);
1942 // tls_config_set_ciphers(tlsconf->config, "legacy");
1943 return 1;
1946 static int moonbr_io_tlsconfgc(lua_State *L) {
1947 moonbr_io_tlsconf_t *tlsconf;
1948 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
1949 if (tlsconf->config) tls_config_free(tlsconf->config);
1950 tlsconf->config = NULL;
1951 return 0;
1954 static int moonbr_io_starttls(lua_State *L) {
1955 moonbr_io_handle_t *handle;
1956 moonbr_io_tlsconf_t *tlsconf;
1957 const char *servername;
1958 struct tls *tls, *tls2;
1959 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1960 if (lua_type(L, 2) == LUA_TTABLE) {
1961 lua_pushcfunction(L, moonbr_io_tlsconf);
1962 lua_pushvalue(L, 2);
1963 lua_call(L, 1, 2);
1964 if (lua_isnil(L, -2)) return 2;
1965 lua_pop(L, 1);
1966 lua_replace(L, 2);
1968 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
1969 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
1970 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
1971 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
1972 if (handle->readbufin || handle->writebufin) {
1973 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
1975 if (tlsconf->server) tls = tls_server();
1976 else {
1977 servername = luaL_checkstring(L, 3);
1978 tls = tls_client();
1980 if (!tls) {
1981 return luaL_error(L, "Could not allocate memory for TLS context");
1983 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
1984 if (tlsconf->server) {
1985 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
1986 handle->servertls = tls;
1987 handle->tls = tls2;
1988 } else {
1989 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
1990 handle->tls = tls;
1992 lua_settop(L, 1);
1993 return 1;
1994 moonbr_io_starttls_error:
1995 lua_pushnil(L);
1996 lua_pushstring(L, tls_error(tls));
1997 tls_free(tls);
1998 return 2;
2001 #endif /* MOONBR_IO_USE_TLS */
2003 static const struct luaL_Reg moonbr_io_handle_methods[] = {
2004 {"read", moonbr_io_read},
2005 {"read_nb", moonbr_io_read_nb},
2006 {"read_call", moonbr_io_read_call},
2007 {"read_yield", moonbr_io_read_yield},
2008 {"drain", moonbr_io_drain},
2009 {"drain_nb", moonbr_io_drain_nb},
2010 {"drain_call", moonbr_io_drain_call},
2011 {"drain_yield", moonbr_io_drain_yield},
2012 {"write", moonbr_io_write},
2013 {"write_nb", moonbr_io_write_nb},
2014 {"write_call", moonbr_io_write_call},
2015 {"write_yield", moonbr_io_write_yield},
2016 {"flush", moonbr_io_flush},
2017 {"flush_nb", moonbr_io_flush_nb},
2018 {"flush_call", moonbr_io_flush_call},
2019 {"flush_yield", moonbr_io_flush_yield},
2020 {"finish", moonbr_io_finish},
2021 {"close", moonbr_io_close},
2022 {"reset", moonbr_io_reset},
2023 #ifdef MOONBR_IO_USE_TLS
2024 {"starttls", moonbr_io_starttls},
2025 #endif
2026 {NULL, NULL}
2027 };
2029 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
2030 {"__index", moonbr_io_handleindex},
2031 {"__newindex", moonbr_io_handlenewindex},
2032 {"__gc", moonbr_io_handlegc},
2033 {NULL, NULL}
2034 };
2036 static const struct luaL_Reg moonbr_io_listener_methods[] = {
2037 {"accept", moonbr_io_accept},
2038 {"accept_nb", moonbr_io_accept_nb},
2039 {"close", moonbr_io_unlisten},
2040 {NULL, NULL}
2041 };
2043 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
2044 {"__gc", moonbr_io_listenergc},
2045 {NULL, NULL}
2046 };
2048 static const struct luaL_Reg moonbr_io_child_methods[] = {
2049 {"kill", moonbr_io_kill},
2050 {"wait", moonbr_io_wait},
2051 {"wait_nb", moonbr_io_wait_nb},
2052 {"wait_call", moonbr_io_wait_call},
2053 {"wait_yield", moonbr_io_wait_yield},
2054 {NULL, NULL}
2055 };
2057 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
2058 {"__index", moonbr_io_childindex},
2059 {"__newindex", moonbr_io_childnewindex},
2060 {"__gc", moonbr_io_childgc},
2061 {NULL, NULL}
2062 };
2064 static const struct luaL_Reg moonbr_io_module_funcs[] = {
2065 {"localconnect", moonbr_io_localconnect},
2066 {"localconnect_nb", moonbr_io_localconnect_nb},
2067 {"tcpconnect", moonbr_io_tcpconnect},
2068 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2069 {"locallisten", moonbr_io_locallisten},
2070 {"tcplisten", moonbr_io_tcplisten},
2071 {"exec", moonbr_io_exec},
2072 {"catch_sigterm", moonbr_io_catch_sigterm},
2073 {"getpid", moonbr_io_getpid},
2074 {"poll", moonbr_io_poll},
2075 {"timeref", moonbr_io_timeref},
2076 #ifdef MOONBR_IO_USE_TLS
2077 {"tlsconf", moonbr_io_tlsconf},
2078 #endif
2079 {NULL, NULL}
2080 };
2082 #ifdef MOONBR_IO_USE_TLS
2084 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2085 {"__gc", moonbr_io_tlsconfgc},
2086 {NULL, NULL}
2087 };
2089 #endif /* MOONBR_IO_USE_TLS */
2091 int luaopen_moonbridge_io(lua_State *L) {
2093 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2095 lua_newtable(L); // module
2097 lua_newtable(L); // public metatable
2098 lua_newtable(L); // handle methods
2099 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2100 lua_pushvalue(L, -1);
2101 lua_setfield(L, -4, "handle_pt");
2102 lua_setfield(L, -2, "__index");
2103 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2105 lua_newtable(L); // handle metatable
2106 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2107 lua_pushvalue(L, -1);
2108 lua_setfield(L, -3, "handle_mt");
2109 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2111 lua_newtable(L); // listener metatable
2112 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2113 lua_newtable(L); // listener methods
2114 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2115 lua_pushvalue(L, -1);
2116 lua_setfield(L, -4, "listener_pt");
2117 lua_setfield(L, -2, "__index");
2118 lua_pushvalue(L, -1);
2119 lua_setfield(L, -3, "listener_mt");
2120 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2122 lua_newtable(L); // child methods
2123 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2124 lua_pushvalue(L, -1);
2125 lua_setfield(L, -3, "child_pt");
2126 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2127 lua_newtable(L); // child metatable
2128 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2129 lua_pushvalue(L, -1);
2130 lua_setfield(L, -3, "child_mt");
2131 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2133 #ifdef MOONBR_IO_USE_TLS
2134 if(tls_init()) {
2135 return luaL_error(L, "Could not initialize TLS library");
2137 lua_newtable(L); // tlsconf metatable
2138 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2139 lua_pushvalue(L, -1);
2140 lua_setfield(L, -3, "tlsconf_mt");
2141 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2142 #endif
2144 moonbr_io_pushhandle(L, 0);
2145 lua_setfield(L, -2, "stdin");
2146 moonbr_io_pushhandle(L, 1);
2147 lua_setfield(L, -2, "stdout");
2148 moonbr_io_pushhandle(L, 2);
2149 lua_setfield(L, -2, "stderr");
2151 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2152 return 1;

Impressum / About Us