moonbridge

view moonbridge_io.c @ 280:1a4f89f4c712

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

Impressum / About Us