moonbridge

view moonbridge_io.c @ 290:70f047d32a0f

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

Impressum / About Us