moonbridge

view moonbridge_io.c @ 320:5fe68ba5fe0e

Raspbian support in Makefile
author jbe
date Sat Dec 22 18:39:17 2018 +0100 (2018-12-22)
parents 8c1aacea1210
children fe1a134a92a4
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_MODULE_REGKEY "moonbridge_io_module"
59 #define MOONBR_IO_HANDLE_MT_REGKEY "moonbridge_io_handle"
60 #define MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY "moonbridge_io_handle_public"
61 #define MOONBR_IO_LISTENER_MT_REGKEY "moonbridge_io_listener"
62 #define MOONBR_IO_CHILD_MT_REGKEY "moonbridge_io_child"
63 #define MOONBR_IO_CHILD_PT_REGKEY "moonbridge_io_child_pt"
65 #ifdef MOONBR_IO_USE_TLS
67 #define MOONBR_IO_TLSCONF_MT_REGKEY "moonbridge_io_tlsconf"
69 typedef struct {
70 struct tls_config *config;
71 int server;
72 } moonbr_io_tlsconf_t;
74 #endif /* MOONBR_IO_USE_TLS */
76 typedef struct {
77 int fd;
78 int issock;
79 sa_family_t addrfam;
80 int finished;
81 int closed;
82 int nonblocking;
83 int nopush;
84 int readerr;
85 int readbufin;
86 int readbufout;
87 int writeerr;
88 size_t writeleft;
89 size_t flushedleft;
90 #if LUA_VERSION_NUM >= 503
91 lua_Integer writeqin;
92 lua_Integer writeqout;
93 #else
94 int writeqin;
95 int writeqout;
96 #endif
97 size_t writeqoff;
98 int writebufin;
99 int writebufout;
100 char readbuf[MOONBR_IO_READBUFLEN];
101 char writebuf[MOONBR_IO_WRITEBUFLEN];
102 #ifdef MOONBR_IO_USE_TLS
103 struct tls *tls;
104 struct tls *servertls;
105 int tlshandshake;
106 int tlsclosing;
107 #endif
108 } moonbr_io_handle_t;
110 typedef struct {
111 int fd;
112 sa_family_t addrfam;
113 int nonblocking;
114 } moonbr_io_listener_t;
116 typedef struct {
117 pid_t pid;
118 int status;
119 int status_valid;
120 } moonbr_io_child_t;
122 volatile sig_atomic_t moonbr_io_sigterm_flag = 0;
123 volatile sig_atomic_t moonbr_io_sigchld_flag = 0;
125 static int moonbr_io_yield(lua_State *L) {
126 return lua_yield(L, lua_gettop(L));
127 }
129 #if LUA_VERSION_NUM >= 503
130 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
131 #else
132 static int moonbr_io_cont_returnall(lua_State *L) {
133 #endif
134 return lua_gettop(L);
135 }
137 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
138 static int yieldfunc(lua_State *L) { \
139 int args; \
140 lua_pushcfunction(L, callfunc); \
141 lua_insert(L, 1); \
142 args = lua_gettop(L); \
143 lua_pushcfunction(L, moonbr_io_yield); \
144 lua_insert(L, 3); \
145 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
146 return lua_gettop(L); \
147 }
149 static int moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
150 int flags;
151 if (handle->nonblocking == nonblocking) return 0;
152 flags = fcntl(handle->fd, F_GETFL, 0);
153 if (flags == -1) return -1;
154 if (nonblocking) flags |= O_NONBLOCK;
155 else flags &= ~O_NONBLOCK;
156 if (fcntl(handle->fd, F_SETFL, flags) == -1) return -1;
157 handle->nonblocking = nonblocking;
158 return 0;
159 }
161 static int moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
162 struct linger lingerval = { 0, };
163 if (!handle->issock) return 0;
164 if (timeout >= 0) {
165 lingerval.l_onoff = 1;
166 lingerval.l_linger = timeout;
167 }
168 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) return -1;
169 return 0;
170 }
172 static inline int moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
173 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
174 if (
175 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
176 handle->nopush == nopush
177 ) return 0;
178 #if defined(TCP_NOPUSH)
179 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) return -1;
180 #elif defined(TCP_CORK)
181 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) return -1;
182 #endif
183 handle->nopush = nopush;
184 #else
185 #warning Neither TCP_NOPUSH nor TCP_CORK is available
186 #endif
187 return 0;
188 }
190 static int moonbr_io_get_rcvbuf(lua_State *L) {
191 moonbr_io_handle_t *handle;
192 int value;
193 socklen_t valsz = sizeof(value);
194 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
195 /* TODO: handle closed and finished I/O handles differently? */
196 if (handle->fd < 0) luaL_error(L, "Attempt to operate on closed or finished I/O handle");
197 if (getsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF, &value, &valsz)) {
198 moonbr_io_prepare_errmsg();
199 moonbr_io_return_prepared_errmsg();
200 }
201 lua_pushinteger(L, value);
202 return 1;
203 }
205 static int moonbr_io_get_sndbuf(lua_State *L) {
206 moonbr_io_handle_t *handle;
207 int value;
208 socklen_t valsz = sizeof(value);
209 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
210 if (handle->fd < 0) luaL_error(L, "Attempt to operate on closed or finished I/O handle");
211 if (getsockopt(handle->fd, SOL_SOCKET, SO_SNDBUF, &value, &valsz)) {
212 moonbr_io_prepare_errmsg();
213 moonbr_io_return_prepared_errmsg();
214 }
215 lua_pushinteger(L, value);
216 return 1;
217 }
219 static int moonbr_io_set_rcvbuf(lua_State *L) {
220 moonbr_io_handle_t *handle;
221 int value;
222 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
223 if (handle->fd < 0) luaL_error(L, "Attempt to operate on closed or finished I/O handle");
224 value = luaL_checkinteger(L, 2);
225 if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value))) {
226 moonbr_io_prepare_errmsg();
227 moonbr_io_return_prepared_errmsg();
228 }
229 lua_pushvalue(L, 1);
230 return 1;
231 }
233 static int moonbr_io_set_sndbuf(lua_State *L) {
234 moonbr_io_handle_t *handle;
235 int value;
236 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
237 if (handle->fd < 0) luaL_error(L, "Attempt to operate on closed or finished I/O handle");
238 value = luaL_checkinteger(L, 2);
239 if (setsockopt(handle->fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value))) {
240 moonbr_io_prepare_errmsg();
241 moonbr_io_return_prepared_errmsg();
242 }
243 lua_pushvalue(L, 1);
244 return 1;
245 }
247 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
248 moonbr_io_handle_t *handle;
249 lua_Integer maxread;
250 const char *terminatorstr;
251 size_t terminatorlen;
252 char terminator = 0; /* initialize to avoid compiler warning */
253 luaL_Buffer luabuf;
254 size_t luabufcnt = 0;
255 int remaining;
256 char *terminatorpos;
257 ssize_t bytesread;
258 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
259 maxread = luaL_optinteger(L, 2, -1);
260 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
261 if (terminatorlen) {
262 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
263 terminator = terminatorstr[0];
264 }
265 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
266 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
267 if (handle->readerr) {
268 lua_pushnil(L);
269 lua_pushliteral(L, "Previous read error");
270 return 2;
271 }
272 if (handle->fd < 0) {
273 /* fake EOF to simulate shutdown */
274 if (!drain) lua_pushliteral(L, "");
275 else lua_pushinteger(L, 0);
276 lua_pushliteral(L, "eof");
277 return 2;
278 }
279 handle->readerr = 1;
280 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
281 if (!drain) luaL_buffinit(L, &luabuf);
282 while (1) {
283 remaining = -1;
284 terminatorpos = NULL;
285 if (
286 maxread >= 0 &&
287 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
288 ) {
289 remaining = (size_t)maxread - luabufcnt;
290 if (terminatorlen) {
291 terminatorpos = memchr(
292 handle->readbuf + handle->readbufout,
293 terminator,
294 remaining
295 );
296 }
297 } else if (terminatorlen) {
298 terminatorpos = memchr(
299 handle->readbuf + handle->readbufout,
300 terminator,
301 handle->readbufin - handle->readbufout
302 );
303 }
304 if (terminatorpos) remaining = 1 + (
305 terminatorpos - (handle->readbuf + handle->readbufout)
306 );
307 if (remaining >= 0) {
308 if (!drain) {
309 luaL_addlstring(
310 &luabuf,
311 handle->readbuf + handle->readbufout,
312 remaining
313 );
314 luaL_pushresult(&luabuf);
315 } else {
316 lua_pushinteger(L, luabufcnt + remaining);
317 }
318 if (terminatorpos) lua_pushliteral(L, "term");
319 else lua_pushliteral(L, "maxlen");
320 handle->readbufout += remaining;
321 if (handle->readbufout == handle->readbufin) {
322 handle->readbufin = 0;
323 handle->readbufout = 0;
324 }
325 handle->readerr = 0;
326 return 2;
327 }
328 if (!drain) luaL_addlstring(
329 &luabuf,
330 handle->readbuf + handle->readbufout,
331 handle->readbufin - handle->readbufout
332 );
333 luabufcnt += handle->readbufin - handle->readbufout;
334 handle->readbufout = 0;
335 #ifdef MOONBR_IO_USE_TLS
336 if (handle->tls) {
337 do {
338 if (!handle->tlshandshake) {
339 do bytesread = tls_handshake(handle->tls);
340 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
341 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
342 handle->tlshandshake = bytesread;
343 errno = EAGAIN;
344 break;
345 }
346 if (bytesread < 0) {
347 lua_pushnil(L);
348 lua_pushstring(L, tls_error(handle->tls));
349 return 2;
350 }
351 handle->tlshandshake = 1;
352 }
353 do bytesread = tls_read(handle->tls, handle->readbuf, MOONBR_IO_READBUFLEN);
354 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
355 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
356 errno = EAGAIN;
357 break;
358 }
359 if (bytesread < 0) {
360 lua_pushnil(L);
361 lua_pushstring(L, tls_error(handle->tls));
362 return 2;
363 }
364 } while (0);
365 }
366 else
367 #endif
368 do bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
369 while (bytesread < 0 && (errno == EINTR));
370 if (
371 bytesread == 0 || (
372 nonblocking &&
373 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
374 )
375 ) {
376 handle->readbufin = 0;
377 if (!drain) luaL_pushresult(&luabuf);
378 else lua_pushinteger(L, luabufcnt);
379 if (bytesread == 0) lua_pushliteral(L, "eof");
380 else lua_pushliteral(L, "block");
381 handle->readerr = 0;
382 return 2;
383 }
384 if (bytesread < 0) moonbr_io_return_errmsg();
385 handle->readbufin = bytesread;
386 }
387 }
389 static int moonbr_io_read(lua_State *L) {
390 return moonbr_io_read_impl(L, 0, 0);
391 }
393 static int moonbr_io_read_nb(lua_State *L) {
394 return moonbr_io_read_impl(L, 1, 0);
395 }
397 static int moonbr_io_drain(lua_State *L) {
398 return moonbr_io_read_impl(L, 0, 1);
399 }
401 static int moonbr_io_drain_nb(lua_State *L) {
402 return moonbr_io_read_impl(L, 1, 1);
403 }
405 #if LUA_VERSION_NUM >= 503
406 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
407 #else
408 static int moonbr_io_read_cont(lua_State *L) {
409 #endif
410 lua_Integer remaining;
411 size_t len;
412 #if !(LUA_VERSION_NUM >= 503)
413 int ctx = 0;
414 int status = lua_getctx(L, &ctx);
415 #endif
416 remaining = lua_tointeger(L, 3);
417 while (1) {
418 lua_pushcfunction(L, moonbr_io_read_nb);
419 lua_pushvalue(L, 1);
420 lua_pushvalue(L, 3);
421 lua_pushvalue(L, 4);
422 lua_call(L, 3, 2);
423 if (lua_isnil(L, -2)) return 2;
424 lua_insert(L, -2);
425 len = lua_rawlen(L, -1);
426 if (ctx == 0) {
427 lua_replace(L, 5);
428 ctx = 1;
429 } else if (ctx == 1) {
430 lua_pushvalue(L, 5);
431 lua_newtable(L);
432 lua_replace(L, 5);
433 lua_rawseti(L, 5, 1);
434 lua_rawseti(L, 5, 2);
435 ctx = 2;
436 } else {
437 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
438 }
439 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
440 lua_pop(L, 1);
441 if (remaining >= 0 && len) {
442 remaining -= len;
443 lua_pushinteger(L, remaining);
444 lua_replace(L, 3);
445 }
446 lua_pushvalue(L, 2);
447 lua_pushvalue(L, 1);
448 lua_pushliteral(L, "r");
449 lua_pushboolean(L, status != LUA_YIELD);
450 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_MODULE_REGKEY);
451 lua_callk(L, 4, 0, ctx, moonbr_io_read_cont);
452 status = LUA_YIELD;
453 }
454 if (ctx != 1) {
455 luaL_Buffer buf;
456 lua_Integer i, chunkcount;
457 chunkcount = lua_rawlen(L, 5);
458 luaL_buffinit(L, &buf);
459 for (i=1; i<=chunkcount && i>0; i++) {
460 lua_rawgeti(L, 5, i);
461 luaL_addvalue(&buf);
462 }
463 luaL_pushresult(&buf);
464 lua_pushvalue(L, -2);
465 }
466 return 2;
467 }
469 static int moonbr_io_read_call(lua_State *L) {
470 lua_settop(L, 4);
471 lua_pushnil(L);
472 #if LUA_VERSION_NUM >= 503
473 return moonbr_io_read_cont(L, 0, 0);
474 #else
475 return moonbr_io_read_cont(L);
476 #endif
477 }
479 moonbr_io_yield_wrapper(moonbr_io_read_yield, moonbr_io_read_call);
481 #if LUA_VERSION_NUM >= 503
482 static int moonbr_io_drain_cont(lua_State *L, int status, lua_KContext ctx) {
483 #else
484 static int moonbr_io_drain_cont(lua_State *L) {
485 #endif
486 lua_Integer remaining, len;
487 size_t totallen = 0;
488 #if !(LUA_VERSION_NUM >= 503)
489 int ctx = 0;
490 int status = lua_getctx(L, &ctx);
491 #endif
492 remaining = lua_tointeger(L, 3);
493 while (1) {
494 lua_pushcfunction(L, moonbr_io_drain_nb);
495 lua_pushvalue(L, 1);
496 lua_pushvalue(L, 3);
497 lua_pushvalue(L, 4);
498 lua_call(L, 3, 2);
499 if (lua_isnil(L, -2)) return 2;
500 lua_insert(L, -2);
501 len = lua_tointeger(L, -1);
502 lua_pop(L, 1);
503 totallen += len;
504 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
505 lua_pop(L, 1);
506 if (remaining >= 0 && len) {
507 remaining -= len;
508 lua_pushinteger(L, remaining);
509 lua_replace(L, 3);
510 }
511 lua_pushvalue(L, 2);
512 lua_pushvalue(L, 1);
513 lua_pushliteral(L, "r");
514 lua_pushboolean(L, status != LUA_YIELD);
515 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_MODULE_REGKEY);
516 lua_callk(L, 4, 0, ctx, moonbr_io_drain_cont);
517 status = LUA_YIELD;
518 }
519 lua_pushinteger(L, totallen);
520 lua_pushvalue(L, -2);
521 return 2;
522 }
524 static int moonbr_io_drain_call(lua_State *L) {
525 #if LUA_VERSION_NUM >= 503
526 return moonbr_io_drain_cont(L, 0, 0);
527 #else
528 return moonbr_io_drain_cont(L);
529 #endif
530 }
532 moonbr_io_yield_wrapper(moonbr_io_drain_yield, moonbr_io_drain_call);
534 #ifdef MOONBR_IO_USE_TLS
536 #define moonbr_io_write_tls(buf, buflen) \
537 if (handle->tls) { \
538 do { \
539 if (!handle->tlshandshake) { \
540 do written = tls_handshake(handle->tls); \
541 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
542 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
543 handle->tlshandshake = written; \
544 errno = EAGAIN; \
545 break; \
546 } \
547 if (written < 0) { \
548 lua_pushnil(L); \
549 lua_pushstring(L, tls_error(handle->tls)); \
550 return 2; \
551 } \
552 handle->tlshandshake = 1; \
553 } \
554 do written = tls_write(handle->tls, (buf), (buflen)); \
555 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
556 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
557 errno = EAGAIN; \
558 break; \
559 } \
560 if (written < 0) { \
561 lua_pushnil(L); \
562 lua_pushstring(L, tls_error(handle->tls)); \
563 return 2; \
564 } \
565 } while (0); \
566 } \
567 else
569 #endif /* MOONBR_IO_USE_TLS */
571 static int moonbr_io_write_impl(lua_State *L, int nonblocking, int flush) {
572 moonbr_io_handle_t *handle;
573 int i, top;
574 const char *str;
575 size_t strlen;
576 ssize_t written;
577 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
578 if (handle->closed) luaL_error(L, "Attempt to write to a closed I/O handle");
579 if (handle->finished) luaL_error(L, "Attempt to write to a finished I/O handle");
580 if (handle->writeerr) {
581 lua_pushnil(L);
582 lua_pushliteral(L, "Previous write error");
583 return 2;
584 }
585 handle->writeerr = 1;
586 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
587 top = lua_gettop(L);
588 lua_getuservalue(L, 1);
589 lua_getfield(L, -1, "writequeue");
590 for (i=2; i<=top; i++) {
591 luaL_checklstring(L, i, &strlen);
592 lua_pushvalue(L, i);
593 lua_rawseti(L, -2, handle->writeqin++);
594 handle->writeleft += strlen;
595 }
596 if (flush) handle->flushedleft = handle->writeleft;
597 while (handle->writeqout != handle->writeqin) {
598 lua_rawgeti(L, -1, handle->writeqout);
599 str = lua_tolstring(L, -1, &strlen);
600 while (handle->writeqoff < strlen) {
601 if (
602 strlen - handle->writeqoff <
603 MOONBR_IO_WRITEBUFLEN - handle->writebufin
604 ) {
605 memcpy(
606 handle->writebuf + handle->writebufin,
607 str + handle->writeqoff,
608 strlen - handle->writeqoff
609 );
610 handle->writebufin += strlen - handle->writeqoff;
611 break;
612 } else {
613 memcpy(
614 handle->writebuf + handle->writebufin,
615 str + handle->writeqoff,
616 MOONBR_IO_WRITEBUFLEN - handle->writebufin
617 );
618 handle->writeqoff += MOONBR_IO_WRITEBUFLEN - handle->writebufin;
619 handle->writebufin = MOONBR_IO_WRITEBUFLEN;
620 while (handle->writebufout < MOONBR_IO_WRITEBUFLEN) {
621 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
622 #ifdef MOONBR_IO_USE_TLS
623 moonbr_io_write_tls(
624 handle->writebuf + handle->writebufout,
625 MOONBR_IO_WRITEBUFLEN - handle->writebufout
626 )
627 #endif
628 written = write(
629 handle->fd,
630 handle->writebuf + handle->writebufout,
631 MOONBR_IO_WRITEBUFLEN - handle->writebufout
632 );
633 if (written < 0) {
634 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
635 goto moonbr_io_write_impl_block;
636 } else if (errno != EINTR) moonbr_io_return_errmsg();
637 } else {
638 handle->writebufout += written;
639 handle->writeleft -= written;
640 if (handle->flushedleft) {
641 if (written >= handle->flushedleft) {
642 handle->flushedleft = 0;
643 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
644 } else {
645 handle->flushedleft -= written;
646 }
647 }
648 }
649 }
650 handle->writebufin = 0;
651 handle->writebufout = 0;
652 }
653 }
654 handle->writeqoff = 0;
655 lua_pop(L, 1);
656 lua_pushnil(L);
657 lua_rawseti(L, -2, handle->writeqout++);
658 }
659 while (handle->flushedleft) {
660 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
661 #ifdef MOONBR_IO_USE_TLS
662 moonbr_io_write_tls(
663 handle->writebuf + handle->writebufout,
664 handle->writebufin - handle->writebufout
665 )
666 #endif
667 written = write(
668 handle->fd,
669 handle->writebuf + handle->writebufout,
670 handle->writebufin - handle->writebufout
671 );
672 if (written < 0) {
673 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
674 goto moonbr_io_write_impl_block;
675 } else if (errno != EINTR) moonbr_io_return_errmsg();
676 } else {
677 handle->writebufout += written;
678 handle->writeleft -= written;
679 if (handle->flushedleft) {
680 if (written >= handle->flushedleft) {
681 handle->flushedleft = 0;
682 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
683 } else {
684 handle->flushedleft -= written;
685 }
686 }
687 }
688 }
689 if (handle->writebufout == handle->writebufin) {
690 handle->writebufin = 0;
691 handle->writebufout = 0;
692 }
693 if (nonblocking) lua_pushinteger(L, 0);
694 else lua_pushvalue(L, 1);
695 handle->writeerr = 0;
696 return 1;
697 moonbr_io_write_impl_block:
698 lua_pushinteger(L, handle->writeleft);
699 handle->writeerr = 0;
700 return 1;
701 }
703 static int moonbr_io_write(lua_State *L) {
704 return moonbr_io_write_impl(L, 0, 0);
705 }
707 static int moonbr_io_write_nb(lua_State *L) {
708 return moonbr_io_write_impl(L, 1, 0);
709 }
711 static int moonbr_io_flush(lua_State *L) {
712 return moonbr_io_write_impl(L, 0, 1);
713 }
715 static int moonbr_io_flush_nb(lua_State *L) {
716 return moonbr_io_write_impl(L, 1, 1);
717 }
719 #if LUA_VERSION_NUM >= 503
720 static int moonbr_io_write_cont(lua_State *L, int status, lua_KContext ctx) {
721 #else
722 static int moonbr_io_write_cont(lua_State *L) {
723 int ctx = 0;
724 int status = lua_getctx(L, &ctx);
725 #endif
726 while (1) {
727 lua_pushcfunction(L, moonbr_io_write_nb);
728 lua_pushvalue(L, 1);
729 lua_call(L, 1, 2);
730 if (lua_isnil(L, -2)) return 2;
731 if (!lua_tointeger(L, -2)) {
732 lua_pushvalue(L, 1);
733 return 1;
734 }
735 lua_pop(L, 2);
736 lua_pushvalue(L, 2);
737 lua_pushvalue(L, 1);
738 lua_pushliteral(L, "w");
739 lua_pushboolean(L, status != LUA_YIELD);
740 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_MODULE_REGKEY);
741 lua_callk(L, 4, 0, 0, moonbr_io_write_cont);
742 status = LUA_YIELD;
743 }
744 }
746 static int moonbr_io_write_call(lua_State *L) {
747 lua_pushcfunction(L, moonbr_io_write_nb);
748 lua_insert(L, 3);
749 lua_pushvalue(L, 1);
750 lua_insert(L, 4);
751 lua_call(L, lua_gettop(L) - 3, 2);
752 if (lua_isnil(L, -2)) return 2;
753 if (!lua_tointeger(L, -2)) {
754 lua_pushvalue(L, 1);
755 return 1;
756 }
757 #if LUA_VERSION_NUM >= 503
758 return moonbr_io_write_cont(L, 0, 0);
759 #else
760 return moonbr_io_write_cont(L);
761 #endif
762 }
764 moonbr_io_yield_wrapper(moonbr_io_write_yield, moonbr_io_write_call);
766 static int moonbr_io_flush_call(lua_State *L) {
767 lua_pushcfunction(L, moonbr_io_flush_nb);
768 lua_insert(L, 3);
769 lua_pushvalue(L, 1);
770 lua_insert(L, 4);
771 lua_call(L, lua_gettop(L) - 3, 2);
772 if (lua_isnil(L, -2)) return 2;
773 if (!lua_tointeger(L, -2)) {
774 lua_pushvalue(L, 1);
775 return 1;
776 }
777 #if LUA_VERSION_NUM >= 503
778 return moonbr_io_write_cont(L, 0, 0);
779 #else
780 return moonbr_io_write_cont(L);
781 #endif
782 }
784 moonbr_io_yield_wrapper(moonbr_io_flush_yield, moonbr_io_flush_call);
786 static int moonbr_io_finish(lua_State *L) {
787 moonbr_io_handle_t *handle;
788 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
789 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
790 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
791 if (handle->writeleft) {
792 lua_pushcfunction(L, moonbr_io_flush);
793 lua_pushvalue(L, 1);
794 if (lua_pcall(L, 1, 2, 0)) {
795 handle->finished = 1;
796 lua_error(L);
797 }
798 if (!lua_toboolean(L, -2)) {
799 handle->finished = 1;
800 return 2;
801 }
802 }
803 handle->finished = 1;
804 #ifdef MOONBR_IO_USE_TLS
805 if ((handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) && !handle->tls) {
806 #else
807 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
808 #endif
809 if (shutdown(handle->fd, SHUT_WR)) moonbr_io_return_errmsg();
810 } else {
811 #ifdef MOONBR_IO_USE_TLS
812 if (handle->tls) {
813 int status;
814 if (moonbr_io_handle_set_nonblocking(L, handle, 1)) moonbr_io_return_errmsg();
815 do status = tls_close(handle->tls);
816 while (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT);
817 if (status) {
818 close(handle->fd);
819 handle->fd = -1;
820 lua_pushnil(L);
821 lua_pushstring(L, tls_error(handle->tls));
822 return 2;
823 }
824 }
825 #endif
826 if (close(handle->fd)) {
827 handle->fd = -1;
828 moonbr_io_return_errmsg();
829 }
830 handle->fd = -1; /* fake EOF on read */
831 }
832 lua_pushboolean(L, 1);
833 return 1;
834 }
836 static int moonbr_io_close_impl(lua_State *L, int nonblocking, int reset) {
837 moonbr_io_handle_t *handle;
838 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
839 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
840 if (!reset && handle->fd >= 0) {
841 if (handle->writeleft) {
842 lua_pushcfunction(L, nonblocking ? moonbr_io_flush_nb : moonbr_io_flush);
843 lua_pushvalue(L, 1);
844 if (lua_pcall(L, 1, 2, 0)) {
845 handle->closed = 1;
846 close(handle->fd);
847 handle->fd = -1;
848 lua_error(L);
849 }
850 if (!nonblocking) handle->closed = 1; /* TODO: handle nonblocking case */
851 if (!lua_toboolean(L, -2)) {
852 close(handle->fd);
853 handle->fd = -1;
854 return 2;
855 }
856 #if LUA_VERSION_NUM >= 503
857 if (nonblocking && lua_tointeger(L, -2)) {
858 #else
859 if (nonblocking && lua_tonumber(L, -2)) {
860 #endif
861 lua_pushliteral(L, "flush");
862 lua_pushvalue(L, -3);
863 return 2;
864 }
865 } else {
866 handle->closed = 1;
867 }
868 #ifdef MOONBR_IO_USE_TLS
869 if (handle->tls) {
870 int status;
871 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
872 do status = tls_close(handle->tls);
873 while (!nonblocking && (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT));
874 if (status == TLS_WANT_POLLIN || status == TLS_WANT_POLLOUT) {
875 handle->tlsclosing = status; /* TODO: handle polling */
876 lua_pushliteral(L, "close");
877 return 1;
878 }
879 if (status) {
880 close(handle->fd);
881 handle->fd = -1;
882 lua_pushnil(L);
883 lua_pushstring(L, tls_error(handle->tls));
884 return 2;
885 }
886 }
887 #endif
888 if (moonbr_io_handle_set_linger(L, handle, -1)) {
889 moonbr_io_prepare_errmsg();
890 close(handle->fd);
891 handle->fd = -1;
892 moonbr_io_return_prepared_errmsg();
893 }
894 } else {
895 handle->closed = 1;
896 }
897 if (handle->fd >= 0) {
898 if (close(handle->fd)) {
899 handle->fd = -1;
900 moonbr_io_return_errmsg();
901 }
902 handle->fd = -1;
903 }
904 lua_pushboolean(L, 1);
905 return 1;
907 }
909 static int moonbr_io_close(lua_State *L) {
910 return moonbr_io_close_impl(L, 0, 0);
911 }
913 static int moonbr_io_reset(lua_State *L) {
914 return moonbr_io_close_impl(L, 0, 1);
915 }
917 static int moonbr_io_handlegc(lua_State *L) {
918 moonbr_io_handle_t *handle;
919 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
920 if (handle->fd >= 0) {
921 lua_pushcfunction(L, moonbr_io_reset);
922 lua_pushvalue(L, 1);
923 lua_pushinteger(L, 0);
924 lua_call(L, 2, 0);
925 }
926 #ifdef MOONBR_IO_USE_TLS
927 if (handle->tls) {
928 tls_free(handle->tls);
929 handle->tls = NULL;
930 }
931 if (handle->servertls) {
932 tls_free(handle->servertls);
933 handle->servertls = NULL;
934 }
935 #endif
936 return 0;
937 }
939 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
940 moonbr_io_handle_t *handle;
941 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
942 if (!handle->closed) {
943 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
944 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
945 lua_call(L, 1, 0);
946 }
947 }
949 static int moonbr_io_pushhandle_impl(lua_State *L) {
950 int *fd;
951 int skip_peeraddr;
952 moonbr_io_handle_t *handle;
953 struct sockaddr addr;
954 socklen_t addrlen;
955 fd = lua_touserdata(L, 1);
956 skip_peeraddr = lua_toboolean(L, 2);
957 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
958 handle->fd = -1; /* avoid closing incomplete handle */
959 addrlen = sizeof(addr);
960 if (getsockname(*fd, &addr, &addrlen)) {
961 if (errno != ENOTSOCK) {
962 moonbr_io_prepare_errmsg();
963 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
964 }
965 handle->issock = 0;
966 } else {
967 handle->issock = 1;
968 handle->addrfam = addr.sa_family;
969 }
970 handle->finished = 0;
971 handle->closed = 0;
972 handle->nonblocking = -1;
973 handle->nopush = -1;
974 handle->readerr = 0;
975 handle->readbufin = 0;
976 handle->readbufout = 0;
977 handle->writeerr = 0;
978 handle->writeleft = 0;
979 handle->flushedleft = 0;
980 handle->writeqin = 0;
981 handle->writeqout = 0;
982 handle->writeqoff = 0;
983 handle->writebufin = 0;
984 handle->writebufout = 0;
985 #ifdef MOONBR_IO_USE_TLS
986 handle->tls = NULL;
987 handle->servertls = NULL;
988 handle->tlshandshake = 0;
989 handle->tlsclosing = 0;
990 #endif
991 handle->fd = *fd; /* required for set_linger call */
992 if (moonbr_io_handle_set_linger(L, handle, 0)) {
993 moonbr_io_prepare_errmsg();
994 handle->fd = -1;
995 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
996 }
997 handle->fd = -1; /* avoid closing incomplete handle */
998 luaL_setmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
999 lua_newtable(L); // uservalue
1000 lua_newtable(L);
1001 lua_setfield(L, -2, "writequeue");
1002 lua_newtable(L); // public
1003 if (handle->addrfam == AF_INET6) {
1004 struct sockaddr_in6 addr_in6;
1005 char addrstrbuf[INET6_ADDRSTRLEN];
1006 const char *addrstr;
1007 addrlen = sizeof(addr_in6);
1008 /* NOTE: According to documentation, getsockname() may fail if connection
1009 * was reset. There seems to be no problem in practice though. */
1010 if (getsockname(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
1011 moonbr_io_prepare_errmsg();
1012 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
1014 if (addrlen > sizeof(addr_in6)) {
1015 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
1017 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
1018 if (!addrstr) {
1019 moonbr_io_prepare_errmsg();
1020 luaL_error(L, "Could not format local IP address: %s", errmsg);
1021 } else {
1022 lua_pushstring(L, addrstr);
1023 lua_setfield(L, -2, "local_ip6");
1025 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
1026 lua_setfield(L, -2, "local_tcpport");
1027 if (!skip_peeraddr) {
1028 /* NOTE: According to documentation, getpeername() may fail if connection
1029 * was reset. There seems to be no problem in practice though. */
1030 if (getpeername(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
1031 moonbr_io_prepare_errmsg();
1032 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
1034 if (addrlen > sizeof(addr_in6)) {
1035 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
1037 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
1038 if (!addrstr) {
1039 moonbr_io_prepare_errmsg();
1040 luaL_error(L, "Could not format remote IP address: %s", errmsg);
1041 } else {
1042 lua_pushstring(L, addrstr);
1043 lua_setfield(L, -2, "remote_ip6");
1045 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
1046 lua_setfield(L, -2, "remote_tcpport");
1048 } else if (handle->addrfam == AF_INET) {
1049 struct sockaddr_in addr_in;
1050 char addrstrbuf[INET_ADDRSTRLEN];
1051 const char *addrstr;
1052 addrlen = sizeof(addr_in);
1053 /* NOTE: According to documentation, getsockname() may fail if connection
1054 * was reset. There seems to be no problem in practice though. */
1055 if (getsockname(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
1056 moonbr_io_prepare_errmsg();
1057 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
1059 if (addrlen > sizeof(addr_in)) {
1060 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
1062 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
1063 if (!addrstr) {
1064 moonbr_io_prepare_errmsg();
1065 luaL_error(L, "Could not format local IP address: %s", errmsg);
1066 } else {
1067 lua_pushstring(L, addrstr);
1068 lua_setfield(L, -2, "local_ip4");
1070 lua_pushinteger(L, ntohs(addr_in.sin_port));
1071 lua_setfield(L, -2, "local_tcpport");
1072 if (!skip_peeraddr) {
1073 /* NOTE: According to documentation, getpeername() may fail if connection
1074 * was reset. There seems to be no problem in practice though. */
1075 if (getpeername(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
1076 moonbr_io_prepare_errmsg();
1077 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
1079 if (addrlen > sizeof(addr_in)) {
1080 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
1082 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
1083 if (!addrstr) {
1084 moonbr_io_prepare_errmsg();
1085 luaL_error(L, "Could not format remote IP address: %s", errmsg);
1086 } else {
1087 lua_pushstring(L, addrstr);
1088 lua_setfield(L, -2, "remote_ip4");
1090 lua_pushinteger(L, ntohs(addr_in.sin_port));
1091 lua_setfield(L, -2, "remote_tcpport");
1094 luaL_setmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1095 lua_setfield(L, -2, "public");
1096 lua_setuservalue(L, -2);
1097 handle->fd = *fd;
1098 *fd = -1; /* closing is now handled by garbage collection */
1099 return 1;
1102 void moonbr_io_pushhandle(lua_State *L, int fd) {
1103 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1104 lua_pushlightuserdata(L, &fd);
1105 if (lua_pcall(L, 1, 1, 0)) {
1106 if (fd != -1) close(fd); // TODO: correct to close file descriptor here?
1107 lua_error(L);
1111 void moonbr_io_pushhandle_skip_peeraddr(lua_State *L, int fd) {
1112 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1113 lua_pushlightuserdata(L, &fd);
1114 lua_pushboolean(L, 1);
1115 if (lua_pcall(L, 2, 1, 0)) {
1116 if (fd != -1) close(fd); // TODO: correct to close file descriptor here?
1117 lua_error(L);
1121 static int moonbr_io_handleindex(lua_State *L) {
1122 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1123 luaL_checkany(L, 2);
1124 lua_getuservalue(L, 1);
1125 lua_getfield(L, -1, "public");
1126 lua_pushvalue(L, 2);
1127 lua_gettable(L, -2);
1128 return 1;
1131 static int moonbr_io_handlenewindex(lua_State *L) {
1132 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1133 luaL_checkany(L, 2);
1134 luaL_checkany(L, 3);
1135 lua_getuservalue(L, 1);
1136 lua_getfield(L, -1, "public");
1137 lua_pushvalue(L, 2);
1138 lua_pushvalue(L, 3);
1139 lua_settable(L, -3);
1140 return 0;
1143 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
1144 const char *path;
1145 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1146 const int path_maxlen = sizeof(struct sockaddr_un) - (
1147 (void *)sockaddr.sun_path - (void *)&sockaddr
1148 ) - 1; /* one byte for termination */
1149 int sock;
1150 path = luaL_checkstring(L, 1);
1151 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1152 strcpy(sockaddr.sun_path, path);
1153 sock = socket(
1154 PF_LOCAL,
1155 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1157 );
1158 if (sock < 0) moonbr_io_return_errmsg();
1159 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1160 if (!nonblocking && errno == EINTR) {
1161 moonbr_io_prepare_errmsg();
1162 close(sock);
1163 moonbr_io_return_prepared_errmsg();
1164 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1166 moonbr_io_pushhandle(L, sock);
1167 return 1;
1170 static int moonbr_io_localconnect(lua_State *L) {
1171 return moonbr_io_localconnect_impl(L, 0);
1174 static int moonbr_io_localconnect_nb(lua_State *L) {
1175 return moonbr_io_localconnect_impl(L, 1);
1178 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
1179 const char *host, *port;
1180 struct addrinfo hints = { 0, };
1181 struct addrinfo *res, *addrinfo;
1182 int errcode;
1183 int sock;
1184 host = luaL_checkstring(L, 1);
1185 port = luaL_checkstring(L, 2);
1186 hints.ai_family = AF_UNSPEC;
1187 hints.ai_socktype = SOCK_STREAM;
1188 hints.ai_protocol = IPPROTO_TCP;
1189 hints.ai_flags = AI_ADDRCONFIG;
1190 errcode = getaddrinfo(host, port, &hints, &res);
1191 if (errcode) {
1192 freeaddrinfo(res);
1193 if (errcode == EAI_SYSTEM) {
1194 moonbr_io_prepare_errmsg();
1195 lua_pushnil(L);
1196 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1197 } else {
1198 lua_pushnil(L);
1199 lua_pushstring(L, gai_strerror(errcode));
1201 return 2;
1203 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1204 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1206 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1207 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1209 addrinfo = res;
1210 moonbr_io_tcpconnect_found:
1211 sock = socket(
1212 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1213 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1214 addrinfo->ai_protocol
1215 );
1216 if (sock < 0) {
1217 moonbr_io_prepare_errmsg();
1218 freeaddrinfo(res);
1219 moonbr_io_return_prepared_errmsg();
1221 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1222 freeaddrinfo(res);
1223 if (!nonblocking && errno == EINTR) {
1224 moonbr_io_prepare_errmsg();
1225 close(sock);
1226 moonbr_io_return_prepared_errmsg();
1227 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1228 } else {
1229 freeaddrinfo(res);
1231 if (nonblocking) {
1232 moonbr_io_pushhandle_skip_peeraddr(L, sock);
1233 if (addrinfo->ai_family == AF_INET6) {
1234 // TODO: fill remote_ip6 and remote_tcpport
1235 } else if (addrinfo->ai_family == AF_INET) {
1236 // TODO: fill remote_ip4 and remote_tcpport
1238 } else {
1239 moonbr_io_pushhandle(L, sock);
1241 return 1;
1244 static int moonbr_io_tcpconnect(lua_State *L) {
1245 return moonbr_io_tcpconnect_impl(L, 0);
1248 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1249 return moonbr_io_tcpconnect_impl(L, 1);
1252 static int moonbr_io_locallisten(lua_State *L) {
1253 moonbr_io_listener_t *listener;
1254 const char *path;
1255 struct stat sb;
1256 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1257 const int path_maxlen = sizeof(struct sockaddr_un) - (
1258 (void *)sockaddr.sun_path - (void *)&sockaddr
1259 ) - 1; /* one byte for termination */
1260 int sock;
1261 path = luaL_checkstring(L, 1);
1262 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1263 strcpy(sockaddr.sun_path, path);
1264 if (stat(path, &sb) == 0) {
1265 if (S_ISSOCK(sb.st_mode)) unlink(path);
1267 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1268 listener->fd = -1;
1269 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1270 sock = socket(
1271 PF_LOCAL,
1272 SOCK_STREAM | SOCK_CLOEXEC,
1274 );
1275 if (sock < 0) moonbr_io_return_errmsg();
1276 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1277 moonbr_io_prepare_errmsg();
1278 close(sock);
1279 moonbr_io_return_prepared_errmsg();
1281 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1282 moonbr_io_prepare_errmsg();
1283 close(sock);
1284 moonbr_io_return_prepared_errmsg();
1286 listener->fd = sock;
1287 listener->addrfam = AF_LOCAL;
1288 listener->nonblocking = -1;
1289 return 1;
1292 static int moonbr_io_tcplisten(lua_State *L) {
1293 moonbr_io_listener_t *listener;
1294 const char *host, *port;
1295 struct addrinfo hints = { 0, };
1296 struct addrinfo *res, *addrinfo;
1297 int errcode;
1298 int sock;
1299 host = luaL_optstring(L, 1, NULL);
1300 port = luaL_checkstring(L, 2);
1301 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1302 listener->fd = -1;
1303 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1304 hints.ai_family = AF_UNSPEC;
1305 hints.ai_socktype = SOCK_STREAM;
1306 hints.ai_protocol = IPPROTO_TCP;
1307 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1308 errcode = getaddrinfo(host, port, &hints, &res);
1309 if (errcode) {
1310 freeaddrinfo(res);
1311 if (errcode == EAI_SYSTEM) {
1312 moonbr_io_prepare_errmsg();
1313 lua_pushnil(L);
1314 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1315 } else {
1316 lua_pushnil(L);
1317 lua_pushstring(L, gai_strerror(errcode));
1319 return 2;
1321 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1322 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1324 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1325 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1327 addrinfo = res;
1328 moonbr_io_tcpconnect_found:
1329 listener->addrfam = addrinfo->ai_family;
1330 sock = socket(
1331 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1332 addrinfo->ai_socktype | SOCK_CLOEXEC,
1333 addrinfo->ai_protocol
1334 );
1335 if (sock < 0) {
1336 moonbr_io_prepare_errmsg();
1337 freeaddrinfo(res);
1338 moonbr_io_return_prepared_errmsg();
1341 static const int reuseval = 1;
1342 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1343 moonbr_io_prepare_errmsg();
1344 freeaddrinfo(res);
1345 close(sock);
1346 lua_pushnil(L);
1347 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1348 return 2;
1351 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1352 moonbr_io_prepare_errmsg();
1353 freeaddrinfo(res);
1354 close(sock);
1355 moonbr_io_return_prepared_errmsg();
1357 freeaddrinfo(res);
1358 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1359 moonbr_io_prepare_errmsg();
1360 close(sock);
1361 moonbr_io_return_prepared_errmsg();
1363 listener->fd = sock;
1364 listener->nonblocking = -1;
1365 return 1;
1368 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1369 moonbr_io_listener_t *listener;
1370 int fd;
1371 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1372 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1373 if (listener->nonblocking != nonblocking) {
1374 int flags;
1375 flags = fcntl(listener->fd, F_GETFL, 0);
1376 if (flags == -1) {
1377 moonbr_io_prepare_errmsg();
1378 close(listener->fd);
1379 listener->fd = -1;
1380 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1382 if (nonblocking) flags |= O_NONBLOCK;
1383 else flags &= ~O_NONBLOCK;
1384 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1385 moonbr_io_prepare_errmsg();
1386 close(listener->fd);
1387 listener->fd = -1;
1388 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1390 listener->nonblocking = nonblocking;
1392 while (1) {
1393 #if defined(__linux__) && !defined(_GNU_SOURCE)
1394 fd = accept(listener->fd, NULL, NULL);
1395 if (fd != -1) {
1396 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
1397 moonbr_io_prepare_errmsg();
1398 close(listener->fd);
1399 listener->fd = -1;
1400 close(fd);
1401 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1404 #else
1405 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1406 #endif
1407 if (fd < 0) {
1408 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1409 lua_pushboolean(L, 0);
1410 lua_pushliteral(L, "No incoming connection pending");
1411 return 2;
1412 } else if (errno != EINTR) moonbr_io_return_errmsg();
1413 } else {
1414 moonbr_io_pushhandle(L, fd);
1415 return 1;
1420 static int moonbr_io_accept(lua_State *L) {
1421 return moonbr_io_accept_impl(L, 0);
1424 static int moonbr_io_accept_nb(lua_State *L) {
1425 return moonbr_io_accept_impl(L, 1);
1428 static int moonbr_io_unlisten(lua_State *L) {
1429 moonbr_io_listener_t *listener;
1430 struct sockaddr_un addr;
1431 socklen_t addrlen;
1432 struct stat sb;
1433 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1434 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1435 addrlen = sizeof(addr);
1436 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1437 if (close(listener->fd)) {
1438 moonbr_io_prepare_errmsg();
1439 listener->fd = -1;
1440 if (addrlen && addrlen <= sizeof(addr)) {
1441 if (stat(addr.sun_path, &sb) == 0) {
1442 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1445 moonbr_io_return_prepared_errmsg();
1447 listener->fd = -1;
1448 if (addrlen && addrlen <= sizeof(addr)) {
1449 if (stat(addr.sun_path, &sb) == 0) {
1450 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1453 lua_pushboolean(L, 1);
1454 return 1;
1457 static int moonbr_io_listenergc(lua_State *L) {
1458 moonbr_io_listener_t *listener;
1459 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1460 if (listener->fd >= 0) close(listener->fd);
1461 listener->fd = -1;
1462 return 0;
1465 static int moonbr_io_exec(lua_State *L) {
1466 char **argv;
1467 int i, argc;
1468 int sockin[2], sockout[2], sockerr[2];
1469 volatile int errorcond = 0;
1470 volatile char errmsgbuf[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG;
1471 moonbr_io_child_t *child;
1472 argc = lua_gettop(L);
1473 argv = lua_newuserdata(L, (argc + 1) * sizeof(char *));
1474 for (i=0; i<argc; i++) argv[i] = (char *)luaL_checkstring(L, i+1);
1475 argv[argc] = NULL;
1476 child = lua_newuserdata(L, sizeof(moonbr_io_child_t));
1477 child->pid = 0;
1478 child->status_valid = 0;
1479 lua_newtable(L);
1480 lua_setuservalue(L, -2);
1481 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1482 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1483 moonbr_io_prepare_errmsg();
1484 lua_pushnil(L);
1485 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1486 return 2;
1488 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1489 moonbr_io_prepare_errmsg();
1490 close(sockin[0]);
1491 close(sockin[1]);
1492 lua_pushnil(L);
1493 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1494 return 2;
1496 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1497 moonbr_io_prepare_errmsg();
1498 close(sockin[0]);
1499 close(sockin[1]);
1500 close(sockout[0]);
1501 close(sockout[1]);
1502 lua_pushnil(L);
1503 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1504 return 2;
1506 child->pid = vfork();
1507 if (child->pid == -1) {
1508 moonbr_io_prepare_errmsg();
1509 close(sockin[0]);
1510 close(sockin[1]);
1511 close(sockout[0]);
1512 close(sockout[1]);
1513 close(sockerr[0]);
1514 close(sockerr[1]);
1515 lua_pushnil(L);
1516 lua_pushfstring(L, "Could not fork: %s", errmsg);
1517 return 2;
1519 if (!child->pid) {
1520 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1521 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1522 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1523 closefrom(3);
1524 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1525 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1526 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1527 if (execvp(argv[0], argv)) {
1528 errorcond = 2;
1529 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1530 _exit(0);
1532 moonbr_io_exec_error1:
1533 errorcond = 1;
1534 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1535 _exit(0);
1537 close(sockin[1]);
1538 close(sockout[1]);
1539 close(sockerr[1]);
1540 if (errorcond) {
1541 int status;
1542 close(sockin[0]);
1543 close(sockout[0]);
1544 close(sockerr[0]);
1545 while (waitpid(child->pid, &status, 0) == -1) {
1546 if (errno != EINTR) {
1547 moonbr_io_prepare_errmsg();
1548 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1551 child->pid = 0;
1552 lua_pushnil(L);
1553 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1554 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1555 return 2;
1557 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1558 lua_pushlightuserdata(L, &sockin[0]);
1559 if (lua_pcall(L, 1, 1, 0)) {
1560 if (sockin[0] != -1) close(sockin[0]);
1561 close(sockout[0]);
1562 close(sockerr[0]);
1563 goto moonbr_io_exec_error2;
1565 lua_setfield(L, -2, "stdin");
1566 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1567 lua_pushlightuserdata(L, &sockout[0]);
1568 if (lua_pcall(L, 1, 1, 0)) {
1569 if (sockout[0] != -1) close(sockout[0]);
1570 close(sockerr[0]);
1571 goto moonbr_io_exec_error2;
1573 lua_setfield(L, -2, "stdout");
1574 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1575 lua_pushlightuserdata(L, &sockerr[0]);
1576 if (lua_pcall(L, 1, 1, 0)) {
1577 if (sockerr[0] != -1) close(sockerr[0]);
1578 goto moonbr_io_exec_error2;
1580 lua_setfield(L, -2, "stderr");
1581 return 1;
1582 moonbr_io_exec_error2:
1584 int status;
1585 while (waitpid(child->pid, &status, 0) == -1) {
1586 if (errno != EINTR) {
1587 moonbr_io_prepare_errmsg();
1588 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1592 child->pid = 0;
1593 return lua_error(L);
1596 static int moonbr_io_childindex(lua_State *L) {
1597 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1598 luaL_checkany(L, 2);
1599 lua_getuservalue(L, 1);
1600 lua_pushvalue(L, 2);
1601 lua_gettable(L, -2);
1602 if (lua_isnil(L, -1)) {
1603 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1604 lua_pushvalue(L, 2);
1605 lua_gettable(L, -2);
1607 return 1;
1610 static int moonbr_io_childnewindex(lua_State *L) {
1611 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1612 luaL_checkany(L, 2);
1613 luaL_checkany(L, 3);
1614 lua_getuservalue(L, 1);
1615 lua_pushvalue(L, 2);
1616 lua_pushvalue(L, 3);
1617 lua_settable(L, -3);
1618 return 0;
1621 static int moonbr_io_childgc(lua_State *L) {
1622 moonbr_io_child_t *child;
1623 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1624 if (child->pid) {
1625 int status;
1626 int pid = child->pid;
1627 child->pid = 0;
1628 if (kill(pid, SIGKILL)) {
1629 moonbr_io_prepare_errmsg();
1630 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1632 while (waitpid(pid, &status, 0) == -1) {
1633 if (errno != EINTR) {
1634 moonbr_io_prepare_errmsg();
1635 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1639 return 0;
1642 static int moonbr_io_kill(lua_State *L) {
1643 moonbr_io_child_t *child;
1644 int sig;
1645 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1646 sig = luaL_optinteger(L, 2, SIGKILL);
1647 if (!child->pid) {
1648 if (!child->status_valid) luaL_error(L, "Attempt to kill an already collected child process");
1649 } else {
1650 if (kill(child->pid, sig)) {
1651 moonbr_io_prepare_errmsg();
1652 luaL_error(L, "Error in kill call: %s", errmsg);
1655 lua_settop(L, 1);
1656 return 1;
1659 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1660 moonbr_io_child_t *child;
1661 int status;
1662 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1663 if (!child->pid) {
1664 if (!child->status_valid) luaL_error(L, "Attempt to wait for an already collected child process");
1665 status = child->status;
1666 child->status_valid = 0;
1667 } else {
1668 pid_t waitedpid;
1669 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1670 if (errno != EINTR) {
1671 moonbr_io_prepare_errmsg();
1672 luaL_error(L, "Error in waitpid call: %s", errmsg);
1675 if (!waitedpid) {
1676 lua_pushboolean(L, 0);
1677 lua_pushliteral(L, "Process is still running");
1678 return 2;
1680 child->pid = 0;
1682 if (WIFEXITED(status)) {
1683 lua_pushinteger(L, WEXITSTATUS(status));
1684 } else if (WIFSIGNALED(status)) {
1685 lua_pushinteger(L, -WTERMSIG(status));
1686 } else {
1687 luaL_error(L, "Unexpected status value returned by waitpid call");
1689 return 1;
1692 static int moonbr_io_wait(lua_State *L) {
1693 return moonbr_io_wait_impl(L, 0);
1696 static int moonbr_io_wait_nb(lua_State *L) {
1697 return moonbr_io_wait_impl(L, 1);
1700 #if LUA_VERSION_NUM >= 503
1701 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1702 #else
1703 static int moonbr_io_wait_cont(lua_State *L) {
1704 #endif
1705 #if !(LUA_VERSION_NUM >= 503)
1706 int ctx = 0;
1707 int status = lua_getctx(L, &ctx);
1708 #endif
1709 while (1) {
1710 lua_pushcfunction(L, moonbr_io_wait_nb);
1711 lua_pushvalue(L, 1);
1712 lua_call(L, 1, 1);
1713 if (!lua_isnil(L, -1)) break;
1714 lua_pushvalue(L, 2);
1715 lua_pushvalue(L, 1);
1716 lua_pushliteral(L, "r");
1717 lua_pushboolean(L, status != LUA_YIELD);
1718 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_MODULE_REGKEY);
1719 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1720 status = LUA_YIELD;
1722 return 1;
1725 static int moonbr_io_wait_call(lua_State *L) {
1726 lua_settop(L, 2);
1727 #if LUA_VERSION_NUM >= 503
1728 return moonbr_io_wait_cont(L, 0, 0);
1729 #else
1730 return moonbr_io_wait_cont(L);
1731 #endif
1734 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1736 static void moonbr_io_sigterm_handler(int sig) {
1737 moonbr_io_sigterm_flag = 1;
1740 static void moonbr_io_sigchld_handler(int sig) {
1741 moonbr_io_sigchld_flag = 1;
1744 int moonbr_io_catch_sigterm(lua_State *L) {
1745 signal(SIGTERM, moonbr_io_sigterm_handler);
1746 return 0;
1749 static int moonbr_io_getpid(lua_State *L) {
1750 lua_pushinteger(L, getpid());
1751 return 1;
1754 #ifdef MOONBR_IO_USE_TLS
1756 #define moonbr_io_poll_tls() \
1757 if (!handle->tlshandshake) { \
1758 force_wakeup = 1; \
1759 continue; \
1760 } \
1761 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1762 if (fd < 0) { \
1763 force_wakeup = 1; \
1764 continue; \
1765 } \
1766 FD_SET(fd, &readfds); \
1767 if (fd+1 > nfds) nfds = fd+1; \
1768 continue; \
1769 } \
1770 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1771 if (fd < 0) { \
1772 force_wakeup = 1; \
1773 continue; \
1774 } \
1775 FD_SET(fd, &writefds); \
1776 if (fd+1 > nfds) nfds = fd+1; \
1777 continue; \
1778 } \
1779 while (0)
1781 #endif /* MOONBR_IO_USE_TLS */
1783 static int moonbr_io_poll(lua_State *L) {
1784 moonbr_io_handle_t *handle;
1785 moonbr_io_listener_t *listener;
1786 moonbr_io_child_t *child;
1787 int fd, isnum;
1788 int nfds = 0;
1789 fd_set readfds, writefds, exceptfds;
1790 struct timespec timeout = {0, };
1791 int force_wakeup = 0;
1792 int use_timeout = 0; // negative for negative timeout
1793 int check_sigterm = 0;
1794 int check_sigchld = 0;
1795 pid_t waitedpid;
1796 sigset_t mask, orig_mask;
1797 int status;
1798 FD_ZERO(&readfds);
1799 FD_ZERO(&writefds);
1800 FD_ZERO(&exceptfds);
1801 if (!lua_isnoneornil(L, 1)) {
1802 luaL_checktype(L, 1, LUA_TTABLE);
1803 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1804 if (lua_toboolean(L, -1)) {
1805 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1806 if (handle) {
1807 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1808 fd = handle->fd;
1809 #if MOONBR_IO_USE_TLS
1810 moonbr_io_poll_tls();
1811 #endif
1812 if (
1813 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1814 handle->readbufin != handle->readbufout /* data pending in buffer */
1815 ) {
1816 force_wakeup = 1;
1817 continue;
1819 } else {
1820 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1821 if (listener) {
1822 fd = listener->fd;
1823 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1824 } else {
1825 child = luaL_testudata(L, -2, MOONBR_IO_CHILD_MT_REGKEY);
1826 if (child) {
1827 if (!child->pid) luaL_error(L, "Attemt to poll an already collected child process");
1828 if (!check_sigchld) {
1829 check_sigchld = 1;
1830 moonbr_io_sigchld_flag = 0;
1831 signal(SIGCHLD, moonbr_io_sigchld_handler);
1833 if (child->status_valid) {
1834 force_wakeup = 1;
1835 } else {
1836 while ((waitedpid = waitpid(child->pid, &status, WNOHANG)) == -1) {
1837 if (errno != EINTR) {
1838 moonbr_io_prepare_errmsg();
1839 luaL_error(L, "Error in waitpid call: %s", errmsg);
1842 if (waitedpid) {
1843 child->pid = 0;
1844 child->status = status;
1845 child->status_valid = 1;
1846 force_wakeup = 1;
1849 continue;
1850 } else {
1851 fd = lua_tointegerx(L, -2, &isnum);
1852 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1856 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1857 FD_SET(fd, &readfds);
1858 if (fd+1 > nfds) nfds = fd+1;
1862 if (!lua_isnoneornil(L, 2)) {
1863 luaL_checktype(L, 2, LUA_TTABLE);
1864 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1865 if (lua_toboolean(L, -1)) {
1866 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1867 if (handle) {
1868 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1869 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1870 fd = handle->fd;
1871 #if MOONBR_IO_USE_TLS
1872 moonbr_io_poll_tls();
1873 #endif
1874 } else {
1875 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1876 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1877 fd = lua_tointegerx(L, -2, &isnum);
1878 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1880 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1881 FD_SET(fd, &writefds);
1882 if (fd+1 > nfds) nfds = fd+1;
1886 if (!lua_isnoneornil(L, 3)) {
1887 lua_Number n;
1888 n = lua_tonumberx(L, 3, &isnum);
1889 if (isnum && n<0) {
1890 use_timeout = -1;
1891 } else if (isnum && n>=0 && n<100000000) {
1892 use_timeout = 1;
1893 timeout.tv_sec = n;
1894 timeout.tv_nsec = 1e9 * (n - timeout.tv_sec);
1895 } else {
1896 luaL_argcheck(L, 0, 3, "not a valid timeout");
1899 if (use_timeout < 0) force_wakeup = 1;
1900 if (!lua_isnoneornil(L, 4)) luaL_checktype(L, 4, LUA_TBOOLEAN);
1901 check_sigterm = lua_toboolean(L, 4);
1902 if ((check_sigterm || check_sigchld) && !force_wakeup) {
1903 sigemptyset(&mask);
1904 if (check_sigterm) sigaddset(&mask, SIGTERM);
1905 if (check_sigchld) sigaddset(&mask, SIGCHLD);
1906 if (sigprocmask(SIG_BLOCK, &mask, &orig_mask)) abort();
1908 if (check_sigterm && moonbr_io_sigterm_flag) {
1909 if (!force_wakeup) {
1910 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1912 lua_pushboolean(L, 0);
1913 lua_pushliteral(L, "SIGTERM received");
1914 lua_pushboolean(L, 1);
1915 return 3;
1917 if (check_sigchld && !force_wakeup && moonbr_io_sigchld_flag) {
1918 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1919 force_wakeup = 1;
1921 if (use_timeout < 0) {
1922 lua_pushboolean(L, 0);
1923 lua_pushliteral(L, "Timeout");
1924 if (check_sigterm) {
1925 lua_pushboolean(L, 0);
1926 return 3;
1927 } else {
1928 return 2;
1931 if (!force_wakeup) {
1932 status = pselect(
1933 nfds, &readfds, &writefds, &exceptfds,
1934 use_timeout ? &timeout : NULL,
1935 (check_sigterm || check_sigchld) ? &orig_mask : NULL
1936 );
1937 if (check_sigterm || check_sigchld) {
1938 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1939 if (check_sigterm && moonbr_io_sigterm_flag) {
1940 lua_pushboolean(L, 0);
1941 lua_pushliteral(L, "SIGTERM received");
1942 lua_pushboolean(L, 1);
1943 return 3;
1946 if (status == -1) {
1947 if (errno == EINTR) {
1948 lua_pushboolean(L, 1);
1949 return 1;
1950 } else {
1951 moonbr_io_prepare_errmsg();
1952 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1954 } else if (status == 0) {
1955 lua_pushboolean(L, 0);
1956 lua_pushliteral(L, "Timeout");
1957 if (check_sigterm) {
1958 lua_pushboolean(L, 0);
1959 return 3;
1960 } else {
1961 return 2;
1965 lua_pushboolean(L, 1);
1966 return 1;
1969 static int moonbr_io_timeref(lua_State *L) {
1970 lua_Number sub;
1971 struct timespec tp;
1972 sub = luaL_optnumber(L, 1, 0);
1973 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1974 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1976 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1977 return 1;
1980 #ifdef MOONBR_IO_USE_TLS
1982 #define moonbr_io_tlsconf_string(name, field, func) \
1983 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1984 lua_getfield(L, 1, (field)); \
1985 valuetype = lua_type(L, -1); \
1986 if (valuetype != LUA_TNIL) { \
1987 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1988 value = lua_tostring(L, -1); \
1989 if (func(tlsconf->config, value)) { \
1990 lua_pushnil(L); \
1991 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1992 return 2; \
1993 } \
1994 } \
1995 lua_pop(L, 1);
1997 #define moonbr_io_tlsconf_binary(name, field, func) \
1998 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1999 lua_getfield(L, 1, (field)); \
2000 valuetype = lua_type(L, -1); \
2001 if (valuetype != LUA_TNIL) { \
2002 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
2003 value = lua_tolstring(L, -1, &valuelen); \
2004 if (func(tlsconf->config, (void *)value, valuelen)) { \
2005 lua_pushnil(L); \
2006 lua_pushliteral(L, "Could not set " name); \
2007 return 2; \
2008 } \
2009 } \
2010 lua_pop(L, 1);
2012 static int moonbr_io_tlsconf(lua_State *L) {
2013 moonbr_io_tlsconf_t *tlsconf;
2014 int valuetype;
2015 const char *value;
2016 size_t valuelen;
2017 luaL_checktype(L, 1, LUA_TTABLE);
2018 tlsconf = lua_newuserdata(L, sizeof(moonbr_io_tlsconf_t));
2019 tlsconf->config = tls_config_new();
2020 if (!tlsconf->config) {
2021 return luaL_error(L, "Could not allocate memory for TLS configuration");
2023 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
2024 lua_getfield(L, 1, "mode");
2025 value = lua_tostring(L, -1);
2026 if (value && !strcmp(value, "server")) tlsconf->server = 1;
2027 else if (value && !strcmp(value, "client")) tlsconf->server = 0;
2028 else luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
2029 lua_pop(L, 1);
2030 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
2031 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
2032 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
2033 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
2034 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
2035 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
2036 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
2037 #if LUA_VERSION_NUM >= 503
2038 valuetype = lua_getfield(L, 1, "verify_client");
2039 #else
2040 lua_getfield(L, 1, "verify_client");
2041 #endif
2042 if (lua_toboolean(L, -1)) {
2043 value = lua_tostring(L, -1);
2044 if (value && !strcmp(value, "required")) {
2045 tls_config_verify_client(tlsconf->config);
2046 } else if (value && !strcmp(value, "optional")) {
2047 tls_config_verify_client_optional(tlsconf->config);
2048 } else {
2049 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
2052 lua_pop(L, 1);
2053 // TODO: configurable legacy support
2054 // tls_config_set_protocols(tlsconf->config, TLS_PROTOCOLS_ALL);
2055 // tls_config_set_ciphers(tlsconf->config, "legacy");
2056 return 1;
2059 static int moonbr_io_tlsconfgc(lua_State *L) {
2060 moonbr_io_tlsconf_t *tlsconf;
2061 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
2062 if (tlsconf->config) tls_config_free(tlsconf->config);
2063 tlsconf->config = NULL;
2064 return 0;
2067 static int moonbr_io_starttls(lua_State *L) {
2068 moonbr_io_handle_t *handle;
2069 moonbr_io_tlsconf_t *tlsconf;
2070 const char *servername;
2071 struct tls *tls, *tls2;
2072 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
2073 if (lua_type(L, 2) == LUA_TTABLE) {
2074 lua_pushcfunction(L, moonbr_io_tlsconf);
2075 lua_pushvalue(L, 2);
2076 lua_call(L, 1, 2);
2077 if (lua_isnil(L, -2)) return 2;
2078 lua_pop(L, 1);
2079 lua_replace(L, 2);
2081 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
2082 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
2083 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
2084 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
2085 if (handle->readbufin || handle->writebufin) {
2086 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
2088 if (tlsconf->server) tls = tls_server();
2089 else {
2090 servername = luaL_checkstring(L, 3);
2091 tls = tls_client();
2093 if (!tls) {
2094 return luaL_error(L, "Could not allocate memory for TLS context");
2096 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
2097 if (tlsconf->server) {
2098 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
2099 handle->servertls = tls;
2100 handle->tls = tls2;
2101 } else {
2102 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
2103 handle->tls = tls;
2105 lua_settop(L, 1);
2106 return 1;
2107 moonbr_io_starttls_error:
2108 lua_pushnil(L);
2109 lua_pushstring(L, tls_error(tls));
2110 tls_free(tls);
2111 return 2;
2114 #endif /* MOONBR_IO_USE_TLS */
2116 static const struct luaL_Reg moonbr_io_handle_methods[] = {
2117 {"get_rcvbuf", moonbr_io_get_rcvbuf},
2118 {"get_sndbuf", moonbr_io_get_sndbuf},
2119 {"set_rcvbuf", moonbr_io_set_rcvbuf},
2120 {"set_sndbuf", moonbr_io_set_sndbuf},
2121 {"read", moonbr_io_read},
2122 {"read_nb", moonbr_io_read_nb},
2123 {"read_call", moonbr_io_read_call},
2124 {"read_yield", moonbr_io_read_yield},
2125 {"drain", moonbr_io_drain},
2126 {"drain_nb", moonbr_io_drain_nb},
2127 {"drain_call", moonbr_io_drain_call},
2128 {"drain_yield", moonbr_io_drain_yield},
2129 {"write", moonbr_io_write},
2130 {"write_nb", moonbr_io_write_nb},
2131 {"write_call", moonbr_io_write_call},
2132 {"write_yield", moonbr_io_write_yield},
2133 {"flush", moonbr_io_flush},
2134 {"flush_nb", moonbr_io_flush_nb},
2135 {"flush_call", moonbr_io_flush_call},
2136 {"flush_yield", moonbr_io_flush_yield},
2137 {"finish", moonbr_io_finish},
2138 {"close", moonbr_io_close},
2139 {"reset", moonbr_io_reset},
2140 #ifdef MOONBR_IO_USE_TLS
2141 {"starttls", moonbr_io_starttls},
2142 #endif
2143 {NULL, NULL}
2144 };
2146 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
2147 {"__index", moonbr_io_handleindex},
2148 {"__newindex", moonbr_io_handlenewindex},
2149 {"__gc", moonbr_io_handlegc},
2150 {NULL, NULL}
2151 };
2153 static const struct luaL_Reg moonbr_io_listener_methods[] = {
2154 {"accept", moonbr_io_accept},
2155 {"accept_nb", moonbr_io_accept_nb},
2156 {"close", moonbr_io_unlisten},
2157 {NULL, NULL}
2158 };
2160 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
2161 {"__gc", moonbr_io_listenergc},
2162 {NULL, NULL}
2163 };
2165 static const struct luaL_Reg moonbr_io_child_methods[] = {
2166 {"kill", moonbr_io_kill},
2167 {"wait", moonbr_io_wait},
2168 {"wait_nb", moonbr_io_wait_nb},
2169 {"wait_call", moonbr_io_wait_call},
2170 {"wait_yield", moonbr_io_wait_yield},
2171 {NULL, NULL}
2172 };
2174 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
2175 {"__index", moonbr_io_childindex},
2176 {"__newindex", moonbr_io_childnewindex},
2177 {"__gc", moonbr_io_childgc},
2178 {NULL, NULL}
2179 };
2181 static const struct luaL_Reg moonbr_io_module_funcs[] = {
2182 {"localconnect", moonbr_io_localconnect},
2183 {"localconnect_nb", moonbr_io_localconnect_nb},
2184 {"tcpconnect", moonbr_io_tcpconnect},
2185 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2186 {"locallisten", moonbr_io_locallisten},
2187 {"tcplisten", moonbr_io_tcplisten},
2188 {"exec", moonbr_io_exec},
2189 {"catch_sigterm", moonbr_io_catch_sigterm},
2190 {"getpid", moonbr_io_getpid},
2191 {"poll", moonbr_io_poll},
2192 {"timeref", moonbr_io_timeref},
2193 #ifdef MOONBR_IO_USE_TLS
2194 {"tlsconf", moonbr_io_tlsconf},
2195 #endif
2196 {NULL, NULL}
2197 };
2199 #ifdef MOONBR_IO_USE_TLS
2201 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2202 {"__gc", moonbr_io_tlsconfgc},
2203 {NULL, NULL}
2204 };
2206 #endif /* MOONBR_IO_USE_TLS */
2208 int luaopen_moonbridge_io(lua_State *L) {
2210 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2212 lua_newtable(L); // module
2213 lua_pushvalue(L, -1);
2214 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_MODULE_REGKEY);
2216 lua_newtable(L); // public metatable
2217 lua_newtable(L); // handle methods
2218 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2219 lua_pushvalue(L, -1);
2220 lua_setfield(L, -4, "handle_pt");
2221 lua_setfield(L, -2, "__index");
2222 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2224 lua_newtable(L); // handle metatable
2225 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2226 lua_pushvalue(L, -1);
2227 lua_setfield(L, -3, "handle_mt");
2228 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2230 lua_newtable(L); // listener metatable
2231 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2232 lua_newtable(L); // listener methods
2233 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2234 lua_pushvalue(L, -1);
2235 lua_setfield(L, -4, "listener_pt");
2236 lua_setfield(L, -2, "__index");
2237 lua_pushvalue(L, -1);
2238 lua_setfield(L, -3, "listener_mt");
2239 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2241 lua_newtable(L); // child methods
2242 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2243 lua_pushvalue(L, -1);
2244 lua_setfield(L, -3, "child_pt");
2245 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2246 lua_newtable(L); // child metatable
2247 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2248 lua_pushvalue(L, -1);
2249 lua_setfield(L, -3, "child_mt");
2250 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2252 #ifdef MOONBR_IO_USE_TLS
2253 if(tls_init()) {
2254 return luaL_error(L, "Could not initialize TLS library");
2256 lua_newtable(L); // tlsconf metatable
2257 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2258 lua_pushvalue(L, -1);
2259 lua_setfield(L, -3, "tlsconf_mt");
2260 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2261 #endif
2263 moonbr_io_pushhandle(L, 0);
2264 lua_setfield(L, -2, "stdin");
2265 moonbr_io_pushhandle(L, 1);
2266 lua_setfield(L, -2, "stdout");
2267 moonbr_io_pushhandle(L, 2);
2268 lua_setfield(L, -2, "stderr");
2270 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2271 return 1;

Impressum / About Us