moonbridge

view moonbridge_io.c @ 284:28aab22e68b6

New implementation of SIGTERM handling
author jbe
date Sun Jun 11 00:02:43 2017 +0200 (2017-06-11)
parents 6bb191b6ead5
children a7395fb91ec3
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"
63 #define MOONBR_IO_SIGNALS_REGKEY "moonbridge_io_signals"
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 } moonbr_io_child_t;
120 static volatile sig_atomic_t moonbr_io_sigterm_flag = 0;
122 static int moonbr_io_yield(lua_State *L) {
123 return lua_yield(L, lua_gettop(L));
124 }
126 #if LUA_VERSION_NUM >= 503
127 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
128 #else
129 static int moonbr_io_cont_returnall(lua_State *L) {
130 #endif
131 return lua_gettop(L);
132 }
134 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
135 static int yieldfunc(lua_State *L) { \
136 int args; \
137 lua_pushcfunction(L, callfunc); \
138 lua_insert(L, 1); \
139 args = lua_gettop(L); \
140 lua_pushcfunction(L, moonbr_io_yield); \
141 lua_insert(L, 3); \
142 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
143 return lua_gettop(L); \
144 }
146 static int moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
147 int flags;
148 if (handle->nonblocking == nonblocking) return 0;
149 flags = fcntl(handle->fd, F_GETFL, 0);
150 if (flags == -1) return -1;
151 if (nonblocking) flags |= O_NONBLOCK;
152 else flags &= ~O_NONBLOCK;
153 if (fcntl(handle->fd, F_SETFL, flags) == -1) return -1;
154 handle->nonblocking = nonblocking;
155 return 0;
156 }
158 static int moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
159 struct linger lingerval = { 0, };
160 if (!handle->issock) return 0;
161 if (timeout >= 0) {
162 lingerval.l_onoff = 1;
163 lingerval.l_linger = timeout;
164 }
165 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) return -1;
166 return 0;
167 }
169 static inline int moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
170 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
171 if (
172 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
173 handle->nopush == nopush
174 ) return 0;
175 #if defined(TCP_NOPUSH)
176 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) return -1;
177 #elif defined(TCP_CORK)
178 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) return -1;
179 #endif
180 handle->nopush = nopush;
181 #else
182 #warning Neither TCP_NOPUSH nor TCP_CORK is available
183 #endif
184 return 0;
185 }
187 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
188 moonbr_io_handle_t *handle;
189 lua_Integer maxread;
190 const char *terminatorstr;
191 size_t terminatorlen;
192 char terminator = 0; /* initialize to avoid compiler warning */
193 luaL_Buffer luabuf;
194 size_t luabufcnt = 0;
195 int remaining;
196 char *terminatorpos;
197 ssize_t bytesread;
198 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
199 maxread = luaL_optinteger(L, 2, -1);
200 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
201 if (terminatorlen) {
202 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
203 terminator = terminatorstr[0];
204 }
205 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
206 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
207 if (handle->readerr) {
208 lua_pushnil(L);
209 lua_pushliteral(L, "Previous read error");
210 return 2;
211 }
212 if (handle->fd < 0) {
213 /* fake EOF to simulate shutdown */
214 if (!drain) lua_pushliteral(L, "");
215 else lua_pushinteger(L, 0);
216 lua_pushliteral(L, "eof");
217 return 2;
218 }
219 handle->readerr = 1;
220 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
221 if (!drain) luaL_buffinit(L, &luabuf);
222 while (1) {
223 remaining = -1;
224 terminatorpos = NULL;
225 if (
226 maxread >= 0 &&
227 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
228 ) {
229 remaining = (size_t)maxread - luabufcnt;
230 if (terminatorlen) {
231 terminatorpos = memchr(
232 handle->readbuf + handle->readbufout,
233 terminator,
234 remaining
235 );
236 }
237 } else if (terminatorlen) {
238 terminatorpos = memchr(
239 handle->readbuf + handle->readbufout,
240 terminator,
241 handle->readbufin - handle->readbufout
242 );
243 }
244 if (terminatorpos) remaining = 1 + (
245 terminatorpos - (handle->readbuf + handle->readbufout)
246 );
247 if (remaining >= 0) {
248 if (!drain) {
249 luaL_addlstring(
250 &luabuf,
251 handle->readbuf + handle->readbufout,
252 remaining
253 );
254 luaL_pushresult(&luabuf);
255 } else {
256 lua_pushinteger(L, luabufcnt + remaining);
257 }
258 if (terminatorpos) lua_pushliteral(L, "term");
259 else lua_pushliteral(L, "maxlen");
260 handle->readbufout += remaining;
261 if (handle->readbufout == handle->readbufin) {
262 handle->readbufin = 0;
263 handle->readbufout = 0;
264 }
265 handle->readerr = 0;
266 return 2;
267 }
268 if (!drain) luaL_addlstring(
269 &luabuf,
270 handle->readbuf + handle->readbufout,
271 handle->readbufin - handle->readbufout
272 );
273 luabufcnt += handle->readbufin - handle->readbufout;
274 handle->readbufout = 0;
275 #ifdef MOONBR_IO_USE_TLS
276 if (handle->tls) {
277 do {
278 if (!handle->tlshandshake) {
279 do bytesread = tls_handshake(handle->tls);
280 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
281 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
282 handle->tlshandshake = bytesread;
283 errno = EAGAIN;
284 break;
285 }
286 if (bytesread < 0) {
287 lua_pushnil(L);
288 lua_pushstring(L, tls_error(handle->tls));
289 return 2;
290 }
291 handle->tlshandshake = 1;
292 }
293 do bytesread = tls_read(handle->tls, handle->readbuf, MOONBR_IO_READBUFLEN);
294 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
295 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
296 errno = EAGAIN;
297 break;
298 }
299 if (bytesread < 0) {
300 lua_pushnil(L);
301 lua_pushstring(L, tls_error(handle->tls));
302 return 2;
303 }
304 } while (0);
305 }
306 else
307 #endif
308 do bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
309 while (bytesread < 0 && (errno == EINTR));
310 if (
311 bytesread == 0 || (
312 nonblocking &&
313 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
314 )
315 ) {
316 handle->readbufin = 0;
317 if (!drain) luaL_pushresult(&luabuf);
318 else lua_pushinteger(L, luabufcnt);
319 if (bytesread == 0) lua_pushliteral(L, "eof");
320 else lua_pushliteral(L, "block");
321 handle->readerr = 0;
322 return 2;
323 }
324 if (bytesread < 0) moonbr_io_return_errmsg();
325 handle->readbufin = bytesread;
326 }
327 }
329 static int moonbr_io_read(lua_State *L) {
330 return moonbr_io_read_impl(L, 0, 0);
331 }
333 static int moonbr_io_read_nb(lua_State *L) {
334 return moonbr_io_read_impl(L, 1, 0);
335 }
337 static int moonbr_io_drain(lua_State *L) {
338 return moonbr_io_read_impl(L, 0, 1);
339 }
341 static int moonbr_io_drain_nb(lua_State *L) {
342 return moonbr_io_read_impl(L, 1, 1);
343 }
345 #if LUA_VERSION_NUM >= 503
346 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
347 #else
348 static int moonbr_io_read_cont(lua_State *L) {
349 #endif
350 lua_Integer remaining;
351 size_t len;
352 #if !(LUA_VERSION_NUM >= 503)
353 int ctx = 0;
354 lua_getctx(L, &ctx);
355 #endif
356 remaining = lua_tointeger(L, 3);
357 while (1) {
358 lua_pushcfunction(L, moonbr_io_read_nb);
359 lua_pushvalue(L, 1);
360 lua_pushvalue(L, 3);
361 lua_pushvalue(L, 4);
362 lua_call(L, 3, 2);
363 if (lua_isnil(L, -2)) return 2;
364 lua_insert(L, -2);
365 len = lua_rawlen(L, -1);
366 if (ctx == 0) {
367 lua_replace(L, 5);
368 ctx = 1;
369 } else if (ctx == 1) {
370 lua_pushvalue(L, 5);
371 lua_newtable(L);
372 lua_replace(L, 5);
373 lua_rawseti(L, 5, 2);
374 lua_rawseti(L, 5, 1);
375 ctx = 2;
376 } else {
377 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
378 }
379 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
380 lua_pop(L, 1);
381 if (remaining >= 0 && len) {
382 remaining -= len;
383 lua_pushinteger(L, remaining);
384 lua_replace(L, 3);
385 }
386 lua_pushvalue(L, 2);
387 lua_callk(L, 0, 0, ctx, moonbr_io_read_cont);
388 }
389 if (ctx == 1) {
390 lua_pushvalue(L, 5);
391 } else {
392 luaL_Buffer buf;
393 lua_Integer i, chunkcount;
394 chunkcount = lua_rawlen(L, 5);
395 luaL_buffinit(L, &buf);
396 for (i=1; i<=chunkcount && i>0; i++) {
397 lua_rawgeti(L, 5, i);
398 luaL_addvalue(&buf);
399 }
400 luaL_pushresult(&buf);
401 }
402 lua_pushvalue(L, -2);
403 return 2;
404 }
406 static int moonbr_io_read_call(lua_State *L) {
407 lua_settop(L, 4);
408 lua_pushnil(L);
409 #if LUA_VERSION_NUM >= 503
410 return moonbr_io_read_cont(L, 0, 0);
411 #else
412 return moonbr_io_read_cont(L);
413 #endif
414 }
416 moonbr_io_yield_wrapper(moonbr_io_read_yield, moonbr_io_read_call);
418 #if LUA_VERSION_NUM >= 503
419 static int moonbr_io_drain_cont(lua_State *L, int status, lua_KContext ctx) {
420 #else
421 static int moonbr_io_drain_cont(lua_State *L) {
422 #endif
423 lua_Integer remaining, len;
424 size_t totallen = 0;
425 #if !(LUA_VERSION_NUM >= 503)
426 int ctx = 0;
427 lua_getctx(L, &ctx);
428 #endif
429 remaining = lua_tointeger(L, 3);
430 while (1) {
431 lua_pushcfunction(L, moonbr_io_drain_nb);
432 lua_pushvalue(L, 1);
433 lua_pushvalue(L, 3);
434 lua_pushvalue(L, 4);
435 lua_call(L, 3, 2);
436 if (lua_isnil(L, -2)) return 2;
437 lua_insert(L, -2);
438 len = lua_tointeger(L, -1);
439 lua_pop(L, 1);
440 totallen += len;
441 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
442 lua_pop(L, 1);
443 if (remaining >= 0 && len) {
444 remaining -= len;
445 lua_pushinteger(L, remaining);
446 lua_replace(L, 3);
447 }
448 lua_pushvalue(L, 2);
449 lua_callk(L, 0, 0, ctx, moonbr_io_drain_cont);
450 }
451 lua_pushinteger(L, totallen);
452 lua_pushvalue(L, -2);
453 return 2;
454 }
456 static int moonbr_io_drain_call(lua_State *L) {
457 #if LUA_VERSION_NUM >= 503
458 return moonbr_io_drain_cont(L, 0, 0);
459 #else
460 return moonbr_io_drain_cont(L);
461 #endif
462 }
464 moonbr_io_yield_wrapper(moonbr_io_drain_yield, moonbr_io_drain_call);
466 #ifdef MOONBR_IO_USE_TLS
468 #define moonbr_io_write_tls(buf, buflen) \
469 if (handle->tls) { \
470 do { \
471 if (!handle->tlshandshake) { \
472 do written = tls_handshake(handle->tls); \
473 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
474 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
475 handle->tlshandshake = written; \
476 errno = EAGAIN; \
477 break; \
478 } \
479 if (written < 0) { \
480 lua_pushnil(L); \
481 lua_pushstring(L, tls_error(handle->tls)); \
482 return 2; \
483 } \
484 handle->tlshandshake = 1; \
485 } \
486 do written = tls_write(handle->tls, (buf), (buflen)); \
487 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
488 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
489 errno = EAGAIN; \
490 break; \
491 } \
492 if (written < 0) { \
493 lua_pushnil(L); \
494 lua_pushstring(L, tls_error(handle->tls)); \
495 return 2; \
496 } \
497 } while (0); \
498 } \
499 else
501 #endif /* MOONBR_IO_USE_TLS */
503 static int moonbr_io_write_impl(lua_State *L, int nonblocking, int flush) {
504 moonbr_io_handle_t *handle;
505 int i, top;
506 const char *str;
507 size_t strlen;
508 ssize_t written;
509 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
510 if (handle->closed) luaL_error(L, "Attempt to write to a closed I/O handle");
511 if (handle->finished) luaL_error(L, "Attempt to write to a finished I/O handle");
512 if (handle->writeerr) {
513 lua_pushnil(L);
514 lua_pushliteral(L, "Previous write error");
515 return 2;
516 }
517 handle->writeerr = 1;
518 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
519 top = lua_gettop(L);
520 lua_getuservalue(L, 1);
521 lua_getfield(L, -1, "writequeue");
522 for (i=2; i<=top; i++) {
523 luaL_checklstring(L, i, &strlen);
524 lua_pushvalue(L, i);
525 lua_rawseti(L, -2, handle->writeqin++);
526 handle->writeleft += strlen;
527 }
528 if (flush) handle->flushedleft = handle->writeleft;
529 while (handle->writeqout != handle->writeqin) {
530 lua_rawgeti(L, -1, handle->writeqout);
531 str = lua_tolstring(L, -1, &strlen);
532 while (handle->writeqoff < strlen) {
533 if (
534 strlen - handle->writeqoff <
535 MOONBR_IO_WRITEBUFLEN - handle->writebufin
536 ) {
537 memcpy(
538 handle->writebuf + handle->writebufin,
539 str + handle->writeqoff,
540 strlen - handle->writeqoff
541 );
542 handle->writebufin += strlen - handle->writeqoff;
543 break;
544 } else {
545 memcpy(
546 handle->writebuf + handle->writebufin,
547 str + handle->writeqoff,
548 MOONBR_IO_WRITEBUFLEN - handle->writebufin
549 );
550 handle->writeqoff += MOONBR_IO_WRITEBUFLEN - handle->writebufin;
551 handle->writebufin = MOONBR_IO_WRITEBUFLEN;
552 while (handle->writebufout < MOONBR_IO_WRITEBUFLEN) {
553 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
554 #ifdef MOONBR_IO_USE_TLS
555 moonbr_io_write_tls(
556 handle->writebuf + handle->writebufout,
557 MOONBR_IO_WRITEBUFLEN - handle->writebufout
558 )
559 #endif
560 written = write(
561 handle->fd,
562 handle->writebuf + handle->writebufout,
563 MOONBR_IO_WRITEBUFLEN - handle->writebufout
564 );
565 if (written < 0) {
566 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
567 goto moonbr_io_write_impl_block;
568 } else if (errno != EINTR) moonbr_io_return_errmsg();
569 } else {
570 handle->writebufout += written;
571 handle->writeleft -= written;
572 if (handle->flushedleft) {
573 if (written >= handle->flushedleft) {
574 handle->flushedleft = 0;
575 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
576 } else {
577 handle->flushedleft -= written;
578 }
579 }
580 }
581 }
582 handle->writebufin = 0;
583 handle->writebufout = 0;
584 }
585 }
586 handle->writeqoff = 0;
587 lua_pop(L, 1);
588 lua_pushnil(L);
589 lua_rawseti(L, -2, handle->writeqout++);
590 }
591 while (handle->flushedleft) {
592 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
593 #ifdef MOONBR_IO_USE_TLS
594 moonbr_io_write_tls(
595 handle->writebuf + handle->writebufout,
596 handle->writebufin - handle->writebufout
597 )
598 #endif
599 written = write(
600 handle->fd,
601 handle->writebuf + handle->writebufout,
602 handle->writebufin - handle->writebufout
603 );
604 if (written < 0) {
605 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
606 goto moonbr_io_write_impl_block;
607 } else if (errno != EINTR) moonbr_io_return_errmsg();
608 } else {
609 handle->writebufout += written;
610 handle->writeleft -= written;
611 if (handle->flushedleft) {
612 if (written >= handle->flushedleft) {
613 handle->flushedleft = 0;
614 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
615 } else {
616 handle->flushedleft -= written;
617 }
618 }
619 }
620 }
621 if (handle->writebufout == handle->writebufin) {
622 handle->writebufin = 0;
623 handle->writebufout = 0;
624 }
625 if (nonblocking) lua_pushinteger(L, 0);
626 else lua_pushvalue(L, 1);
627 handle->writeerr = 0;
628 return 1;
629 moonbr_io_write_impl_block:
630 lua_pushinteger(L, handle->writeleft);
631 handle->writeerr = 0;
632 return 1;
633 }
635 static int moonbr_io_write(lua_State *L) {
636 return moonbr_io_write_impl(L, 0, 0);
637 }
639 static int moonbr_io_write_nb(lua_State *L) {
640 return moonbr_io_write_impl(L, 1, 0);
641 }
643 static int moonbr_io_flush(lua_State *L) {
644 return moonbr_io_write_impl(L, 0, 1);
645 }
647 static int moonbr_io_flush_nb(lua_State *L) {
648 return moonbr_io_write_impl(L, 1, 1);
649 }
651 #if LUA_VERSION_NUM >= 503
652 static int moonbr_io_write_cont(lua_State *L, int status, lua_KContext ctx) {
653 #else
654 static int moonbr_io_write_cont(lua_State *L) {
655 #endif
656 while (1) {
657 lua_pushcfunction(L, moonbr_io_write_nb);
658 lua_pushvalue(L, 1);
659 lua_call(L, 1, 2);
660 if (lua_isnil(L, -2)) return 2;
661 if (!lua_tointeger(L, -2)) {
662 lua_pushvalue(L, 1);
663 return 1;
664 }
665 lua_pop(L, 2);
666 lua_pushvalue(L, 2);
667 lua_callk(L, 0, 0, 0, moonbr_io_write_cont);
668 }
669 }
671 static int moonbr_io_write_call(lua_State *L) {
672 lua_pushcfunction(L, moonbr_io_write_nb);
673 lua_insert(L, 3);
674 lua_pushvalue(L, 1);
675 lua_insert(L, 4);
676 lua_call(L, lua_gettop(L) - 3, 2);
677 if (lua_isnil(L, -2)) return 2;
678 if (!lua_tointeger(L, -2)) {
679 lua_pushvalue(L, 1);
680 return 1;
681 }
682 #if LUA_VERSION_NUM >= 503
683 return moonbr_io_write_cont(L, 0, 0);
684 #else
685 return moonbr_io_write_cont(L);
686 #endif
687 }
689 moonbr_io_yield_wrapper(moonbr_io_write_yield, moonbr_io_write_call);
691 static int moonbr_io_flush_call(lua_State *L) {
692 lua_pushcfunction(L, moonbr_io_flush_nb);
693 lua_insert(L, 3);
694 lua_pushvalue(L, 1);
695 lua_insert(L, 4);
696 lua_call(L, lua_gettop(L) - 3, 2);
697 if (lua_isnil(L, -2)) return 2;
698 if (!lua_tointeger(L, -2)) {
699 lua_pushvalue(L, 1);
700 return 1;
701 }
702 #if LUA_VERSION_NUM >= 503
703 return moonbr_io_write_cont(L, 0, 0);
704 #else
705 return moonbr_io_write_cont(L);
706 #endif
707 }
709 moonbr_io_yield_wrapper(moonbr_io_flush_yield, moonbr_io_flush_call);
711 static int moonbr_io_finish(lua_State *L) {
712 moonbr_io_handle_t *handle;
713 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
714 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
715 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
716 if (handle->writeleft) {
717 lua_pushcfunction(L, moonbr_io_flush);
718 lua_pushvalue(L, 1);
719 if (lua_pcall(L, 1, 2, 0)) {
720 handle->finished = 1;
721 lua_error(L);
722 }
723 if (!lua_toboolean(L, -2)) {
724 handle->finished = 1;
725 return 2;
726 }
727 }
728 handle->finished = 1;
729 #ifdef MOONBR_IO_USE_TLS
730 if ((handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) && !handle->tls) {
731 #else
732 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
733 #endif
734 if (shutdown(handle->fd, SHUT_WR)) moonbr_io_return_errmsg();
735 } else {
736 #ifdef MOONBR_IO_USE_TLS
737 if (handle->tls) {
738 int status;
739 if (moonbr_io_handle_set_nonblocking(L, handle, 1)) moonbr_io_return_errmsg();
740 do status = tls_close(handle->tls);
741 while (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT);
742 if (status) {
743 close(handle->fd);
744 handle->fd = -1;
745 lua_pushnil(L);
746 lua_pushstring(L, tls_error(handle->tls));
747 return 2;
748 }
749 }
750 #endif
751 if (close(handle->fd)) {
752 handle->fd = -1;
753 moonbr_io_return_errmsg();
754 }
755 handle->fd = -1; /* fake EOF on read */
756 }
757 lua_pushboolean(L, 1);
758 return 1;
759 }
761 static int moonbr_io_close_impl(lua_State *L, int nonblocking, int reset) {
762 moonbr_io_handle_t *handle;
763 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
764 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
765 if (!reset && handle->fd >= 0) {
766 if (handle->writeleft) {
767 lua_pushcfunction(L, nonblocking ? moonbr_io_flush_nb : moonbr_io_flush);
768 lua_pushvalue(L, 1);
769 if (lua_pcall(L, 1, 2, 0)) {
770 handle->closed = 1;
771 close(handle->fd);
772 handle->fd = -1;
773 lua_error(L);
774 }
775 if (!nonblocking) handle->closed = 1; /* TODO: handle nonblocking case */
776 if (!lua_toboolean(L, -2)) {
777 close(handle->fd);
778 handle->fd = -1;
779 return 2;
780 }
781 #if LUA_VERSION_NUM >= 503
782 if (nonblocking && lua_tointeger(L, -2)) {
783 #else
784 if (nonblocking && lua_tonumber(L, -2)) {
785 #endif
786 lua_pushliteral(L, "flush");
787 lua_pushvalue(L, -3);
788 return 2;
789 }
790 } else {
791 handle->closed = 1;
792 }
793 #ifdef MOONBR_IO_USE_TLS
794 if (handle->tls) {
795 int status;
796 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
797 do status = tls_close(handle->tls);
798 while (!nonblocking && (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT));
799 if (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT) {
800 handle->tlsclosing = status; /* TODO: handle polling */
801 lua_pushliteral(L, "close");
802 return 1;
803 }
804 if (status) {
805 close(handle->fd);
806 handle->fd = -1;
807 lua_pushnil(L);
808 lua_pushstring(L, tls_error(handle->tls));
809 return 2;
810 }
811 }
812 #endif
813 if (moonbr_io_handle_set_linger(L, handle, -1)) {
814 moonbr_io_prepare_errmsg();
815 close(handle->fd);
816 handle->fd = -1;
817 moonbr_io_return_prepared_errmsg();
818 }
819 } else {
820 handle->closed = 1;
821 }
822 if (handle->fd >= 0) {
823 if (close(handle->fd)) {
824 handle->fd = -1;
825 moonbr_io_return_errmsg();
826 }
827 handle->fd = -1;
828 }
829 lua_pushboolean(L, 1);
830 return 1;
832 }
834 static int moonbr_io_close(lua_State *L) {
835 return moonbr_io_close_impl(L, 0, 0);
836 }
838 static int moonbr_io_reset(lua_State *L) {
839 return moonbr_io_close_impl(L, 0, 1);
840 }
842 static int moonbr_io_handlegc(lua_State *L) {
843 moonbr_io_handle_t *handle;
844 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
845 if (handle->fd >= 0) {
846 lua_pushcfunction(L, moonbr_io_reset);
847 lua_pushvalue(L, 1);
848 lua_pushinteger(L, 0);
849 lua_call(L, 2, 0);
850 }
851 #ifdef MOONBR_IO_USE_TLS
852 if (handle->tls) {
853 tls_free(handle->tls);
854 handle->tls = NULL;
855 }
856 if (handle->servertls) {
857 tls_free(handle->servertls);
858 handle->servertls = NULL;
859 }
860 #endif
861 return 0;
862 }
864 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
865 moonbr_io_handle_t *handle;
866 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
867 if (!handle->closed) {
868 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
869 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
870 lua_call(L, 1, 0);
871 }
872 }
874 static int moonbr_io_pushhandle_impl(lua_State *L) {
875 int *fd;
876 moonbr_io_handle_t *handle;
877 struct sockaddr addr;
878 socklen_t addrlen;
879 fd = lua_touserdata(L, 1);
880 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
881 handle->fd = -1; /* avoid closing incomplete handle */
882 addrlen = sizeof(addr);
883 if (getsockname(*fd, &addr, &addrlen)) {
884 if (errno != ENOTSOCK) {
885 moonbr_io_prepare_errmsg();
886 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
887 }
888 handle->issock = 0;
889 } else {
890 handle->issock = 1;
891 handle->addrfam = addr.sa_family;
892 }
893 handle->finished = 0;
894 handle->closed = 0;
895 handle->nonblocking = -1;
896 handle->nopush = -1;
897 handle->readerr = 0;
898 handle->readbufin = 0;
899 handle->readbufout = 0;
900 handle->writeerr = 0;
901 handle->writeleft = 0;
902 handle->flushedleft = 0;
903 handle->writeqin = 0;
904 handle->writeqout = 0;
905 handle->writeqoff = 0;
906 handle->writebufin = 0;
907 handle->writebufout = 0;
908 #ifdef MOONBR_IO_USE_TLS
909 handle->tls = NULL;
910 handle->servertls = NULL;
911 handle->tlshandshake = 0;
912 handle->tlsclosing = 0;
913 #endif
914 handle->fd = *fd; /* required for set_linger call */
915 if (moonbr_io_handle_set_linger(L, handle, 0)) {
916 moonbr_io_prepare_errmsg();
917 handle->fd = -1;
918 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
919 }
920 handle->fd = -1; /* avoid closing incomplete handle */
921 luaL_setmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
922 lua_newtable(L); // uservalue
923 lua_newtable(L);
924 lua_setfield(L, -2, "writequeue");
925 lua_newtable(L); // public
926 if (handle->addrfam == AF_INET6) {
927 struct sockaddr_in6 addr_in6;
928 char addrstrbuf[INET6_ADDRSTRLEN];
929 const char *addrstr;
930 addrlen = sizeof(addr_in6);
931 if (getsockname(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
932 moonbr_io_prepare_errmsg();
933 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
934 }
935 if (addrlen > sizeof(addr_in6)) {
936 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
937 }
938 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
939 if (!addrstr) {
940 moonbr_io_prepare_errmsg();
941 luaL_error(L, "Could not format local IP address: %s", errmsg);
942 } else {
943 lua_pushstring(L, addrstr);
944 lua_setfield(L, -2, "local_ip6");
945 }
946 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
947 lua_setfield(L, -2, "local_tcpport");
948 if (getpeername(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
949 moonbr_io_prepare_errmsg();
950 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
951 }
952 if (addrlen > sizeof(addr_in6)) {
953 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
954 }
955 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
956 if (!addrstr) {
957 moonbr_io_prepare_errmsg();
958 luaL_error(L, "Could not format remote IP address: %s", errmsg);
959 } else {
960 lua_pushstring(L, addrstr);
961 lua_setfield(L, -2, "remote_ip6");
962 }
963 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
964 lua_setfield(L, -2, "remote_tcpport");
965 } else if (handle->addrfam == AF_INET) {
966 struct sockaddr_in addr_in;
967 char addrstrbuf[INET_ADDRSTRLEN];
968 const char *addrstr;
969 addrlen = sizeof(addr_in);
970 if (getsockname(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
971 moonbr_io_prepare_errmsg();
972 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
973 }
974 if (addrlen > sizeof(addr_in)) {
975 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
976 }
977 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
978 if (!addrstr) {
979 moonbr_io_prepare_errmsg();
980 luaL_error(L, "Could not format local IP address: %s", errmsg);
981 } else {
982 lua_pushstring(L, addrstr);
983 lua_setfield(L, -2, "local_ip4");
984 }
985 lua_pushinteger(L, ntohs(addr_in.sin_port));
986 lua_setfield(L, -2, "local_tcpport");
987 if (getpeername(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
988 moonbr_io_prepare_errmsg();
989 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
990 }
991 if (addrlen > sizeof(addr_in)) {
992 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
993 }
994 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
995 if (!addrstr) {
996 moonbr_io_prepare_errmsg();
997 luaL_error(L, "Could not format remote IP address: %s", errmsg);
998 } else {
999 lua_pushstring(L, addrstr);
1000 lua_setfield(L, -2, "remote_ip4");
1002 lua_pushinteger(L, ntohs(addr_in.sin_port));
1003 lua_setfield(L, -2, "remote_tcpport");
1005 luaL_setmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1006 lua_setfield(L, -2, "public");
1007 lua_setuservalue(L, -2);
1008 handle->fd = *fd;
1009 *fd = -1; /* closing is now handled by garbage collection */
1010 return 1;
1013 void moonbr_io_pushhandle(lua_State *L, int fd) {
1014 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1015 lua_pushlightuserdata(L, &fd);
1016 if (lua_pcall(L, 1, 1, 0)) {
1017 if (fd != -1) close(fd); // TODO: correct to close file descriptor here?
1018 lua_error(L);
1022 static int moonbr_io_handleindex(lua_State *L) {
1023 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1024 luaL_checkany(L, 2);
1025 lua_getuservalue(L, 1);
1026 lua_getfield(L, -1, "public");
1027 lua_pushvalue(L, 2);
1028 lua_gettable(L, -2);
1029 return 1;
1032 static int moonbr_io_handlenewindex(lua_State *L) {
1033 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1034 luaL_checkany(L, 2);
1035 luaL_checkany(L, 3);
1036 lua_getuservalue(L, 1);
1037 lua_getfield(L, -1, "public");
1038 lua_pushvalue(L, 2);
1039 lua_pushvalue(L, 3);
1040 lua_settable(L, -3);
1041 return 0;
1044 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
1045 const char *path;
1046 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1047 const int path_maxlen = sizeof(struct sockaddr_un) - (
1048 (void *)sockaddr.sun_path - (void *)&sockaddr
1049 ) - 1; /* one byte for termination */
1050 int sock;
1051 path = luaL_checkstring(L, 1);
1052 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1053 strcpy(sockaddr.sun_path, path);
1054 sock = socket(
1055 PF_LOCAL,
1056 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1058 );
1059 if (sock < 0) moonbr_io_return_errmsg();
1060 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1061 if (!nonblocking && errno == EINTR) {
1062 moonbr_io_prepare_errmsg();
1063 close(sock);
1064 moonbr_io_return_prepared_errmsg();
1065 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1067 moonbr_io_pushhandle(L, sock);
1068 return 1;
1071 static int moonbr_io_localconnect(lua_State *L) {
1072 return moonbr_io_localconnect_impl(L, 0);
1075 static int moonbr_io_localconnect_nb(lua_State *L) {
1076 return moonbr_io_localconnect_impl(L, 1);
1079 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
1080 const char *host, *port;
1081 struct addrinfo hints = { 0, };
1082 struct addrinfo *res, *addrinfo;
1083 int errcode;
1084 int sock;
1085 host = luaL_checkstring(L, 1);
1086 port = luaL_checkstring(L, 2);
1087 hints.ai_family = AF_UNSPEC;
1088 hints.ai_socktype = SOCK_STREAM;
1089 hints.ai_protocol = IPPROTO_TCP;
1090 hints.ai_flags = AI_ADDRCONFIG;
1091 errcode = getaddrinfo(host, port, &hints, &res);
1092 if (errcode) {
1093 freeaddrinfo(res);
1094 if (errcode == EAI_SYSTEM) {
1095 moonbr_io_prepare_errmsg();
1096 lua_pushnil(L);
1097 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1098 } else {
1099 lua_pushnil(L);
1100 lua_pushstring(L, gai_strerror(errcode));
1102 return 2;
1104 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1105 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1107 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1108 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1110 addrinfo = res;
1111 moonbr_io_tcpconnect_found:
1112 sock = socket(
1113 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1114 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1115 addrinfo->ai_protocol
1116 );
1117 if (sock < 0) {
1118 moonbr_io_prepare_errmsg();
1119 freeaddrinfo(res);
1120 moonbr_io_return_prepared_errmsg();
1122 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1123 freeaddrinfo(res);
1124 if (!nonblocking && errno == EINTR) {
1125 moonbr_io_prepare_errmsg();
1126 close(sock);
1127 moonbr_io_return_prepared_errmsg();
1128 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1129 } else {
1130 freeaddrinfo(res);
1132 moonbr_io_pushhandle(L, sock);
1133 return 1;
1136 static int moonbr_io_tcpconnect(lua_State *L) {
1137 return moonbr_io_tcpconnect_impl(L, 0);
1140 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1141 return moonbr_io_tcpconnect_impl(L, 1);
1144 static int moonbr_io_locallisten(lua_State *L) {
1145 moonbr_io_listener_t *listener;
1146 const char *path;
1147 struct stat sb;
1148 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1149 const int path_maxlen = sizeof(struct sockaddr_un) - (
1150 (void *)sockaddr.sun_path - (void *)&sockaddr
1151 ) - 1; /* one byte for termination */
1152 int sock;
1153 path = luaL_checkstring(L, 1);
1154 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1155 strcpy(sockaddr.sun_path, path);
1156 if (stat(path, &sb) == 0) {
1157 if (S_ISSOCK(sb.st_mode)) unlink(path);
1159 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1160 listener->fd = -1;
1161 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1162 sock = socket(
1163 PF_LOCAL,
1164 SOCK_STREAM | SOCK_CLOEXEC,
1166 );
1167 if (sock < 0) moonbr_io_return_errmsg();
1168 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1169 moonbr_io_prepare_errmsg();
1170 close(sock);
1171 moonbr_io_return_prepared_errmsg();
1173 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1174 moonbr_io_prepare_errmsg();
1175 close(sock);
1176 moonbr_io_return_prepared_errmsg();
1178 listener->fd = sock;
1179 listener->addrfam = AF_LOCAL;
1180 listener->nonblocking = -1;
1181 return 1;
1184 static int moonbr_io_tcplisten(lua_State *L) {
1185 moonbr_io_listener_t *listener;
1186 const char *host, *port;
1187 struct addrinfo hints = { 0, };
1188 struct addrinfo *res, *addrinfo;
1189 int errcode;
1190 int sock;
1191 host = luaL_optstring(L, 1, NULL);
1192 port = luaL_checkstring(L, 2);
1193 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1194 listener->fd = -1;
1195 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1196 hints.ai_family = AF_UNSPEC;
1197 hints.ai_socktype = SOCK_STREAM;
1198 hints.ai_protocol = IPPROTO_TCP;
1199 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1200 errcode = getaddrinfo(host, port, &hints, &res);
1201 if (errcode) {
1202 freeaddrinfo(res);
1203 if (errcode == EAI_SYSTEM) {
1204 moonbr_io_prepare_errmsg();
1205 lua_pushnil(L);
1206 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1207 } else {
1208 lua_pushnil(L);
1209 lua_pushstring(L, gai_strerror(errcode));
1211 return 2;
1213 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1214 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1216 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1217 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1219 addrinfo = res;
1220 moonbr_io_tcpconnect_found:
1221 listener->addrfam = addrinfo->ai_family;
1222 sock = socket(
1223 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1224 addrinfo->ai_socktype | SOCK_CLOEXEC,
1225 addrinfo->ai_protocol
1226 );
1227 if (sock < 0) {
1228 moonbr_io_prepare_errmsg();
1229 freeaddrinfo(res);
1230 moonbr_io_return_prepared_errmsg();
1233 static const int reuseval = 1;
1234 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1235 moonbr_io_prepare_errmsg();
1236 freeaddrinfo(res);
1237 close(sock);
1238 lua_pushnil(L);
1239 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1240 return 2;
1243 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1244 moonbr_io_prepare_errmsg();
1245 freeaddrinfo(res);
1246 close(sock);
1247 moonbr_io_return_prepared_errmsg();
1249 freeaddrinfo(res);
1250 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1251 moonbr_io_prepare_errmsg();
1252 close(sock);
1253 moonbr_io_return_prepared_errmsg();
1255 listener->fd = sock;
1256 listener->nonblocking = -1;
1257 return 1;
1260 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1261 moonbr_io_listener_t *listener;
1262 int fd;
1263 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1264 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1265 if (listener->nonblocking != nonblocking) {
1266 int flags;
1267 flags = fcntl(listener->fd, F_GETFL, 0);
1268 if (flags == -1) {
1269 moonbr_io_prepare_errmsg();
1270 close(listener->fd);
1271 listener->fd = -1;
1272 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1274 if (nonblocking) flags |= O_NONBLOCK;
1275 else flags &= ~O_NONBLOCK;
1276 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1277 moonbr_io_prepare_errmsg();
1278 close(listener->fd);
1279 listener->fd = -1;
1280 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1282 listener->nonblocking = nonblocking;
1284 while (1) {
1285 #if defined(__linux__) && !defined(_GNU_SOURCE)
1286 fd = accept(listener->fd, NULL, NULL);
1287 if (fd != -1) {
1288 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
1289 moonbr_io_prepare_errmsg();
1290 close(listener->fd);
1291 listener->fd = -1;
1292 close(fd);
1293 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1296 #else
1297 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1298 #endif
1299 if (fd < 0) {
1300 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1301 lua_pushboolean(L, 0);
1302 lua_pushliteral(L, "No incoming connection pending");
1303 return 2;
1304 } else if (errno != EINTR) moonbr_io_return_errmsg();
1305 } else {
1306 moonbr_io_pushhandle(L, fd);
1307 return 1;
1312 static int moonbr_io_accept(lua_State *L) {
1313 return moonbr_io_accept_impl(L, 0);
1316 static int moonbr_io_accept_nb(lua_State *L) {
1317 return moonbr_io_accept_impl(L, 1);
1320 static int moonbr_io_unlisten(lua_State *L) {
1321 moonbr_io_listener_t *listener;
1322 struct sockaddr_un addr;
1323 socklen_t addrlen;
1324 struct stat sb;
1325 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1326 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1327 addrlen = sizeof(addr);
1328 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1329 if (close(listener->fd)) {
1330 moonbr_io_prepare_errmsg();
1331 listener->fd = -1;
1332 if (addrlen && addrlen <= sizeof(addr)) {
1333 if (stat(addr.sun_path, &sb) == 0) {
1334 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1337 moonbr_io_return_prepared_errmsg();
1339 listener->fd = -1;
1340 if (addrlen && addrlen <= sizeof(addr)) {
1341 if (stat(addr.sun_path, &sb) == 0) {
1342 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1345 lua_pushboolean(L, 1);
1346 return 1;
1349 static int moonbr_io_listenergc(lua_State *L) {
1350 moonbr_io_listener_t *listener;
1351 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1352 if (listener->fd >= 0) close(listener->fd);
1353 listener->fd = -1;
1354 return 0;
1357 static int moonbr_io_exec(lua_State *L) {
1358 char **argv;
1359 int i, argc;
1360 int sockin[2], sockout[2], sockerr[2];
1361 volatile int errorcond = 0;
1362 volatile char errmsgbuf[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG;
1363 moonbr_io_child_t *child;
1364 argc = lua_gettop(L);
1365 argv = lua_newuserdata(L, (argc + 1) * sizeof(char *));
1366 for (i=0; i<argc; i++) argv[i] = (char *)luaL_checkstring(L, i+1);
1367 argv[argc] = NULL;
1368 child = lua_newuserdata(L, sizeof(moonbr_io_child_t));
1369 child->pid = 0;
1370 lua_newtable(L);
1371 lua_setuservalue(L, -2);
1372 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1373 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1374 moonbr_io_prepare_errmsg();
1375 lua_pushnil(L);
1376 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1377 return 2;
1379 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1380 moonbr_io_prepare_errmsg();
1381 close(sockin[0]);
1382 close(sockin[1]);
1383 lua_pushnil(L);
1384 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1385 return 2;
1387 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1388 moonbr_io_prepare_errmsg();
1389 close(sockin[0]);
1390 close(sockin[1]);
1391 close(sockout[0]);
1392 close(sockout[1]);
1393 lua_pushnil(L);
1394 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1395 return 2;
1397 child->pid = vfork();
1398 if (child->pid == -1) {
1399 moonbr_io_prepare_errmsg();
1400 close(sockin[0]);
1401 close(sockin[1]);
1402 close(sockout[0]);
1403 close(sockout[1]);
1404 close(sockerr[0]);
1405 close(sockerr[1]);
1406 lua_pushnil(L);
1407 lua_pushfstring(L, "Could not fork: %s", errmsg);
1408 return 2;
1410 if (!child->pid) {
1411 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1412 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1413 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1414 closefrom(3);
1415 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1416 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1417 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1418 if (execvp(argv[0], argv)) {
1419 errorcond = 2;
1420 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1421 _exit(0);
1423 moonbr_io_exec_error1:
1424 errorcond = 1;
1425 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1426 _exit(0);
1428 close(sockin[1]);
1429 close(sockout[1]);
1430 close(sockerr[1]);
1431 if (errorcond) {
1432 int status;
1433 close(sockin[0]);
1434 close(sockout[0]);
1435 close(sockerr[0]);
1436 while (waitpid(child->pid, &status, 0) == -1) {
1437 if (errno != EINTR) {
1438 moonbr_io_prepare_errmsg();
1439 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1442 child->pid = 0;
1443 lua_pushnil(L);
1444 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1445 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1446 return 2;
1448 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1449 lua_pushlightuserdata(L, &sockin[0]);
1450 if (lua_pcall(L, 1, 1, 0)) {
1451 if (sockin[0] != -1) close(sockin[0]);
1452 close(sockout[0]);
1453 close(sockerr[0]);
1454 goto moonbr_io_exec_error2;
1456 lua_setfield(L, -2, "stdin");
1457 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1458 lua_pushlightuserdata(L, &sockout[0]);
1459 if (lua_pcall(L, 1, 1, 0)) {
1460 if (sockout[0] != -1) close(sockout[0]);
1461 close(sockerr[0]);
1462 goto moonbr_io_exec_error2;
1464 lua_setfield(L, -2, "stdout");
1465 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1466 lua_pushlightuserdata(L, &sockerr[0]);
1467 if (lua_pcall(L, 1, 1, 0)) {
1468 if (sockerr[0] != -1) close(sockerr[0]);
1469 goto moonbr_io_exec_error2;
1471 lua_setfield(L, -2, "stderr");
1472 return 1;
1473 moonbr_io_exec_error2:
1475 int status;
1476 while (waitpid(child->pid, &status, 0) == -1) {
1477 if (errno != EINTR) {
1478 moonbr_io_prepare_errmsg();
1479 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1483 child->pid = 0;
1484 return lua_error(L);
1487 static int moonbr_io_childindex(lua_State *L) {
1488 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1489 luaL_checkany(L, 2);
1490 lua_getuservalue(L, 1);
1491 lua_pushvalue(L, 2);
1492 lua_gettable(L, -2);
1493 if (lua_isnil(L, -1)) {
1494 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1495 lua_pushvalue(L, 2);
1496 lua_gettable(L, -2);
1498 return 1;
1501 static int moonbr_io_childnewindex(lua_State *L) {
1502 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1503 luaL_checkany(L, 2);
1504 luaL_checkany(L, 3);
1505 lua_getuservalue(L, 1);
1506 lua_pushvalue(L, 2);
1507 lua_pushvalue(L, 3);
1508 lua_settable(L, -3);
1509 return 0;
1512 static int moonbr_io_childgc(lua_State *L) {
1513 moonbr_io_child_t *child;
1514 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1515 if (child->pid) {
1516 int status;
1517 int pid = child->pid;
1518 child->pid = 0;
1519 if (kill(pid, SIGKILL)) {
1520 moonbr_io_prepare_errmsg();
1521 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1523 while (waitpid(pid, &status, 0) == -1) {
1524 if (errno != EINTR) {
1525 moonbr_io_prepare_errmsg();
1526 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1530 return 0;
1533 static int moonbr_io_kill(lua_State *L) {
1534 moonbr_io_child_t *child;
1535 int sig;
1536 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1537 if (lua_type(L, 2) == LUA_TSTRING) {
1538 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_SIGNALS_REGKEY);
1539 lua_pushvalue(L, 2);
1540 lua_gettable(L, -2);
1541 sig = lua_tointeger(L, -1);
1542 if (!sig) {
1543 lua_pushvalue(L, 2);
1544 luaL_error(L, "Unknown signal \"%s\"", lua_tostring(L, 2));
1546 } else {
1547 sig = luaL_optinteger(L, 2, SIGKILL);
1549 if (!child->pid) luaL_error(L, "Attempt to kill an already collected child process");
1550 if (kill(child->pid, sig)) {
1551 moonbr_io_prepare_errmsg();
1552 luaL_error(L, "Error in kill call: %s", errmsg);
1554 lua_settop(L, 1);
1555 return 1;
1558 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1559 moonbr_io_child_t *child;
1560 pid_t waitedpid;
1561 int status;
1562 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1563 if (!child->pid) luaL_error(L, "Attempt to wait for an already collected child process");
1564 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1565 if (errno != EINTR) {
1566 moonbr_io_prepare_errmsg();
1567 luaL_error(L, "Error in waitpid call: %s", errmsg);
1570 if (!waitedpid) {
1571 lua_pushboolean(L, 0);
1572 lua_pushliteral(L, "Process is still running");
1573 return 2;
1574 } else {
1575 child->pid = 0;
1576 if (WIFEXITED(status)) {
1577 lua_pushinteger(L, WEXITSTATUS(status));
1578 } else if (WIFSIGNALED(status)) {
1579 lua_pushinteger(L, -WTERMSIG(status));
1580 } else {
1581 luaL_error(L, "Unexpected status value returned by waitpid call");
1583 return 1;
1587 static int moonbr_io_wait(lua_State *L) {
1588 return moonbr_io_wait_impl(L, 0);
1591 static int moonbr_io_wait_nb(lua_State *L) {
1592 return moonbr_io_wait_impl(L, 1);
1595 #if LUA_VERSION_NUM >= 503
1596 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1597 #else
1598 static int moonbr_io_wait_cont(lua_State *L) {
1599 #endif
1600 #if !(LUA_VERSION_NUM >= 503)
1601 int ctx = 0;
1602 lua_getctx(L, &ctx);
1603 #endif
1604 while (1) {
1605 lua_pushcfunction(L, moonbr_io_wait_nb);
1606 lua_pushvalue(L, 1);
1607 lua_call(L, 1, 1);
1608 if (!lua_isnil(L, -1)) break;
1609 lua_pushvalue(L, 2);
1610 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1612 return 1;
1615 static int moonbr_io_wait_call(lua_State *L) {
1616 lua_settop(L, 2);
1617 #if LUA_VERSION_NUM >= 503
1618 return moonbr_io_wait_cont(L, 0, 0);
1619 #else
1620 return moonbr_io_wait_cont(L);
1621 #endif
1624 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1626 static void moonbr_io_sigterm_handler(int sig) {
1627 moonbr_io_sigterm_flag = 1;
1630 int moonbr_io_sigterm_setup(lua_State *L) {
1631 signal(SIGTERM, moonbr_io_sigterm_handler);
1632 return 0;
1635 static int moonbr_io_sigterm_received(lua_State *L) {
1636 lua_pushboolean(L, moonbr_io_sigterm_flag);
1637 return 1;
1640 static int moonbr_io_getpid(lua_State *L) {
1641 lua_pushinteger(L, getpid());
1642 return 1;
1645 #ifdef MOONBR_IO_USE_TLS
1647 #define moonbr_io_poll_tls() \
1648 if (!handle->tlshandshake) { \
1649 lua_pushboolean(L, 1); \
1650 return 1; \
1651 } \
1652 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1653 if (fd < 0) { \
1654 lua_pushboolean(L, 1); \
1655 return 1; \
1656 } \
1657 FD_SET(fd, &readfds); \
1658 if (fd+1 > nfds) nfds = fd+1; \
1659 continue; \
1660 } \
1661 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1662 if (fd < 0) { \
1663 lua_pushboolean(L, 1); \
1664 return 1; \
1665 } \
1666 FD_SET(fd, &writefds); \
1667 if (fd+1 > nfds) nfds = fd+1; \
1668 continue; \
1669 } \
1670 while (0)
1672 #endif /* MOONBR_IO_USE_TLS */
1674 static int moonbr_io_poll(lua_State *L) {
1675 moonbr_io_handle_t *handle;
1676 moonbr_io_listener_t *listener;
1677 int fd, isnum;
1678 int nfds = 0;
1679 fd_set readfds, writefds, exceptfds;
1680 struct timespec timeout = {0, };
1681 int use_timeout = 0;
1682 int check_sigterm = 0;
1683 sigset_t mask, orig_mask;
1684 int status;
1685 FD_ZERO(&readfds);
1686 FD_ZERO(&writefds);
1687 FD_ZERO(&exceptfds);
1688 if (!lua_isnoneornil(L, 1)) {
1689 luaL_checktype(L, 1, LUA_TTABLE);
1690 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1691 if (lua_toboolean(L, -1)) {
1692 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1693 if (handle) {
1694 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1695 fd = handle->fd;
1696 #if MOONBR_IO_USE_TLS
1697 moonbr_io_poll_tls();
1698 #endif
1699 if (
1700 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1701 handle->readbufin != handle->readbufout /* data pending in buffer */
1702 ) {
1703 lua_pushboolean(L, 1);
1704 return 1;
1706 } else {
1707 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1708 if (listener) {
1709 fd = listener->fd;
1710 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1711 } else {
1712 fd = lua_tointegerx(L, -2, &isnum);
1713 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1716 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1717 FD_SET(fd, &readfds);
1718 if (fd+1 > nfds) nfds = fd+1;
1722 if (!lua_isnoneornil(L, 2)) {
1723 luaL_checktype(L, 2, LUA_TTABLE);
1724 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1725 if (lua_toboolean(L, -1)) {
1726 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1727 if (handle) {
1728 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1729 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1730 fd = handle->fd;
1731 #if MOONBR_IO_USE_TLS
1732 moonbr_io_poll_tls();
1733 #endif
1734 } else {
1735 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1736 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1737 fd = lua_tointegerx(L, -2, &isnum);
1738 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1740 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1741 FD_SET(fd, &writefds);
1742 if (fd+1 > nfds) nfds = fd+1;
1746 if (!lua_isnoneornil(L, 3)) {
1747 lua_Number n;
1748 n = lua_tonumberx(L, 3, &isnum);
1749 if (isnum && n<0) {
1750 lua_pushboolean(L, 0);
1751 lua_pushliteral(L, "Negative timeout");
1752 return 2;
1753 } else if (isnum && n>=0 && n<100000000) {
1754 timeout.tv_sec = n;
1755 timeout.tv_nsec = 1e9 * (n - timeout.tv_sec);
1756 } else {
1757 luaL_argcheck(L, 0, 3, "not a valid timeout");
1759 use_timeout = 1;
1761 if (!lua_isnoneornil(L, 4)) luaL_checktype(L, 4, LUA_TBOOLEAN);
1762 check_sigterm = lua_toboolean(L, 4);
1763 if (check_sigterm) {
1764 sigemptyset(&mask);
1765 sigaddset(&mask, SIGTERM);
1766 sigprocmask(SIG_BLOCK, &mask, &orig_mask);
1767 if (moonbr_io_sigterm_flag) {
1768 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1769 lua_pushboolean(L, 0);
1770 lua_pushliteral(L, "SIGTERM received");
1771 return 2;
1774 status = pselect(nfds, &readfds, &writefds, &exceptfds, use_timeout ? &timeout : NULL, check_sigterm ? &orig_mask : NULL);
1775 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1776 if (moonbr_io_sigterm_flag) {
1777 lua_pushboolean(L, 0);
1778 lua_pushliteral(L, "SIGTERM received");
1779 return 2;
1781 if (status == -1) {
1782 if (errno == EINTR) {
1783 lua_pushboolean(L, 1);
1784 return 1;
1785 } else {
1786 moonbr_io_prepare_errmsg();
1787 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1789 } else if (status == 0) {
1790 lua_pushboolean(L, 0);
1791 lua_pushliteral(L, "Timeout while polling file descriptors");
1792 return 2;
1793 } else {
1794 lua_pushboolean(L, 1);
1795 return 1;
1799 static int moonbr_io_timeref(lua_State *L) {
1800 lua_Number sub;
1801 struct timespec tp;
1802 sub = luaL_optnumber(L, 1, 0);
1803 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1804 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1806 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1807 return 1;
1810 #ifdef MOONBR_IO_USE_TLS
1812 #define moonbr_io_tlsconf_string(name, field, func) \
1813 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1814 lua_getfield(L, 1, (field)); \
1815 valuetype = lua_type(L, -1); \
1816 if (valuetype != LUA_TNIL) { \
1817 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1818 value = lua_tostring(L, -1); \
1819 if (func(tlsconf->config, value)) { \
1820 lua_pushnil(L); \
1821 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1822 return 2; \
1823 } \
1824 } \
1825 lua_pop(L, 1);
1827 #define moonbr_io_tlsconf_binary(name, field, func) \
1828 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1829 lua_getfield(L, 1, (field)); \
1830 valuetype = lua_type(L, -1); \
1831 if (valuetype != LUA_TNIL) { \
1832 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1833 value = lua_tolstring(L, -1, &valuelen); \
1834 if (func(tlsconf->config, (void *)value, valuelen)) { \
1835 lua_pushnil(L); \
1836 lua_pushliteral(L, "Could not set " name); \
1837 return 2; \
1838 } \
1839 } \
1840 lua_pop(L, 1);
1842 static int moonbr_io_tlsconf(lua_State *L) {
1843 moonbr_io_tlsconf_t *tlsconf;
1844 int valuetype;
1845 const char *value;
1846 size_t valuelen;
1847 luaL_checktype(L, 1, LUA_TTABLE);
1848 tlsconf = lua_newuserdata(L, sizeof(moonbr_io_tlsconf_t));
1849 tlsconf->config = tls_config_new();
1850 if (!tlsconf->config) {
1851 return luaL_error(L, "Could not allocate memory for TLS configuration");
1853 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
1854 lua_getfield(L, 1, "mode");
1855 value = lua_tostring(L, -1);
1856 if (value && !strcmp(value, "server")) tlsconf->server = 1;
1857 else if (value && !strcmp(value, "client")) tlsconf->server = 0;
1858 else luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
1859 lua_pop(L, 1);
1860 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
1861 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
1862 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
1863 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
1864 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
1865 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
1866 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
1867 #if LUA_VERSION_NUM >= 503
1868 valuetype = lua_getfield(L, 1, "verify_client");
1869 #else
1870 lua_getfield(L, 1, "verify_client");
1871 #endif
1872 if (lua_toboolean(L, -1)) {
1873 value = lua_tostring(L, -1);
1874 if (value && !strcmp(value, "required")) {
1875 tls_config_verify_client(tlsconf->config);
1876 } else if (value && !strcmp(value, "optional")) {
1877 tls_config_verify_client_optional(tlsconf->config);
1878 } else {
1879 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
1882 lua_pop(L, 1);
1883 // TODO: configurable legacy support
1884 // tls_config_set_protocols(tlsconf->config, TLS_PROTOCOLS_ALL);
1885 // tls_config_set_ciphers(tlsconf->config, "legacy");
1886 return 1;
1889 static int moonbr_io_tlsconfgc(lua_State *L) {
1890 moonbr_io_tlsconf_t *tlsconf;
1891 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
1892 if (tlsconf->config) tls_config_free(tlsconf->config);
1893 tlsconf->config = NULL;
1894 return 0;
1897 static int moonbr_io_starttls(lua_State *L) {
1898 moonbr_io_handle_t *handle;
1899 moonbr_io_tlsconf_t *tlsconf;
1900 const char *servername;
1901 struct tls *tls, *tls2;
1902 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1903 if (lua_type(L, 2) == LUA_TTABLE) {
1904 lua_pushcfunction(L, moonbr_io_tlsconf);
1905 lua_pushvalue(L, 2);
1906 lua_call(L, 1, 2);
1907 if (lua_isnil(L, -2)) return 2;
1908 lua_pop(L, 1);
1909 lua_replace(L, 2);
1911 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
1912 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
1913 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
1914 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
1915 if (handle->readbufin || handle->writebufin) {
1916 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
1918 if (tlsconf->server) tls = tls_server();
1919 else {
1920 servername = luaL_checkstring(L, 3);
1921 tls = tls_client();
1923 if (!tls) {
1924 return luaL_error(L, "Could not allocate memory for TLS context");
1926 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
1927 if (tlsconf->server) {
1928 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
1929 handle->servertls = tls;
1930 handle->tls = tls2;
1931 } else {
1932 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
1933 handle->tls = tls;
1935 lua_settop(L, 1);
1936 return 1;
1937 moonbr_io_starttls_error:
1938 lua_pushnil(L);
1939 lua_pushstring(L, tls_error(tls));
1940 tls_free(tls);
1941 return 2;
1944 #endif /* MOONBR_IO_USE_TLS */
1946 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1947 {"read", moonbr_io_read},
1948 {"read_nb", moonbr_io_read_nb},
1949 {"read_call", moonbr_io_read_call},
1950 {"read_yield", moonbr_io_read_yield},
1951 {"drain", moonbr_io_drain},
1952 {"drain_nb", moonbr_io_drain_nb},
1953 {"drain_call", moonbr_io_drain_call},
1954 {"drain_yield", moonbr_io_drain_yield},
1955 {"write", moonbr_io_write},
1956 {"write_nb", moonbr_io_write_nb},
1957 {"write_call", moonbr_io_write_call},
1958 {"write_yield", moonbr_io_write_yield},
1959 {"flush", moonbr_io_flush},
1960 {"flush_nb", moonbr_io_flush_nb},
1961 {"flush_call", moonbr_io_flush_call},
1962 {"flush_yield", moonbr_io_flush_yield},
1963 {"finish", moonbr_io_finish},
1964 {"close", moonbr_io_close},
1965 {"reset", moonbr_io_reset},
1966 #ifdef MOONBR_IO_USE_TLS
1967 {"starttls", moonbr_io_starttls},
1968 #endif
1969 {NULL, NULL}
1970 };
1972 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1973 {"__index", moonbr_io_handleindex},
1974 {"__newindex", moonbr_io_handlenewindex},
1975 {"__gc", moonbr_io_handlegc},
1976 {NULL, NULL}
1977 };
1979 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1980 {"accept", moonbr_io_accept},
1981 {"accept_nb", moonbr_io_accept_nb},
1982 {"close", moonbr_io_unlisten},
1983 {NULL, NULL}
1984 };
1986 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1987 {"__gc", moonbr_io_listenergc},
1988 {NULL, NULL}
1989 };
1991 static const struct luaL_Reg moonbr_io_child_methods[] = {
1992 {"kill", moonbr_io_kill},
1993 {"wait", moonbr_io_wait},
1994 {"wait_nb", moonbr_io_wait_nb},
1995 {"wait_call", moonbr_io_wait_call},
1996 {"wait_yield", moonbr_io_wait_yield},
1997 {NULL, NULL}
1998 };
2000 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
2001 {"__index", moonbr_io_childindex},
2002 {"__newindex", moonbr_io_childnewindex},
2003 {"__gc", moonbr_io_childgc},
2004 {NULL, NULL}
2005 };
2007 static const struct luaL_Reg moonbr_io_module_funcs[] = {
2008 {"localconnect", moonbr_io_localconnect},
2009 {"localconnect_nb", moonbr_io_localconnect_nb},
2010 {"tcpconnect", moonbr_io_tcpconnect},
2011 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2012 {"locallisten", moonbr_io_locallisten},
2013 {"tcplisten", moonbr_io_tcplisten},
2014 {"exec", moonbr_io_exec},
2015 {"sigterm_setup", moonbr_io_sigterm_setup},
2016 {"sigterm_received", moonbr_io_sigterm_received},
2017 {"getpid", moonbr_io_getpid},
2018 {"poll", moonbr_io_poll},
2019 {"timeref", moonbr_io_timeref},
2020 #ifdef MOONBR_IO_USE_TLS
2021 {"tlsconf", moonbr_io_tlsconf},
2022 #endif
2023 {NULL, NULL}
2024 };
2026 #ifdef MOONBR_IO_USE_TLS
2028 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2029 {"__gc", moonbr_io_tlsconfgc},
2030 {NULL, NULL}
2031 };
2033 #endif /* MOONBR_IO_USE_TLS */
2035 int luaopen_moonbridge_io(lua_State *L) {
2037 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2039 lua_newtable(L); // module
2041 lua_newtable(L); // public metatable
2042 lua_newtable(L); // handle methods
2043 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2044 lua_pushvalue(L, -1);
2045 lua_setfield(L, -4, "handle_pt");
2046 lua_setfield(L, -2, "__index");
2047 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2049 lua_newtable(L); // handle metatable
2050 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2051 lua_pushvalue(L, -1);
2052 lua_setfield(L, -3, "handle_mt");
2053 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2055 lua_newtable(L); // listener metatable
2056 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2057 lua_newtable(L); // listener methods
2058 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2059 lua_pushvalue(L, -1);
2060 lua_setfield(L, -4, "listener_pt");
2061 lua_setfield(L, -2, "__index");
2062 lua_pushvalue(L, -1);
2063 lua_setfield(L, -3, "listener_mt");
2064 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2066 lua_newtable(L); // child methods
2067 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2068 lua_pushvalue(L, -1);
2069 lua_setfield(L, -3, "child_pt");
2070 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2071 lua_newtable(L); // child metatable
2072 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2073 lua_pushvalue(L, -1);
2074 lua_setfield(L, -3, "child_mt");
2075 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2077 #ifdef MOONBR_IO_USE_TLS
2078 if(tls_init()) {
2079 return luaL_error(L, "Could not initialize TLS library");
2081 lua_newtable(L); // tlsconf metatable
2082 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2083 lua_pushvalue(L, -1);
2084 lua_setfield(L, -3, "tlsconf_mt");
2085 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2086 #endif
2088 moonbr_io_pushhandle(L, 0);
2089 lua_setfield(L, -2, "stdin");
2090 moonbr_io_pushhandle(L, 1);
2091 lua_setfield(L, -2, "stdout");
2092 moonbr_io_pushhandle(L, 2);
2093 lua_setfield(L, -2, "stderr");
2095 lua_newtable(L); // signal numbers
2096 lua_pushinteger(L, SIGHUP); lua_setfield(L, -2, "HUP");
2097 lua_pushinteger(L, SIGINT); lua_setfield(L, -2, "INT");
2098 lua_pushinteger(L, SIGQUIT); lua_setfield(L, -2, "QUIT");
2099 lua_pushinteger(L, SIGABRT); lua_setfield(L, -2, "ABRT");
2100 lua_pushinteger(L, SIGPIPE); lua_setfield(L, -2, "PIPE");
2101 lua_pushinteger(L, SIGALRM); lua_setfield(L, -2, "ALRM");
2102 lua_pushinteger(L, SIGTERM); lua_setfield(L, -2, "TERM");
2103 lua_pushinteger(L, SIGTSTP); lua_setfield(L, -2, "TSTP");
2104 lua_pushinteger(L, SIGCONT); lua_setfield(L, -2, "CONT");
2105 lua_pushinteger(L, SIGVTALRM); lua_setfield(L, -2, "VTALRM");
2106 #ifdef SIGINFO
2107 lua_pushinteger(L, SIGINFO); lua_setfield(L, -2, "INFO");
2108 #endif
2109 lua_pushinteger(L, SIGUSR1); lua_setfield(L, -2, "USR1");
2110 lua_pushinteger(L, SIGUSR2); lua_setfield(L, -2, "USR2");
2111 lua_pushvalue(L, -1);
2112 lua_setfield(L, -3, "signals");
2113 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_SIGNALS_REGKEY);
2115 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2116 return 1;

Impressum / About Us