moonbridge

view moonbridge_io.c @ 281:6bb191b6ead5

Make :kill(signal) accept also strings and default to signal 9 (KILL); Improved error handling of :kill(signal)
author jbe
date Thu Jun 08 01:52:18 2017 +0200 (2017-06-08)
parents 1a4f89f4c712
children 28aab22e68b6
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 int pid = child->pid;
1522 child->pid = 0;
1523 if (kill(pid, SIGKILL)) {
1524 moonbr_io_prepare_errmsg();
1525 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1527 while (waitpid(pid, &status, 0) == -1) {
1528 if (errno != EINTR) {
1529 moonbr_io_prepare_errmsg();
1530 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1534 return 0;
1537 static int moonbr_io_kill(lua_State *L) {
1538 moonbr_io_child_t *child;
1539 int sig;
1540 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1541 if (lua_type(L, 2) == LUA_TSTRING) {
1542 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_SIGNALS_REGKEY);
1543 lua_pushvalue(L, 2);
1544 lua_gettable(L, -2);
1545 sig = lua_tointeger(L, -1);
1546 if (!sig) {
1547 lua_pushvalue(L, 2);
1548 luaL_error(L, "Unknown signal \"%s\"", lua_tostring(L, 2));
1550 } else {
1551 sig = luaL_optinteger(L, 2, SIGKILL);
1553 if (!child->pid) luaL_error(L, "Attempt to kill an already collected child process");
1554 if (kill(child->pid, sig)) {
1555 moonbr_io_prepare_errmsg();
1556 luaL_error(L, "Error in kill call: %s", errmsg);
1558 lua_settop(L, 1);
1559 return 1;
1562 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1563 moonbr_io_child_t *child;
1564 pid_t waitedpid;
1565 int status;
1566 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1567 if (!child->pid) luaL_error(L, "Attempt to wait for an already collected child process");
1568 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1569 if (errno != EINTR) {
1570 moonbr_io_prepare_errmsg();
1571 luaL_error(L, "Error in waitpid call: %s", errmsg);
1574 if (!waitedpid) {
1575 lua_pushboolean(L, 0);
1576 lua_pushliteral(L, "Process is still running");
1577 return 2;
1578 } else {
1579 child->pid = 0;
1580 if (WIFEXITED(status)) {
1581 lua_pushinteger(L, WEXITSTATUS(status));
1582 } else if (WIFSIGNALED(status)) {
1583 lua_pushinteger(L, -WTERMSIG(status));
1584 } else {
1585 luaL_error(L, "Unexpected status value returned by waitpid call");
1587 return 1;
1591 static int moonbr_io_wait(lua_State *L) {
1592 return moonbr_io_wait_impl(L, 0);
1595 static int moonbr_io_wait_nb(lua_State *L) {
1596 return moonbr_io_wait_impl(L, 1);
1599 #if LUA_VERSION_NUM >= 503
1600 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1601 #else
1602 static int moonbr_io_wait_cont(lua_State *L) {
1603 #endif
1604 #if !(LUA_VERSION_NUM >= 503)
1605 int ctx = 0;
1606 lua_getctx(L, &ctx);
1607 #endif
1608 while (1) {
1609 lua_pushcfunction(L, moonbr_io_wait_nb);
1610 lua_pushvalue(L, 1);
1611 lua_call(L, 1, 1);
1612 if (!lua_isnil(L, -1)) break;
1613 lua_pushvalue(L, 2);
1614 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1616 return 1;
1619 static int moonbr_io_wait_call(lua_State *L) {
1620 lua_settop(L, 2);
1621 #if LUA_VERSION_NUM >= 503
1622 return moonbr_io_wait_cont(L, 0, 0);
1623 #else
1624 return moonbr_io_wait_cont(L);
1625 #endif
1628 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1630 static void moonbr_io_signalhandler(int sig) {
1631 int errno2 = errno;
1632 char buf[1] = {'.'};
1633 write(moonbr_io_signalfd_write(sig), buf, 1);
1634 errno = errno2;
1637 static int moonbr_io_signalsocket(lua_State *L) {
1638 int sig, fd;
1639 if (lua_type(L, 1) == LUA_TSTRING) {
1640 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_SIGNALS_REGKEY);
1641 lua_pushvalue(L, 1);
1642 lua_gettable(L, -2);
1643 sig = lua_tointeger(L, -1);
1644 if (!sig) {
1645 lua_pushvalue(L, 1);
1646 luaL_error(L, "Unknown signal \"%s\"", lua_tostring(L, 1));
1648 } else {
1649 sig = luaL_checkinteger(L, 1);
1651 if (sig < 1 || sig > MOONBR_IO_MAXSIGNUM) {
1652 luaL_error(L, "Signal number %i out of range", sig);
1654 if (moonbr_io_signalfd_read(sig) < 0) {
1655 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, moonbr_io_signalfds+2*sig)) {
1656 luaL_error(L, "Could not create socket pair for signal queueing");
1659 errno = 0;
1660 signal(sig, moonbr_io_signalhandler);
1661 if (errno) luaL_error(L, "Could not install signal handler (invalid signal number %i?)", sig);
1662 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_SIGNALSOCKETS_REGKEY);
1663 lua_pushinteger(L, sig);
1664 lua_gettable(L, -2);
1665 if (!lua_isnil(L, -1)) return 1;
1666 fd = dup(moonbr_io_signalfd_read(sig)); /* avoid close on Lua error */
1667 if (fd < 0) luaL_error(L, "Could not create duplicated file descriptor for signal socket");
1668 moonbr_io_pushhandle(L, fd);
1669 lua_pushinteger(L, sig);
1670 lua_pushvalue(L, -2);
1671 lua_settable(L, -5); /* store reference to signal socket in cache table */
1672 return 1;
1675 static int moonbr_io_getpid(lua_State *L) {
1676 lua_pushinteger(L, getpid());
1677 return 1;
1680 #ifdef MOONBR_IO_USE_TLS
1682 #define moonbr_io_poll_tls() \
1683 if (!handle->tlshandshake) { \
1684 lua_pushboolean(L, 1); \
1685 return 1; \
1686 } \
1687 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1688 if (fd < 0) { \
1689 lua_pushboolean(L, 1); \
1690 return 1; \
1691 } \
1692 FD_SET(fd, &readfds); \
1693 if (fd+1 > nfds) nfds = fd+1; \
1694 continue; \
1695 } \
1696 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1697 if (fd < 0) { \
1698 lua_pushboolean(L, 1); \
1699 return 1; \
1700 } \
1701 FD_SET(fd, &writefds); \
1702 if (fd+1 > nfds) nfds = fd+1; \
1703 continue; \
1704 } \
1705 while (0)
1707 #endif /* MOONBR_IO_USE_TLS */
1709 static int moonbr_io_poll(lua_State *L) {
1710 moonbr_io_handle_t *handle;
1711 moonbr_io_listener_t *listener;
1712 int fd, isnum;
1713 int nfds = 0;
1714 fd_set readfds, writefds, exceptfds;
1715 struct timeval timeout = {0, };
1716 int status;
1717 FD_ZERO(&readfds);
1718 FD_ZERO(&writefds);
1719 FD_ZERO(&exceptfds);
1720 if (!lua_isnoneornil(L, 1)) {
1721 luaL_checktype(L, 1, LUA_TTABLE);
1722 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1723 if (lua_toboolean(L, -1)) {
1724 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1725 if (handle) {
1726 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1727 fd = handle->fd;
1728 #if MOONBR_IO_USE_TLS
1729 moonbr_io_poll_tls();
1730 #endif
1731 if (
1732 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1733 handle->readbufin != handle->readbufout /* data pending in buffer */
1734 ) {
1735 lua_pushboolean(L, 1);
1736 return 1;
1738 } else {
1739 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1740 if (listener) {
1741 fd = listener->fd;
1742 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1743 } else {
1744 fd = lua_tointegerx(L, -2, &isnum);
1745 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1748 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1749 FD_SET(fd, &readfds);
1750 if (fd+1 > nfds) nfds = fd+1;
1754 if (!lua_isnoneornil(L, 2)) {
1755 luaL_checktype(L, 2, LUA_TTABLE);
1756 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1757 if (lua_toboolean(L, -1)) {
1758 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1759 if (handle) {
1760 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1761 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1762 fd = handle->fd;
1763 #if MOONBR_IO_USE_TLS
1764 moonbr_io_poll_tls();
1765 #endif
1766 } else {
1767 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1768 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1769 fd = lua_tointegerx(L, -2, &isnum);
1770 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1772 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1773 FD_SET(fd, &writefds);
1774 if (fd+1 > nfds) nfds = fd+1;
1778 if (!lua_isnoneornil(L, 3)) {
1779 lua_Number n;
1780 n = lua_tonumberx(L, 3, &isnum);
1781 if (isnum && n<0) {
1782 lua_pushboolean(L, 0);
1783 lua_pushliteral(L, "Negative timeout");
1784 return 2;
1785 } else if (isnum && n>=0 && n<100000000) {
1786 timeout.tv_sec = n;
1787 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1788 } else {
1789 luaL_argcheck(L, 0, 3, "not a valid timeout");
1791 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1792 } else {
1793 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1795 if (status == -1) {
1796 if (errno == EINTR) {
1797 lua_pushboolean(L, 1);
1798 return 1;
1799 } else {
1800 moonbr_io_prepare_errmsg();
1801 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1803 } else if (status == 0) {
1804 lua_pushboolean(L, 0);
1805 lua_pushliteral(L, "Timeout while polling file descriptors");
1806 return 2;
1807 } else {
1808 lua_pushboolean(L, 1);
1809 return 1;
1813 static int moonbr_io_timeref(lua_State *L) {
1814 lua_Number sub;
1815 struct timespec tp;
1816 sub = luaL_optnumber(L, 1, 0);
1817 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1818 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1820 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1821 return 1;
1824 #ifdef MOONBR_IO_USE_TLS
1826 #define moonbr_io_tlsconf_string(name, field, func) \
1827 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1828 lua_getfield(L, 1, (field)); \
1829 valuetype = lua_type(L, -1); \
1830 if (valuetype != LUA_TNIL) { \
1831 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1832 value = lua_tostring(L, -1); \
1833 if (func(tlsconf->config, value)) { \
1834 lua_pushnil(L); \
1835 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1836 return 2; \
1837 } \
1838 } \
1839 lua_pop(L, 1);
1841 #define moonbr_io_tlsconf_binary(name, field, func) \
1842 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1843 lua_getfield(L, 1, (field)); \
1844 valuetype = lua_type(L, -1); \
1845 if (valuetype != LUA_TNIL) { \
1846 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1847 value = lua_tolstring(L, -1, &valuelen); \
1848 if (func(tlsconf->config, (void *)value, valuelen)) { \
1849 lua_pushnil(L); \
1850 lua_pushliteral(L, "Could not set " name); \
1851 return 2; \
1852 } \
1853 } \
1854 lua_pop(L, 1);
1856 static int moonbr_io_tlsconf(lua_State *L) {
1857 moonbr_io_tlsconf_t *tlsconf;
1858 int valuetype;
1859 const char *value;
1860 size_t valuelen;
1861 luaL_checktype(L, 1, LUA_TTABLE);
1862 tlsconf = lua_newuserdata(L, sizeof(moonbr_io_tlsconf_t));
1863 tlsconf->config = tls_config_new();
1864 if (!tlsconf->config) {
1865 return luaL_error(L, "Could not allocate memory for TLS configuration");
1867 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
1868 lua_getfield(L, 1, "mode");
1869 value = lua_tostring(L, -1);
1870 if (value && !strcmp(value, "server")) tlsconf->server = 1;
1871 else if (value && !strcmp(value, "client")) tlsconf->server = 0;
1872 else luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
1873 lua_pop(L, 1);
1874 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
1875 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
1876 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
1877 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
1878 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
1879 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
1880 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
1881 #if LUA_VERSION_NUM >= 503
1882 valuetype = lua_getfield(L, 1, "verify_client");
1883 #else
1884 lua_getfield(L, 1, "verify_client");
1885 #endif
1886 if (lua_toboolean(L, -1)) {
1887 value = lua_tostring(L, -1);
1888 if (value && !strcmp(value, "required")) {
1889 tls_config_verify_client(tlsconf->config);
1890 } else if (value && !strcmp(value, "optional")) {
1891 tls_config_verify_client_optional(tlsconf->config);
1892 } else {
1893 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
1896 lua_pop(L, 1);
1897 // TODO: configurable legacy support
1898 // tls_config_set_protocols(tlsconf->config, TLS_PROTOCOLS_ALL);
1899 // tls_config_set_ciphers(tlsconf->config, "legacy");
1900 return 1;
1903 static int moonbr_io_tlsconfgc(lua_State *L) {
1904 moonbr_io_tlsconf_t *tlsconf;
1905 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
1906 if (tlsconf->config) tls_config_free(tlsconf->config);
1907 tlsconf->config = NULL;
1908 return 0;
1911 static int moonbr_io_starttls(lua_State *L) {
1912 moonbr_io_handle_t *handle;
1913 moonbr_io_tlsconf_t *tlsconf;
1914 const char *servername;
1915 struct tls *tls, *tls2;
1916 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1917 if (lua_type(L, 2) == LUA_TTABLE) {
1918 lua_pushcfunction(L, moonbr_io_tlsconf);
1919 lua_pushvalue(L, 2);
1920 lua_call(L, 1, 2);
1921 if (lua_isnil(L, -2)) return 2;
1922 lua_pop(L, 1);
1923 lua_replace(L, 2);
1925 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
1926 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
1927 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
1928 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
1929 if (handle->readbufin || handle->writebufin) {
1930 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
1932 if (tlsconf->server) tls = tls_server();
1933 else {
1934 servername = luaL_checkstring(L, 3);
1935 tls = tls_client();
1937 if (!tls) {
1938 return luaL_error(L, "Could not allocate memory for TLS context");
1940 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
1941 if (tlsconf->server) {
1942 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
1943 handle->servertls = tls;
1944 handle->tls = tls2;
1945 } else {
1946 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
1947 handle->tls = tls;
1949 lua_settop(L, 1);
1950 return 1;
1951 moonbr_io_starttls_error:
1952 lua_pushnil(L);
1953 lua_pushstring(L, tls_error(tls));
1954 tls_free(tls);
1955 return 2;
1958 #endif /* MOONBR_IO_USE_TLS */
1960 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1961 {"read", moonbr_io_read},
1962 {"read_nb", moonbr_io_read_nb},
1963 {"read_call", moonbr_io_read_call},
1964 {"read_yield", moonbr_io_read_yield},
1965 {"drain", moonbr_io_drain},
1966 {"drain_nb", moonbr_io_drain_nb},
1967 {"drain_call", moonbr_io_drain_call},
1968 {"drain_yield", moonbr_io_drain_yield},
1969 {"write", moonbr_io_write},
1970 {"write_nb", moonbr_io_write_nb},
1971 {"write_call", moonbr_io_write_call},
1972 {"write_yield", moonbr_io_write_yield},
1973 {"flush", moonbr_io_flush},
1974 {"flush_nb", moonbr_io_flush_nb},
1975 {"flush_call", moonbr_io_flush_call},
1976 {"flush_yield", moonbr_io_flush_yield},
1977 {"finish", moonbr_io_finish},
1978 {"close", moonbr_io_close},
1979 {"reset", moonbr_io_reset},
1980 #ifdef MOONBR_IO_USE_TLS
1981 {"starttls", moonbr_io_starttls},
1982 #endif
1983 {NULL, NULL}
1984 };
1986 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1987 {"__index", moonbr_io_handleindex},
1988 {"__newindex", moonbr_io_handlenewindex},
1989 {"__gc", moonbr_io_handlegc},
1990 {NULL, NULL}
1991 };
1993 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1994 {"accept", moonbr_io_accept},
1995 {"accept_nb", moonbr_io_accept_nb},
1996 {"close", moonbr_io_unlisten},
1997 {NULL, NULL}
1998 };
2000 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
2001 {"__gc", moonbr_io_listenergc},
2002 {NULL, NULL}
2003 };
2005 static const struct luaL_Reg moonbr_io_child_methods[] = {
2006 {"kill", moonbr_io_kill},
2007 {"wait", moonbr_io_wait},
2008 {"wait_nb", moonbr_io_wait_nb},
2009 {"wait_call", moonbr_io_wait_call},
2010 {"wait_yield", moonbr_io_wait_yield},
2011 {NULL, NULL}
2012 };
2014 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
2015 {"__index", moonbr_io_childindex},
2016 {"__newindex", moonbr_io_childnewindex},
2017 {"__gc", moonbr_io_childgc},
2018 {NULL, NULL}
2019 };
2021 static const struct luaL_Reg moonbr_io_module_funcs[] = {
2022 {"localconnect", moonbr_io_localconnect},
2023 {"localconnect_nb", moonbr_io_localconnect_nb},
2024 {"tcpconnect", moonbr_io_tcpconnect},
2025 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2026 {"locallisten", moonbr_io_locallisten},
2027 {"tcplisten", moonbr_io_tcplisten},
2028 {"exec", moonbr_io_exec},
2029 {"signalsocket", moonbr_io_signalsocket},
2030 {"getpid", moonbr_io_getpid},
2031 {"poll", moonbr_io_poll},
2032 {"timeref", moonbr_io_timeref},
2033 #ifdef MOONBR_IO_USE_TLS
2034 {"tlsconf", moonbr_io_tlsconf},
2035 #endif
2036 {NULL, NULL}
2037 };
2039 #ifdef MOONBR_IO_USE_TLS
2041 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2042 {"__gc", moonbr_io_tlsconfgc},
2043 {NULL, NULL}
2044 };
2046 #endif /* MOONBR_IO_USE_TLS */
2048 int luaopen_moonbridge_io(lua_State *L) {
2050 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2052 int i;
2053 for (i=0; i<=MOONBR_IO_MAXSIGNUM; i++) {
2054 moonbr_io_signalfd_read(i) = -1;
2055 moonbr_io_signalfd_write(i) = -1;
2059 lua_newtable(L); // module
2061 lua_newtable(L); // public metatable
2062 lua_newtable(L); // handle methods
2063 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2064 lua_pushvalue(L, -1);
2065 lua_setfield(L, -4, "handle_pt");
2066 lua_setfield(L, -2, "__index");
2067 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2069 lua_newtable(L); // handle metatable
2070 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2071 lua_pushvalue(L, -1);
2072 lua_setfield(L, -3, "handle_mt");
2073 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2075 lua_newtable(L); // listener metatable
2076 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2077 lua_newtable(L); // listener methods
2078 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2079 lua_pushvalue(L, -1);
2080 lua_setfield(L, -4, "listener_pt");
2081 lua_setfield(L, -2, "__index");
2082 lua_pushvalue(L, -1);
2083 lua_setfield(L, -3, "listener_mt");
2084 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2086 lua_newtable(L); // child methods
2087 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2088 lua_pushvalue(L, -1);
2089 lua_setfield(L, -3, "child_pt");
2090 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2091 lua_newtable(L); // child metatable
2092 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2093 lua_pushvalue(L, -1);
2094 lua_setfield(L, -3, "child_mt");
2095 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2097 #ifdef MOONBR_IO_USE_TLS
2098 if(tls_init()) {
2099 return luaL_error(L, "Could not initialize TLS library");
2101 lua_newtable(L); // tlsconf metatable
2102 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2103 lua_pushvalue(L, -1);
2104 lua_setfield(L, -3, "tlsconf_mt");
2105 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2106 #endif
2108 moonbr_io_pushhandle(L, 0);
2109 lua_setfield(L, -2, "stdin");
2110 moonbr_io_pushhandle(L, 1);
2111 lua_setfield(L, -2, "stdout");
2112 moonbr_io_pushhandle(L, 2);
2113 lua_setfield(L, -2, "stderr");
2115 lua_newtable(L); // signal numbers
2116 lua_pushinteger(L, SIGHUP); lua_setfield(L, -2, "HUP");
2117 lua_pushinteger(L, SIGINT); lua_setfield(L, -2, "INT");
2118 lua_pushinteger(L, SIGQUIT); lua_setfield(L, -2, "QUIT");
2119 lua_pushinteger(L, SIGABRT); lua_setfield(L, -2, "ABRT");
2120 lua_pushinteger(L, SIGPIPE); lua_setfield(L, -2, "PIPE");
2121 lua_pushinteger(L, SIGALRM); lua_setfield(L, -2, "ALRM");
2122 lua_pushinteger(L, SIGTERM); lua_setfield(L, -2, "TERM");
2123 lua_pushinteger(L, SIGTSTP); lua_setfield(L, -2, "TSTP");
2124 lua_pushinteger(L, SIGCONT); lua_setfield(L, -2, "CONT");
2125 lua_pushinteger(L, SIGVTALRM); lua_setfield(L, -2, "VTALRM");
2126 #ifdef SIGINFO
2127 lua_pushinteger(L, SIGINFO); lua_setfield(L, -2, "INFO");
2128 #endif
2129 lua_pushinteger(L, SIGUSR1); lua_setfield(L, -2, "USR1");
2130 lua_pushinteger(L, SIGUSR2); lua_setfield(L, -2, "USR2");
2131 lua_pushvalue(L, -1);
2132 lua_setfield(L, -3, "signals");
2133 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_SIGNALS_REGKEY);
2135 lua_newtable(L); // signal sockets
2136 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_SIGNALSOCKETS_REGKEY);
2138 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2139 return 1;

Impressum / About Us