moonbridge

view moonbridge_io.c @ 315:15132b3c053d

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

Impressum / About Us