moonbridge

view moonbridge_io.c @ 263:3a346a82031a

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

Impressum / About Us