moonbridge

view moonbridge_io.c @ 255:a22a6c19457f

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

Impressum / About Us