moonbridge

view moonbridge_io.c @ 327:a8b1012856a5

Bugfix: Do not use freeaddrinfo() if getaddrinfo() failed
author jbe
date Sun Dec 20 20:57:41 2020 +0100 (23 months ago)
parents 4379766473ec
children fb8f86d3703e
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 (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1349 moonbr_io_prepare_errmsg();
1350 freeaddrinfo(res);
1351 close(sock);
1352 moonbr_io_return_prepared_errmsg();
1354 freeaddrinfo(res);
1355 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1356 moonbr_io_prepare_errmsg();
1357 close(sock);
1358 moonbr_io_return_prepared_errmsg();
1360 listener->fd = sock;
1361 listener->nonblocking = -1;
1362 return 1;
1365 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1366 moonbr_io_listener_t *listener;
1367 int fd;
1368 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1369 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1370 if (listener->nonblocking != nonblocking) {
1371 int flags;
1372 flags = fcntl(listener->fd, F_GETFL, 0);
1373 if (flags == -1) {
1374 moonbr_io_prepare_errmsg();
1375 close(listener->fd);
1376 listener->fd = -1;
1377 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1379 if (nonblocking) flags |= O_NONBLOCK;
1380 else flags &= ~O_NONBLOCK;
1381 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1382 moonbr_io_prepare_errmsg();
1383 close(listener->fd);
1384 listener->fd = -1;
1385 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1387 listener->nonblocking = nonblocking;
1389 while (1) {
1390 #if defined(__linux__) && !defined(_GNU_SOURCE)
1391 fd = accept(listener->fd, NULL, NULL);
1392 if (fd != -1) {
1393 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
1394 moonbr_io_prepare_errmsg();
1395 close(listener->fd);
1396 listener->fd = -1;
1397 close(fd);
1398 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1401 #else
1402 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1403 #endif
1404 if (fd < 0) {
1405 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1406 lua_pushboolean(L, 0);
1407 lua_pushliteral(L, "No incoming connection pending");
1408 return 2;
1409 } else if (errno != EINTR) moonbr_io_return_errmsg();
1410 } else {
1411 moonbr_io_pushhandle(L, fd);
1412 return 1;
1417 static int moonbr_io_accept(lua_State *L) {
1418 return moonbr_io_accept_impl(L, 0);
1421 static int moonbr_io_accept_nb(lua_State *L) {
1422 return moonbr_io_accept_impl(L, 1);
1425 static int moonbr_io_unlisten(lua_State *L) {
1426 moonbr_io_listener_t *listener;
1427 struct sockaddr_un addr;
1428 socklen_t addrlen;
1429 struct stat sb;
1430 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1431 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1432 addrlen = sizeof(addr);
1433 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1434 if (close(listener->fd)) {
1435 moonbr_io_prepare_errmsg();
1436 listener->fd = -1;
1437 if (addrlen && addrlen <= sizeof(addr)) {
1438 if (stat(addr.sun_path, &sb) == 0) {
1439 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1442 moonbr_io_return_prepared_errmsg();
1444 listener->fd = -1;
1445 if (addrlen && addrlen <= sizeof(addr)) {
1446 if (stat(addr.sun_path, &sb) == 0) {
1447 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1450 lua_pushboolean(L, 1);
1451 return 1;
1454 static int moonbr_io_listenergc(lua_State *L) {
1455 moonbr_io_listener_t *listener;
1456 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1457 if (listener->fd >= 0) close(listener->fd);
1458 listener->fd = -1;
1459 return 0;
1462 static int moonbr_io_exec(lua_State *L) {
1463 char **argv;
1464 int i, argc;
1465 int sockin[2], sockout[2], sockerr[2];
1466 volatile int errorcond = 0;
1467 volatile char errmsgbuf[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG;
1468 moonbr_io_child_t *child;
1469 argc = lua_gettop(L);
1470 argv = lua_newuserdata(L, (argc + 1) * sizeof(char *));
1471 for (i=0; i<argc; i++) argv[i] = (char *)luaL_checkstring(L, i+1);
1472 argv[argc] = NULL;
1473 child = lua_newuserdata(L, sizeof(moonbr_io_child_t));
1474 child->pid = 0;
1475 child->status_valid = 0;
1476 lua_newtable(L);
1477 lua_setuservalue(L, -2);
1478 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1479 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1480 moonbr_io_prepare_errmsg();
1481 lua_pushnil(L);
1482 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1483 return 2;
1485 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1486 moonbr_io_prepare_errmsg();
1487 close(sockin[0]);
1488 close(sockin[1]);
1489 lua_pushnil(L);
1490 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1491 return 2;
1493 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1494 moonbr_io_prepare_errmsg();
1495 close(sockin[0]);
1496 close(sockin[1]);
1497 close(sockout[0]);
1498 close(sockout[1]);
1499 lua_pushnil(L);
1500 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1501 return 2;
1503 child->pid = vfork();
1504 if (child->pid == -1) {
1505 moonbr_io_prepare_errmsg();
1506 close(sockin[0]);
1507 close(sockin[1]);
1508 close(sockout[0]);
1509 close(sockout[1]);
1510 close(sockerr[0]);
1511 close(sockerr[1]);
1512 lua_pushnil(L);
1513 lua_pushfstring(L, "Could not fork: %s", errmsg);
1514 return 2;
1516 if (!child->pid) {
1517 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1518 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1519 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1520 closefrom(3);
1521 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1522 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1523 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1524 if (execvp(argv[0], argv)) {
1525 errorcond = 2;
1526 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1527 _exit(0);
1529 moonbr_io_exec_error1:
1530 errorcond = 1;
1531 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1532 _exit(0);
1534 close(sockin[1]);
1535 close(sockout[1]);
1536 close(sockerr[1]);
1537 if (errorcond) {
1538 int status;
1539 close(sockin[0]);
1540 close(sockout[0]);
1541 close(sockerr[0]);
1542 while (waitpid(child->pid, &status, 0) == -1) {
1543 if (errno != EINTR) {
1544 moonbr_io_prepare_errmsg();
1545 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1548 child->pid = 0;
1549 lua_pushnil(L);
1550 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1551 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1552 return 2;
1554 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1555 lua_pushlightuserdata(L, &sockin[0]);
1556 if (lua_pcall(L, 1, 1, 0)) {
1557 if (sockin[0] != -1) close(sockin[0]);
1558 close(sockout[0]);
1559 close(sockerr[0]);
1560 goto moonbr_io_exec_error2;
1562 lua_setfield(L, -2, "stdin");
1563 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1564 lua_pushlightuserdata(L, &sockout[0]);
1565 if (lua_pcall(L, 1, 1, 0)) {
1566 if (sockout[0] != -1) close(sockout[0]);
1567 close(sockerr[0]);
1568 goto moonbr_io_exec_error2;
1570 lua_setfield(L, -2, "stdout");
1571 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1572 lua_pushlightuserdata(L, &sockerr[0]);
1573 if (lua_pcall(L, 1, 1, 0)) {
1574 if (sockerr[0] != -1) close(sockerr[0]);
1575 goto moonbr_io_exec_error2;
1577 lua_setfield(L, -2, "stderr");
1578 return 1;
1579 moonbr_io_exec_error2:
1581 int status;
1582 while (waitpid(child->pid, &status, 0) == -1) {
1583 if (errno != EINTR) {
1584 moonbr_io_prepare_errmsg();
1585 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1589 child->pid = 0;
1590 return lua_error(L);
1593 static int moonbr_io_childindex(lua_State *L) {
1594 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1595 luaL_checkany(L, 2);
1596 lua_getuservalue(L, 1);
1597 lua_pushvalue(L, 2);
1598 lua_gettable(L, -2);
1599 if (lua_isnil(L, -1)) {
1600 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1601 lua_pushvalue(L, 2);
1602 lua_gettable(L, -2);
1604 return 1;
1607 static int moonbr_io_childnewindex(lua_State *L) {
1608 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1609 luaL_checkany(L, 2);
1610 luaL_checkany(L, 3);
1611 lua_getuservalue(L, 1);
1612 lua_pushvalue(L, 2);
1613 lua_pushvalue(L, 3);
1614 lua_settable(L, -3);
1615 return 0;
1618 static int moonbr_io_childgc(lua_State *L) {
1619 moonbr_io_child_t *child;
1620 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1621 if (child->pid) {
1622 int status;
1623 int pid = child->pid;
1624 child->pid = 0;
1625 if (kill(pid, SIGKILL)) {
1626 moonbr_io_prepare_errmsg();
1627 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1629 while (waitpid(pid, &status, 0) == -1) {
1630 if (errno != EINTR) {
1631 moonbr_io_prepare_errmsg();
1632 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1636 return 0;
1639 static int moonbr_io_kill(lua_State *L) {
1640 moonbr_io_child_t *child;
1641 int sig;
1642 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1643 sig = luaL_optinteger(L, 2, SIGKILL);
1644 if (!child->pid) {
1645 if (!child->status_valid) luaL_error(L, "Attempt to kill an already collected child process");
1646 } else {
1647 if (kill(child->pid, sig)) {
1648 moonbr_io_prepare_errmsg();
1649 luaL_error(L, "Error in kill call: %s", errmsg);
1652 lua_settop(L, 1);
1653 return 1;
1656 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1657 moonbr_io_child_t *child;
1658 int status;
1659 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1660 if (!child->pid) {
1661 if (!child->status_valid) luaL_error(L, "Attempt to wait for an already collected child process");
1662 status = child->status;
1663 child->status_valid = 0;
1664 } else {
1665 pid_t waitedpid;
1666 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1667 if (errno != EINTR) {
1668 moonbr_io_prepare_errmsg();
1669 luaL_error(L, "Error in waitpid call: %s", errmsg);
1672 if (!waitedpid) {
1673 lua_pushboolean(L, 0);
1674 lua_pushliteral(L, "Process is still running");
1675 return 2;
1677 child->pid = 0;
1679 if (WIFEXITED(status)) {
1680 lua_pushinteger(L, WEXITSTATUS(status));
1681 } else if (WIFSIGNALED(status)) {
1682 lua_pushinteger(L, -WTERMSIG(status));
1683 } else {
1684 luaL_error(L, "Unexpected status value returned by waitpid call");
1686 return 1;
1689 static int moonbr_io_wait(lua_State *L) {
1690 return moonbr_io_wait_impl(L, 0);
1693 static int moonbr_io_wait_nb(lua_State *L) {
1694 return moonbr_io_wait_impl(L, 1);
1697 #if LUA_VERSION_NUM >= 503
1698 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1699 #else
1700 static int moonbr_io_wait_cont(lua_State *L) {
1701 #endif
1702 #if !(LUA_VERSION_NUM >= 503)
1703 int ctx = 0;
1704 int status = lua_getctx(L, &ctx);
1705 #endif
1706 while (1) {
1707 lua_pushcfunction(L, moonbr_io_wait_nb);
1708 lua_pushvalue(L, 1);
1709 lua_call(L, 1, 1);
1710 if (!lua_isnil(L, -1)) break;
1711 lua_pushvalue(L, 2);
1712 lua_pushvalue(L, 1);
1713 lua_pushliteral(L, "r");
1714 lua_pushboolean(L, status != LUA_YIELD);
1715 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_MODULE_REGKEY);
1716 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1717 status = LUA_YIELD;
1719 return 1;
1722 static int moonbr_io_wait_call(lua_State *L) {
1723 lua_settop(L, 2);
1724 #if LUA_VERSION_NUM >= 503
1725 return moonbr_io_wait_cont(L, 0, 0);
1726 #else
1727 return moonbr_io_wait_cont(L);
1728 #endif
1731 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1733 static void moonbr_io_sigterm_handler(int sig) {
1734 moonbr_io_sigterm_flag = 1;
1737 static void moonbr_io_sigchld_handler(int sig) {
1738 moonbr_io_sigchld_flag = 1;
1741 int moonbr_io_catch_sigterm(lua_State *L) {
1742 signal(SIGTERM, moonbr_io_sigterm_handler);
1743 return 0;
1746 static int moonbr_io_getpid(lua_State *L) {
1747 lua_pushinteger(L, getpid());
1748 return 1;
1751 #ifdef MOONBR_IO_USE_TLS
1753 #define moonbr_io_poll_tls() \
1754 if (!handle->tlshandshake) { \
1755 force_wakeup = 1; \
1756 continue; \
1757 } \
1758 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1759 if (fd < 0) { \
1760 force_wakeup = 1; \
1761 continue; \
1762 } \
1763 FD_SET(fd, &readfds); \
1764 if (fd+1 > nfds) nfds = fd+1; \
1765 continue; \
1766 } \
1767 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1768 if (fd < 0) { \
1769 force_wakeup = 1; \
1770 continue; \
1771 } \
1772 FD_SET(fd, &writefds); \
1773 if (fd+1 > nfds) nfds = fd+1; \
1774 continue; \
1775 } \
1776 while (0)
1778 #endif /* MOONBR_IO_USE_TLS */
1780 static int moonbr_io_poll(lua_State *L) {
1781 moonbr_io_handle_t *handle;
1782 moonbr_io_listener_t *listener;
1783 moonbr_io_child_t *child;
1784 int fd, isnum;
1785 int nfds = 0;
1786 fd_set readfds, writefds, exceptfds;
1787 struct timespec timeout = {0, };
1788 int force_wakeup = 0;
1789 int use_timeout = 0; // negative for negative timeout
1790 int check_sigterm = 0;
1791 int check_sigchld = 0;
1792 pid_t waitedpid;
1793 sigset_t mask, orig_mask;
1794 int status;
1795 FD_ZERO(&readfds);
1796 FD_ZERO(&writefds);
1797 FD_ZERO(&exceptfds);
1798 if (!lua_isnoneornil(L, 1)) {
1799 luaL_checktype(L, 1, LUA_TTABLE);
1800 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1801 if (lua_toboolean(L, -1)) {
1802 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1803 if (handle) {
1804 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1805 fd = handle->fd;
1806 #if MOONBR_IO_USE_TLS
1807 moonbr_io_poll_tls();
1808 #endif
1809 if (
1810 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1811 handle->readbufin != handle->readbufout /* data pending in buffer */
1812 ) {
1813 force_wakeup = 1;
1814 continue;
1816 } else {
1817 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1818 if (listener) {
1819 fd = listener->fd;
1820 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1821 } else {
1822 child = luaL_testudata(L, -2, MOONBR_IO_CHILD_MT_REGKEY);
1823 if (child) {
1824 if (!child->pid) luaL_error(L, "Attemt to poll an already collected child process");
1825 if (!check_sigchld) {
1826 check_sigchld = 1;
1827 moonbr_io_sigchld_flag = 0;
1828 signal(SIGCHLD, moonbr_io_sigchld_handler);
1830 if (child->status_valid) {
1831 force_wakeup = 1;
1832 } else {
1833 while ((waitedpid = waitpid(child->pid, &status, WNOHANG)) == -1) {
1834 if (errno != EINTR) {
1835 moonbr_io_prepare_errmsg();
1836 luaL_error(L, "Error in waitpid call: %s", errmsg);
1839 if (waitedpid) {
1840 child->pid = 0;
1841 child->status = status;
1842 child->status_valid = 1;
1843 force_wakeup = 1;
1846 continue;
1847 } else {
1848 fd = lua_tointegerx(L, -2, &isnum);
1849 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1853 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1854 FD_SET(fd, &readfds);
1855 if (fd+1 > nfds) nfds = fd+1;
1859 if (!lua_isnoneornil(L, 2)) {
1860 luaL_checktype(L, 2, LUA_TTABLE);
1861 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1862 if (lua_toboolean(L, -1)) {
1863 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1864 if (handle) {
1865 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1866 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1867 fd = handle->fd;
1868 #if MOONBR_IO_USE_TLS
1869 moonbr_io_poll_tls();
1870 #endif
1871 } else {
1872 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1873 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1874 fd = lua_tointegerx(L, -2, &isnum);
1875 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1877 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1878 FD_SET(fd, &writefds);
1879 if (fd+1 > nfds) nfds = fd+1;
1883 if (!lua_isnoneornil(L, 3)) {
1884 lua_Number n;
1885 n = lua_tonumberx(L, 3, &isnum);
1886 if (isnum && n<0) {
1887 use_timeout = -1;
1888 } else if (isnum && n>=0 && n<100000000) {
1889 use_timeout = 1;
1890 timeout.tv_sec = n;
1891 timeout.tv_nsec = 1e9 * (n - timeout.tv_sec);
1892 } else {
1893 luaL_argcheck(L, 0, 3, "not a valid timeout");
1896 if (use_timeout < 0) force_wakeup = 1;
1897 if (!lua_isnoneornil(L, 4)) luaL_checktype(L, 4, LUA_TBOOLEAN);
1898 check_sigterm = lua_toboolean(L, 4);
1899 if ((check_sigterm || check_sigchld) && !force_wakeup) {
1900 sigemptyset(&mask);
1901 if (check_sigterm) sigaddset(&mask, SIGTERM);
1902 if (check_sigchld) sigaddset(&mask, SIGCHLD);
1903 if (sigprocmask(SIG_BLOCK, &mask, &orig_mask)) abort();
1905 if (check_sigterm && moonbr_io_sigterm_flag) {
1906 if (!force_wakeup) {
1907 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1909 lua_pushboolean(L, 0);
1910 lua_pushliteral(L, "SIGTERM received");
1911 lua_pushboolean(L, 1);
1912 return 3;
1914 if (check_sigchld && !force_wakeup && moonbr_io_sigchld_flag) {
1915 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1916 force_wakeup = 1;
1918 if (use_timeout < 0) {
1919 lua_pushboolean(L, 0);
1920 lua_pushliteral(L, "Timeout");
1921 if (check_sigterm) {
1922 lua_pushboolean(L, 0);
1923 return 3;
1924 } else {
1925 return 2;
1928 if (!force_wakeup) {
1929 status = pselect(
1930 nfds, &readfds, &writefds, &exceptfds,
1931 use_timeout ? &timeout : NULL,
1932 (check_sigterm || check_sigchld) ? &orig_mask : NULL
1933 );
1934 if (check_sigterm || check_sigchld) {
1935 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1936 if (check_sigterm && moonbr_io_sigterm_flag) {
1937 lua_pushboolean(L, 0);
1938 lua_pushliteral(L, "SIGTERM received");
1939 lua_pushboolean(L, 1);
1940 return 3;
1943 if (status == -1) {
1944 if (errno == EINTR) {
1945 lua_pushboolean(L, 1);
1946 return 1;
1947 } else {
1948 moonbr_io_prepare_errmsg();
1949 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1951 } else if (status == 0) {
1952 lua_pushboolean(L, 0);
1953 lua_pushliteral(L, "Timeout");
1954 if (check_sigterm) {
1955 lua_pushboolean(L, 0);
1956 return 3;
1957 } else {
1958 return 2;
1962 lua_pushboolean(L, 1);
1963 return 1;
1966 static int moonbr_io_timeref(lua_State *L) {
1967 lua_Number sub;
1968 struct timespec tp;
1969 sub = luaL_optnumber(L, 1, 0);
1970 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1971 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1973 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1974 return 1;
1977 #ifdef MOONBR_IO_USE_TLS
1979 #define moonbr_io_tlsconf_string(name, field, func) \
1980 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1981 lua_getfield(L, 1, (field)); \
1982 valuetype = lua_type(L, -1); \
1983 if (valuetype != LUA_TNIL) { \
1984 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1985 value = lua_tostring(L, -1); \
1986 if (func(tlsconf->config, value)) { \
1987 lua_pushnil(L); \
1988 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1989 return 2; \
1990 } \
1991 } \
1992 lua_pop(L, 1);
1994 #define moonbr_io_tlsconf_binary(name, field, func) \
1995 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1996 lua_getfield(L, 1, (field)); \
1997 valuetype = lua_type(L, -1); \
1998 if (valuetype != LUA_TNIL) { \
1999 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
2000 value = lua_tolstring(L, -1, &valuelen); \
2001 if (func(tlsconf->config, (void *)value, valuelen)) { \
2002 lua_pushnil(L); \
2003 lua_pushliteral(L, "Could not set " name); \
2004 return 2; \
2005 } \
2006 } \
2007 lua_pop(L, 1);
2009 static int moonbr_io_tlsconf(lua_State *L) {
2010 moonbr_io_tlsconf_t *tlsconf;
2011 int valuetype;
2012 const char *value;
2013 size_t valuelen;
2014 luaL_checktype(L, 1, LUA_TTABLE);
2015 tlsconf = lua_newuserdata(L, sizeof(moonbr_io_tlsconf_t));
2016 tlsconf->config = tls_config_new();
2017 if (!tlsconf->config) {
2018 return luaL_error(L, "Could not allocate memory for TLS configuration");
2020 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
2021 lua_getfield(L, 1, "mode");
2022 value = lua_tostring(L, -1);
2023 if (value && !strcmp(value, "server")) tlsconf->server = 1;
2024 else if (value && !strcmp(value, "client")) tlsconf->server = 0;
2025 else luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
2026 lua_pop(L, 1);
2027 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
2028 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
2029 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
2030 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
2031 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
2032 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
2033 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
2034 #if LUA_VERSION_NUM >= 503
2035 valuetype = lua_getfield(L, 1, "verify_client");
2036 #else
2037 lua_getfield(L, 1, "verify_client");
2038 #endif
2039 if (lua_toboolean(L, -1)) {
2040 value = lua_tostring(L, -1);
2041 if (value && !strcmp(value, "required")) {
2042 tls_config_verify_client(tlsconf->config);
2043 } else if (value && !strcmp(value, "optional")) {
2044 tls_config_verify_client_optional(tlsconf->config);
2045 } else {
2046 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
2049 lua_pop(L, 1);
2050 // TODO: configurable legacy support
2051 // tls_config_set_protocols(tlsconf->config, TLS_PROTOCOLS_ALL);
2052 // tls_config_set_ciphers(tlsconf->config, "legacy");
2053 return 1;
2056 static int moonbr_io_tlsconfgc(lua_State *L) {
2057 moonbr_io_tlsconf_t *tlsconf;
2058 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
2059 if (tlsconf->config) tls_config_free(tlsconf->config);
2060 tlsconf->config = NULL;
2061 return 0;
2064 static int moonbr_io_starttls(lua_State *L) {
2065 moonbr_io_handle_t *handle;
2066 moonbr_io_tlsconf_t *tlsconf;
2067 const char *servername;
2068 struct tls *tls, *tls2;
2069 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
2070 if (lua_type(L, 2) == LUA_TTABLE) {
2071 lua_pushcfunction(L, moonbr_io_tlsconf);
2072 lua_pushvalue(L, 2);
2073 lua_call(L, 1, 2);
2074 if (lua_isnil(L, -2)) return 2;
2075 lua_pop(L, 1);
2076 lua_replace(L, 2);
2078 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
2079 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
2080 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
2081 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
2082 if (handle->readbufin || handle->writebufin) {
2083 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
2085 if (tlsconf->server) tls = tls_server();
2086 else {
2087 servername = luaL_checkstring(L, 3);
2088 tls = tls_client();
2090 if (!tls) {
2091 return luaL_error(L, "Could not allocate memory for TLS context");
2093 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
2094 if (tlsconf->server) {
2095 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
2096 handle->servertls = tls;
2097 handle->tls = tls2;
2098 } else {
2099 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
2100 handle->tls = tls;
2102 lua_settop(L, 1);
2103 return 1;
2104 moonbr_io_starttls_error:
2105 lua_pushnil(L);
2106 lua_pushstring(L, tls_error(tls));
2107 tls_free(tls);
2108 return 2;
2111 #endif /* MOONBR_IO_USE_TLS */
2113 static const struct luaL_Reg moonbr_io_handle_methods[] = {
2114 {"get_rcvbuf", moonbr_io_get_rcvbuf},
2115 {"get_sndbuf", moonbr_io_get_sndbuf},
2116 {"set_rcvbuf", moonbr_io_set_rcvbuf},
2117 {"set_sndbuf", moonbr_io_set_sndbuf},
2118 {"read", moonbr_io_read},
2119 {"read_nb", moonbr_io_read_nb},
2120 {"read_call", moonbr_io_read_call},
2121 {"read_yield", moonbr_io_read_yield},
2122 {"drain", moonbr_io_drain},
2123 {"drain_nb", moonbr_io_drain_nb},
2124 {"drain_call", moonbr_io_drain_call},
2125 {"drain_yield", moonbr_io_drain_yield},
2126 {"write", moonbr_io_write},
2127 {"write_nb", moonbr_io_write_nb},
2128 {"write_call", moonbr_io_write_call},
2129 {"write_yield", moonbr_io_write_yield},
2130 {"flush", moonbr_io_flush},
2131 {"flush_nb", moonbr_io_flush_nb},
2132 {"flush_call", moonbr_io_flush_call},
2133 {"flush_yield", moonbr_io_flush_yield},
2134 {"finish", moonbr_io_finish},
2135 {"close", moonbr_io_close},
2136 {"reset", moonbr_io_reset},
2137 #ifdef MOONBR_IO_USE_TLS
2138 {"starttls", moonbr_io_starttls},
2139 #endif
2140 {NULL, NULL}
2141 };
2143 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
2144 {"__index", moonbr_io_handleindex},
2145 {"__newindex", moonbr_io_handlenewindex},
2146 {"__gc", moonbr_io_handlegc},
2147 {NULL, NULL}
2148 };
2150 static const struct luaL_Reg moonbr_io_listener_methods[] = {
2151 {"accept", moonbr_io_accept},
2152 {"accept_nb", moonbr_io_accept_nb},
2153 {"close", moonbr_io_unlisten},
2154 {NULL, NULL}
2155 };
2157 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
2158 {"__gc", moonbr_io_listenergc},
2159 {NULL, NULL}
2160 };
2162 static const struct luaL_Reg moonbr_io_child_methods[] = {
2163 {"kill", moonbr_io_kill},
2164 {"wait", moonbr_io_wait},
2165 {"wait_nb", moonbr_io_wait_nb},
2166 {"wait_call", moonbr_io_wait_call},
2167 {"wait_yield", moonbr_io_wait_yield},
2168 {NULL, NULL}
2169 };
2171 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
2172 {"__index", moonbr_io_childindex},
2173 {"__newindex", moonbr_io_childnewindex},
2174 {"__gc", moonbr_io_childgc},
2175 {NULL, NULL}
2176 };
2178 static const struct luaL_Reg moonbr_io_module_funcs[] = {
2179 {"localconnect", moonbr_io_localconnect},
2180 {"localconnect_nb", moonbr_io_localconnect_nb},
2181 {"tcpconnect", moonbr_io_tcpconnect},
2182 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2183 {"locallisten", moonbr_io_locallisten},
2184 {"tcplisten", moonbr_io_tcplisten},
2185 {"exec", moonbr_io_exec},
2186 {"catch_sigterm", moonbr_io_catch_sigterm},
2187 {"getpid", moonbr_io_getpid},
2188 {"poll", moonbr_io_poll},
2189 {"timeref", moonbr_io_timeref},
2190 #ifdef MOONBR_IO_USE_TLS
2191 {"tlsconf", moonbr_io_tlsconf},
2192 #endif
2193 {NULL, NULL}
2194 };
2196 #ifdef MOONBR_IO_USE_TLS
2198 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2199 {"__gc", moonbr_io_tlsconfgc},
2200 {NULL, NULL}
2201 };
2203 #endif /* MOONBR_IO_USE_TLS */
2205 int luaopen_moonbridge_io(lua_State *L) {
2207 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2209 lua_newtable(L); // module
2210 lua_pushvalue(L, -1);
2211 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_MODULE_REGKEY);
2213 lua_newtable(L); // public metatable
2214 lua_newtable(L); // handle methods
2215 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2216 lua_pushvalue(L, -1);
2217 lua_setfield(L, -4, "handle_pt");
2218 lua_setfield(L, -2, "__index");
2219 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2221 lua_newtable(L); // handle metatable
2222 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2223 lua_pushvalue(L, -1);
2224 lua_setfield(L, -3, "handle_mt");
2225 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2227 lua_newtable(L); // listener metatable
2228 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2229 lua_newtable(L); // listener methods
2230 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2231 lua_pushvalue(L, -1);
2232 lua_setfield(L, -4, "listener_pt");
2233 lua_setfield(L, -2, "__index");
2234 lua_pushvalue(L, -1);
2235 lua_setfield(L, -3, "listener_mt");
2236 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2238 lua_newtable(L); // child methods
2239 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2240 lua_pushvalue(L, -1);
2241 lua_setfield(L, -3, "child_pt");
2242 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2243 lua_newtable(L); // child metatable
2244 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2245 lua_pushvalue(L, -1);
2246 lua_setfield(L, -3, "child_mt");
2247 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2249 #ifdef MOONBR_IO_USE_TLS
2250 if(tls_init()) {
2251 return luaL_error(L, "Could not initialize TLS library");
2253 lua_newtable(L); // tlsconf metatable
2254 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2255 lua_pushvalue(L, -1);
2256 lua_setfield(L, -3, "tlsconf_mt");
2257 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2258 #endif
2260 moonbr_io_pushhandle(L, 0);
2261 lua_setfield(L, -2, "stdin");
2262 moonbr_io_pushhandle(L, 1);
2263 lua_setfield(L, -2, "stdout");
2264 moonbr_io_pushhandle(L, 2);
2265 lua_setfield(L, -2, "stderr");
2267 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2268 return 1;

Impressum / About Us