moonbridge

view moonbridge_io.c @ 326:4379766473ec

Fixed proper errno handling for blocking I/O in localconnect function for connecting to sockets
author jbe
date Tue Jun 23 12:25:58 2020 +0200 (7 weeks ago)
parents fe1a134a92a4
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 freeaddrinfo(res);
1192 if (errcode == EAI_SYSTEM) {
1193 moonbr_io_prepare_errmsg();
1194 lua_pushnil(L);
1195 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1196 } else {
1197 lua_pushnil(L);
1198 lua_pushstring(L, gai_strerror(errcode));
1200 return 2;
1202 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1203 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1205 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1206 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1208 addrinfo = res;
1209 moonbr_io_tcpconnect_found:
1210 sock = socket(
1211 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1212 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1213 addrinfo->ai_protocol
1214 );
1215 if (sock < 0) {
1216 moonbr_io_prepare_errmsg();
1217 freeaddrinfo(res);
1218 moonbr_io_return_prepared_errmsg();
1220 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1221 freeaddrinfo(res);
1222 if (!nonblocking && errno == EINTR) {
1223 moonbr_io_prepare_errmsg();
1224 close(sock);
1225 moonbr_io_return_prepared_errmsg();
1226 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1227 } else {
1228 freeaddrinfo(res);
1230 if (nonblocking) {
1231 moonbr_io_pushhandle_skip_peeraddr(L, sock);
1232 if (addrinfo->ai_family == AF_INET6) {
1233 // TODO: fill remote_ip6 and remote_tcpport
1234 } else if (addrinfo->ai_family == AF_INET) {
1235 // TODO: fill remote_ip4 and remote_tcpport
1237 } else {
1238 moonbr_io_pushhandle(L, sock);
1240 return 1;
1243 static int moonbr_io_tcpconnect(lua_State *L) {
1244 return moonbr_io_tcpconnect_impl(L, 0);
1247 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1248 return moonbr_io_tcpconnect_impl(L, 1);
1251 static int moonbr_io_locallisten(lua_State *L) {
1252 moonbr_io_listener_t *listener;
1253 const char *path;
1254 struct stat sb;
1255 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1256 const int path_maxlen = sizeof(struct sockaddr_un) - (
1257 (void *)sockaddr.sun_path - (void *)&sockaddr
1258 ) - 1; /* one byte for termination */
1259 int sock;
1260 path = luaL_checkstring(L, 1);
1261 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1262 strcpy(sockaddr.sun_path, path);
1263 if (stat(path, &sb) == 0) {
1264 if (S_ISSOCK(sb.st_mode)) unlink(path);
1266 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1267 listener->fd = -1;
1268 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1269 sock = socket(
1270 PF_LOCAL,
1271 SOCK_STREAM | SOCK_CLOEXEC,
1273 );
1274 if (sock < 0) moonbr_io_return_errmsg();
1275 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1276 moonbr_io_prepare_errmsg();
1277 close(sock);
1278 moonbr_io_return_prepared_errmsg();
1280 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1281 moonbr_io_prepare_errmsg();
1282 close(sock);
1283 moonbr_io_return_prepared_errmsg();
1285 listener->fd = sock;
1286 listener->addrfam = AF_LOCAL;
1287 listener->nonblocking = -1;
1288 return 1;
1291 static int moonbr_io_tcplisten(lua_State *L) {
1292 moonbr_io_listener_t *listener;
1293 const char *host, *port;
1294 struct addrinfo hints = { 0, };
1295 struct addrinfo *res, *addrinfo;
1296 int errcode;
1297 int sock;
1298 host = luaL_optstring(L, 1, NULL);
1299 port = luaL_checkstring(L, 2);
1300 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1301 listener->fd = -1;
1302 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1303 hints.ai_family = AF_UNSPEC;
1304 hints.ai_socktype = SOCK_STREAM;
1305 hints.ai_protocol = IPPROTO_TCP;
1306 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1307 errcode = getaddrinfo(host, port, &hints, &res);
1308 if (errcode) {
1309 freeaddrinfo(res);
1310 if (errcode == EAI_SYSTEM) {
1311 moonbr_io_prepare_errmsg();
1312 lua_pushnil(L);
1313 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1314 } else {
1315 lua_pushnil(L);
1316 lua_pushstring(L, gai_strerror(errcode));
1318 return 2;
1320 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1321 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1323 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1324 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1326 addrinfo = res;
1327 moonbr_io_tcpconnect_found:
1328 listener->addrfam = addrinfo->ai_family;
1329 sock = socket(
1330 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1331 addrinfo->ai_socktype | SOCK_CLOEXEC,
1332 addrinfo->ai_protocol
1333 );
1334 if (sock < 0) {
1335 moonbr_io_prepare_errmsg();
1336 freeaddrinfo(res);
1337 moonbr_io_return_prepared_errmsg();
1340 static const int reuseval = 1;
1341 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1342 moonbr_io_prepare_errmsg();
1343 freeaddrinfo(res);
1344 close(sock);
1345 lua_pushnil(L);
1346 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1347 return 2;
1350 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1351 moonbr_io_prepare_errmsg();
1352 freeaddrinfo(res);
1353 close(sock);
1354 moonbr_io_return_prepared_errmsg();
1356 freeaddrinfo(res);
1357 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1358 moonbr_io_prepare_errmsg();
1359 close(sock);
1360 moonbr_io_return_prepared_errmsg();
1362 listener->fd = sock;
1363 listener->nonblocking = -1;
1364 return 1;
1367 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1368 moonbr_io_listener_t *listener;
1369 int fd;
1370 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1371 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1372 if (listener->nonblocking != nonblocking) {
1373 int flags;
1374 flags = fcntl(listener->fd, F_GETFL, 0);
1375 if (flags == -1) {
1376 moonbr_io_prepare_errmsg();
1377 close(listener->fd);
1378 listener->fd = -1;
1379 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1381 if (nonblocking) flags |= O_NONBLOCK;
1382 else flags &= ~O_NONBLOCK;
1383 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1384 moonbr_io_prepare_errmsg();
1385 close(listener->fd);
1386 listener->fd = -1;
1387 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1389 listener->nonblocking = nonblocking;
1391 while (1) {
1392 #if defined(__linux__) && !defined(_GNU_SOURCE)
1393 fd = accept(listener->fd, NULL, NULL);
1394 if (fd != -1) {
1395 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
1396 moonbr_io_prepare_errmsg();
1397 close(listener->fd);
1398 listener->fd = -1;
1399 close(fd);
1400 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1403 #else
1404 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1405 #endif
1406 if (fd < 0) {
1407 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1408 lua_pushboolean(L, 0);
1409 lua_pushliteral(L, "No incoming connection pending");
1410 return 2;
1411 } else if (errno != EINTR) moonbr_io_return_errmsg();
1412 } else {
1413 moonbr_io_pushhandle(L, fd);
1414 return 1;
1419 static int moonbr_io_accept(lua_State *L) {
1420 return moonbr_io_accept_impl(L, 0);
1423 static int moonbr_io_accept_nb(lua_State *L) {
1424 return moonbr_io_accept_impl(L, 1);
1427 static int moonbr_io_unlisten(lua_State *L) {
1428 moonbr_io_listener_t *listener;
1429 struct sockaddr_un addr;
1430 socklen_t addrlen;
1431 struct stat sb;
1432 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1433 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1434 addrlen = sizeof(addr);
1435 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1436 if (close(listener->fd)) {
1437 moonbr_io_prepare_errmsg();
1438 listener->fd = -1;
1439 if (addrlen && addrlen <= sizeof(addr)) {
1440 if (stat(addr.sun_path, &sb) == 0) {
1441 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1444 moonbr_io_return_prepared_errmsg();
1446 listener->fd = -1;
1447 if (addrlen && addrlen <= sizeof(addr)) {
1448 if (stat(addr.sun_path, &sb) == 0) {
1449 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1452 lua_pushboolean(L, 1);
1453 return 1;
1456 static int moonbr_io_listenergc(lua_State *L) {
1457 moonbr_io_listener_t *listener;
1458 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1459 if (listener->fd >= 0) close(listener->fd);
1460 listener->fd = -1;
1461 return 0;
1464 static int moonbr_io_exec(lua_State *L) {
1465 char **argv;
1466 int i, argc;
1467 int sockin[2], sockout[2], sockerr[2];
1468 volatile int errorcond = 0;
1469 volatile char errmsgbuf[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG;
1470 moonbr_io_child_t *child;
1471 argc = lua_gettop(L);
1472 argv = lua_newuserdata(L, (argc + 1) * sizeof(char *));
1473 for (i=0; i<argc; i++) argv[i] = (char *)luaL_checkstring(L, i+1);
1474 argv[argc] = NULL;
1475 child = lua_newuserdata(L, sizeof(moonbr_io_child_t));
1476 child->pid = 0;
1477 child->status_valid = 0;
1478 lua_newtable(L);
1479 lua_setuservalue(L, -2);
1480 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1481 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1482 moonbr_io_prepare_errmsg();
1483 lua_pushnil(L);
1484 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1485 return 2;
1487 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1488 moonbr_io_prepare_errmsg();
1489 close(sockin[0]);
1490 close(sockin[1]);
1491 lua_pushnil(L);
1492 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1493 return 2;
1495 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1496 moonbr_io_prepare_errmsg();
1497 close(sockin[0]);
1498 close(sockin[1]);
1499 close(sockout[0]);
1500 close(sockout[1]);
1501 lua_pushnil(L);
1502 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1503 return 2;
1505 child->pid = vfork();
1506 if (child->pid == -1) {
1507 moonbr_io_prepare_errmsg();
1508 close(sockin[0]);
1509 close(sockin[1]);
1510 close(sockout[0]);
1511 close(sockout[1]);
1512 close(sockerr[0]);
1513 close(sockerr[1]);
1514 lua_pushnil(L);
1515 lua_pushfstring(L, "Could not fork: %s", errmsg);
1516 return 2;
1518 if (!child->pid) {
1519 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1520 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1521 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1522 closefrom(3);
1523 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1524 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1525 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1526 if (execvp(argv[0], argv)) {
1527 errorcond = 2;
1528 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1529 _exit(0);
1531 moonbr_io_exec_error1:
1532 errorcond = 1;
1533 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1534 _exit(0);
1536 close(sockin[1]);
1537 close(sockout[1]);
1538 close(sockerr[1]);
1539 if (errorcond) {
1540 int status;
1541 close(sockin[0]);
1542 close(sockout[0]);
1543 close(sockerr[0]);
1544 while (waitpid(child->pid, &status, 0) == -1) {
1545 if (errno != EINTR) {
1546 moonbr_io_prepare_errmsg();
1547 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1550 child->pid = 0;
1551 lua_pushnil(L);
1552 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1553 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1554 return 2;
1556 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1557 lua_pushlightuserdata(L, &sockin[0]);
1558 if (lua_pcall(L, 1, 1, 0)) {
1559 if (sockin[0] != -1) close(sockin[0]);
1560 close(sockout[0]);
1561 close(sockerr[0]);
1562 goto moonbr_io_exec_error2;
1564 lua_setfield(L, -2, "stdin");
1565 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1566 lua_pushlightuserdata(L, &sockout[0]);
1567 if (lua_pcall(L, 1, 1, 0)) {
1568 if (sockout[0] != -1) close(sockout[0]);
1569 close(sockerr[0]);
1570 goto moonbr_io_exec_error2;
1572 lua_setfield(L, -2, "stdout");
1573 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1574 lua_pushlightuserdata(L, &sockerr[0]);
1575 if (lua_pcall(L, 1, 1, 0)) {
1576 if (sockerr[0] != -1) close(sockerr[0]);
1577 goto moonbr_io_exec_error2;
1579 lua_setfield(L, -2, "stderr");
1580 return 1;
1581 moonbr_io_exec_error2:
1583 int status;
1584 while (waitpid(child->pid, &status, 0) == -1) {
1585 if (errno != EINTR) {
1586 moonbr_io_prepare_errmsg();
1587 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1591 child->pid = 0;
1592 return lua_error(L);
1595 static int moonbr_io_childindex(lua_State *L) {
1596 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1597 luaL_checkany(L, 2);
1598 lua_getuservalue(L, 1);
1599 lua_pushvalue(L, 2);
1600 lua_gettable(L, -2);
1601 if (lua_isnil(L, -1)) {
1602 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1603 lua_pushvalue(L, 2);
1604 lua_gettable(L, -2);
1606 return 1;
1609 static int moonbr_io_childnewindex(lua_State *L) {
1610 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1611 luaL_checkany(L, 2);
1612 luaL_checkany(L, 3);
1613 lua_getuservalue(L, 1);
1614 lua_pushvalue(L, 2);
1615 lua_pushvalue(L, 3);
1616 lua_settable(L, -3);
1617 return 0;
1620 static int moonbr_io_childgc(lua_State *L) {
1621 moonbr_io_child_t *child;
1622 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1623 if (child->pid) {
1624 int status;
1625 int pid = child->pid;
1626 child->pid = 0;
1627 if (kill(pid, SIGKILL)) {
1628 moonbr_io_prepare_errmsg();
1629 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1631 while (waitpid(pid, &status, 0) == -1) {
1632 if (errno != EINTR) {
1633 moonbr_io_prepare_errmsg();
1634 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1638 return 0;
1641 static int moonbr_io_kill(lua_State *L) {
1642 moonbr_io_child_t *child;
1643 int sig;
1644 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1645 sig = luaL_optinteger(L, 2, SIGKILL);
1646 if (!child->pid) {
1647 if (!child->status_valid) luaL_error(L, "Attempt to kill an already collected child process");
1648 } else {
1649 if (kill(child->pid, sig)) {
1650 moonbr_io_prepare_errmsg();
1651 luaL_error(L, "Error in kill call: %s", errmsg);
1654 lua_settop(L, 1);
1655 return 1;
1658 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1659 moonbr_io_child_t *child;
1660 int status;
1661 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1662 if (!child->pid) {
1663 if (!child->status_valid) luaL_error(L, "Attempt to wait for an already collected child process");
1664 status = child->status;
1665 child->status_valid = 0;
1666 } else {
1667 pid_t waitedpid;
1668 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1669 if (errno != EINTR) {
1670 moonbr_io_prepare_errmsg();
1671 luaL_error(L, "Error in waitpid call: %s", errmsg);
1674 if (!waitedpid) {
1675 lua_pushboolean(L, 0);
1676 lua_pushliteral(L, "Process is still running");
1677 return 2;
1679 child->pid = 0;
1681 if (WIFEXITED(status)) {
1682 lua_pushinteger(L, WEXITSTATUS(status));
1683 } else if (WIFSIGNALED(status)) {
1684 lua_pushinteger(L, -WTERMSIG(status));
1685 } else {
1686 luaL_error(L, "Unexpected status value returned by waitpid call");
1688 return 1;
1691 static int moonbr_io_wait(lua_State *L) {
1692 return moonbr_io_wait_impl(L, 0);
1695 static int moonbr_io_wait_nb(lua_State *L) {
1696 return moonbr_io_wait_impl(L, 1);
1699 #if LUA_VERSION_NUM >= 503
1700 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1701 #else
1702 static int moonbr_io_wait_cont(lua_State *L) {
1703 #endif
1704 #if !(LUA_VERSION_NUM >= 503)
1705 int ctx = 0;
1706 int status = lua_getctx(L, &ctx);
1707 #endif
1708 while (1) {
1709 lua_pushcfunction(L, moonbr_io_wait_nb);
1710 lua_pushvalue(L, 1);
1711 lua_call(L, 1, 1);
1712 if (!lua_isnil(L, -1)) break;
1713 lua_pushvalue(L, 2);
1714 lua_pushvalue(L, 1);
1715 lua_pushliteral(L, "r");
1716 lua_pushboolean(L, status != LUA_YIELD);
1717 lua_getfield(L, LUA_REGISTRYINDEX, MOONBR_IO_MODULE_REGKEY);
1718 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1719 status = LUA_YIELD;
1721 return 1;
1724 static int moonbr_io_wait_call(lua_State *L) {
1725 lua_settop(L, 2);
1726 #if LUA_VERSION_NUM >= 503
1727 return moonbr_io_wait_cont(L, 0, 0);
1728 #else
1729 return moonbr_io_wait_cont(L);
1730 #endif
1733 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1735 static void moonbr_io_sigterm_handler(int sig) {
1736 moonbr_io_sigterm_flag = 1;
1739 static void moonbr_io_sigchld_handler(int sig) {
1740 moonbr_io_sigchld_flag = 1;
1743 int moonbr_io_catch_sigterm(lua_State *L) {
1744 signal(SIGTERM, moonbr_io_sigterm_handler);
1745 return 0;
1748 static int moonbr_io_getpid(lua_State *L) {
1749 lua_pushinteger(L, getpid());
1750 return 1;
1753 #ifdef MOONBR_IO_USE_TLS
1755 #define moonbr_io_poll_tls() \
1756 if (!handle->tlshandshake) { \
1757 force_wakeup = 1; \
1758 continue; \
1759 } \
1760 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1761 if (fd < 0) { \
1762 force_wakeup = 1; \
1763 continue; \
1764 } \
1765 FD_SET(fd, &readfds); \
1766 if (fd+1 > nfds) nfds = fd+1; \
1767 continue; \
1768 } \
1769 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1770 if (fd < 0) { \
1771 force_wakeup = 1; \
1772 continue; \
1773 } \
1774 FD_SET(fd, &writefds); \
1775 if (fd+1 > nfds) nfds = fd+1; \
1776 continue; \
1777 } \
1778 while (0)
1780 #endif /* MOONBR_IO_USE_TLS */
1782 static int moonbr_io_poll(lua_State *L) {
1783 moonbr_io_handle_t *handle;
1784 moonbr_io_listener_t *listener;
1785 moonbr_io_child_t *child;
1786 int fd, isnum;
1787 int nfds = 0;
1788 fd_set readfds, writefds, exceptfds;
1789 struct timespec timeout = {0, };
1790 int force_wakeup = 0;
1791 int use_timeout = 0; // negative for negative timeout
1792 int check_sigterm = 0;
1793 int check_sigchld = 0;
1794 pid_t waitedpid;
1795 sigset_t mask, orig_mask;
1796 int status;
1797 FD_ZERO(&readfds);
1798 FD_ZERO(&writefds);
1799 FD_ZERO(&exceptfds);
1800 if (!lua_isnoneornil(L, 1)) {
1801 luaL_checktype(L, 1, LUA_TTABLE);
1802 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1803 if (lua_toboolean(L, -1)) {
1804 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1805 if (handle) {
1806 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1807 fd = handle->fd;
1808 #if MOONBR_IO_USE_TLS
1809 moonbr_io_poll_tls();
1810 #endif
1811 if (
1812 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1813 handle->readbufin != handle->readbufout /* data pending in buffer */
1814 ) {
1815 force_wakeup = 1;
1816 continue;
1818 } else {
1819 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1820 if (listener) {
1821 fd = listener->fd;
1822 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1823 } else {
1824 child = luaL_testudata(L, -2, MOONBR_IO_CHILD_MT_REGKEY);
1825 if (child) {
1826 if (!child->pid) luaL_error(L, "Attemt to poll an already collected child process");
1827 if (!check_sigchld) {
1828 check_sigchld = 1;
1829 moonbr_io_sigchld_flag = 0;
1830 signal(SIGCHLD, moonbr_io_sigchld_handler);
1832 if (child->status_valid) {
1833 force_wakeup = 1;
1834 } else {
1835 while ((waitedpid = waitpid(child->pid, &status, WNOHANG)) == -1) {
1836 if (errno != EINTR) {
1837 moonbr_io_prepare_errmsg();
1838 luaL_error(L, "Error in waitpid call: %s", errmsg);
1841 if (waitedpid) {
1842 child->pid = 0;
1843 child->status = status;
1844 child->status_valid = 1;
1845 force_wakeup = 1;
1848 continue;
1849 } else {
1850 fd = lua_tointegerx(L, -2, &isnum);
1851 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1855 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1856 FD_SET(fd, &readfds);
1857 if (fd+1 > nfds) nfds = fd+1;
1861 if (!lua_isnoneornil(L, 2)) {
1862 luaL_checktype(L, 2, LUA_TTABLE);
1863 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1864 if (lua_toboolean(L, -1)) {
1865 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1866 if (handle) {
1867 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1868 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1869 fd = handle->fd;
1870 #if MOONBR_IO_USE_TLS
1871 moonbr_io_poll_tls();
1872 #endif
1873 } else {
1874 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1875 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1876 fd = lua_tointegerx(L, -2, &isnum);
1877 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1879 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1880 FD_SET(fd, &writefds);
1881 if (fd+1 > nfds) nfds = fd+1;
1885 if (!lua_isnoneornil(L, 3)) {
1886 lua_Number n;
1887 n = lua_tonumberx(L, 3, &isnum);
1888 if (isnum && n<0) {
1889 use_timeout = -1;
1890 } else if (isnum && n>=0 && n<100000000) {
1891 use_timeout = 1;
1892 timeout.tv_sec = n;
1893 timeout.tv_nsec = 1e9 * (n - timeout.tv_sec);
1894 } else {
1895 luaL_argcheck(L, 0, 3, "not a valid timeout");
1898 if (use_timeout < 0) force_wakeup = 1;
1899 if (!lua_isnoneornil(L, 4)) luaL_checktype(L, 4, LUA_TBOOLEAN);
1900 check_sigterm = lua_toboolean(L, 4);
1901 if ((check_sigterm || check_sigchld) && !force_wakeup) {
1902 sigemptyset(&mask);
1903 if (check_sigterm) sigaddset(&mask, SIGTERM);
1904 if (check_sigchld) sigaddset(&mask, SIGCHLD);
1905 if (sigprocmask(SIG_BLOCK, &mask, &orig_mask)) abort();
1907 if (check_sigterm && moonbr_io_sigterm_flag) {
1908 if (!force_wakeup) {
1909 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1911 lua_pushboolean(L, 0);
1912 lua_pushliteral(L, "SIGTERM received");
1913 lua_pushboolean(L, 1);
1914 return 3;
1916 if (check_sigchld && !force_wakeup && moonbr_io_sigchld_flag) {
1917 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1918 force_wakeup = 1;
1920 if (use_timeout < 0) {
1921 lua_pushboolean(L, 0);
1922 lua_pushliteral(L, "Timeout");
1923 if (check_sigterm) {
1924 lua_pushboolean(L, 0);
1925 return 3;
1926 } else {
1927 return 2;
1930 if (!force_wakeup) {
1931 status = pselect(
1932 nfds, &readfds, &writefds, &exceptfds,
1933 use_timeout ? &timeout : NULL,
1934 (check_sigterm || check_sigchld) ? &orig_mask : NULL
1935 );
1936 if (check_sigterm || check_sigchld) {
1937 if (sigprocmask(SIG_SETMASK, &orig_mask, NULL)) abort();
1938 if (check_sigterm && moonbr_io_sigterm_flag) {
1939 lua_pushboolean(L, 0);
1940 lua_pushliteral(L, "SIGTERM received");
1941 lua_pushboolean(L, 1);
1942 return 3;
1945 if (status == -1) {
1946 if (errno == EINTR) {
1947 lua_pushboolean(L, 1);
1948 return 1;
1949 } else {
1950 moonbr_io_prepare_errmsg();
1951 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1953 } else if (status == 0) {
1954 lua_pushboolean(L, 0);
1955 lua_pushliteral(L, "Timeout");
1956 if (check_sigterm) {
1957 lua_pushboolean(L, 0);
1958 return 3;
1959 } else {
1960 return 2;
1964 lua_pushboolean(L, 1);
1965 return 1;
1968 static int moonbr_io_timeref(lua_State *L) {
1969 lua_Number sub;
1970 struct timespec tp;
1971 sub = luaL_optnumber(L, 1, 0);
1972 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1973 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1975 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1976 return 1;
1979 #ifdef MOONBR_IO_USE_TLS
1981 #define moonbr_io_tlsconf_string(name, field, func) \
1982 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1983 lua_getfield(L, 1, (field)); \
1984 valuetype = lua_type(L, -1); \
1985 if (valuetype != LUA_TNIL) { \
1986 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1987 value = lua_tostring(L, -1); \
1988 if (func(tlsconf->config, value)) { \
1989 lua_pushnil(L); \
1990 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1991 return 2; \
1992 } \
1993 } \
1994 lua_pop(L, 1);
1996 #define moonbr_io_tlsconf_binary(name, field, func) \
1997 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1998 lua_getfield(L, 1, (field)); \
1999 valuetype = lua_type(L, -1); \
2000 if (valuetype != LUA_TNIL) { \
2001 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
2002 value = lua_tolstring(L, -1, &valuelen); \
2003 if (func(tlsconf->config, (void *)value, valuelen)) { \
2004 lua_pushnil(L); \
2005 lua_pushliteral(L, "Could not set " name); \
2006 return 2; \
2007 } \
2008 } \
2009 lua_pop(L, 1);
2011 static int moonbr_io_tlsconf(lua_State *L) {
2012 moonbr_io_tlsconf_t *tlsconf;
2013 int valuetype;
2014 const char *value;
2015 size_t valuelen;
2016 luaL_checktype(L, 1, LUA_TTABLE);
2017 tlsconf = lua_newuserdata(L, sizeof(moonbr_io_tlsconf_t));
2018 tlsconf->config = tls_config_new();
2019 if (!tlsconf->config) {
2020 return luaL_error(L, "Could not allocate memory for TLS configuration");
2022 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
2023 lua_getfield(L, 1, "mode");
2024 value = lua_tostring(L, -1);
2025 if (value && !strcmp(value, "server")) tlsconf->server = 1;
2026 else if (value && !strcmp(value, "client")) tlsconf->server = 0;
2027 else luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
2028 lua_pop(L, 1);
2029 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
2030 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
2031 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
2032 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
2033 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
2034 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
2035 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
2036 #if LUA_VERSION_NUM >= 503
2037 valuetype = lua_getfield(L, 1, "verify_client");
2038 #else
2039 lua_getfield(L, 1, "verify_client");
2040 #endif
2041 if (lua_toboolean(L, -1)) {
2042 value = lua_tostring(L, -1);
2043 if (value && !strcmp(value, "required")) {
2044 tls_config_verify_client(tlsconf->config);
2045 } else if (value && !strcmp(value, "optional")) {
2046 tls_config_verify_client_optional(tlsconf->config);
2047 } else {
2048 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
2051 lua_pop(L, 1);
2052 // TODO: configurable legacy support
2053 // tls_config_set_protocols(tlsconf->config, TLS_PROTOCOLS_ALL);
2054 // tls_config_set_ciphers(tlsconf->config, "legacy");
2055 return 1;
2058 static int moonbr_io_tlsconfgc(lua_State *L) {
2059 moonbr_io_tlsconf_t *tlsconf;
2060 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
2061 if (tlsconf->config) tls_config_free(tlsconf->config);
2062 tlsconf->config = NULL;
2063 return 0;
2066 static int moonbr_io_starttls(lua_State *L) {
2067 moonbr_io_handle_t *handle;
2068 moonbr_io_tlsconf_t *tlsconf;
2069 const char *servername;
2070 struct tls *tls, *tls2;
2071 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
2072 if (lua_type(L, 2) == LUA_TTABLE) {
2073 lua_pushcfunction(L, moonbr_io_tlsconf);
2074 lua_pushvalue(L, 2);
2075 lua_call(L, 1, 2);
2076 if (lua_isnil(L, -2)) return 2;
2077 lua_pop(L, 1);
2078 lua_replace(L, 2);
2080 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
2081 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
2082 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
2083 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
2084 if (handle->readbufin || handle->writebufin) {
2085 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
2087 if (tlsconf->server) tls = tls_server();
2088 else {
2089 servername = luaL_checkstring(L, 3);
2090 tls = tls_client();
2092 if (!tls) {
2093 return luaL_error(L, "Could not allocate memory for TLS context");
2095 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
2096 if (tlsconf->server) {
2097 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
2098 handle->servertls = tls;
2099 handle->tls = tls2;
2100 } else {
2101 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
2102 handle->tls = tls;
2104 lua_settop(L, 1);
2105 return 1;
2106 moonbr_io_starttls_error:
2107 lua_pushnil(L);
2108 lua_pushstring(L, tls_error(tls));
2109 tls_free(tls);
2110 return 2;
2113 #endif /* MOONBR_IO_USE_TLS */
2115 static const struct luaL_Reg moonbr_io_handle_methods[] = {
2116 {"get_rcvbuf", moonbr_io_get_rcvbuf},
2117 {"get_sndbuf", moonbr_io_get_sndbuf},
2118 {"set_rcvbuf", moonbr_io_set_rcvbuf},
2119 {"set_sndbuf", moonbr_io_set_sndbuf},
2120 {"read", moonbr_io_read},
2121 {"read_nb", moonbr_io_read_nb},
2122 {"read_call", moonbr_io_read_call},
2123 {"read_yield", moonbr_io_read_yield},
2124 {"drain", moonbr_io_drain},
2125 {"drain_nb", moonbr_io_drain_nb},
2126 {"drain_call", moonbr_io_drain_call},
2127 {"drain_yield", moonbr_io_drain_yield},
2128 {"write", moonbr_io_write},
2129 {"write_nb", moonbr_io_write_nb},
2130 {"write_call", moonbr_io_write_call},
2131 {"write_yield", moonbr_io_write_yield},
2132 {"flush", moonbr_io_flush},
2133 {"flush_nb", moonbr_io_flush_nb},
2134 {"flush_call", moonbr_io_flush_call},
2135 {"flush_yield", moonbr_io_flush_yield},
2136 {"finish", moonbr_io_finish},
2137 {"close", moonbr_io_close},
2138 {"reset", moonbr_io_reset},
2139 #ifdef MOONBR_IO_USE_TLS
2140 {"starttls", moonbr_io_starttls},
2141 #endif
2142 {NULL, NULL}
2143 };
2145 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
2146 {"__index", moonbr_io_handleindex},
2147 {"__newindex", moonbr_io_handlenewindex},
2148 {"__gc", moonbr_io_handlegc},
2149 {NULL, NULL}
2150 };
2152 static const struct luaL_Reg moonbr_io_listener_methods[] = {
2153 {"accept", moonbr_io_accept},
2154 {"accept_nb", moonbr_io_accept_nb},
2155 {"close", moonbr_io_unlisten},
2156 {NULL, NULL}
2157 };
2159 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
2160 {"__gc", moonbr_io_listenergc},
2161 {NULL, NULL}
2162 };
2164 static const struct luaL_Reg moonbr_io_child_methods[] = {
2165 {"kill", moonbr_io_kill},
2166 {"wait", moonbr_io_wait},
2167 {"wait_nb", moonbr_io_wait_nb},
2168 {"wait_call", moonbr_io_wait_call},
2169 {"wait_yield", moonbr_io_wait_yield},
2170 {NULL, NULL}
2171 };
2173 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
2174 {"__index", moonbr_io_childindex},
2175 {"__newindex", moonbr_io_childnewindex},
2176 {"__gc", moonbr_io_childgc},
2177 {NULL, NULL}
2178 };
2180 static const struct luaL_Reg moonbr_io_module_funcs[] = {
2181 {"localconnect", moonbr_io_localconnect},
2182 {"localconnect_nb", moonbr_io_localconnect_nb},
2183 {"tcpconnect", moonbr_io_tcpconnect},
2184 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2185 {"locallisten", moonbr_io_locallisten},
2186 {"tcplisten", moonbr_io_tcplisten},
2187 {"exec", moonbr_io_exec},
2188 {"catch_sigterm", moonbr_io_catch_sigterm},
2189 {"getpid", moonbr_io_getpid},
2190 {"poll", moonbr_io_poll},
2191 {"timeref", moonbr_io_timeref},
2192 #ifdef MOONBR_IO_USE_TLS
2193 {"tlsconf", moonbr_io_tlsconf},
2194 #endif
2195 {NULL, NULL}
2196 };
2198 #ifdef MOONBR_IO_USE_TLS
2200 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2201 {"__gc", moonbr_io_tlsconfgc},
2202 {NULL, NULL}
2203 };
2205 #endif /* MOONBR_IO_USE_TLS */
2207 int luaopen_moonbridge_io(lua_State *L) {
2209 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2211 lua_newtable(L); // module
2212 lua_pushvalue(L, -1);
2213 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_MODULE_REGKEY);
2215 lua_newtable(L); // public metatable
2216 lua_newtable(L); // handle methods
2217 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2218 lua_pushvalue(L, -1);
2219 lua_setfield(L, -4, "handle_pt");
2220 lua_setfield(L, -2, "__index");
2221 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2223 lua_newtable(L); // handle metatable
2224 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2225 lua_pushvalue(L, -1);
2226 lua_setfield(L, -3, "handle_mt");
2227 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2229 lua_newtable(L); // listener metatable
2230 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2231 lua_newtable(L); // listener methods
2232 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2233 lua_pushvalue(L, -1);
2234 lua_setfield(L, -4, "listener_pt");
2235 lua_setfield(L, -2, "__index");
2236 lua_pushvalue(L, -1);
2237 lua_setfield(L, -3, "listener_mt");
2238 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2240 lua_newtable(L); // child methods
2241 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2242 lua_pushvalue(L, -1);
2243 lua_setfield(L, -3, "child_pt");
2244 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2245 lua_newtable(L); // child metatable
2246 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2247 lua_pushvalue(L, -1);
2248 lua_setfield(L, -3, "child_mt");
2249 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2251 #ifdef MOONBR_IO_USE_TLS
2252 if(tls_init()) {
2253 return luaL_error(L, "Could not initialize TLS library");
2255 lua_newtable(L); // tlsconf metatable
2256 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2257 lua_pushvalue(L, -1);
2258 lua_setfield(L, -3, "tlsconf_mt");
2259 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2260 #endif
2262 moonbr_io_pushhandle(L, 0);
2263 lua_setfield(L, -2, "stdin");
2264 moonbr_io_pushhandle(L, 1);
2265 lua_setfield(L, -2, "stdout");
2266 moonbr_io_pushhandle(L, 2);
2267 lua_setfield(L, -2, "stderr");
2269 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2270 return 1;

Impressum / About Us