moonbridge

view moonbridge_io.c @ 256:ff7eea59be93

Bugfix: Do not throw (hard) Lua error in moonbr_io_handle_set_nonblocking, moonbr_io_handle_set_linger, and moonbr_io_handle_set_nopush (may cause Lua error on connection reset)
author jbe
date Sun Sep 18 00:59:31 2016 +0200 (2016-09-18)
parents a22a6c19457f
children 77a7ca00ad34
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_errmsg() \
46 char errmsg[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG; \
47 strerror_r(errno, errmsg, MOONBR_IO_MAXSTRERRORLEN)
49 #define MOONBR_IO_HANDLE_MT_REGKEY "moonbridge_io_handle"
50 #define MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY "moonbridge_io_handle_public"
51 #define MOONBR_IO_LISTENER_MT_REGKEY "moonbridge_io_listener"
52 #define MOONBR_IO_CHILD_MT_REGKEY "moonbridge_io_child"
53 #define MOONBR_IO_CHILD_PT_REGKEY "moonbridge_io_child_pt"
55 #ifdef MOONBR_IO_USE_TLS
56 #define MOONBR_IO_TLSCONF_MT_REGKEY "moonbridge_io_tlsconf"
58 typedef struct {
59 struct tls_config *config;
60 int server;
61 } moonbr_io_tlsconf_t;
62 #endif
64 typedef struct {
65 int fd;
66 int issock;
67 sa_family_t addrfam;
68 int finished;
69 int closed;
70 int nonblocking;
71 int nopush;
72 int readerr;
73 int readbufin;
74 int readbufout;
75 int writeerr;
76 size_t writeleft;
77 size_t flushedleft;
78 #if LUA_VERSION_NUM >= 503
79 lua_Integer writeqin;
80 lua_Integer writeqout;
81 #else
82 int writeqin;
83 int writeqout;
84 #endif
85 size_t writeqoff;
86 int writebufin;
87 int writebufout;
88 char readbuf[MOONBR_IO_READBUFLEN];
89 char writebuf[MOONBR_IO_WRITEBUFLEN];
90 #ifdef MOONBR_IO_USE_TLS
91 struct tls *tls;
92 struct tls *servertls;
93 int tlshandshake;
94 #endif
95 } moonbr_io_handle_t;
97 typedef struct {
98 int fd;
99 sa_family_t addrfam;
100 int nonblocking;
101 } moonbr_io_listener_t;
103 typedef struct {
104 pid_t pid;
105 } moonbr_io_child_t;
107 static int moonbr_io_yield(lua_State *L) {
108 return lua_yield(L, lua_gettop(L));
109 }
111 #if LUA_VERSION_NUM >= 503
112 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
113 #else
114 static int moonbr_io_cont_returnall(lua_State *L) {
115 #endif
116 return lua_gettop(L);
117 }
119 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
120 static int yieldfunc(lua_State *L) { \
121 int args; \
122 lua_pushcfunction(L, callfunc); \
123 lua_insert(L, 1); \
124 args = lua_gettop(L); \
125 lua_pushcfunction(L, moonbr_io_yield); \
126 lua_insert(L, 3); \
127 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
128 return lua_gettop(L); \
129 }
131 static int moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
132 int flags;
133 if (handle->nonblocking == nonblocking) return 0;
134 flags = fcntl(handle->fd, F_GETFL, 0);
135 if (flags == -1) return -1;
136 if (nonblocking) flags |= O_NONBLOCK;
137 else flags &= ~O_NONBLOCK;
138 if (fcntl(handle->fd, F_SETFL, flags) == -1) return -1;
139 handle->nonblocking = nonblocking;
140 return 0;
141 }
143 static int moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
144 struct linger lingerval = { 0, };
145 if (!handle->issock) return 0;
146 if (timeout >= 0) {
147 lingerval.l_onoff = 1;
148 lingerval.l_linger = timeout;
149 }
150 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) return -1;
151 return 0;
152 }
154 static inline int moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
155 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
156 if (
157 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
158 handle->nopush == nopush
159 ) return 0;
160 #if defined(TCP_NOPUSH)
161 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) return -1;
162 #elif defined(TCP_CORK)
163 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) return -1;
164 #endif
165 handle->nopush = nopush;
166 #else
167 #warning Neither TCP_NOPUSH nor TCP_CORK is available
168 #endif
169 return 0;
170 }
172 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
173 moonbr_io_handle_t *handle;
174 lua_Integer maxread;
175 const char *terminatorstr;
176 size_t terminatorlen;
177 char terminator = 0; /* initialize to avoid compiler warning */
178 luaL_Buffer luabuf;
179 size_t luabufcnt = 0;
180 int remaining;
181 char *terminatorpos;
182 ssize_t bytesread;
183 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
184 maxread = luaL_optinteger(L, 2, -1);
185 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
186 if (terminatorlen) {
187 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
188 terminator = terminatorstr[0];
189 }
190 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
191 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
192 if (handle->readerr) {
193 lua_pushnil(L);
194 lua_pushliteral(L, "Previous read error");
195 return 2;
196 }
197 if (handle->fd < 0) {
198 /* fake EOF to simulate shutdown */
199 if (!drain) lua_pushliteral(L, "");
200 else lua_pushinteger(L, 0);
201 lua_pushliteral(L, "eof");
202 return 2;
203 }
204 handle->readerr = 1;
205 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) {
206 moonbr_io_errmsg();
207 lua_pushnil(L);
208 lua_pushstring(L, errmsg);
209 return 2;
210 }
211 if (!drain) luaL_buffinit(L, &luabuf);
212 while (1) {
213 remaining = -1;
214 terminatorpos = NULL;
215 if (
216 maxread >= 0 &&
217 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
218 ) {
219 remaining = (size_t)maxread - luabufcnt;
220 if (terminatorlen) {
221 terminatorpos = memchr(
222 handle->readbuf + handle->readbufout,
223 terminator,
224 remaining
225 );
226 }
227 } else if (terminatorlen) {
228 terminatorpos = memchr(
229 handle->readbuf + handle->readbufout,
230 terminator,
231 handle->readbufin - handle->readbufout
232 );
233 }
234 if (terminatorpos) remaining = 1 + (
235 terminatorpos - (handle->readbuf + handle->readbufout)
236 );
237 if (remaining >= 0) {
238 if (!drain) {
239 luaL_addlstring(
240 &luabuf,
241 handle->readbuf + handle->readbufout,
242 remaining
243 );
244 luaL_pushresult(&luabuf);
245 } else {
246 lua_pushinteger(L, luabufcnt + remaining);
247 }
248 if (terminatorpos) lua_pushliteral(L, "term");
249 else lua_pushliteral(L, "maxlen");
250 handle->readbufout += remaining;
251 if (handle->readbufout == handle->readbufin) {
252 handle->readbufin = 0;
253 handle->readbufout = 0;
254 }
255 handle->readerr = 0;
256 return 2;
257 }
258 if (!drain) luaL_addlstring(
259 &luabuf,
260 handle->readbuf + handle->readbufout,
261 handle->readbufin - handle->readbufout
262 );
263 luabufcnt += handle->readbufin - handle->readbufout;
264 handle->readbufout = 0;
265 #ifdef MOONBR_IO_USE_TLS
266 if (handle->tls) {
267 do {
268 if (!handle->tlshandshake) {
269 do bytesread = tls_handshake(handle->tls);
270 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
271 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
272 handle->tlshandshake = bytesread;
273 errno = EAGAIN;
274 break;
275 }
276 if (bytesread < 0) {
277 lua_pushnil(L);
278 lua_pushstring(L, tls_error(handle->tls));
279 return 2;
280 }
281 handle->tlshandshake = 1;
282 }
283 do bytesread = tls_read(handle->tls, handle->readbuf, MOONBR_IO_READBUFLEN);
284 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
285 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
286 errno = EAGAIN;
287 break;
288 }
289 if (bytesread < 0) {
290 lua_pushnil(L);
291 lua_pushstring(L, tls_error(handle->tls));
292 return 2;
293 }
294 } while (0);
295 }
296 else
297 #endif
298 do bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
299 while (bytesread < 0 && (errno == EINTR));
300 if (
301 bytesread == 0 || (
302 nonblocking &&
303 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
304 )
305 ) {
306 handle->readbufin = 0;
307 if (!drain) luaL_pushresult(&luabuf);
308 else lua_pushinteger(L, luabufcnt);
309 if (bytesread == 0) lua_pushliteral(L, "eof");
310 else lua_pushliteral(L, "block");
311 handle->readerr = 0;
312 return 2;
313 }
314 if (bytesread < 0) {
315 moonbr_io_errmsg();
316 lua_pushnil(L);
317 lua_pushstring(L, errmsg);
318 return 2;
319 }
320 handle->readbufin = bytesread;
321 }
322 }
324 static int moonbr_io_read(lua_State *L) {
325 return moonbr_io_read_impl(L, 0, 0);
326 }
328 static int moonbr_io_read_nb(lua_State *L) {
329 return moonbr_io_read_impl(L, 1, 0);
330 }
332 static int moonbr_io_drain(lua_State *L) {
333 return moonbr_io_read_impl(L, 0, 1);
334 }
336 static int moonbr_io_drain_nb(lua_State *L) {
337 return moonbr_io_read_impl(L, 1, 1);
338 }
340 #if LUA_VERSION_NUM >= 503
341 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
342 #else
343 static int moonbr_io_read_cont(lua_State *L) {
344 #endif
345 lua_Integer remaining;
346 size_t len;
347 #if !(LUA_VERSION_NUM >= 503)
348 int ctx = 0;
349 lua_getctx(L, &ctx);
350 #endif
351 remaining = lua_tointeger(L, 3);
352 while (1) {
353 lua_pushcfunction(L, moonbr_io_read_nb);
354 lua_pushvalue(L, 1);
355 lua_pushvalue(L, 3);
356 lua_pushvalue(L, 4);
357 lua_call(L, 3, 2);
358 if (lua_isnil(L, -2)) return 2;
359 lua_insert(L, -2);
360 len = lua_rawlen(L, -1);
361 if (ctx == 0) {
362 lua_replace(L, 5);
363 ctx = 1;
364 } else if (ctx == 1) {
365 lua_pushvalue(L, 5);
366 lua_newtable(L);
367 lua_replace(L, 5);
368 lua_rawseti(L, 5, 2);
369 lua_rawseti(L, 5, 1);
370 ctx = 2;
371 } else {
372 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
373 }
374 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
375 lua_pop(L, 1);
376 if (remaining >= 0 && len) {
377 remaining -= len;
378 lua_pushinteger(L, remaining);
379 lua_replace(L, 3);
380 }
381 lua_pushvalue(L, 2);
382 lua_callk(L, 0, 0, ctx, moonbr_io_read_cont);
383 }
384 if (ctx == 1) {
385 lua_pushvalue(L, 5);
386 } else {
387 luaL_Buffer buf;
388 lua_Integer i, chunkcount;
389 chunkcount = lua_rawlen(L, 5);
390 luaL_buffinit(L, &buf);
391 for (i=1; i<=chunkcount && i>0; i++) {
392 lua_rawgeti(L, 5, i);
393 luaL_addvalue(&buf);
394 }
395 luaL_pushresult(&buf);
396 }
397 lua_pushvalue(L, -2);
398 return 2;
399 }
401 static int moonbr_io_read_call(lua_State *L) {
402 lua_settop(L, 4);
403 lua_pushnil(L);
404 #if LUA_VERSION_NUM >= 503
405 return moonbr_io_read_cont(L, 0, 0);
406 #else
407 return moonbr_io_read_cont(L);
408 #endif
409 }
411 moonbr_io_yield_wrapper(moonbr_io_read_yield, moonbr_io_read_call);
413 #if LUA_VERSION_NUM >= 503
414 static int moonbr_io_drain_cont(lua_State *L, int status, lua_KContext ctx) {
415 #else
416 static int moonbr_io_drain_cont(lua_State *L) {
417 #endif
418 lua_Integer remaining, len;
419 size_t totallen = 0;
420 #if !(LUA_VERSION_NUM >= 503)
421 int ctx = 0;
422 lua_getctx(L, &ctx);
423 #endif
424 remaining = lua_tointeger(L, 3);
425 while (1) {
426 lua_pushcfunction(L, moonbr_io_drain_nb);
427 lua_pushvalue(L, 1);
428 lua_pushvalue(L, 3);
429 lua_pushvalue(L, 4);
430 lua_call(L, 3, 2);
431 if (lua_isnil(L, -2)) return 2;
432 lua_insert(L, -2);
433 len = lua_tointeger(L, -1);
434 lua_pop(L, 1);
435 totallen += len;
436 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
437 lua_pop(L, 1);
438 if (remaining >= 0 && len) {
439 remaining -= len;
440 lua_pushinteger(L, remaining);
441 lua_replace(L, 3);
442 }
443 lua_pushvalue(L, 2);
444 lua_callk(L, 0, 0, ctx, moonbr_io_drain_cont);
445 }
446 lua_pushinteger(L, totallen);
447 lua_pushvalue(L, -2);
448 return 2;
449 }
451 static int moonbr_io_drain_call(lua_State *L) {
452 #if LUA_VERSION_NUM >= 503
453 return moonbr_io_drain_cont(L, 0, 0);
454 #else
455 return moonbr_io_drain_cont(L);
456 #endif
457 }
459 moonbr_io_yield_wrapper(moonbr_io_drain_yield, moonbr_io_drain_call);
461 #ifdef MOONBR_IO_USE_TLS
462 #define moonbr_io_write_tls(buf, buflen) \
463 if (handle->tls) { \
464 do { \
465 if (!handle->tlshandshake) { \
466 do written = tls_handshake(handle->tls); \
467 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
468 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
469 handle->tlshandshake = written; \
470 errno = EAGAIN; \
471 break; \
472 } \
473 if (written < 0) { \
474 lua_pushnil(L); \
475 lua_pushstring(L, tls_error(handle->tls)); \
476 return 2; \
477 } \
478 handle->tlshandshake = 1; \
479 } \
480 do written = tls_write(handle->tls, (buf), (buflen)); \
481 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
482 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
483 errno = EAGAIN; \
484 break; \
485 } \
486 if (written < 0) { \
487 lua_pushnil(L); \
488 lua_pushstring(L, tls_error(handle->tls)); \
489 return 2; \
490 } \
491 } while (0); \
492 } \
493 else
494 #endif
496 static int moonbr_io_write_impl(lua_State *L, int nonblocking, int flush) {
497 moonbr_io_handle_t *handle;
498 int i, top;
499 const char *str;
500 size_t strlen;
501 ssize_t written;
502 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
503 if (handle->closed) luaL_error(L, "Attempt to write to a closed I/O handle");
504 if (handle->finished) luaL_error(L, "Attempt to write to a finished I/O handle");
505 if (handle->writeerr) {
506 lua_pushnil(L);
507 lua_pushliteral(L, "Previous write error");
508 return 2;
509 }
510 handle->writeerr = 1;
511 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) {
512 moonbr_io_errmsg();
513 lua_pushnil(L);
514 lua_pushstring(L, errmsg);
515 return 2;
516 }
517 top = lua_gettop(L);
518 lua_getuservalue(L, 1);
519 lua_getfield(L, -1, "writequeue");
520 for (i=2; i<=top; i++) {
521 luaL_checklstring(L, i, &strlen);
522 lua_pushvalue(L, i);
523 lua_rawseti(L, -2, handle->writeqin++);
524 handle->writeleft += strlen;
525 }
526 if (flush) handle->flushedleft = handle->writeleft;
527 while (handle->writeqout != handle->writeqin) {
528 lua_rawgeti(L, -1, handle->writeqout);
529 str = lua_tolstring(L, -1, &strlen);
530 while (handle->writeqoff < strlen) {
531 if (
532 strlen - handle->writeqoff <
533 MOONBR_IO_WRITEBUFLEN - handle->writebufin
534 ) {
535 memcpy(
536 handle->writebuf + handle->writebufin,
537 str + handle->writeqoff,
538 strlen - handle->writeqoff
539 );
540 handle->writebufin += strlen - handle->writeqoff;
541 break;
542 } else {
543 memcpy(
544 handle->writebuf + handle->writebufin,
545 str + handle->writeqoff,
546 MOONBR_IO_WRITEBUFLEN - handle->writebufin
547 );
548 handle->writeqoff += MOONBR_IO_WRITEBUFLEN - handle->writebufin;
549 handle->writebufin = MOONBR_IO_WRITEBUFLEN;
550 while (handle->writebufout < MOONBR_IO_WRITEBUFLEN) {
551 if (moonbr_io_handle_set_nopush(L, handle, 1)) {
552 moonbr_io_errmsg();
553 lua_pushnil(L);
554 lua_pushstring(L, errmsg);
555 return 2;
556 }
557 #ifdef MOONBR_IO_USE_TLS
558 moonbr_io_write_tls(
559 handle->writebuf + handle->writebufout,
560 MOONBR_IO_WRITEBUFLEN - handle->writebufout
561 )
562 #endif
563 written = write(
564 handle->fd,
565 handle->writebuf + handle->writebufout,
566 MOONBR_IO_WRITEBUFLEN - handle->writebufout
567 );
568 if (written < 0) {
569 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
570 goto moonbr_io_write_impl_block;
571 } else if (errno != EINTR) {
572 moonbr_io_errmsg();
573 lua_pushnil(L);
574 lua_pushstring(L, errmsg);
575 return 2;
576 }
577 } else {
578 handle->writebufout += written;
579 handle->writeleft -= written;
580 if (handle->flushedleft) {
581 if (written >= handle->flushedleft) {
582 handle->flushedleft = 0;
583 if (moonbr_io_handle_set_nopush(L, handle, 0)) {
584 moonbr_io_errmsg();
585 lua_pushnil(L);
586 lua_pushstring(L, errmsg);
587 return 2;
588 }
589 } else {
590 handle->flushedleft -= written;
591 }
592 }
593 }
594 }
595 handle->writebufin = 0;
596 handle->writebufout = 0;
597 }
598 }
599 handle->writeqoff = 0;
600 lua_pop(L, 1);
601 lua_pushnil(L);
602 lua_rawseti(L, -2, handle->writeqout++);
603 }
604 while (handle->flushedleft) {
605 if (moonbr_io_handle_set_nopush(L, handle, 1)) {
606 moonbr_io_errmsg();
607 lua_pushnil(L);
608 lua_pushstring(L, errmsg);
609 return 2;
610 }
611 #ifdef MOONBR_IO_USE_TLS
612 moonbr_io_write_tls(
613 handle->writebuf + handle->writebufout,
614 handle->writebufin - handle->writebufout
615 )
616 #endif
617 written = write(
618 handle->fd,
619 handle->writebuf + handle->writebufout,
620 handle->writebufin - handle->writebufout
621 );
622 if (written < 0) {
623 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
624 goto moonbr_io_write_impl_block;
625 } else if (errno != EINTR) {
626 moonbr_io_errmsg();
627 lua_pushnil(L);
628 lua_pushstring(L, errmsg);
629 return 2;
630 }
631 } else {
632 handle->writebufout += written;
633 handle->writeleft -= written;
634 if (handle->flushedleft) {
635 if (written >= handle->flushedleft) {
636 handle->flushedleft = 0;
637 if (moonbr_io_handle_set_nopush(L, handle, 0)) {
638 moonbr_io_errmsg();
639 lua_pushnil(L);
640 lua_pushstring(L, errmsg);
641 return 2;
642 }
643 } else {
644 handle->flushedleft -= written;
645 }
646 }
647 }
648 }
649 if (handle->writebufout == handle->writebufin) {
650 handle->writebufin = 0;
651 handle->writebufout = 0;
652 }
653 if (nonblocking) lua_pushinteger(L, 0);
654 else lua_pushvalue(L, 1);
655 handle->writeerr = 0;
656 return 1;
657 moonbr_io_write_impl_block:
658 lua_pushinteger(L, handle->writeleft);
659 handle->writeerr = 0;
660 return 1;
661 }
663 static int moonbr_io_write(lua_State *L) {
664 return moonbr_io_write_impl(L, 0, 0);
665 }
667 static int moonbr_io_write_nb(lua_State *L) {
668 return moonbr_io_write_impl(L, 1, 0);
669 }
671 static int moonbr_io_flush(lua_State *L) {
672 return moonbr_io_write_impl(L, 0, 1);
673 }
675 static int moonbr_io_flush_nb(lua_State *L) {
676 return moonbr_io_write_impl(L, 1, 1);
677 }
679 #if LUA_VERSION_NUM >= 503
680 static int moonbr_io_write_cont(lua_State *L, int status, lua_KContext ctx) {
681 #else
682 static int moonbr_io_write_cont(lua_State *L) {
683 #endif
684 while (1) {
685 lua_pushcfunction(L, moonbr_io_write_nb);
686 lua_pushvalue(L, 1);
687 lua_call(L, 1, 2);
688 if (lua_isnil(L, -2)) return 2;
689 if (!lua_tointeger(L, -2)) {
690 lua_pushvalue(L, 1);
691 return 1;
692 }
693 lua_pop(L, 2);
694 lua_pushvalue(L, 2);
695 lua_callk(L, 0, 0, 0, moonbr_io_write_cont);
696 }
697 }
699 static int moonbr_io_write_call(lua_State *L) {
700 lua_pushcfunction(L, moonbr_io_write_nb);
701 lua_insert(L, 3);
702 lua_pushvalue(L, 1);
703 lua_insert(L, 4);
704 lua_call(L, lua_gettop(L) - 3, 2);
705 if (lua_isnil(L, -2)) return 2;
706 if (!lua_tointeger(L, -2)) {
707 lua_pushvalue(L, 1);
708 return 1;
709 }
710 #if LUA_VERSION_NUM >= 503
711 return moonbr_io_write_cont(L, 0, 0);
712 #else
713 return moonbr_io_write_cont(L);
714 #endif
715 }
717 moonbr_io_yield_wrapper(moonbr_io_write_yield, moonbr_io_write_call);
719 static int moonbr_io_flush_call(lua_State *L) {
720 lua_pushcfunction(L, moonbr_io_flush_nb);
721 lua_insert(L, 3);
722 lua_pushvalue(L, 1);
723 lua_insert(L, 4);
724 lua_call(L, lua_gettop(L) - 3, 2);
725 if (lua_isnil(L, -2)) return 2;
726 if (!lua_tointeger(L, -2)) {
727 lua_pushvalue(L, 1);
728 return 1;
729 }
730 #if LUA_VERSION_NUM >= 503
731 return moonbr_io_write_cont(L, 0, 0);
732 #else
733 return moonbr_io_write_cont(L);
734 #endif
735 }
737 moonbr_io_yield_wrapper(moonbr_io_flush_yield, moonbr_io_flush_call);
739 static int moonbr_io_finish(lua_State *L) {
740 moonbr_io_handle_t *handle;
741 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
742 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
743 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
744 if (handle->writeleft) {
745 lua_pushcfunction(L, moonbr_io_flush);
746 lua_pushvalue(L, 1);
747 if (lua_pcall(L, 1, 2, 0)) {
748 handle->finished = 1;
749 lua_error(L);
750 }
751 if (!lua_toboolean(L, -2)) {
752 handle->finished = 1;
753 return 2;
754 }
755 }
756 handle->finished = 1;
757 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
758 if (shutdown(handle->fd, SHUT_WR)) {
759 moonbr_io_errmsg();
760 lua_pushnil(L);
761 lua_pushstring(L, errmsg);
762 return 2;
763 }
764 } else {
765 #ifdef MOONBR_IO_USE_TLS
766 if (handle->tls) tls_close(handle->tls);
767 #endif
768 if (close(handle->fd)) {
769 moonbr_io_errmsg();
770 handle->fd = -1;
771 lua_pushnil(L);
772 lua_pushstring(L, errmsg);
773 return 2;
774 }
775 handle->fd = -1; /* fake EOF on read */
776 }
777 lua_pushboolean(L, 1);
778 return 1;
779 }
781 static int moonbr_io_close_impl(lua_State *L, int reset) {
782 moonbr_io_handle_t *handle;
783 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
784 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
785 if (!reset) {
786 if (handle->writeleft) {
787 lua_pushcfunction(L, moonbr_io_flush);
788 lua_pushvalue(L, 1);
789 if (lua_pcall(L, 1, 2, 0)) {
790 handle->closed = 1;
791 close(handle->fd);
792 handle->fd = -1;
793 lua_error(L);
794 }
795 handle->closed = 1;
796 if (!lua_toboolean(L, -2)) {
797 close(handle->fd);
798 handle->fd = -1;
799 return 2;
800 }
801 } else {
802 handle->closed = 1;
803 }
804 if (moonbr_io_handle_set_linger(L, handle, -1)) {
805 moonbr_io_errmsg();
806 close(handle->fd);
807 handle->fd = -1;
808 lua_pushnil(L);
809 lua_pushstring(L, errmsg);
810 return 2;
811 }
812 } else {
813 handle->closed = 1;
814 }
815 if (handle->fd >= 0) {
816 #ifdef MOONBR_IO_USE_TLS
817 if (handle->tls) tls_close(handle->tls);
818 #endif
819 if (close(handle->fd)) {
820 moonbr_io_errmsg();
821 handle->fd = -1;
822 lua_pushnil(L);
823 lua_pushstring(L, errmsg);
824 return 2;
825 }
826 handle->fd = -1;
827 }
828 lua_pushboolean(L, 1);
829 return 1;
831 }
833 static int moonbr_io_close(lua_State *L) {
834 return moonbr_io_close_impl(L, 0);
835 }
837 static int moonbr_io_reset(lua_State *L) {
838 return moonbr_io_close_impl(L, 1);
839 }
841 static int moonbr_io_handlegc(lua_State *L) {
842 moonbr_io_handle_t *handle;
843 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
844 if (handle->fd >= 0) {
845 lua_pushcfunction(L, moonbr_io_reset);
846 lua_pushvalue(L, 1);
847 lua_pushinteger(L, 0);
848 lua_call(L, 2, 0);
849 }
850 #ifdef MOONBR_IO_USE_TLS
851 if (handle->tls) {
852 tls_free(handle->tls);
853 handle->tls = NULL;
854 }
855 if (handle->servertls) {
856 tls_free(handle->servertls);
857 handle->servertls = NULL;
858 }
859 #endif
860 return 0;
861 }
863 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
864 moonbr_io_handle_t *handle;
865 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
866 if (!handle->closed) {
867 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
868 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
869 lua_call(L, 1, 0);
870 }
871 }
873 static int moonbr_io_pushhandle_impl(lua_State *L) {
874 int *fd;
875 moonbr_io_handle_t *handle;
876 struct sockaddr addr;
877 socklen_t addrlen;
878 fd = lua_touserdata(L, 1);
879 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
880 handle->fd = -1; /* avoid closing incomplete handle */
881 addrlen = sizeof(addr);
882 if (getsockname(*fd, &addr, &addrlen)) {
883 if (errno != ENOTSOCK) {
884 moonbr_io_errmsg();
885 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
886 }
887 handle->issock = 0;
888 } else {
889 handle->issock = 1;
890 handle->addrfam = addr.sa_family;
891 }
892 handle->finished = 0;
893 handle->closed = 0;
894 handle->nonblocking = -1;
895 handle->nopush = -1;
896 handle->readerr = 0;
897 handle->readbufin = 0;
898 handle->readbufout = 0;
899 handle->writeerr = 0;
900 handle->writeleft = 0;
901 handle->flushedleft = 0;
902 handle->writeqin = 0;
903 handle->writeqout = 0;
904 handle->writeqoff = 0;
905 handle->writebufin = 0;
906 handle->writebufout = 0;
907 #ifdef MOONBR_IO_USE_TLS
908 handle->tls = NULL;
909 handle->servertls = NULL;
910 handle->tlshandshake = 0;
911 #endif
912 handle->fd = *fd; /* required for set_linger call */
913 if (moonbr_io_handle_set_linger(L, handle, 0)) {
914 moonbr_io_errmsg();
915 handle->fd = -1;
916 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
917 }
918 handle->fd = -1; /* avoid closing incomplete handle */
919 luaL_setmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
920 lua_newtable(L); // uservalue
921 lua_newtable(L);
922 lua_setfield(L, -2, "writequeue");
923 lua_newtable(L); // public
924 if (handle->addrfam == AF_INET6) {
925 struct sockaddr_in6 addr_in6;
926 char addrstrbuf[INET6_ADDRSTRLEN];
927 const char *addrstr;
928 addrlen = sizeof(addr_in6);
929 if (getsockname(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
930 moonbr_io_errmsg();
931 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
932 }
933 if (addrlen > sizeof(addr_in6)) {
934 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
935 }
936 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
937 if (!addrstr) {
938 moonbr_io_errmsg();
939 luaL_error(L, "Could not format local IP address: %s", errmsg);
940 } else {
941 lua_pushstring(L, addrstr);
942 lua_setfield(L, -2, "local_ip6");
943 }
944 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
945 lua_setfield(L, -2, "local_tcpport");
946 if (getpeername(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
947 moonbr_io_errmsg();
948 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
949 }
950 if (addrlen > sizeof(addr_in6)) {
951 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
952 }
953 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
954 if (!addrstr) {
955 moonbr_io_errmsg();
956 luaL_error(L, "Could not format remote IP address: %s", errmsg);
957 } else {
958 lua_pushstring(L, addrstr);
959 lua_setfield(L, -2, "remote_ip6");
960 }
961 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
962 lua_setfield(L, -2, "remote_tcpport");
963 } else if (handle->addrfam == AF_INET) {
964 struct sockaddr_in addr_in;
965 char addrstrbuf[INET_ADDRSTRLEN];
966 const char *addrstr;
967 addrlen = sizeof(addr_in);
968 if (getsockname(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
969 moonbr_io_errmsg();
970 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
971 }
972 if (addrlen > sizeof(addr_in)) {
973 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
974 }
975 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
976 if (!addrstr) {
977 moonbr_io_errmsg();
978 luaL_error(L, "Could not format local IP address: %s", errmsg);
979 } else {
980 lua_pushstring(L, addrstr);
981 lua_setfield(L, -2, "local_ip4");
982 }
983 lua_pushinteger(L, ntohs(addr_in.sin_port));
984 lua_setfield(L, -2, "local_tcpport");
985 if (getpeername(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
986 moonbr_io_errmsg();
987 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
988 }
989 if (addrlen > sizeof(addr_in)) {
990 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
991 }
992 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
993 if (!addrstr) {
994 moonbr_io_errmsg();
995 luaL_error(L, "Could not format remote IP address: %s", errmsg);
996 } else {
997 lua_pushstring(L, addrstr);
998 lua_setfield(L, -2, "remote_ip4");
999 }
1000 lua_pushinteger(L, ntohs(addr_in.sin_port));
1001 lua_setfield(L, -2, "remote_tcpport");
1003 luaL_setmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1004 lua_setfield(L, -2, "public");
1005 lua_setuservalue(L, -2);
1006 handle->fd = *fd;
1007 *fd = -1; /* closing is now handled by garbage collection */
1008 return 1;
1011 void moonbr_io_pushhandle(lua_State *L, int fd) {
1012 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1013 lua_pushlightuserdata(L, &fd);
1014 if (lua_pcall(L, 1, 1, 0)) {
1015 if (fd != -1) close(fd); // TODO: correct to close file descriptor here?
1016 lua_error(L);
1020 static int moonbr_io_handleindex(lua_State *L) {
1021 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1022 luaL_checkany(L, 2);
1023 lua_getuservalue(L, 1);
1024 lua_getfield(L, -1, "public");
1025 lua_pushvalue(L, 2);
1026 lua_gettable(L, -2);
1027 return 1;
1030 static int moonbr_io_handlenewindex(lua_State *L) {
1031 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1032 luaL_checkany(L, 2);
1033 luaL_checkany(L, 3);
1034 lua_getuservalue(L, 1);
1035 lua_getfield(L, -1, "public");
1036 lua_pushvalue(L, 2);
1037 lua_pushvalue(L, 3);
1038 lua_settable(L, -3);
1039 return 0;
1042 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
1043 const char *path;
1044 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1045 const int path_maxlen = sizeof(struct sockaddr_un) - (
1046 (void *)sockaddr.sun_path - (void *)&sockaddr
1047 ) - 1; /* one byte for termination */
1048 int sock;
1049 path = luaL_checkstring(L, 1);
1050 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1051 strcpy(sockaddr.sun_path, path);
1052 sock = socket(
1053 PF_LOCAL,
1054 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1056 );
1057 if (sock < 0) {
1058 moonbr_io_errmsg();
1059 lua_pushnil(L);
1060 lua_pushstring(L, errmsg);
1061 return 2;
1063 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1064 if (!nonblocking && errno == EINTR) {
1065 moonbr_io_errmsg();
1066 close(sock);
1067 lua_pushnil(L);
1068 lua_pushstring(L, errmsg);
1069 return 2;
1070 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
1071 moonbr_io_errmsg();
1072 lua_pushnil(L);
1073 lua_pushstring(L, errmsg);
1074 return 2;
1077 moonbr_io_pushhandle(L, sock);
1078 return 1;
1081 static int moonbr_io_localconnect(lua_State *L) {
1082 return moonbr_io_localconnect_impl(L, 0);
1085 static int moonbr_io_localconnect_nb(lua_State *L) {
1086 return moonbr_io_localconnect_impl(L, 1);
1089 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
1090 const char *host, *port;
1091 struct addrinfo hints = { 0, };
1092 struct addrinfo *res, *addrinfo;
1093 int errcode;
1094 int sock;
1095 host = luaL_checkstring(L, 1);
1096 port = luaL_checkstring(L, 2);
1097 hints.ai_family = AF_UNSPEC;
1098 hints.ai_socktype = SOCK_STREAM;
1099 hints.ai_protocol = IPPROTO_TCP;
1100 hints.ai_flags = AI_ADDRCONFIG;
1101 errcode = getaddrinfo(host, port, &hints, &res);
1102 if (errcode) {
1103 freeaddrinfo(res);
1104 if (errcode == EAI_SYSTEM) {
1105 moonbr_io_errmsg();
1106 lua_pushnil(L);
1107 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1108 } else {
1109 lua_pushnil(L);
1110 lua_pushstring(L, gai_strerror(errcode));
1112 return 2;
1114 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1115 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1117 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1118 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1120 addrinfo = res;
1121 moonbr_io_tcpconnect_found:
1122 sock = socket(
1123 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1124 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1125 addrinfo->ai_protocol
1126 );
1127 if (sock < 0) {
1128 moonbr_io_errmsg();
1129 freeaddrinfo(res);
1130 lua_pushnil(L);
1131 lua_pushstring(L, errmsg);
1132 return 2;
1134 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1135 freeaddrinfo(res);
1136 if (!nonblocking && errno == EINTR) {
1137 moonbr_io_errmsg();
1138 close(sock);
1139 lua_pushnil(L);
1140 lua_pushstring(L, errmsg);
1141 return 2;
1142 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
1143 moonbr_io_errmsg();
1144 lua_pushnil(L);
1145 lua_pushstring(L, errmsg);
1146 return 2;
1148 } else {
1149 freeaddrinfo(res);
1151 moonbr_io_pushhandle(L, sock);
1152 return 1;
1155 static int moonbr_io_tcpconnect(lua_State *L) {
1156 return moonbr_io_tcpconnect_impl(L, 0);
1159 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1160 return moonbr_io_tcpconnect_impl(L, 1);
1163 static int moonbr_io_locallisten(lua_State *L) {
1164 moonbr_io_listener_t *listener;
1165 const char *path;
1166 struct stat sb;
1167 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1168 const int path_maxlen = sizeof(struct sockaddr_un) - (
1169 (void *)sockaddr.sun_path - (void *)&sockaddr
1170 ) - 1; /* one byte for termination */
1171 int sock;
1172 path = luaL_checkstring(L, 1);
1173 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1174 strcpy(sockaddr.sun_path, path);
1175 if (stat(path, &sb) == 0) {
1176 if (S_ISSOCK(sb.st_mode)) unlink(path);
1178 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1179 listener->fd = -1;
1180 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1181 sock = socket(
1182 PF_LOCAL,
1183 SOCK_STREAM | SOCK_CLOEXEC,
1185 );
1186 if (sock < 0) {
1187 moonbr_io_errmsg();
1188 lua_pushnil(L);
1189 lua_pushstring(L, errmsg);
1190 return 2;
1192 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1193 moonbr_io_errmsg();
1194 close(sock);
1195 lua_pushnil(L);
1196 lua_pushstring(L, errmsg);
1197 return 2;
1199 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1200 moonbr_io_errmsg();
1201 close(sock);
1202 lua_pushnil(L);
1203 lua_pushstring(L, errmsg);
1204 return 2;
1206 listener->fd = sock;
1207 listener->addrfam = AF_LOCAL;
1208 listener->nonblocking = -1;
1209 return 1;
1212 static int moonbr_io_tcplisten(lua_State *L) {
1213 moonbr_io_listener_t *listener;
1214 const char *host, *port;
1215 struct addrinfo hints = { 0, };
1216 struct addrinfo *res, *addrinfo;
1217 int errcode;
1218 int sock;
1219 host = luaL_optstring(L, 1, NULL);
1220 port = luaL_checkstring(L, 2);
1221 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1222 listener->fd = -1;
1223 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1224 hints.ai_family = AF_UNSPEC;
1225 hints.ai_socktype = SOCK_STREAM;
1226 hints.ai_protocol = IPPROTO_TCP;
1227 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1228 errcode = getaddrinfo(host, port, &hints, &res);
1229 if (errcode) {
1230 freeaddrinfo(res);
1231 if (errcode == EAI_SYSTEM) {
1232 moonbr_io_errmsg();
1233 lua_pushnil(L);
1234 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1235 } else {
1236 lua_pushnil(L);
1237 lua_pushstring(L, gai_strerror(errcode));
1239 return 2;
1241 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1242 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1244 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1245 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1247 addrinfo = res;
1248 moonbr_io_tcpconnect_found:
1249 listener->addrfam = addrinfo->ai_family;
1250 sock = socket(
1251 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1252 addrinfo->ai_socktype | SOCK_CLOEXEC,
1253 addrinfo->ai_protocol
1254 );
1255 if (sock < 0) {
1256 moonbr_io_errmsg();
1257 freeaddrinfo(res);
1258 lua_pushnil(L);
1259 lua_pushstring(L, errmsg);
1260 return 2;
1263 static const int reuseval = 1;
1264 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1265 moonbr_io_errmsg();
1266 freeaddrinfo(res);
1267 close(sock);
1268 lua_pushnil(L);
1269 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1270 return 2;
1273 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1274 moonbr_io_errmsg();
1275 freeaddrinfo(res);
1276 close(sock);
1277 lua_pushnil(L);
1278 lua_pushstring(L, errmsg);
1279 return 2;
1281 freeaddrinfo(res);
1282 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1283 moonbr_io_errmsg();
1284 close(sock);
1285 lua_pushnil(L);
1286 lua_pushstring(L, errmsg);
1287 return 2;
1289 listener->fd = sock;
1290 listener->nonblocking = -1;
1291 return 1;
1294 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1295 moonbr_io_listener_t *listener;
1296 int fd;
1297 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1298 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1299 if (listener->nonblocking != nonblocking) {
1300 int flags;
1301 flags = fcntl(listener->fd, F_GETFL, 0);
1302 if (flags == -1) {
1303 moonbr_io_errmsg();
1304 close(listener->fd);
1305 listener->fd = -1;
1306 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1308 if (nonblocking) flags |= O_NONBLOCK;
1309 else flags &= ~O_NONBLOCK;
1310 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1311 moonbr_io_errmsg();
1312 close(listener->fd);
1313 listener->fd = -1;
1314 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1316 listener->nonblocking = nonblocking;
1318 while (1) {
1319 #if defined(__linux__) && !defined(_GNU_SOURCE)
1320 fd = accept(listener->fd, NULL, NULL);
1321 if (fd != -1) {
1322 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
1323 moonbr_io_errmsg();
1324 close(listener->fd);
1325 listener->fd = -1;
1326 close(fd);
1327 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1330 #else
1331 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1332 #endif
1333 if (fd < 0) {
1334 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1335 lua_pushboolean(L, 0);
1336 lua_pushliteral(L, "No incoming connection pending");
1337 return 2;
1338 } else if (errno != EINTR) {
1339 moonbr_io_errmsg();
1340 lua_pushnil(L);
1341 lua_pushstring(L, errmsg);
1342 return 2;
1344 } else {
1345 moonbr_io_pushhandle(L, fd);
1346 return 1;
1351 static int moonbr_io_accept(lua_State *L) {
1352 return moonbr_io_accept_impl(L, 0);
1355 static int moonbr_io_accept_nb(lua_State *L) {
1356 return moonbr_io_accept_impl(L, 1);
1359 static int moonbr_io_unlisten(lua_State *L) {
1360 moonbr_io_listener_t *listener;
1361 struct sockaddr_un addr;
1362 socklen_t addrlen;
1363 struct stat sb;
1364 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1365 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1366 addrlen = sizeof(addr);
1367 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1368 if (close(listener->fd)) {
1369 moonbr_io_errmsg();
1370 listener->fd = -1;
1371 if (addrlen && addrlen <= sizeof(addr)) {
1372 if (stat(addr.sun_path, &sb) == 0) {
1373 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1376 lua_pushnil(L);
1377 lua_pushstring(L, errmsg);
1378 return 2;
1380 listener->fd = -1;
1381 if (addrlen && addrlen <= sizeof(addr)) {
1382 if (stat(addr.sun_path, &sb) == 0) {
1383 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1386 lua_pushboolean(L, 1);
1387 return 1;
1390 static int moonbr_io_listenergc(lua_State *L) {
1391 moonbr_io_listener_t *listener;
1392 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1393 if (listener->fd >= 0) close(listener->fd);
1394 listener->fd = -1;
1395 return 0;
1398 static int moonbr_io_exec(lua_State *L) {
1399 char **argv;
1400 int i, argc;
1401 int sockin[2], sockout[2], sockerr[2];
1402 volatile int errorcond = 0;
1403 volatile char errmsgbuf[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG;
1404 moonbr_io_child_t *child;
1405 argc = lua_gettop(L);
1406 argv = lua_newuserdata(L, (argc + 1) * sizeof(char *));
1407 for (i=0; i<argc; i++) argv[i] = (char *)luaL_checkstring(L, i+1);
1408 argv[argc] = NULL;
1409 child = lua_newuserdata(L, sizeof(moonbr_io_child_t));
1410 child->pid = 0;
1411 lua_newtable(L);
1412 lua_setuservalue(L, -2);
1413 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1414 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1415 moonbr_io_errmsg();
1416 lua_pushnil(L);
1417 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1418 return 2;
1420 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1421 moonbr_io_errmsg();
1422 close(sockin[0]);
1423 close(sockin[1]);
1424 lua_pushnil(L);
1425 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1426 return 2;
1428 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1429 moonbr_io_errmsg();
1430 close(sockin[0]);
1431 close(sockin[1]);
1432 close(sockout[0]);
1433 close(sockout[1]);
1434 lua_pushnil(L);
1435 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1436 return 2;
1438 child->pid = vfork();
1439 if (child->pid == -1) {
1440 moonbr_io_errmsg();
1441 close(sockin[0]);
1442 close(sockin[1]);
1443 close(sockout[0]);
1444 close(sockout[1]);
1445 close(sockerr[0]);
1446 close(sockerr[1]);
1447 lua_pushnil(L);
1448 lua_pushfstring(L, "Could not fork: %s", errmsg);
1449 return 2;
1451 if (!child->pid) {
1452 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1453 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1454 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1455 closefrom(3);
1456 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1457 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1458 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1459 if (execvp(argv[0], argv)) {
1460 errorcond = 2;
1461 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1462 _exit(0);
1464 moonbr_io_exec_error1:
1465 errorcond = 1;
1466 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1467 _exit(0);
1469 close(sockin[1]);
1470 close(sockout[1]);
1471 close(sockerr[1]);
1472 if (errorcond) {
1473 int status;
1474 close(sockin[0]);
1475 close(sockout[0]);
1476 close(sockerr[0]);
1477 while (waitpid(child->pid, &status, 0) == -1) {
1478 if (errno != EINTR) {
1479 moonbr_io_errmsg();
1480 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1483 child->pid = 0;
1484 lua_pushnil(L);
1485 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1486 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1487 return 2;
1489 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1490 lua_pushlightuserdata(L, &sockin[0]);
1491 if (lua_pcall(L, 1, 1, 0)) {
1492 if (sockin[0] != -1) close(sockin[0]);
1493 close(sockout[0]);
1494 close(sockerr[0]);
1495 goto moonbr_io_exec_error2;
1497 lua_setfield(L, -2, "stdin");
1498 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1499 lua_pushlightuserdata(L, &sockout[0]);
1500 if (lua_pcall(L, 1, 1, 0)) {
1501 if (sockout[0] != -1) close(sockout[0]);
1502 close(sockerr[0]);
1503 goto moonbr_io_exec_error2;
1505 lua_setfield(L, -2, "stdout");
1506 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1507 lua_pushlightuserdata(L, &sockerr[0]);
1508 if (lua_pcall(L, 1, 1, 0)) {
1509 if (sockerr[0] != -1) close(sockerr[0]);
1510 goto moonbr_io_exec_error2;
1512 lua_setfield(L, -2, "stderr");
1513 return 1;
1514 moonbr_io_exec_error2:
1516 int status;
1517 while (waitpid(child->pid, &status, 0) == -1) {
1518 if (errno != EINTR) {
1519 moonbr_io_errmsg();
1520 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1524 child->pid = 0;
1525 return lua_error(L);
1528 static int moonbr_io_childindex(lua_State *L) {
1529 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1530 luaL_checkany(L, 2);
1531 lua_getuservalue(L, 1);
1532 lua_pushvalue(L, 2);
1533 lua_gettable(L, -2);
1534 if (lua_isnil(L, -1)) {
1535 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1536 lua_pushvalue(L, 2);
1537 lua_gettable(L, -2);
1539 return 1;
1542 static int moonbr_io_childnewindex(lua_State *L) {
1543 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1544 luaL_checkany(L, 2);
1545 luaL_checkany(L, 3);
1546 lua_getuservalue(L, 1);
1547 lua_pushvalue(L, 2);
1548 lua_pushvalue(L, 3);
1549 lua_settable(L, -3);
1550 return 0;
1553 static int moonbr_io_childgc(lua_State *L) {
1554 moonbr_io_child_t *child;
1555 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1556 if (child->pid) {
1557 int status;
1558 if (kill(child->pid, SIGKILL)) {
1559 moonbr_io_errmsg();
1560 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1562 while (waitpid(child->pid, &status, 0) == -1) {
1563 if (errno != EINTR) {
1564 moonbr_io_errmsg();
1565 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1569 return 0;
1572 static int moonbr_io_kill(lua_State *L) {
1573 moonbr_io_child_t *child;
1574 int sig;
1575 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1576 sig = luaL_optinteger(L, 2, SIGTERM);
1577 if (!child->pid) luaL_error(L, "Attempt to kill an already collected child process");
1578 if (kill(child->pid, sig)) {
1579 moonbr_io_errmsg();
1580 luaL_error(L, "Error in kill call: %s", errmsg);
1582 lua_settop(L, 1);
1583 return 1;
1586 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1587 moonbr_io_child_t *child;
1588 pid_t waitedpid;
1589 int status;
1590 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1591 if (!child->pid) luaL_error(L, "Attempt to wait for an already collected child process");
1592 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1593 if (errno != EINTR) {
1594 moonbr_io_errmsg();
1595 luaL_error(L, "Error in waitpid call: %s", errmsg);
1598 if (!waitedpid) {
1599 lua_pushboolean(L, 0);
1600 lua_pushliteral(L, "Process is still running");
1601 return 2;
1602 } else {
1603 child->pid = 0;
1604 if (WIFEXITED(status)) {
1605 lua_pushinteger(L, WEXITSTATUS(status));
1606 } else if (WIFSIGNALED(status)) {
1607 lua_pushinteger(L, -WTERMSIG(status));
1608 } else {
1609 luaL_error(L, "Unexpected status value returned by waitpid call");
1611 return 1;
1615 static int moonbr_io_wait(lua_State *L) {
1616 return moonbr_io_wait_impl(L, 0);
1619 static int moonbr_io_wait_nb(lua_State *L) {
1620 return moonbr_io_wait_impl(L, 1);
1623 #if LUA_VERSION_NUM >= 503
1624 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1625 #else
1626 static int moonbr_io_wait_cont(lua_State *L) {
1627 #endif
1628 #if !(LUA_VERSION_NUM >= 503)
1629 int ctx = 0;
1630 lua_getctx(L, &ctx);
1631 #endif
1632 while (1) {
1633 lua_pushcfunction(L, moonbr_io_wait_nb);
1634 lua_pushvalue(L, 1);
1635 lua_call(L, 1, 1);
1636 if (!lua_isnil(L, -1)) break;
1637 lua_pushvalue(L, 2);
1638 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1640 return 1;
1643 static int moonbr_io_wait_call(lua_State *L) {
1644 lua_settop(L, 2);
1645 #if LUA_VERSION_NUM >= 503
1646 return moonbr_io_wait_cont(L, 0, 0);
1647 #else
1648 return moonbr_io_wait_cont(L);
1649 #endif
1652 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1654 #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)
1679 #endif
1681 static int moonbr_io_poll(lua_State *L) {
1682 moonbr_io_handle_t *handle;
1683 moonbr_io_listener_t *listener;
1684 int fd, isnum;
1685 int nfds = 0;
1686 fd_set readfds, writefds, exceptfds;
1687 struct timeval timeout = {0, };
1688 int status;
1689 FD_ZERO(&readfds);
1690 FD_ZERO(&writefds);
1691 FD_ZERO(&exceptfds);
1692 if (!lua_isnoneornil(L, 1)) {
1693 luaL_checktype(L, 1, LUA_TTABLE);
1694 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1695 if (lua_toboolean(L, -1)) {
1696 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1697 if (handle) {
1698 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1699 fd = handle->fd;
1700 #if MOONBR_IO_USE_TLS
1701 moonbr_io_poll_tls();
1702 #endif
1703 if (
1704 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1705 handle->readbufin != handle->readbufout /* data pending in buffer */
1706 ) {
1707 lua_pushboolean(L, 1);
1708 return 1;
1710 } else {
1711 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1712 if (listener) {
1713 fd = listener->fd;
1714 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1715 } else {
1716 fd = lua_tointegerx(L, -2, &isnum);
1717 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1720 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1721 FD_SET(fd, &readfds);
1722 if (fd+1 > nfds) nfds = fd+1;
1726 if (!lua_isnoneornil(L, 2)) {
1727 luaL_checktype(L, 2, LUA_TTABLE);
1728 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1729 if (lua_toboolean(L, -1)) {
1730 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1731 if (handle) {
1732 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1733 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1734 fd = handle->fd;
1735 #if MOONBR_IO_USE_TLS
1736 moonbr_io_poll_tls();
1737 #endif
1738 } else {
1739 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1740 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1741 fd = lua_tointegerx(L, -2, &isnum);
1742 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1744 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1745 FD_SET(fd, &writefds);
1746 if (fd+1 > nfds) nfds = fd+1;
1750 if (!lua_isnoneornil(L, 3)) {
1751 lua_Number n;
1752 n = lua_tonumberx(L, 3, &isnum);
1753 if (isnum && n<0) {
1754 lua_pushboolean(L, 0);
1755 lua_pushliteral(L, "Negative timeout");
1756 return 2;
1757 } else if (isnum && n>=0 && n<100000000) {
1758 timeout.tv_sec = n;
1759 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1760 } else {
1761 luaL_argcheck(L, 0, 3, "not a valid timeout");
1763 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1764 } else {
1765 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1767 if (status == -1) {
1768 if (errno == EINTR) {
1769 lua_pushnil(L);
1770 lua_pushliteral(L, "Signal received while polling file descriptors");
1771 return 2;
1772 } else {
1773 moonbr_io_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 #ifdef MOONBR_IO_USE_TLS
1902 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
1903 #endif
1904 if (handle->readbufin || handle->writebufin) {
1905 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
1907 if (tlsconf->server) tls = tls_server();
1908 else {
1909 servername = luaL_checkstring(L, 3);
1910 tls = tls_client();
1912 if (!tls) {
1913 return luaL_error(L, "Could not allocate memory for TLS context");
1915 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
1916 if (tlsconf->server) {
1917 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
1918 handle->servertls = tls;
1919 handle->tls = tls2;
1920 } else {
1921 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
1922 handle->tls = tls;
1924 lua_settop(L, 1);
1925 return 1;
1926 moonbr_io_starttls_error:
1927 lua_pushnil(L);
1928 lua_pushstring(L, tls_error(tls));
1929 tls_free(tls);
1930 return 2;
1933 #endif
1935 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1936 {"read", moonbr_io_read},
1937 {"read_nb", moonbr_io_read_nb},
1938 {"read_call", moonbr_io_read_call},
1939 {"read_yield", moonbr_io_read_yield},
1940 {"drain", moonbr_io_drain},
1941 {"drain_nb", moonbr_io_drain_nb},
1942 {"drain_call", moonbr_io_drain_call},
1943 {"drain_yield", moonbr_io_drain_yield},
1944 {"write", moonbr_io_write},
1945 {"write_nb", moonbr_io_write_nb},
1946 {"write_call", moonbr_io_write_call},
1947 {"write_yield", moonbr_io_write_yield},
1948 {"flush", moonbr_io_flush},
1949 {"flush_nb", moonbr_io_flush_nb},
1950 {"flush_call", moonbr_io_flush_call},
1951 {"flush_yield", moonbr_io_flush_yield},
1952 {"finish", moonbr_io_finish},
1953 {"close", moonbr_io_close},
1954 {"reset", moonbr_io_reset},
1955 #ifdef MOONBR_IO_USE_TLS
1956 {"starttls", moonbr_io_starttls},
1957 #endif
1958 {NULL, NULL}
1959 };
1961 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1962 {"__index", moonbr_io_handleindex},
1963 {"__newindex", moonbr_io_handlenewindex},
1964 {"__gc", moonbr_io_handlegc},
1965 {NULL, NULL}
1966 };
1968 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1969 {"accept", moonbr_io_accept},
1970 {"accept_nb", moonbr_io_accept_nb},
1971 {"close", moonbr_io_unlisten},
1972 {NULL, NULL}
1973 };
1975 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1976 {"__gc", moonbr_io_listenergc},
1977 {NULL, NULL}
1978 };
1980 static const struct luaL_Reg moonbr_io_child_methods[] = {
1981 {"kill", moonbr_io_kill},
1982 {"wait", moonbr_io_wait},
1983 {"wait_nb", moonbr_io_wait_nb},
1984 {"wait_call", moonbr_io_wait_call},
1985 {"wait_yield", moonbr_io_wait_yield},
1986 {NULL, NULL}
1987 };
1989 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
1990 {"__index", moonbr_io_childindex},
1991 {"__newindex", moonbr_io_childnewindex},
1992 {"__gc", moonbr_io_childgc},
1993 {NULL, NULL}
1994 };
1996 static const struct luaL_Reg moonbr_io_module_funcs[] = {
1997 {"localconnect", moonbr_io_localconnect},
1998 {"localconnect_nb", moonbr_io_localconnect_nb},
1999 {"tcpconnect", moonbr_io_tcpconnect},
2000 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2001 {"locallisten", moonbr_io_locallisten},
2002 {"tcplisten", moonbr_io_tcplisten},
2003 {"exec", moonbr_io_exec},
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
2013 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2014 {"__gc", moonbr_io_tlsconfgc},
2015 {NULL, NULL}
2016 };
2017 #endif
2019 int luaopen_moonbridge_io(lua_State *L) {
2021 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2023 lua_newtable(L); // module
2025 lua_newtable(L); // public metatable
2026 lua_newtable(L); // handle methods
2027 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2028 lua_pushvalue(L, -1);
2029 lua_setfield(L, -4, "handle_pt");
2030 lua_setfield(L, -2, "__index");
2031 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2033 lua_newtable(L); // handle metatable
2034 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2035 lua_pushvalue(L, -1);
2036 lua_setfield(L, -3, "handle_mt");
2037 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2039 lua_newtable(L); // listener metatable
2040 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2041 lua_newtable(L); // listener methods
2042 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2043 lua_pushvalue(L, -1);
2044 lua_setfield(L, -4, "listener_pt");
2045 lua_setfield(L, -2, "__index");
2046 lua_pushvalue(L, -1);
2047 lua_setfield(L, -3, "listener_mt");
2048 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2050 lua_newtable(L); // child methods
2051 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2052 lua_pushvalue(L, -1);
2053 lua_setfield(L, -3, "child_pt");
2054 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2055 lua_newtable(L); // child metatable
2056 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2057 lua_pushvalue(L, -1);
2058 lua_setfield(L, -3, "child_mt");
2059 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2061 #ifdef MOONBR_IO_USE_TLS
2062 if(tls_init()) {
2063 return luaL_error(L, "Could not initialize TLS library");
2065 lua_newtable(L); // tlsconf metatable
2066 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2067 lua_pushvalue(L, -1);
2068 lua_setfield(L, -3, "tlsconf_mt");
2069 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2070 #endif
2072 moonbr_io_pushhandle(L, 0);
2073 lua_setfield(L, -2, "stdin");
2074 moonbr_io_pushhandle(L, 1);
2075 lua_setfield(L, -2, "stdout");
2076 moonbr_io_pushhandle(L, 2);
2077 lua_setfield(L, -2, "stderr");
2079 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2080 return 1;

Impressum / About Us