moonbridge

view moonbridge_io.c @ 258:56c12449bba0

Code reformatting (of #ifdef MOONBR_IO_USE_TLS)
author jbe
date Sun Sep 18 12:02:38 2016 +0200 (2016-09-18)
parents 77a7ca00ad34
children 385b6607785a
line source
2 #ifndef __has_include
3 #define __has_include(x) 0
4 #endif
6 #include <stdlib.h>
7 #include <stdint.h>
8 #include <string.h>
9 #include <errno.h>
10 #include <unistd.h>
11 #include <signal.h>
12 #include <fcntl.h>
13 #include <sys/stat.h>
14 #include <sys/socket.h>
15 #include <sys/un.h>
16 #include <netinet/in.h>
17 #include <netinet/tcp.h>
18 #include <sys/select.h>
19 #include <time.h>
20 #include <netdb.h>
21 #include <arpa/inet.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #if defined(__linux__) || __has_include(<bsd/unistd.h>)
25 #include <bsd/unistd.h>
26 #endif
28 #ifdef MOONBR_IO_USE_TLS
29 #include <tls.h>
30 #endif
32 #include <lua.h>
33 #include <lauxlib.h>
34 #include <lualib.h>
36 #include <assert.h>
38 #define MOONBR_IO_MAXSTRERRORLEN 80
39 #define MOONBR_IO_READBUFLEN 4096
40 #define MOONBR_IO_WRITEBUFLEN 4096
42 #define MOONBR_IO_LISTEN_BACKLOG 1024
44 #define MOONBR_IO_STRERROR_R_MSG "Error detail unavailable due to noncompliant strerror_r() implementation"
45 #define moonbr_io_prepare_errmsg() \
46 char errmsg[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG; \
47 strerror_r(errno, errmsg, MOONBR_IO_MAXSTRERRORLEN)
48 #define moonbr_io_return_prepared_errmsg() \
49 lua_pushnil(L); \
50 lua_pushstring(L, errmsg); \
51 return 2
52 #define moonbr_io_return_errmsg() \
53 do { \
54 moonbr_io_prepare_errmsg(); \
55 moonbr_io_return_prepared_errmsg(); \
56 } while (0)
58 #define MOONBR_IO_HANDLE_MT_REGKEY "moonbridge_io_handle"
59 #define MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY "moonbridge_io_handle_public"
60 #define MOONBR_IO_LISTENER_MT_REGKEY "moonbridge_io_listener"
61 #define MOONBR_IO_CHILD_MT_REGKEY "moonbridge_io_child"
62 #define MOONBR_IO_CHILD_PT_REGKEY "moonbridge_io_child_pt"
64 #ifdef MOONBR_IO_USE_TLS
66 #define MOONBR_IO_TLSCONF_MT_REGKEY "moonbridge_io_tlsconf"
68 typedef struct {
69 struct tls_config *config;
70 int server;
71 } moonbr_io_tlsconf_t;
73 #endif /* MOONBR_IO_USE_TLS */
75 typedef struct {
76 int fd;
77 int issock;
78 sa_family_t addrfam;
79 int finished;
80 int closed;
81 int nonblocking;
82 int nopush;
83 int readerr;
84 int readbufin;
85 int readbufout;
86 int writeerr;
87 size_t writeleft;
88 size_t flushedleft;
89 #if LUA_VERSION_NUM >= 503
90 lua_Integer writeqin;
91 lua_Integer writeqout;
92 #else
93 int writeqin;
94 int writeqout;
95 #endif
96 size_t writeqoff;
97 int writebufin;
98 int writebufout;
99 char readbuf[MOONBR_IO_READBUFLEN];
100 char writebuf[MOONBR_IO_WRITEBUFLEN];
101 #ifdef MOONBR_IO_USE_TLS
102 struct tls *tls;
103 struct tls *servertls;
104 int tlshandshake;
105 #endif
106 } moonbr_io_handle_t;
108 typedef struct {
109 int fd;
110 sa_family_t addrfam;
111 int nonblocking;
112 } moonbr_io_listener_t;
114 typedef struct {
115 pid_t pid;
116 } moonbr_io_child_t;
118 static int moonbr_io_yield(lua_State *L) {
119 return lua_yield(L, lua_gettop(L));
120 }
122 #if LUA_VERSION_NUM >= 503
123 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
124 #else
125 static int moonbr_io_cont_returnall(lua_State *L) {
126 #endif
127 return lua_gettop(L);
128 }
130 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
131 static int yieldfunc(lua_State *L) { \
132 int args; \
133 lua_pushcfunction(L, callfunc); \
134 lua_insert(L, 1); \
135 args = lua_gettop(L); \
136 lua_pushcfunction(L, moonbr_io_yield); \
137 lua_insert(L, 3); \
138 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
139 return lua_gettop(L); \
140 }
142 static int moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
143 int flags;
144 if (handle->nonblocking == nonblocking) return 0;
145 flags = fcntl(handle->fd, F_GETFL, 0);
146 if (flags == -1) return -1;
147 if (nonblocking) flags |= O_NONBLOCK;
148 else flags &= ~O_NONBLOCK;
149 if (fcntl(handle->fd, F_SETFL, flags) == -1) return -1;
150 handle->nonblocking = nonblocking;
151 return 0;
152 }
154 static int moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
155 struct linger lingerval = { 0, };
156 if (!handle->issock) return 0;
157 if (timeout >= 0) {
158 lingerval.l_onoff = 1;
159 lingerval.l_linger = timeout;
160 }
161 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) return -1;
162 return 0;
163 }
165 static inline int moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
166 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
167 if (
168 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
169 handle->nopush == nopush
170 ) return 0;
171 #if defined(TCP_NOPUSH)
172 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) return -1;
173 #elif defined(TCP_CORK)
174 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) return -1;
175 #endif
176 handle->nopush = nopush;
177 #else
178 #warning Neither TCP_NOPUSH nor TCP_CORK is available
179 #endif
180 return 0;
181 }
183 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
184 moonbr_io_handle_t *handle;
185 lua_Integer maxread;
186 const char *terminatorstr;
187 size_t terminatorlen;
188 char terminator = 0; /* initialize to avoid compiler warning */
189 luaL_Buffer luabuf;
190 size_t luabufcnt = 0;
191 int remaining;
192 char *terminatorpos;
193 ssize_t bytesread;
194 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
195 maxread = luaL_optinteger(L, 2, -1);
196 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
197 if (terminatorlen) {
198 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
199 terminator = terminatorstr[0];
200 }
201 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
202 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
203 if (handle->readerr) {
204 lua_pushnil(L);
205 lua_pushliteral(L, "Previous read error");
206 return 2;
207 }
208 if (handle->fd < 0) {
209 /* fake EOF to simulate shutdown */
210 if (!drain) lua_pushliteral(L, "");
211 else lua_pushinteger(L, 0);
212 lua_pushliteral(L, "eof");
213 return 2;
214 }
215 handle->readerr = 1;
216 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
217 if (!drain) luaL_buffinit(L, &luabuf);
218 while (1) {
219 remaining = -1;
220 terminatorpos = NULL;
221 if (
222 maxread >= 0 &&
223 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
224 ) {
225 remaining = (size_t)maxread - luabufcnt;
226 if (terminatorlen) {
227 terminatorpos = memchr(
228 handle->readbuf + handle->readbufout,
229 terminator,
230 remaining
231 );
232 }
233 } else if (terminatorlen) {
234 terminatorpos = memchr(
235 handle->readbuf + handle->readbufout,
236 terminator,
237 handle->readbufin - handle->readbufout
238 );
239 }
240 if (terminatorpos) remaining = 1 + (
241 terminatorpos - (handle->readbuf + handle->readbufout)
242 );
243 if (remaining >= 0) {
244 if (!drain) {
245 luaL_addlstring(
246 &luabuf,
247 handle->readbuf + handle->readbufout,
248 remaining
249 );
250 luaL_pushresult(&luabuf);
251 } else {
252 lua_pushinteger(L, luabufcnt + remaining);
253 }
254 if (terminatorpos) lua_pushliteral(L, "term");
255 else lua_pushliteral(L, "maxlen");
256 handle->readbufout += remaining;
257 if (handle->readbufout == handle->readbufin) {
258 handle->readbufin = 0;
259 handle->readbufout = 0;
260 }
261 handle->readerr = 0;
262 return 2;
263 }
264 if (!drain) luaL_addlstring(
265 &luabuf,
266 handle->readbuf + handle->readbufout,
267 handle->readbufin - handle->readbufout
268 );
269 luabufcnt += handle->readbufin - handle->readbufout;
270 handle->readbufout = 0;
271 #ifdef MOONBR_IO_USE_TLS
272 if (handle->tls) {
273 do {
274 if (!handle->tlshandshake) {
275 do bytesread = tls_handshake(handle->tls);
276 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
277 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
278 handle->tlshandshake = bytesread;
279 errno = EAGAIN;
280 break;
281 }
282 if (bytesread < 0) {
283 lua_pushnil(L);
284 lua_pushstring(L, tls_error(handle->tls));
285 return 2;
286 }
287 handle->tlshandshake = 1;
288 }
289 do bytesread = tls_read(handle->tls, handle->readbuf, MOONBR_IO_READBUFLEN);
290 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
291 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
292 errno = EAGAIN;
293 break;
294 }
295 if (bytesread < 0) {
296 lua_pushnil(L);
297 lua_pushstring(L, tls_error(handle->tls));
298 return 2;
299 }
300 } while (0);
301 }
302 else
303 #endif
304 do bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
305 while (bytesread < 0 && (errno == EINTR));
306 if (
307 bytesread == 0 || (
308 nonblocking &&
309 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
310 )
311 ) {
312 handle->readbufin = 0;
313 if (!drain) luaL_pushresult(&luabuf);
314 else lua_pushinteger(L, luabufcnt);
315 if (bytesread == 0) lua_pushliteral(L, "eof");
316 else lua_pushliteral(L, "block");
317 handle->readerr = 0;
318 return 2;
319 }
320 if (bytesread < 0) moonbr_io_return_errmsg();
321 handle->readbufin = bytesread;
322 }
323 }
325 static int moonbr_io_read(lua_State *L) {
326 return moonbr_io_read_impl(L, 0, 0);
327 }
329 static int moonbr_io_read_nb(lua_State *L) {
330 return moonbr_io_read_impl(L, 1, 0);
331 }
333 static int moonbr_io_drain(lua_State *L) {
334 return moonbr_io_read_impl(L, 0, 1);
335 }
337 static int moonbr_io_drain_nb(lua_State *L) {
338 return moonbr_io_read_impl(L, 1, 1);
339 }
341 #if LUA_VERSION_NUM >= 503
342 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
343 #else
344 static int moonbr_io_read_cont(lua_State *L) {
345 #endif
346 lua_Integer remaining;
347 size_t len;
348 #if !(LUA_VERSION_NUM >= 503)
349 int ctx = 0;
350 lua_getctx(L, &ctx);
351 #endif
352 remaining = lua_tointeger(L, 3);
353 while (1) {
354 lua_pushcfunction(L, moonbr_io_read_nb);
355 lua_pushvalue(L, 1);
356 lua_pushvalue(L, 3);
357 lua_pushvalue(L, 4);
358 lua_call(L, 3, 2);
359 if (lua_isnil(L, -2)) return 2;
360 lua_insert(L, -2);
361 len = lua_rawlen(L, -1);
362 if (ctx == 0) {
363 lua_replace(L, 5);
364 ctx = 1;
365 } else if (ctx == 1) {
366 lua_pushvalue(L, 5);
367 lua_newtable(L);
368 lua_replace(L, 5);
369 lua_rawseti(L, 5, 2);
370 lua_rawseti(L, 5, 1);
371 ctx = 2;
372 } else {
373 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
374 }
375 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
376 lua_pop(L, 1);
377 if (remaining >= 0 && len) {
378 remaining -= len;
379 lua_pushinteger(L, remaining);
380 lua_replace(L, 3);
381 }
382 lua_pushvalue(L, 2);
383 lua_callk(L, 0, 0, ctx, moonbr_io_read_cont);
384 }
385 if (ctx == 1) {
386 lua_pushvalue(L, 5);
387 } else {
388 luaL_Buffer buf;
389 lua_Integer i, chunkcount;
390 chunkcount = lua_rawlen(L, 5);
391 luaL_buffinit(L, &buf);
392 for (i=1; i<=chunkcount && i>0; i++) {
393 lua_rawgeti(L, 5, i);
394 luaL_addvalue(&buf);
395 }
396 luaL_pushresult(&buf);
397 }
398 lua_pushvalue(L, -2);
399 return 2;
400 }
402 static int moonbr_io_read_call(lua_State *L) {
403 lua_settop(L, 4);
404 lua_pushnil(L);
405 #if LUA_VERSION_NUM >= 503
406 return moonbr_io_read_cont(L, 0, 0);
407 #else
408 return moonbr_io_read_cont(L);
409 #endif
410 }
412 moonbr_io_yield_wrapper(moonbr_io_read_yield, moonbr_io_read_call);
414 #if LUA_VERSION_NUM >= 503
415 static int moonbr_io_drain_cont(lua_State *L, int status, lua_KContext ctx) {
416 #else
417 static int moonbr_io_drain_cont(lua_State *L) {
418 #endif
419 lua_Integer remaining, len;
420 size_t totallen = 0;
421 #if !(LUA_VERSION_NUM >= 503)
422 int ctx = 0;
423 lua_getctx(L, &ctx);
424 #endif
425 remaining = lua_tointeger(L, 3);
426 while (1) {
427 lua_pushcfunction(L, moonbr_io_drain_nb);
428 lua_pushvalue(L, 1);
429 lua_pushvalue(L, 3);
430 lua_pushvalue(L, 4);
431 lua_call(L, 3, 2);
432 if (lua_isnil(L, -2)) return 2;
433 lua_insert(L, -2);
434 len = lua_tointeger(L, -1);
435 lua_pop(L, 1);
436 totallen += len;
437 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
438 lua_pop(L, 1);
439 if (remaining >= 0 && len) {
440 remaining -= len;
441 lua_pushinteger(L, remaining);
442 lua_replace(L, 3);
443 }
444 lua_pushvalue(L, 2);
445 lua_callk(L, 0, 0, ctx, moonbr_io_drain_cont);
446 }
447 lua_pushinteger(L, totallen);
448 lua_pushvalue(L, -2);
449 return 2;
450 }
452 static int moonbr_io_drain_call(lua_State *L) {
453 #if LUA_VERSION_NUM >= 503
454 return moonbr_io_drain_cont(L, 0, 0);
455 #else
456 return moonbr_io_drain_cont(L);
457 #endif
458 }
460 moonbr_io_yield_wrapper(moonbr_io_drain_yield, moonbr_io_drain_call);
462 #ifdef MOONBR_IO_USE_TLS
464 #define moonbr_io_write_tls(buf, buflen) \
465 if (handle->tls) { \
466 do { \
467 if (!handle->tlshandshake) { \
468 do written = tls_handshake(handle->tls); \
469 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
470 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
471 handle->tlshandshake = written; \
472 errno = EAGAIN; \
473 break; \
474 } \
475 if (written < 0) { \
476 lua_pushnil(L); \
477 lua_pushstring(L, tls_error(handle->tls)); \
478 return 2; \
479 } \
480 handle->tlshandshake = 1; \
481 } \
482 do written = tls_write(handle->tls, (buf), (buflen)); \
483 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
484 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
485 errno = EAGAIN; \
486 break; \
487 } \
488 if (written < 0) { \
489 lua_pushnil(L); \
490 lua_pushstring(L, tls_error(handle->tls)); \
491 return 2; \
492 } \
493 } while (0); \
494 } \
495 else
497 #endif /* MOONBR_IO_USE_TLS */
499 static int moonbr_io_write_impl(lua_State *L, int nonblocking, int flush) {
500 moonbr_io_handle_t *handle;
501 int i, top;
502 const char *str;
503 size_t strlen;
504 ssize_t written;
505 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
506 if (handle->closed) luaL_error(L, "Attempt to write to a closed I/O handle");
507 if (handle->finished) luaL_error(L, "Attempt to write to a finished I/O handle");
508 if (handle->writeerr) {
509 lua_pushnil(L);
510 lua_pushliteral(L, "Previous write error");
511 return 2;
512 }
513 handle->writeerr = 1;
514 if (moonbr_io_handle_set_nonblocking(L, handle, nonblocking)) moonbr_io_return_errmsg();
515 top = lua_gettop(L);
516 lua_getuservalue(L, 1);
517 lua_getfield(L, -1, "writequeue");
518 for (i=2; i<=top; i++) {
519 luaL_checklstring(L, i, &strlen);
520 lua_pushvalue(L, i);
521 lua_rawseti(L, -2, handle->writeqin++);
522 handle->writeleft += strlen;
523 }
524 if (flush) handle->flushedleft = handle->writeleft;
525 while (handle->writeqout != handle->writeqin) {
526 lua_rawgeti(L, -1, handle->writeqout);
527 str = lua_tolstring(L, -1, &strlen);
528 while (handle->writeqoff < strlen) {
529 if (
530 strlen - handle->writeqoff <
531 MOONBR_IO_WRITEBUFLEN - handle->writebufin
532 ) {
533 memcpy(
534 handle->writebuf + handle->writebufin,
535 str + handle->writeqoff,
536 strlen - handle->writeqoff
537 );
538 handle->writebufin += strlen - handle->writeqoff;
539 break;
540 } else {
541 memcpy(
542 handle->writebuf + handle->writebufin,
543 str + handle->writeqoff,
544 MOONBR_IO_WRITEBUFLEN - handle->writebufin
545 );
546 handle->writeqoff += MOONBR_IO_WRITEBUFLEN - handle->writebufin;
547 handle->writebufin = MOONBR_IO_WRITEBUFLEN;
548 while (handle->writebufout < MOONBR_IO_WRITEBUFLEN) {
549 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
550 #ifdef MOONBR_IO_USE_TLS
551 moonbr_io_write_tls(
552 handle->writebuf + handle->writebufout,
553 MOONBR_IO_WRITEBUFLEN - handle->writebufout
554 )
555 #endif
556 written = write(
557 handle->fd,
558 handle->writebuf + handle->writebufout,
559 MOONBR_IO_WRITEBUFLEN - handle->writebufout
560 );
561 if (written < 0) {
562 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
563 goto moonbr_io_write_impl_block;
564 } else if (errno != EINTR) moonbr_io_return_errmsg();
565 } else {
566 handle->writebufout += written;
567 handle->writeleft -= written;
568 if (handle->flushedleft) {
569 if (written >= handle->flushedleft) {
570 handle->flushedleft = 0;
571 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
572 } else {
573 handle->flushedleft -= written;
574 }
575 }
576 }
577 }
578 handle->writebufin = 0;
579 handle->writebufout = 0;
580 }
581 }
582 handle->writeqoff = 0;
583 lua_pop(L, 1);
584 lua_pushnil(L);
585 lua_rawseti(L, -2, handle->writeqout++);
586 }
587 while (handle->flushedleft) {
588 if (moonbr_io_handle_set_nopush(L, handle, 1)) moonbr_io_return_errmsg();
589 #ifdef MOONBR_IO_USE_TLS
590 moonbr_io_write_tls(
591 handle->writebuf + handle->writebufout,
592 handle->writebufin - handle->writebufout
593 )
594 #endif
595 written = write(
596 handle->fd,
597 handle->writebuf + handle->writebufout,
598 handle->writebufin - handle->writebufout
599 );
600 if (written < 0) {
601 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
602 goto moonbr_io_write_impl_block;
603 } else if (errno != EINTR) moonbr_io_return_errmsg();
604 } else {
605 handle->writebufout += written;
606 handle->writeleft -= written;
607 if (handle->flushedleft) {
608 if (written >= handle->flushedleft) {
609 handle->flushedleft = 0;
610 if (moonbr_io_handle_set_nopush(L, handle, 0)) moonbr_io_return_errmsg();
611 } else {
612 handle->flushedleft -= written;
613 }
614 }
615 }
616 }
617 if (handle->writebufout == handle->writebufin) {
618 handle->writebufin = 0;
619 handle->writebufout = 0;
620 }
621 if (nonblocking) lua_pushinteger(L, 0);
622 else lua_pushvalue(L, 1);
623 handle->writeerr = 0;
624 return 1;
625 moonbr_io_write_impl_block:
626 lua_pushinteger(L, handle->writeleft);
627 handle->writeerr = 0;
628 return 1;
629 }
631 static int moonbr_io_write(lua_State *L) {
632 return moonbr_io_write_impl(L, 0, 0);
633 }
635 static int moonbr_io_write_nb(lua_State *L) {
636 return moonbr_io_write_impl(L, 1, 0);
637 }
639 static int moonbr_io_flush(lua_State *L) {
640 return moonbr_io_write_impl(L, 0, 1);
641 }
643 static int moonbr_io_flush_nb(lua_State *L) {
644 return moonbr_io_write_impl(L, 1, 1);
645 }
647 #if LUA_VERSION_NUM >= 503
648 static int moonbr_io_write_cont(lua_State *L, int status, lua_KContext ctx) {
649 #else
650 static int moonbr_io_write_cont(lua_State *L) {
651 #endif
652 while (1) {
653 lua_pushcfunction(L, moonbr_io_write_nb);
654 lua_pushvalue(L, 1);
655 lua_call(L, 1, 2);
656 if (lua_isnil(L, -2)) return 2;
657 if (!lua_tointeger(L, -2)) {
658 lua_pushvalue(L, 1);
659 return 1;
660 }
661 lua_pop(L, 2);
662 lua_pushvalue(L, 2);
663 lua_callk(L, 0, 0, 0, moonbr_io_write_cont);
664 }
665 }
667 static int moonbr_io_write_call(lua_State *L) {
668 lua_pushcfunction(L, moonbr_io_write_nb);
669 lua_insert(L, 3);
670 lua_pushvalue(L, 1);
671 lua_insert(L, 4);
672 lua_call(L, lua_gettop(L) - 3, 2);
673 if (lua_isnil(L, -2)) return 2;
674 if (!lua_tointeger(L, -2)) {
675 lua_pushvalue(L, 1);
676 return 1;
677 }
678 #if LUA_VERSION_NUM >= 503
679 return moonbr_io_write_cont(L, 0, 0);
680 #else
681 return moonbr_io_write_cont(L);
682 #endif
683 }
685 moonbr_io_yield_wrapper(moonbr_io_write_yield, moonbr_io_write_call);
687 static int moonbr_io_flush_call(lua_State *L) {
688 lua_pushcfunction(L, moonbr_io_flush_nb);
689 lua_insert(L, 3);
690 lua_pushvalue(L, 1);
691 lua_insert(L, 4);
692 lua_call(L, lua_gettop(L) - 3, 2);
693 if (lua_isnil(L, -2)) return 2;
694 if (!lua_tointeger(L, -2)) {
695 lua_pushvalue(L, 1);
696 return 1;
697 }
698 #if LUA_VERSION_NUM >= 503
699 return moonbr_io_write_cont(L, 0, 0);
700 #else
701 return moonbr_io_write_cont(L);
702 #endif
703 }
705 moonbr_io_yield_wrapper(moonbr_io_flush_yield, moonbr_io_flush_call);
707 static int moonbr_io_finish(lua_State *L) {
708 moonbr_io_handle_t *handle;
709 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
710 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
711 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
712 if (handle->writeleft) {
713 lua_pushcfunction(L, moonbr_io_flush);
714 lua_pushvalue(L, 1);
715 if (lua_pcall(L, 1, 2, 0)) {
716 handle->finished = 1;
717 lua_error(L);
718 }
719 if (!lua_toboolean(L, -2)) {
720 handle->finished = 1;
721 return 2;
722 }
723 }
724 handle->finished = 1;
725 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
726 if (shutdown(handle->fd, SHUT_WR)) moonbr_io_return_errmsg();
727 } else {
728 #ifdef MOONBR_IO_USE_TLS
729 if (handle->tls) tls_close(handle->tls);
730 #endif
731 if (close(handle->fd)) {
732 handle->fd = -1;
733 moonbr_io_return_errmsg();
734 }
735 handle->fd = -1; /* fake EOF on read */
736 }
737 lua_pushboolean(L, 1);
738 return 1;
739 }
741 static int moonbr_io_close_impl(lua_State *L, int reset) {
742 moonbr_io_handle_t *handle;
743 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
744 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
745 if (!reset) {
746 if (handle->writeleft) {
747 lua_pushcfunction(L, moonbr_io_flush);
748 lua_pushvalue(L, 1);
749 if (lua_pcall(L, 1, 2, 0)) {
750 handle->closed = 1;
751 close(handle->fd);
752 handle->fd = -1;
753 lua_error(L);
754 }
755 handle->closed = 1;
756 if (!lua_toboolean(L, -2)) {
757 close(handle->fd);
758 handle->fd = -1;
759 return 2;
760 }
761 } else {
762 handle->closed = 1;
763 }
764 if (moonbr_io_handle_set_linger(L, handle, -1)) {
765 moonbr_io_prepare_errmsg();
766 close(handle->fd);
767 handle->fd = -1;
768 moonbr_io_return_prepared_errmsg();
769 }
770 } else {
771 handle->closed = 1;
772 }
773 if (handle->fd >= 0) {
774 #ifdef MOONBR_IO_USE_TLS
775 if (handle->tls) tls_close(handle->tls);
776 #endif
777 if (close(handle->fd)) {
778 handle->fd = -1;
779 moonbr_io_return_errmsg();
780 }
781 handle->fd = -1;
782 }
783 lua_pushboolean(L, 1);
784 return 1;
786 }
788 static int moonbr_io_close(lua_State *L) {
789 return moonbr_io_close_impl(L, 0);
790 }
792 static int moonbr_io_reset(lua_State *L) {
793 return moonbr_io_close_impl(L, 1);
794 }
796 static int moonbr_io_handlegc(lua_State *L) {
797 moonbr_io_handle_t *handle;
798 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
799 if (handle->fd >= 0) {
800 lua_pushcfunction(L, moonbr_io_reset);
801 lua_pushvalue(L, 1);
802 lua_pushinteger(L, 0);
803 lua_call(L, 2, 0);
804 }
805 #ifdef MOONBR_IO_USE_TLS
806 if (handle->tls) {
807 tls_free(handle->tls);
808 handle->tls = NULL;
809 }
810 if (handle->servertls) {
811 tls_free(handle->servertls);
812 handle->servertls = NULL;
813 }
814 #endif
815 return 0;
816 }
818 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
819 moonbr_io_handle_t *handle;
820 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
821 if (!handle->closed) {
822 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
823 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
824 lua_call(L, 1, 0);
825 }
826 }
828 static int moonbr_io_pushhandle_impl(lua_State *L) {
829 int *fd;
830 moonbr_io_handle_t *handle;
831 struct sockaddr addr;
832 socklen_t addrlen;
833 fd = lua_touserdata(L, 1);
834 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
835 handle->fd = -1; /* avoid closing incomplete handle */
836 addrlen = sizeof(addr);
837 if (getsockname(*fd, &addr, &addrlen)) {
838 if (errno != ENOTSOCK) {
839 moonbr_io_prepare_errmsg();
840 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
841 }
842 handle->issock = 0;
843 } else {
844 handle->issock = 1;
845 handle->addrfam = addr.sa_family;
846 }
847 handle->finished = 0;
848 handle->closed = 0;
849 handle->nonblocking = -1;
850 handle->nopush = -1;
851 handle->readerr = 0;
852 handle->readbufin = 0;
853 handle->readbufout = 0;
854 handle->writeerr = 0;
855 handle->writeleft = 0;
856 handle->flushedleft = 0;
857 handle->writeqin = 0;
858 handle->writeqout = 0;
859 handle->writeqoff = 0;
860 handle->writebufin = 0;
861 handle->writebufout = 0;
862 #ifdef MOONBR_IO_USE_TLS
863 handle->tls = NULL;
864 handle->servertls = NULL;
865 handle->tlshandshake = 0;
866 #endif
867 handle->fd = *fd; /* required for set_linger call */
868 if (moonbr_io_handle_set_linger(L, handle, 0)) {
869 moonbr_io_prepare_errmsg();
870 handle->fd = -1;
871 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
872 }
873 handle->fd = -1; /* avoid closing incomplete handle */
874 luaL_setmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
875 lua_newtable(L); // uservalue
876 lua_newtable(L);
877 lua_setfield(L, -2, "writequeue");
878 lua_newtable(L); // public
879 if (handle->addrfam == AF_INET6) {
880 struct sockaddr_in6 addr_in6;
881 char addrstrbuf[INET6_ADDRSTRLEN];
882 const char *addrstr;
883 addrlen = sizeof(addr_in6);
884 if (getsockname(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
885 moonbr_io_prepare_errmsg();
886 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
887 }
888 if (addrlen > sizeof(addr_in6)) {
889 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
890 }
891 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
892 if (!addrstr) {
893 moonbr_io_prepare_errmsg();
894 luaL_error(L, "Could not format local IP address: %s", errmsg);
895 } else {
896 lua_pushstring(L, addrstr);
897 lua_setfield(L, -2, "local_ip6");
898 }
899 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
900 lua_setfield(L, -2, "local_tcpport");
901 if (getpeername(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
902 moonbr_io_prepare_errmsg();
903 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
904 }
905 if (addrlen > sizeof(addr_in6)) {
906 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
907 }
908 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
909 if (!addrstr) {
910 moonbr_io_prepare_errmsg();
911 luaL_error(L, "Could not format remote IP address: %s", errmsg);
912 } else {
913 lua_pushstring(L, addrstr);
914 lua_setfield(L, -2, "remote_ip6");
915 }
916 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
917 lua_setfield(L, -2, "remote_tcpport");
918 } else if (handle->addrfam == AF_INET) {
919 struct sockaddr_in addr_in;
920 char addrstrbuf[INET_ADDRSTRLEN];
921 const char *addrstr;
922 addrlen = sizeof(addr_in);
923 if (getsockname(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
924 moonbr_io_prepare_errmsg();
925 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
926 }
927 if (addrlen > sizeof(addr_in)) {
928 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
929 }
930 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
931 if (!addrstr) {
932 moonbr_io_prepare_errmsg();
933 luaL_error(L, "Could not format local IP address: %s", errmsg);
934 } else {
935 lua_pushstring(L, addrstr);
936 lua_setfield(L, -2, "local_ip4");
937 }
938 lua_pushinteger(L, ntohs(addr_in.sin_port));
939 lua_setfield(L, -2, "local_tcpport");
940 if (getpeername(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
941 moonbr_io_prepare_errmsg();
942 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
943 }
944 if (addrlen > sizeof(addr_in)) {
945 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
946 }
947 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
948 if (!addrstr) {
949 moonbr_io_prepare_errmsg();
950 luaL_error(L, "Could not format remote IP address: %s", errmsg);
951 } else {
952 lua_pushstring(L, addrstr);
953 lua_setfield(L, -2, "remote_ip4");
954 }
955 lua_pushinteger(L, ntohs(addr_in.sin_port));
956 lua_setfield(L, -2, "remote_tcpport");
957 }
958 luaL_setmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
959 lua_setfield(L, -2, "public");
960 lua_setuservalue(L, -2);
961 handle->fd = *fd;
962 *fd = -1; /* closing is now handled by garbage collection */
963 return 1;
964 }
966 void moonbr_io_pushhandle(lua_State *L, int fd) {
967 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
968 lua_pushlightuserdata(L, &fd);
969 if (lua_pcall(L, 1, 1, 0)) {
970 if (fd != -1) close(fd); // TODO: correct to close file descriptor here?
971 lua_error(L);
972 }
973 }
975 static int moonbr_io_handleindex(lua_State *L) {
976 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
977 luaL_checkany(L, 2);
978 lua_getuservalue(L, 1);
979 lua_getfield(L, -1, "public");
980 lua_pushvalue(L, 2);
981 lua_gettable(L, -2);
982 return 1;
983 }
985 static int moonbr_io_handlenewindex(lua_State *L) {
986 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
987 luaL_checkany(L, 2);
988 luaL_checkany(L, 3);
989 lua_getuservalue(L, 1);
990 lua_getfield(L, -1, "public");
991 lua_pushvalue(L, 2);
992 lua_pushvalue(L, 3);
993 lua_settable(L, -3);
994 return 0;
995 }
997 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
998 const char *path;
999 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1000 const int path_maxlen = sizeof(struct sockaddr_un) - (
1001 (void *)sockaddr.sun_path - (void *)&sockaddr
1002 ) - 1; /* one byte for termination */
1003 int sock;
1004 path = luaL_checkstring(L, 1);
1005 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1006 strcpy(sockaddr.sun_path, path);
1007 sock = socket(
1008 PF_LOCAL,
1009 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1011 );
1012 if (sock < 0) moonbr_io_return_errmsg();
1013 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1014 if (!nonblocking && errno == EINTR) {
1015 moonbr_io_prepare_errmsg();
1016 close(sock);
1017 moonbr_io_return_prepared_errmsg();
1018 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1020 moonbr_io_pushhandle(L, sock);
1021 return 1;
1024 static int moonbr_io_localconnect(lua_State *L) {
1025 return moonbr_io_localconnect_impl(L, 0);
1028 static int moonbr_io_localconnect_nb(lua_State *L) {
1029 return moonbr_io_localconnect_impl(L, 1);
1032 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
1033 const char *host, *port;
1034 struct addrinfo hints = { 0, };
1035 struct addrinfo *res, *addrinfo;
1036 int errcode;
1037 int sock;
1038 host = luaL_checkstring(L, 1);
1039 port = luaL_checkstring(L, 2);
1040 hints.ai_family = AF_UNSPEC;
1041 hints.ai_socktype = SOCK_STREAM;
1042 hints.ai_protocol = IPPROTO_TCP;
1043 hints.ai_flags = AI_ADDRCONFIG;
1044 errcode = getaddrinfo(host, port, &hints, &res);
1045 if (errcode) {
1046 freeaddrinfo(res);
1047 if (errcode == EAI_SYSTEM) {
1048 moonbr_io_prepare_errmsg();
1049 lua_pushnil(L);
1050 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1051 } else {
1052 lua_pushnil(L);
1053 lua_pushstring(L, gai_strerror(errcode));
1055 return 2;
1057 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1058 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1060 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1061 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1063 addrinfo = res;
1064 moonbr_io_tcpconnect_found:
1065 sock = socket(
1066 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1067 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1068 addrinfo->ai_protocol
1069 );
1070 if (sock < 0) {
1071 moonbr_io_prepare_errmsg();
1072 freeaddrinfo(res);
1073 moonbr_io_return_prepared_errmsg();
1075 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1076 freeaddrinfo(res);
1077 if (!nonblocking && errno == EINTR) {
1078 moonbr_io_prepare_errmsg();
1079 close(sock);
1080 moonbr_io_return_prepared_errmsg();
1081 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) moonbr_io_return_errmsg();
1082 } else {
1083 freeaddrinfo(res);
1085 moonbr_io_pushhandle(L, sock);
1086 return 1;
1089 static int moonbr_io_tcpconnect(lua_State *L) {
1090 return moonbr_io_tcpconnect_impl(L, 0);
1093 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1094 return moonbr_io_tcpconnect_impl(L, 1);
1097 static int moonbr_io_locallisten(lua_State *L) {
1098 moonbr_io_listener_t *listener;
1099 const char *path;
1100 struct stat sb;
1101 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1102 const int path_maxlen = sizeof(struct sockaddr_un) - (
1103 (void *)sockaddr.sun_path - (void *)&sockaddr
1104 ) - 1; /* one byte for termination */
1105 int sock;
1106 path = luaL_checkstring(L, 1);
1107 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1108 strcpy(sockaddr.sun_path, path);
1109 if (stat(path, &sb) == 0) {
1110 if (S_ISSOCK(sb.st_mode)) unlink(path);
1112 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1113 listener->fd = -1;
1114 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1115 sock = socket(
1116 PF_LOCAL,
1117 SOCK_STREAM | SOCK_CLOEXEC,
1119 );
1120 if (sock < 0) moonbr_io_return_errmsg();
1121 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1122 moonbr_io_prepare_errmsg();
1123 close(sock);
1124 moonbr_io_return_prepared_errmsg();
1126 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1127 moonbr_io_prepare_errmsg();
1128 close(sock);
1129 moonbr_io_return_prepared_errmsg();
1131 listener->fd = sock;
1132 listener->addrfam = AF_LOCAL;
1133 listener->nonblocking = -1;
1134 return 1;
1137 static int moonbr_io_tcplisten(lua_State *L) {
1138 moonbr_io_listener_t *listener;
1139 const char *host, *port;
1140 struct addrinfo hints = { 0, };
1141 struct addrinfo *res, *addrinfo;
1142 int errcode;
1143 int sock;
1144 host = luaL_optstring(L, 1, NULL);
1145 port = luaL_checkstring(L, 2);
1146 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1147 listener->fd = -1;
1148 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1149 hints.ai_family = AF_UNSPEC;
1150 hints.ai_socktype = SOCK_STREAM;
1151 hints.ai_protocol = IPPROTO_TCP;
1152 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1153 errcode = getaddrinfo(host, port, &hints, &res);
1154 if (errcode) {
1155 freeaddrinfo(res);
1156 if (errcode == EAI_SYSTEM) {
1157 moonbr_io_prepare_errmsg();
1158 lua_pushnil(L);
1159 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1160 } else {
1161 lua_pushnil(L);
1162 lua_pushstring(L, gai_strerror(errcode));
1164 return 2;
1166 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1167 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1169 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1170 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1172 addrinfo = res;
1173 moonbr_io_tcpconnect_found:
1174 listener->addrfam = addrinfo->ai_family;
1175 sock = socket(
1176 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1177 addrinfo->ai_socktype | SOCK_CLOEXEC,
1178 addrinfo->ai_protocol
1179 );
1180 if (sock < 0) {
1181 moonbr_io_prepare_errmsg();
1182 freeaddrinfo(res);
1183 moonbr_io_return_prepared_errmsg();
1186 static const int reuseval = 1;
1187 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1188 moonbr_io_prepare_errmsg();
1189 freeaddrinfo(res);
1190 close(sock);
1191 lua_pushnil(L);
1192 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1193 return 2;
1196 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1197 moonbr_io_prepare_errmsg();
1198 freeaddrinfo(res);
1199 close(sock);
1200 moonbr_io_return_prepared_errmsg();
1202 freeaddrinfo(res);
1203 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1204 moonbr_io_prepare_errmsg();
1205 close(sock);
1206 moonbr_io_return_prepared_errmsg();
1208 listener->fd = sock;
1209 listener->nonblocking = -1;
1210 return 1;
1213 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1214 moonbr_io_listener_t *listener;
1215 int fd;
1216 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1217 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1218 if (listener->nonblocking != nonblocking) {
1219 int flags;
1220 flags = fcntl(listener->fd, F_GETFL, 0);
1221 if (flags == -1) {
1222 moonbr_io_prepare_errmsg();
1223 close(listener->fd);
1224 listener->fd = -1;
1225 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1227 if (nonblocking) flags |= O_NONBLOCK;
1228 else flags &= ~O_NONBLOCK;
1229 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1230 moonbr_io_prepare_errmsg();
1231 close(listener->fd);
1232 listener->fd = -1;
1233 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1235 listener->nonblocking = nonblocking;
1237 while (1) {
1238 #if defined(__linux__) && !defined(_GNU_SOURCE)
1239 fd = accept(listener->fd, NULL, NULL);
1240 if (fd != -1) {
1241 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
1242 moonbr_io_prepare_errmsg();
1243 close(listener->fd);
1244 listener->fd = -1;
1245 close(fd);
1246 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1249 #else
1250 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1251 #endif
1252 if (fd < 0) {
1253 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1254 lua_pushboolean(L, 0);
1255 lua_pushliteral(L, "No incoming connection pending");
1256 return 2;
1257 } else if (errno != EINTR) moonbr_io_return_errmsg();
1258 } else {
1259 moonbr_io_pushhandle(L, fd);
1260 return 1;
1265 static int moonbr_io_accept(lua_State *L) {
1266 return moonbr_io_accept_impl(L, 0);
1269 static int moonbr_io_accept_nb(lua_State *L) {
1270 return moonbr_io_accept_impl(L, 1);
1273 static int moonbr_io_unlisten(lua_State *L) {
1274 moonbr_io_listener_t *listener;
1275 struct sockaddr_un addr;
1276 socklen_t addrlen;
1277 struct stat sb;
1278 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1279 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1280 addrlen = sizeof(addr);
1281 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1282 if (close(listener->fd)) {
1283 moonbr_io_prepare_errmsg();
1284 listener->fd = -1;
1285 if (addrlen && addrlen <= sizeof(addr)) {
1286 if (stat(addr.sun_path, &sb) == 0) {
1287 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1290 moonbr_io_return_prepared_errmsg();
1292 listener->fd = -1;
1293 if (addrlen && addrlen <= sizeof(addr)) {
1294 if (stat(addr.sun_path, &sb) == 0) {
1295 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1298 lua_pushboolean(L, 1);
1299 return 1;
1302 static int moonbr_io_listenergc(lua_State *L) {
1303 moonbr_io_listener_t *listener;
1304 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1305 if (listener->fd >= 0) close(listener->fd);
1306 listener->fd = -1;
1307 return 0;
1310 static int moonbr_io_exec(lua_State *L) {
1311 char **argv;
1312 int i, argc;
1313 int sockin[2], sockout[2], sockerr[2];
1314 volatile int errorcond = 0;
1315 volatile char errmsgbuf[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG;
1316 moonbr_io_child_t *child;
1317 argc = lua_gettop(L);
1318 argv = lua_newuserdata(L, (argc + 1) * sizeof(char *));
1319 for (i=0; i<argc; i++) argv[i] = (char *)luaL_checkstring(L, i+1);
1320 argv[argc] = NULL;
1321 child = lua_newuserdata(L, sizeof(moonbr_io_child_t));
1322 child->pid = 0;
1323 lua_newtable(L);
1324 lua_setuservalue(L, -2);
1325 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1326 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1327 moonbr_io_prepare_errmsg();
1328 lua_pushnil(L);
1329 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1330 return 2;
1332 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1333 moonbr_io_prepare_errmsg();
1334 close(sockin[0]);
1335 close(sockin[1]);
1336 lua_pushnil(L);
1337 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1338 return 2;
1340 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1341 moonbr_io_prepare_errmsg();
1342 close(sockin[0]);
1343 close(sockin[1]);
1344 close(sockout[0]);
1345 close(sockout[1]);
1346 lua_pushnil(L);
1347 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1348 return 2;
1350 child->pid = vfork();
1351 if (child->pid == -1) {
1352 moonbr_io_prepare_errmsg();
1353 close(sockin[0]);
1354 close(sockin[1]);
1355 close(sockout[0]);
1356 close(sockout[1]);
1357 close(sockerr[0]);
1358 close(sockerr[1]);
1359 lua_pushnil(L);
1360 lua_pushfstring(L, "Could not fork: %s", errmsg);
1361 return 2;
1363 if (!child->pid) {
1364 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1365 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1366 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1367 closefrom(3);
1368 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1369 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1370 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1371 if (execvp(argv[0], argv)) {
1372 errorcond = 2;
1373 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1374 _exit(0);
1376 moonbr_io_exec_error1:
1377 errorcond = 1;
1378 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1379 _exit(0);
1381 close(sockin[1]);
1382 close(sockout[1]);
1383 close(sockerr[1]);
1384 if (errorcond) {
1385 int status;
1386 close(sockin[0]);
1387 close(sockout[0]);
1388 close(sockerr[0]);
1389 while (waitpid(child->pid, &status, 0) == -1) {
1390 if (errno != EINTR) {
1391 moonbr_io_prepare_errmsg();
1392 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1395 child->pid = 0;
1396 lua_pushnil(L);
1397 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1398 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1399 return 2;
1401 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1402 lua_pushlightuserdata(L, &sockin[0]);
1403 if (lua_pcall(L, 1, 1, 0)) {
1404 if (sockin[0] != -1) close(sockin[0]);
1405 close(sockout[0]);
1406 close(sockerr[0]);
1407 goto moonbr_io_exec_error2;
1409 lua_setfield(L, -2, "stdin");
1410 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1411 lua_pushlightuserdata(L, &sockout[0]);
1412 if (lua_pcall(L, 1, 1, 0)) {
1413 if (sockout[0] != -1) close(sockout[0]);
1414 close(sockerr[0]);
1415 goto moonbr_io_exec_error2;
1417 lua_setfield(L, -2, "stdout");
1418 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1419 lua_pushlightuserdata(L, &sockerr[0]);
1420 if (lua_pcall(L, 1, 1, 0)) {
1421 if (sockerr[0] != -1) close(sockerr[0]);
1422 goto moonbr_io_exec_error2;
1424 lua_setfield(L, -2, "stderr");
1425 return 1;
1426 moonbr_io_exec_error2:
1428 int status;
1429 while (waitpid(child->pid, &status, 0) == -1) {
1430 if (errno != EINTR) {
1431 moonbr_io_prepare_errmsg();
1432 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1436 child->pid = 0;
1437 return lua_error(L);
1440 static int moonbr_io_childindex(lua_State *L) {
1441 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1442 luaL_checkany(L, 2);
1443 lua_getuservalue(L, 1);
1444 lua_pushvalue(L, 2);
1445 lua_gettable(L, -2);
1446 if (lua_isnil(L, -1)) {
1447 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1448 lua_pushvalue(L, 2);
1449 lua_gettable(L, -2);
1451 return 1;
1454 static int moonbr_io_childnewindex(lua_State *L) {
1455 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1456 luaL_checkany(L, 2);
1457 luaL_checkany(L, 3);
1458 lua_getuservalue(L, 1);
1459 lua_pushvalue(L, 2);
1460 lua_pushvalue(L, 3);
1461 lua_settable(L, -3);
1462 return 0;
1465 static int moonbr_io_childgc(lua_State *L) {
1466 moonbr_io_child_t *child;
1467 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1468 if (child->pid) {
1469 int status;
1470 if (kill(child->pid, SIGKILL)) {
1471 moonbr_io_prepare_errmsg();
1472 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1474 while (waitpid(child->pid, &status, 0) == -1) {
1475 if (errno != EINTR) {
1476 moonbr_io_prepare_errmsg();
1477 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1481 return 0;
1484 static int moonbr_io_kill(lua_State *L) {
1485 moonbr_io_child_t *child;
1486 int sig;
1487 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1488 sig = luaL_optinteger(L, 2, SIGTERM);
1489 if (!child->pid) luaL_error(L, "Attempt to kill an already collected child process");
1490 if (kill(child->pid, sig)) {
1491 moonbr_io_prepare_errmsg();
1492 luaL_error(L, "Error in kill call: %s", errmsg);
1494 lua_settop(L, 1);
1495 return 1;
1498 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1499 moonbr_io_child_t *child;
1500 pid_t waitedpid;
1501 int status;
1502 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1503 if (!child->pid) luaL_error(L, "Attempt to wait for an already collected child process");
1504 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1505 if (errno != EINTR) {
1506 moonbr_io_prepare_errmsg();
1507 luaL_error(L, "Error in waitpid call: %s", errmsg);
1510 if (!waitedpid) {
1511 lua_pushboolean(L, 0);
1512 lua_pushliteral(L, "Process is still running");
1513 return 2;
1514 } else {
1515 child->pid = 0;
1516 if (WIFEXITED(status)) {
1517 lua_pushinteger(L, WEXITSTATUS(status));
1518 } else if (WIFSIGNALED(status)) {
1519 lua_pushinteger(L, -WTERMSIG(status));
1520 } else {
1521 luaL_error(L, "Unexpected status value returned by waitpid call");
1523 return 1;
1527 static int moonbr_io_wait(lua_State *L) {
1528 return moonbr_io_wait_impl(L, 0);
1531 static int moonbr_io_wait_nb(lua_State *L) {
1532 return moonbr_io_wait_impl(L, 1);
1535 #if LUA_VERSION_NUM >= 503
1536 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1537 #else
1538 static int moonbr_io_wait_cont(lua_State *L) {
1539 #endif
1540 #if !(LUA_VERSION_NUM >= 503)
1541 int ctx = 0;
1542 lua_getctx(L, &ctx);
1543 #endif
1544 while (1) {
1545 lua_pushcfunction(L, moonbr_io_wait_nb);
1546 lua_pushvalue(L, 1);
1547 lua_call(L, 1, 1);
1548 if (!lua_isnil(L, -1)) break;
1549 lua_pushvalue(L, 2);
1550 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1552 return 1;
1555 static int moonbr_io_wait_call(lua_State *L) {
1556 lua_settop(L, 2);
1557 #if LUA_VERSION_NUM >= 503
1558 return moonbr_io_wait_cont(L, 0, 0);
1559 #else
1560 return moonbr_io_wait_cont(L);
1561 #endif
1564 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1566 #ifdef MOONBR_IO_USE_TLS
1568 #define moonbr_io_poll_tls() \
1569 if (!handle->tlshandshake) { \
1570 lua_pushboolean(L, 1); \
1571 return 1; \
1572 } \
1573 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1574 if (fd < 0) { \
1575 lua_pushboolean(L, 1); \
1576 return 1; \
1577 } \
1578 FD_SET(fd, &readfds); \
1579 if (fd+1 > nfds) nfds = fd+1; \
1580 continue; \
1581 } \
1582 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1583 if (fd < 0) { \
1584 lua_pushboolean(L, 1); \
1585 return 1; \
1586 } \
1587 FD_SET(fd, &writefds); \
1588 if (fd+1 > nfds) nfds = fd+1; \
1589 continue; \
1590 } \
1591 while (0)
1593 #endif /* MOONBR_IO_USE_TLS */
1595 static int moonbr_io_poll(lua_State *L) {
1596 moonbr_io_handle_t *handle;
1597 moonbr_io_listener_t *listener;
1598 int fd, isnum;
1599 int nfds = 0;
1600 fd_set readfds, writefds, exceptfds;
1601 struct timeval timeout = {0, };
1602 int status;
1603 FD_ZERO(&readfds);
1604 FD_ZERO(&writefds);
1605 FD_ZERO(&exceptfds);
1606 if (!lua_isnoneornil(L, 1)) {
1607 luaL_checktype(L, 1, LUA_TTABLE);
1608 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1609 if (lua_toboolean(L, -1)) {
1610 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1611 if (handle) {
1612 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1613 fd = handle->fd;
1614 #if MOONBR_IO_USE_TLS
1615 moonbr_io_poll_tls();
1616 #endif
1617 if (
1618 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1619 handle->readbufin != handle->readbufout /* data pending in buffer */
1620 ) {
1621 lua_pushboolean(L, 1);
1622 return 1;
1624 } else {
1625 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1626 if (listener) {
1627 fd = listener->fd;
1628 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1629 } else {
1630 fd = lua_tointegerx(L, -2, &isnum);
1631 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1634 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1635 FD_SET(fd, &readfds);
1636 if (fd+1 > nfds) nfds = fd+1;
1640 if (!lua_isnoneornil(L, 2)) {
1641 luaL_checktype(L, 2, LUA_TTABLE);
1642 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1643 if (lua_toboolean(L, -1)) {
1644 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1645 if (handle) {
1646 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1647 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1648 fd = handle->fd;
1649 #if MOONBR_IO_USE_TLS
1650 moonbr_io_poll_tls();
1651 #endif
1652 } else {
1653 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1654 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1655 fd = lua_tointegerx(L, -2, &isnum);
1656 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1658 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1659 FD_SET(fd, &writefds);
1660 if (fd+1 > nfds) nfds = fd+1;
1664 if (!lua_isnoneornil(L, 3)) {
1665 lua_Number n;
1666 n = lua_tonumberx(L, 3, &isnum);
1667 if (isnum && n<0) {
1668 lua_pushboolean(L, 0);
1669 lua_pushliteral(L, "Negative timeout");
1670 return 2;
1671 } else if (isnum && n>=0 && n<100000000) {
1672 timeout.tv_sec = n;
1673 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1674 } else {
1675 luaL_argcheck(L, 0, 3, "not a valid timeout");
1677 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1678 } else {
1679 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1681 if (status == -1) {
1682 if (errno == EINTR) {
1683 lua_pushnil(L);
1684 lua_pushliteral(L, "Signal received while polling file descriptors");
1685 return 2;
1686 } else {
1687 moonbr_io_prepare_errmsg();
1688 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1690 } else if (status == 0) {
1691 lua_pushboolean(L, 0);
1692 lua_pushliteral(L, "Timeout while polling file descriptors");
1693 return 2;
1694 } else {
1695 lua_pushboolean(L, 1);
1696 return 1;
1700 static int moonbr_io_timeref(lua_State *L) {
1701 lua_Number sub;
1702 struct timespec tp;
1703 sub = luaL_optnumber(L, 1, 0);
1704 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1705 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1707 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1708 return 1;
1711 #ifdef MOONBR_IO_USE_TLS
1713 #define moonbr_io_tlsconf_string(name, field, func) \
1714 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1715 lua_getfield(L, 1, (field)); \
1716 valuetype = lua_type(L, -1); \
1717 if (valuetype != LUA_TNIL) { \
1718 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1719 value = lua_tostring(L, -1); \
1720 if (func(tlsconf->config, value)) { \
1721 lua_pushnil(L); \
1722 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1723 return 2; \
1724 } \
1725 } \
1726 lua_pop(L, 1);
1728 #define moonbr_io_tlsconf_binary(name, field, func) \
1729 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1730 lua_getfield(L, 1, (field)); \
1731 valuetype = lua_type(L, -1); \
1732 if (valuetype != LUA_TNIL) { \
1733 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1734 value = lua_tolstring(L, -1, &valuelen); \
1735 if (func(tlsconf->config, (void *)value, valuelen)) { \
1736 lua_pushnil(L); \
1737 lua_pushliteral(L, "Could not set " name); \
1738 return 2; \
1739 } \
1740 } \
1741 lua_pop(L, 1);
1743 static int moonbr_io_tlsconf(lua_State *L) {
1744 moonbr_io_tlsconf_t *tlsconf;
1745 int valuetype;
1746 const char *value;
1747 size_t valuelen;
1748 luaL_checktype(L, 1, LUA_TTABLE);
1749 tlsconf = lua_newuserdata(L, sizeof(moonbr_io_tlsconf_t));
1750 tlsconf->config = tls_config_new();
1751 if (!tlsconf->config) {
1752 return luaL_error(L, "Could not allocate memory for TLS configuration");
1754 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
1755 lua_getfield(L, 1, "mode");
1756 value = lua_tostring(L, -1);
1757 if (value && !strcmp(value, "server")) tlsconf->server = 1;
1758 else if (value && !strcmp(value, "client")) tlsconf->server = 0;
1759 else luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
1760 lua_pop(L, 1);
1761 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
1762 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
1763 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
1764 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
1765 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
1766 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
1767 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
1768 #if LUA_VERSION_NUM >= 503
1769 valuetype = lua_getfield(L, 1, "verify_client");
1770 #else
1771 lua_getfield(L, 1, "verify_client");
1772 #endif
1773 if (lua_toboolean(L, -1)) {
1774 value = lua_tostring(L, -1);
1775 if (value && !strcmp(value, "required")) {
1776 tls_config_verify_client(tlsconf->config);
1777 } else if (value && !strcmp(value, "optional")) {
1778 tls_config_verify_client_optional(tlsconf->config);
1779 } else {
1780 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
1783 lua_pop(L, 1);
1784 // TODO: configurable legacy support
1785 // tls_config_set_protocols(tlsconf->config, TLS_PROTOCOLS_ALL);
1786 // tls_config_set_ciphers(tlsconf->config, "legacy");
1787 return 1;
1790 static int moonbr_io_tlsconfgc(lua_State *L) {
1791 moonbr_io_tlsconf_t *tlsconf;
1792 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
1793 if (tlsconf->config) tls_config_free(tlsconf->config);
1794 tlsconf->config = NULL;
1795 return 0;
1798 static int moonbr_io_starttls(lua_State *L) {
1799 moonbr_io_handle_t *handle;
1800 moonbr_io_tlsconf_t *tlsconf;
1801 const char *servername;
1802 struct tls *tls, *tls2;
1803 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1804 if (lua_type(L, 2) == LUA_TTABLE) {
1805 lua_pushcfunction(L, moonbr_io_tlsconf);
1806 lua_pushvalue(L, 2);
1807 lua_call(L, 1, 2);
1808 if (lua_isnil(L, -2)) return 2;
1809 lua_pop(L, 1);
1810 lua_replace(L, 2);
1812 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
1813 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
1814 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
1815 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
1816 if (handle->readbufin || handle->writebufin) {
1817 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
1819 if (tlsconf->server) tls = tls_server();
1820 else {
1821 servername = luaL_checkstring(L, 3);
1822 tls = tls_client();
1824 if (!tls) {
1825 return luaL_error(L, "Could not allocate memory for TLS context");
1827 if (tls_configure(tls, tlsconf->config)) goto moonbr_io_starttls_error;
1828 if (tlsconf->server) {
1829 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
1830 handle->servertls = tls;
1831 handle->tls = tls2;
1832 } else {
1833 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
1834 handle->tls = tls;
1836 lua_settop(L, 1);
1837 return 1;
1838 moonbr_io_starttls_error:
1839 lua_pushnil(L);
1840 lua_pushstring(L, tls_error(tls));
1841 tls_free(tls);
1842 return 2;
1845 #endif /* MOONBR_IO_USE_TLS */
1847 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1848 {"read", moonbr_io_read},
1849 {"read_nb", moonbr_io_read_nb},
1850 {"read_call", moonbr_io_read_call},
1851 {"read_yield", moonbr_io_read_yield},
1852 {"drain", moonbr_io_drain},
1853 {"drain_nb", moonbr_io_drain_nb},
1854 {"drain_call", moonbr_io_drain_call},
1855 {"drain_yield", moonbr_io_drain_yield},
1856 {"write", moonbr_io_write},
1857 {"write_nb", moonbr_io_write_nb},
1858 {"write_call", moonbr_io_write_call},
1859 {"write_yield", moonbr_io_write_yield},
1860 {"flush", moonbr_io_flush},
1861 {"flush_nb", moonbr_io_flush_nb},
1862 {"flush_call", moonbr_io_flush_call},
1863 {"flush_yield", moonbr_io_flush_yield},
1864 {"finish", moonbr_io_finish},
1865 {"close", moonbr_io_close},
1866 {"reset", moonbr_io_reset},
1867 #ifdef MOONBR_IO_USE_TLS
1868 {"starttls", moonbr_io_starttls},
1869 #endif
1870 {NULL, NULL}
1871 };
1873 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1874 {"__index", moonbr_io_handleindex},
1875 {"__newindex", moonbr_io_handlenewindex},
1876 {"__gc", moonbr_io_handlegc},
1877 {NULL, NULL}
1878 };
1880 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1881 {"accept", moonbr_io_accept},
1882 {"accept_nb", moonbr_io_accept_nb},
1883 {"close", moonbr_io_unlisten},
1884 {NULL, NULL}
1885 };
1887 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1888 {"__gc", moonbr_io_listenergc},
1889 {NULL, NULL}
1890 };
1892 static const struct luaL_Reg moonbr_io_child_methods[] = {
1893 {"kill", moonbr_io_kill},
1894 {"wait", moonbr_io_wait},
1895 {"wait_nb", moonbr_io_wait_nb},
1896 {"wait_call", moonbr_io_wait_call},
1897 {"wait_yield", moonbr_io_wait_yield},
1898 {NULL, NULL}
1899 };
1901 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
1902 {"__index", moonbr_io_childindex},
1903 {"__newindex", moonbr_io_childnewindex},
1904 {"__gc", moonbr_io_childgc},
1905 {NULL, NULL}
1906 };
1908 static const struct luaL_Reg moonbr_io_module_funcs[] = {
1909 {"localconnect", moonbr_io_localconnect},
1910 {"localconnect_nb", moonbr_io_localconnect_nb},
1911 {"tcpconnect", moonbr_io_tcpconnect},
1912 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
1913 {"locallisten", moonbr_io_locallisten},
1914 {"tcplisten", moonbr_io_tcplisten},
1915 {"exec", moonbr_io_exec},
1916 {"poll", moonbr_io_poll},
1917 {"timeref", moonbr_io_timeref},
1918 #ifdef MOONBR_IO_USE_TLS
1919 {"tlsconf", moonbr_io_tlsconf},
1920 #endif
1921 {NULL, NULL}
1922 };
1924 #ifdef MOONBR_IO_USE_TLS
1926 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
1927 {"__gc", moonbr_io_tlsconfgc},
1928 {NULL, NULL}
1929 };
1931 #endif /* MOONBR_IO_USE_TLS */
1933 int luaopen_moonbridge_io(lua_State *L) {
1935 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
1937 lua_newtable(L); // module
1939 lua_newtable(L); // public metatable
1940 lua_newtable(L); // handle methods
1941 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
1942 lua_pushvalue(L, -1);
1943 lua_setfield(L, -4, "handle_pt");
1944 lua_setfield(L, -2, "__index");
1945 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1947 lua_newtable(L); // handle metatable
1948 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
1949 lua_pushvalue(L, -1);
1950 lua_setfield(L, -3, "handle_mt");
1951 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
1953 lua_newtable(L); // listener metatable
1954 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
1955 lua_newtable(L); // listener methods
1956 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
1957 lua_pushvalue(L, -1);
1958 lua_setfield(L, -4, "listener_pt");
1959 lua_setfield(L, -2, "__index");
1960 lua_pushvalue(L, -1);
1961 lua_setfield(L, -3, "listener_mt");
1962 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
1964 lua_newtable(L); // child methods
1965 luaL_setfuncs(L, moonbr_io_child_methods, 0);
1966 lua_pushvalue(L, -1);
1967 lua_setfield(L, -3, "child_pt");
1968 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
1969 lua_newtable(L); // child metatable
1970 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
1971 lua_pushvalue(L, -1);
1972 lua_setfield(L, -3, "child_mt");
1973 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
1975 #ifdef MOONBR_IO_USE_TLS
1976 if(tls_init()) {
1977 return luaL_error(L, "Could not initialize TLS library");
1979 lua_newtable(L); // tlsconf metatable
1980 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
1981 lua_pushvalue(L, -1);
1982 lua_setfield(L, -3, "tlsconf_mt");
1983 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
1984 #endif
1986 moonbr_io_pushhandle(L, 0);
1987 lua_setfield(L, -2, "stdin");
1988 moonbr_io_pushhandle(L, 1);
1989 lua_setfield(L, -2, "stdout");
1990 moonbr_io_pushhandle(L, 2);
1991 lua_setfield(L, -2, "stderr");
1993 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
1994 return 1;

Impressum / About Us