moonbridge

view moonbridge_io.c @ 267:5f437005e2ef

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

Impressum / About Us