moonbridge

view moonbridge_io.c @ 333:15dfa1e9b629

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

Impressum / About Us