moonbridge

view moonbridge_io.c @ 250:28bffa2af1ec

Perform TLS handshake in :read and :write methods and store TLS_WANT_POLLIN, TLS_WANT_POLLOUT in handle structure
author jbe
date Fri Aug 26 23:15:56 2016 +0200 (2016-08-26)
parents 53962483bf1c
children f3988723732a
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_errmsg() \
46 char errmsg[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG; \
47 strerror_r(errno, errmsg, MOONBR_IO_MAXSTRERRORLEN)
49 #define MOONBR_IO_HANDLE_MT_REGKEY "moonbridge_io_handle"
50 #define MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY "moonbridge_io_handle_public"
51 #define MOONBR_IO_LISTENER_MT_REGKEY "moonbridge_io_listener"
52 #define MOONBR_IO_CHILD_MT_REGKEY "moonbridge_io_child"
53 #define MOONBR_IO_CHILD_PT_REGKEY "moonbridge_io_child_pt"
55 #ifdef MOONBR_IO_USE_TLS
56 #define MOONBR_IO_TLSCONF_MT_REGKEY "moonbridge_io_tlsconf"
57 #endif
59 typedef struct {
60 int fd;
61 int issock;
62 sa_family_t addrfam;
63 int finished;
64 int closed;
65 int nonblocking;
66 int nopush;
67 int readerr;
68 int readbufin;
69 int readbufout;
70 int writeerr;
71 size_t writeleft;
72 size_t flushedleft;
73 #if LUA_VERSION_NUM >= 503
74 lua_Integer writeqin;
75 lua_Integer writeqout;
76 #else
77 int writeqin;
78 int writeqout;
79 #endif
80 size_t writeqoff;
81 int writebufin;
82 int writebufout;
83 char readbuf[MOONBR_IO_READBUFLEN];
84 char writebuf[MOONBR_IO_WRITEBUFLEN];
85 #ifdef MOONBR_IO_USE_TLS
86 struct tls *tls;
87 struct tls *servertls;
88 int tlshandshake;
89 #endif
90 } moonbr_io_handle_t;
92 typedef struct {
93 int fd;
94 sa_family_t addrfam;
95 int nonblocking;
96 } moonbr_io_listener_t;
98 typedef struct {
99 pid_t pid;
100 } moonbr_io_child_t;
102 static int moonbr_io_yield(lua_State *L) {
103 return lua_yield(L, lua_gettop(L));
104 }
106 #if LUA_VERSION_NUM >= 503
107 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
108 #else
109 static int moonbr_io_cont_returnall(lua_State *L) {
110 #endif
111 return lua_gettop(L);
112 }
114 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
115 static int yieldfunc(lua_State *L) { \
116 int args; \
117 lua_pushcfunction(L, callfunc); \
118 lua_insert(L, 1); \
119 args = lua_gettop(L); \
120 lua_pushcfunction(L, moonbr_io_yield); \
121 lua_insert(L, 3); \
122 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
123 return lua_gettop(L); \
124 }
126 static void moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
127 int flags;
128 if (handle->nonblocking == nonblocking) return;
129 flags = fcntl(handle->fd, F_GETFL, 0);
130 if (flags == -1) {
131 moonbr_io_errmsg();
132 close(handle->fd);
133 handle->fd = -1;
134 handle->closed = 1;
135 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
136 }
137 if (nonblocking) flags |= O_NONBLOCK;
138 else flags &= ~O_NONBLOCK;
139 if (fcntl(handle->fd, F_SETFL, flags) == -1) {
140 moonbr_io_errmsg();
141 close(handle->fd);
142 handle->fd = -1;
143 handle->closed = 1;
144 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
145 }
146 handle->nonblocking = nonblocking;
147 }
149 static void moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
150 struct linger lingerval = { 0, };
151 if (!handle->issock) return;
152 if (timeout >= 0) {
153 lingerval.l_onoff = 1;
154 lingerval.l_linger = timeout;
155 }
156 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) {
157 moonbr_io_errmsg();
158 close(handle->fd);
159 handle->fd = -1;
160 handle->closed = 1;
161 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
162 }
163 }
165 static inline void 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;
171 #if defined(TCP_NOPUSH)
172 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) {
173 #elif defined(TCP_CORK)
174 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) {
175 #endif
176 moonbr_io_errmsg();
177 close(handle->fd);
178 handle->fd = -1;
179 handle->closed = 1;
180 #if defined(TCP_NOPUSH)
181 luaL_error(L, "Unexpected error while setting TCP_NOPUSH with setsockopt: %s", errmsg);
182 #elif defined(TCP_CORK)
183 luaL_error(L, "Unexpected error while setting TCP_CORK with setsockopt: %s", errmsg);
184 #endif
185 }
186 handle->nopush = nopush;
187 #else
188 #warning Neither TCP_NOPUSH nor TCP_CORK is available
189 #endif
190 }
192 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
193 moonbr_io_handle_t *handle;
194 lua_Integer maxread;
195 const char *terminatorstr;
196 size_t terminatorlen;
197 char terminator = 0; /* initialize to avoid compiler warning */
198 luaL_Buffer luabuf;
199 size_t luabufcnt = 0;
200 int remaining;
201 char *terminatorpos;
202 ssize_t bytesread;
203 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
204 maxread = luaL_optinteger(L, 2, -1);
205 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
206 if (terminatorlen) {
207 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
208 terminator = terminatorstr[0];
209 }
210 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
211 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
212 if (handle->readerr) {
213 lua_pushnil(L);
214 lua_pushliteral(L, "Previous read error");
215 return 2;
216 }
217 if (handle->fd < 0) {
218 /* fake EOF to simulate shutdown */
219 if (!drain) lua_pushliteral(L, "");
220 else lua_pushinteger(L, 0);
221 lua_pushliteral(L, "eof");
222 return 2;
223 }
224 handle->readerr = 1;
225 moonbr_io_handle_set_nonblocking(L, handle, nonblocking);
226 if (!drain) luaL_buffinit(L, &luabuf);
227 while (1) {
228 remaining = -1;
229 terminatorpos = NULL;
230 if (
231 maxread >= 0 &&
232 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
233 ) {
234 remaining = (size_t)maxread - luabufcnt;
235 if (terminatorlen) {
236 terminatorpos = memchr(
237 handle->readbuf + handle->readbufout,
238 terminator,
239 remaining
240 );
241 }
242 } else if (terminatorlen) {
243 terminatorpos = memchr(
244 handle->readbuf + handle->readbufout,
245 terminator,
246 handle->readbufin - handle->readbufout
247 );
248 }
249 if (terminatorpos) remaining = 1 + (
250 terminatorpos - (handle->readbuf + handle->readbufout)
251 );
252 if (remaining >= 0) {
253 if (!drain) {
254 luaL_addlstring(
255 &luabuf,
256 handle->readbuf + handle->readbufout,
257 remaining
258 );
259 luaL_pushresult(&luabuf);
260 } else {
261 lua_pushinteger(L, luabufcnt + remaining);
262 }
263 if (terminatorpos) lua_pushliteral(L, "term");
264 else lua_pushliteral(L, "maxlen");
265 handle->readbufout += remaining;
266 if (handle->readbufout == handle->readbufin) {
267 handle->readbufin = 0;
268 handle->readbufout = 0;
269 }
270 handle->readerr = 0;
271 return 2;
272 }
273 if (!drain) luaL_addlstring(
274 &luabuf,
275 handle->readbuf + handle->readbufout,
276 handle->readbufin - handle->readbufout
277 );
278 luabufcnt += handle->readbufin - handle->readbufout;
279 handle->readbufout = 0;
280 #ifdef MOONBR_IO_USE_TLS
281 if (handle->tls) {
282 do {
283 if (!handle->tlshandshake) {
284 do bytesread = tls_handshake(handle->tls);
285 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
286 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
287 handle->tlshandshake = bytesread;
288 errno = EAGAIN;
289 break;
290 }
291 if (bytesread < 0) {
292 lua_pushnil(L);
293 lua_pushstring(L, tls_error(handle->tls));
294 return 2;
295 }
296 handle->tlshandshake = 1;
297 }
298 do bytesread = tls_read(handle->tls, handle->readbuf, MOONBR_IO_READBUFLEN);
299 while (!nonblocking && (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT));
300 if (bytesread == TLS_WANT_POLLIN || bytesread == TLS_WANT_POLLOUT) {
301 errno = EAGAIN;
302 break;
303 }
304 if (bytesread < 0) {
305 lua_pushnil(L);
306 lua_pushstring(L, tls_error(handle->tls));
307 return 2;
308 }
309 } while (0);
310 }
311 else
312 #endif
313 do bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
314 while (bytesread < 0 && (errno == EINTR));
315 if (
316 bytesread == 0 || (
317 nonblocking &&
318 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
319 )
320 ) {
321 handle->readbufin = 0;
322 if (!drain) luaL_pushresult(&luabuf);
323 else lua_pushinteger(L, luabufcnt);
324 if (bytesread == 0) lua_pushliteral(L, "eof");
325 else lua_pushliteral(L, "block");
326 handle->readerr = 0;
327 return 2;
328 }
329 if (bytesread < 0) {
330 moonbr_io_errmsg();
331 lua_pushnil(L);
332 lua_pushstring(L, errmsg);
333 return 2;
334 }
335 handle->readbufin = bytesread;
336 }
337 }
339 static int moonbr_io_read(lua_State *L) {
340 return moonbr_io_read_impl(L, 0, 0);
341 }
343 static int moonbr_io_read_nb(lua_State *L) {
344 return moonbr_io_read_impl(L, 1, 0);
345 }
347 static int moonbr_io_drain(lua_State *L) {
348 return moonbr_io_read_impl(L, 0, 1);
349 }
351 static int moonbr_io_drain_nb(lua_State *L) {
352 return moonbr_io_read_impl(L, 1, 1);
353 }
355 #if LUA_VERSION_NUM >= 503
356 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
357 #else
358 static int moonbr_io_read_cont(lua_State *L) {
359 #endif
360 lua_Integer remaining;
361 size_t len;
362 #if !(LUA_VERSION_NUM >= 503)
363 int ctx = 0;
364 lua_getctx(L, &ctx);
365 #endif
366 remaining = lua_tointeger(L, 3);
367 while (1) {
368 lua_pushcfunction(L, moonbr_io_read_nb);
369 lua_pushvalue(L, 1);
370 lua_pushvalue(L, 3);
371 lua_pushvalue(L, 4);
372 lua_call(L, 3, 2);
373 if (lua_isnil(L, -2)) return 2;
374 lua_insert(L, -2);
375 len = lua_rawlen(L, -1);
376 if (ctx == 0) {
377 lua_replace(L, 5);
378 ctx = 1;
379 } else if (ctx == 1) {
380 lua_pushvalue(L, 5);
381 lua_newtable(L);
382 lua_replace(L, 5);
383 lua_rawseti(L, 5, 2);
384 lua_rawseti(L, 5, 1);
385 ctx = 2;
386 } else {
387 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
388 }
389 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
390 lua_pop(L, 1);
391 if (remaining >= 0 && len) {
392 remaining -= len;
393 lua_pushinteger(L, remaining);
394 lua_replace(L, 3);
395 }
396 lua_pushvalue(L, 2);
397 lua_callk(L, 0, 0, ctx, moonbr_io_read_cont);
398 }
399 if (ctx == 1) {
400 lua_pushvalue(L, 5);
401 } else {
402 luaL_Buffer buf;
403 lua_Integer i, chunkcount;
404 chunkcount = lua_rawlen(L, 5);
405 luaL_buffinit(L, &buf);
406 for (i=1; i<=chunkcount && i>0; i++) {
407 lua_rawgeti(L, 5, i);
408 luaL_addvalue(&buf);
409 }
410 luaL_pushresult(&buf);
411 }
412 lua_pushvalue(L, -2);
413 return 2;
414 }
416 static int moonbr_io_read_call(lua_State *L) {
417 lua_settop(L, 4);
418 lua_pushnil(L);
419 #if LUA_VERSION_NUM >= 503
420 return moonbr_io_read_cont(L, 0, 0);
421 #else
422 return moonbr_io_read_cont(L);
423 #endif
424 }
426 moonbr_io_yield_wrapper(moonbr_io_read_yield, moonbr_io_read_call);
428 #if LUA_VERSION_NUM >= 503
429 static int moonbr_io_drain_cont(lua_State *L, int status, lua_KContext ctx) {
430 #else
431 static int moonbr_io_drain_cont(lua_State *L) {
432 #endif
433 lua_Integer remaining, len;
434 size_t totallen = 0;
435 #if !(LUA_VERSION_NUM >= 503)
436 int ctx = 0;
437 lua_getctx(L, &ctx);
438 #endif
439 remaining = lua_tointeger(L, 3);
440 while (1) {
441 lua_pushcfunction(L, moonbr_io_drain_nb);
442 lua_pushvalue(L, 1);
443 lua_pushvalue(L, 3);
444 lua_pushvalue(L, 4);
445 lua_call(L, 3, 2);
446 if (lua_isnil(L, -2)) return 2;
447 lua_insert(L, -2);
448 len = lua_tointeger(L, -1);
449 lua_pop(L, 1);
450 totallen += len;
451 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
452 lua_pop(L, 1);
453 if (remaining >= 0 && len) {
454 remaining -= len;
455 lua_pushinteger(L, remaining);
456 lua_replace(L, 3);
457 }
458 lua_pushvalue(L, 2);
459 lua_callk(L, 0, 0, ctx, moonbr_io_drain_cont);
460 }
461 lua_pushinteger(L, totallen);
462 lua_pushvalue(L, -2);
463 return 2;
464 }
466 static int moonbr_io_drain_call(lua_State *L) {
467 #if LUA_VERSION_NUM >= 503
468 return moonbr_io_drain_cont(L, 0, 0);
469 #else
470 return moonbr_io_drain_cont(L);
471 #endif
472 }
474 moonbr_io_yield_wrapper(moonbr_io_drain_yield, moonbr_io_drain_call);
476 #ifdef MOONBR_IO_USE_TLS
477 #define moonbr_io_write_tls(buf, buflen) \
478 if (handle->tls) { \
479 do { \
480 if (!handle->tlshandshake) { \
481 do written = tls_handshake(handle->tls); \
482 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
483 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
484 handle->tlshandshake = written; \
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 handle->tlshandshake = 1; \
494 } \
495 do written = tls_write(handle->tls, (buf), (buflen)); \
496 while (!nonblocking && (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT)); \
497 if (written == TLS_WANT_POLLIN || written == TLS_WANT_POLLOUT) { \
498 errno = EAGAIN; \
499 break; \
500 } \
501 if (written < 0) { \
502 lua_pushnil(L); \
503 lua_pushstring(L, tls_error(handle->tls)); \
504 return 2; \
505 } \
506 } while (0); \
507 } \
508 else
509 #endif
511 static int moonbr_io_write_impl(lua_State *L, int nonblocking, int flush) {
512 moonbr_io_handle_t *handle;
513 int i, top;
514 const char *str;
515 size_t strlen;
516 ssize_t written;
517 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
518 if (handle->closed) luaL_error(L, "Attempt to write to a closed I/O handle");
519 if (handle->finished) luaL_error(L, "Attempt to write to a finished I/O handle");
520 if (handle->writeerr) {
521 lua_pushnil(L);
522 lua_pushliteral(L, "Previous write error");
523 return 2;
524 }
525 handle->writeerr = 1;
526 moonbr_io_handle_set_nonblocking(L, handle, nonblocking);
527 top = lua_gettop(L);
528 lua_getuservalue(L, 1);
529 lua_getfield(L, -1, "writequeue");
530 for (i=2; i<=top; i++) {
531 luaL_checklstring(L, i, &strlen);
532 lua_pushvalue(L, i);
533 lua_rawseti(L, -2, handle->writeqin++);
534 handle->writeleft += strlen;
535 }
536 if (flush) handle->flushedleft = handle->writeleft;
537 while (handle->writeqout != handle->writeqin) {
538 lua_rawgeti(L, -1, handle->writeqout);
539 str = lua_tolstring(L, -1, &strlen);
540 while (handle->writeqoff < strlen) {
541 if (
542 strlen - handle->writeqoff <
543 MOONBR_IO_WRITEBUFLEN - handle->writebufin
544 ) {
545 memcpy(
546 handle->writebuf + handle->writebufin,
547 str + handle->writeqoff,
548 strlen - handle->writeqoff
549 );
550 handle->writebufin += strlen - handle->writeqoff;
551 break;
552 } else {
553 memcpy(
554 handle->writebuf + handle->writebufin,
555 str + handle->writeqoff,
556 MOONBR_IO_WRITEBUFLEN - handle->writebufin
557 );
558 handle->writeqoff += MOONBR_IO_WRITEBUFLEN - handle->writebufin;
559 handle->writebufin = MOONBR_IO_WRITEBUFLEN;
560 while (handle->writebufout < MOONBR_IO_WRITEBUFLEN) {
561 moonbr_io_handle_set_nopush(L, handle, 1);
562 #ifdef MOONBR_IO_USE_TLS
563 moonbr_io_write_tls(
564 handle->writebuf + handle->writebufout,
565 MOONBR_IO_WRITEBUFLEN - handle->writebufout
566 )
567 #endif
568 written = write(
569 handle->fd,
570 handle->writebuf + handle->writebufout,
571 MOONBR_IO_WRITEBUFLEN - handle->writebufout
572 );
573 if (written < 0) {
574 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
575 goto moonbr_io_write_impl_block;
576 } else if (errno != EINTR) {
577 moonbr_io_errmsg();
578 lua_pushnil(L);
579 lua_pushstring(L, errmsg);
580 return 2;
581 }
582 } else {
583 handle->writebufout += written;
584 handle->writeleft -= written;
585 if (handle->flushedleft) {
586 if (written >= handle->flushedleft) {
587 handle->flushedleft = 0;
588 moonbr_io_handle_set_nopush(L, handle, 0);
589 } else {
590 handle->flushedleft -= written;
591 }
592 }
593 }
594 }
595 handle->writebufin = 0;
596 handle->writebufout = 0;
597 }
598 }
599 handle->writeqoff = 0;
600 lua_pop(L, 1);
601 lua_pushnil(L);
602 lua_rawseti(L, -2, handle->writeqout++);
603 }
604 while (handle->flushedleft) {
605 moonbr_io_handle_set_nopush(L, handle, 1);
606 #ifdef MOONBR_IO_USE_TLS
607 moonbr_io_write_tls(
608 handle->writebuf + handle->writebufout,
609 handle->writebufin - handle->writebufout
610 )
611 #endif
612 written = write(
613 handle->fd,
614 handle->writebuf + handle->writebufout,
615 handle->writebufin - handle->writebufout
616 );
617 if (written < 0) {
618 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
619 goto moonbr_io_write_impl_block;
620 } else if (errno != EINTR) {
621 moonbr_io_errmsg();
622 lua_pushnil(L);
623 lua_pushstring(L, errmsg);
624 return 2;
625 }
626 } else {
627 handle->writebufout += written;
628 handle->writeleft -= written;
629 if (handle->flushedleft) {
630 if (written >= handle->flushedleft) {
631 handle->flushedleft = 0;
632 moonbr_io_handle_set_nopush(L, handle, 0);
633 } else {
634 handle->flushedleft -= written;
635 }
636 }
637 }
638 }
639 if (handle->writebufout == handle->writebufin) {
640 handle->writebufin = 0;
641 handle->writebufout = 0;
642 }
643 if (nonblocking) lua_pushinteger(L, 0);
644 else lua_pushvalue(L, 1);
645 handle->writeerr = 0;
646 return 1;
647 moonbr_io_write_impl_block:
648 lua_pushinteger(L, handle->writeleft);
649 handle->writeerr = 0;
650 return 1;
651 }
653 static int moonbr_io_write(lua_State *L) {
654 return moonbr_io_write_impl(L, 0, 0);
655 }
657 static int moonbr_io_write_nb(lua_State *L) {
658 return moonbr_io_write_impl(L, 1, 0);
659 }
661 static int moonbr_io_flush(lua_State *L) {
662 return moonbr_io_write_impl(L, 0, 1);
663 }
665 static int moonbr_io_flush_nb(lua_State *L) {
666 return moonbr_io_write_impl(L, 1, 1);
667 }
669 #if LUA_VERSION_NUM >= 503
670 static int moonbr_io_write_cont(lua_State *L, int status, lua_KContext ctx) {
671 #else
672 static int moonbr_io_write_cont(lua_State *L) {
673 #endif
674 while (1) {
675 lua_pushcfunction(L, moonbr_io_write_nb);
676 lua_pushvalue(L, 1);
677 lua_call(L, 1, 2);
678 if (lua_isnil(L, -2)) return 2;
679 if (!lua_tointeger(L, -2)) {
680 lua_pushvalue(L, 1);
681 return 1;
682 }
683 lua_pop(L, 2);
684 lua_pushvalue(L, 2);
685 lua_callk(L, 0, 0, 0, moonbr_io_write_cont);
686 }
687 }
689 static int moonbr_io_write_call(lua_State *L) {
690 lua_pushcfunction(L, moonbr_io_write_nb);
691 lua_insert(L, 3);
692 lua_pushvalue(L, 1);
693 lua_insert(L, 4);
694 lua_call(L, lua_gettop(L) - 3, 2);
695 if (lua_isnil(L, -2)) return 2;
696 if (!lua_tointeger(L, -2)) {
697 lua_pushvalue(L, 1);
698 return 1;
699 }
700 #if LUA_VERSION_NUM >= 503
701 return moonbr_io_write_cont(L, 0, 0);
702 #else
703 return moonbr_io_write_cont(L);
704 #endif
705 }
707 moonbr_io_yield_wrapper(moonbr_io_write_yield, moonbr_io_write_call);
709 static int moonbr_io_flush_call(lua_State *L) {
710 lua_pushcfunction(L, moonbr_io_flush_nb);
711 lua_insert(L, 3);
712 lua_pushvalue(L, 1);
713 lua_insert(L, 4);
714 lua_call(L, lua_gettop(L) - 3, 2);
715 if (lua_isnil(L, -2)) return 2;
716 if (!lua_tointeger(L, -2)) {
717 lua_pushvalue(L, 1);
718 return 1;
719 }
720 #if LUA_VERSION_NUM >= 503
721 return moonbr_io_write_cont(L, 0, 0);
722 #else
723 return moonbr_io_write_cont(L);
724 #endif
725 }
727 moonbr_io_yield_wrapper(moonbr_io_flush_yield, moonbr_io_flush_call);
729 static int moonbr_io_finish(lua_State *L) {
730 moonbr_io_handle_t *handle;
731 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
732 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
733 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
734 if (handle->writeleft) {
735 lua_pushcfunction(L, moonbr_io_flush);
736 lua_pushvalue(L, 1);
737 if (lua_pcall(L, 1, 2, 0)) {
738 handle->finished = 1;
739 lua_error(L);
740 }
741 if (!lua_toboolean(L, -2)) {
742 handle->finished = 1;
743 return 2;
744 }
745 }
746 handle->finished = 1;
747 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
748 if (shutdown(handle->fd, SHUT_WR)) {
749 moonbr_io_errmsg();
750 lua_pushnil(L);
751 lua_pushstring(L, errmsg);
752 return 2;
753 }
754 } else {
755 if (close(handle->fd)) {
756 moonbr_io_errmsg();
757 handle->fd = -1;
758 lua_pushnil(L);
759 lua_pushstring(L, errmsg);
760 return 2;
761 }
762 handle->fd = -1; /* fake EOF on read */
763 }
764 lua_pushboolean(L, 1);
765 return 1;
766 }
768 static int moonbr_io_close_impl(lua_State *L, int reset) {
769 moonbr_io_handle_t *handle;
770 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
771 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
772 if (!reset) {
773 if (handle->writeleft) {
774 lua_pushcfunction(L, moonbr_io_flush);
775 lua_pushvalue(L, 1);
776 if (lua_pcall(L, 1, 2, 0)) {
777 handle->closed = 1;
778 close(handle->fd);
779 handle->fd = -1;
780 lua_error(L);
781 }
782 handle->closed = 1;
783 if (!lua_toboolean(L, -2)) {
784 close(handle->fd);
785 handle->fd = -1;
786 return 2;
787 }
788 } else {
789 handle->closed = 1;
790 moonbr_io_handle_set_linger(L, handle, -1);
791 }
792 } else {
793 handle->closed = 1;
794 }
795 if (handle->fd >= 0) {
796 if (close(handle->fd)) {
797 moonbr_io_errmsg();
798 handle->fd = -1;
799 lua_pushnil(L);
800 lua_pushstring(L, errmsg);
801 return 2;
802 }
803 handle->fd = -1;
804 }
805 lua_pushboolean(L, 1);
806 return 1;
808 }
810 static int moonbr_io_close(lua_State *L) {
811 return moonbr_io_close_impl(L, 0);
812 }
814 static int moonbr_io_reset(lua_State *L) {
815 return moonbr_io_close_impl(L, 1);
816 }
818 static int moonbr_io_handlegc(lua_State *L) {
819 moonbr_io_handle_t *handle;
820 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
821 if (handle->fd >= 0) {
822 lua_pushcfunction(L, moonbr_io_reset);
823 lua_pushvalue(L, 1);
824 lua_pushinteger(L, 0);
825 lua_call(L, 2, 0);
826 }
827 #ifdef MOONBR_IO_USE_TLS
828 if (handle->tls) {
829 tls_free(handle->tls);
830 handle->tls = NULL;
831 }
832 if (handle->servertls) {
833 tls_free(handle->servertls);
834 handle->servertls = NULL;
835 }
836 #endif
837 return 0;
838 }
840 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
841 moonbr_io_handle_t *handle;
842 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
843 if (!handle->closed) {
844 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
845 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
846 lua_call(L, 1, 0);
847 }
848 }
850 static int moonbr_io_pushhandle_impl(lua_State *L) {
851 int *fd;
852 moonbr_io_handle_t *handle;
853 struct sockaddr addr;
854 socklen_t addrlen;
855 fd = lua_touserdata(L, 1);
856 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
857 handle->fd = -1; /* avoid closing incomplete handle */
858 addrlen = sizeof(addr);
859 if (getsockname(*fd, &addr, &addrlen)) {
860 if (errno != ENOTSOCK) {
861 moonbr_io_errmsg();
862 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
863 }
864 handle->issock = 0;
865 } else {
866 handle->issock = 1;
867 handle->addrfam = addr.sa_family;
868 }
869 handle->finished = 0;
870 handle->closed = 0;
871 handle->nonblocking = -1;
872 handle->nopush = -1;
873 handle->readerr = 0;
874 handle->readbufin = 0;
875 handle->readbufout = 0;
876 handle->writeerr = 0;
877 handle->writeleft = 0;
878 handle->flushedleft = 0;
879 handle->writeqin = 0;
880 handle->writeqout = 0;
881 handle->writeqoff = 0;
882 handle->writebufin = 0;
883 handle->writebufout = 0;
884 #ifdef MOONBR_IO_USE_TLS
885 handle->tls = NULL;
886 handle->servertls = NULL;
887 handle->tlshandshake = 0;
888 #endif
889 handle->fd = *fd; /* required for set_linger call */
890 moonbr_io_handle_set_linger(L, handle, 0);
891 handle->fd = -1; /* avoid closing incomplete handle */
892 luaL_setmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
893 lua_newtable(L); // uservalue
894 lua_newtable(L);
895 lua_setfield(L, -2, "writequeue");
896 lua_newtable(L); // public
897 if (handle->addrfam == AF_INET6) {
898 struct sockaddr_in6 addr_in6;
899 char addrstrbuf[INET6_ADDRSTRLEN];
900 const char *addrstr;
901 addrlen = sizeof(addr_in6);
902 if (getsockname(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
903 moonbr_io_errmsg();
904 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
905 }
906 if (addrlen > sizeof(addr_in6)) {
907 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
908 }
909 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
910 if (!addrstr) {
911 moonbr_io_errmsg();
912 luaL_error(L, "Could not format local IP address: %s", errmsg);
913 } else {
914 lua_pushstring(L, addrstr);
915 lua_setfield(L, -2, "local_ip6");
916 }
917 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
918 lua_setfield(L, -2, "local_tcpport");
919 if (getpeername(*fd, (struct sockaddr *)&addr_in6, &addrlen)) {
920 moonbr_io_errmsg();
921 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
922 }
923 if (addrlen > sizeof(addr_in6)) {
924 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
925 }
926 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
927 if (!addrstr) {
928 moonbr_io_errmsg();
929 luaL_error(L, "Could not format remote IP address: %s", errmsg);
930 } else {
931 lua_pushstring(L, addrstr);
932 lua_setfield(L, -2, "remote_ip6");
933 }
934 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
935 lua_setfield(L, -2, "remote_tcpport");
936 } else if (handle->addrfam == AF_INET) {
937 struct sockaddr_in addr_in;
938 char addrstrbuf[INET_ADDRSTRLEN];
939 const char *addrstr;
940 addrlen = sizeof(addr_in);
941 if (getsockname(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
942 moonbr_io_errmsg();
943 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
944 }
945 if (addrlen > sizeof(addr_in)) {
946 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
947 }
948 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
949 if (!addrstr) {
950 moonbr_io_errmsg();
951 luaL_error(L, "Could not format local IP address: %s", errmsg);
952 } else {
953 lua_pushstring(L, addrstr);
954 lua_setfield(L, -2, "local_ip4");
955 }
956 lua_pushinteger(L, ntohs(addr_in.sin_port));
957 lua_setfield(L, -2, "local_tcpport");
958 if (getpeername(*fd, (struct sockaddr *)&addr_in, &addrlen)) {
959 moonbr_io_errmsg();
960 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
961 }
962 if (addrlen > sizeof(addr_in)) {
963 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
964 }
965 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
966 if (!addrstr) {
967 moonbr_io_errmsg();
968 luaL_error(L, "Could not format remote IP address: %s", errmsg);
969 } else {
970 lua_pushstring(L, addrstr);
971 lua_setfield(L, -2, "remote_ip4");
972 }
973 lua_pushinteger(L, ntohs(addr_in.sin_port));
974 lua_setfield(L, -2, "remote_tcpport");
975 }
976 luaL_setmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
977 lua_setfield(L, -2, "public");
978 lua_setuservalue(L, -2);
979 handle->fd = *fd;
980 *fd = -1; /* closing is now handled by garbage collection */
981 return 1;
982 }
984 void moonbr_io_pushhandle(lua_State *L, int fd) {
985 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
986 lua_pushlightuserdata(L, &fd);
987 if (lua_pcall(L, 1, 1, 0)) {
988 if (fd != -1) close(fd);
989 lua_error(L);
990 }
991 }
993 static int moonbr_io_handleindex(lua_State *L) {
994 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
995 luaL_checkany(L, 2);
996 lua_getuservalue(L, 1);
997 lua_getfield(L, -1, "public");
998 lua_pushvalue(L, 2);
999 lua_gettable(L, -2);
1000 return 1;
1003 static int moonbr_io_handlenewindex(lua_State *L) {
1004 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1005 luaL_checkany(L, 2);
1006 luaL_checkany(L, 3);
1007 lua_getuservalue(L, 1);
1008 lua_getfield(L, -1, "public");
1009 lua_pushvalue(L, 2);
1010 lua_pushvalue(L, 3);
1011 lua_settable(L, -3);
1012 return 0;
1015 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
1016 const char *path;
1017 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1018 const int path_maxlen = sizeof(struct sockaddr_un) - (
1019 (void *)sockaddr.sun_path - (void *)&sockaddr
1020 ) - 1; /* one byte for termination */
1021 int sock;
1022 path = luaL_checkstring(L, 1);
1023 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1024 strcpy(sockaddr.sun_path, path);
1025 sock = socket(
1026 PF_LOCAL,
1027 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1029 );
1030 if (sock < 0) {
1031 moonbr_io_errmsg();
1032 lua_pushnil(L);
1033 lua_pushstring(L, errmsg);
1034 return 2;
1036 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1037 if (!nonblocking && errno == EINTR) {
1038 moonbr_io_errmsg();
1039 close(sock);
1040 lua_pushnil(L);
1041 lua_pushstring(L, errmsg);
1042 return 2;
1043 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
1044 moonbr_io_errmsg();
1045 lua_pushnil(L);
1046 lua_pushstring(L, errmsg);
1047 return 2;
1050 moonbr_io_pushhandle(L, sock);
1051 return 1;
1054 static int moonbr_io_localconnect(lua_State *L) {
1055 return moonbr_io_localconnect_impl(L, 0);
1058 static int moonbr_io_localconnect_nb(lua_State *L) {
1059 return moonbr_io_localconnect_impl(L, 1);
1062 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
1063 const char *host, *port;
1064 struct addrinfo hints = { 0, };
1065 struct addrinfo *res, *addrinfo;
1066 int errcode;
1067 int sock;
1068 host = luaL_checkstring(L, 1);
1069 port = luaL_checkstring(L, 2);
1070 hints.ai_family = AF_UNSPEC;
1071 hints.ai_socktype = SOCK_STREAM;
1072 hints.ai_protocol = IPPROTO_TCP;
1073 hints.ai_flags = AI_ADDRCONFIG;
1074 errcode = getaddrinfo(host, port, &hints, &res);
1075 if (errcode) {
1076 freeaddrinfo(res);
1077 if (errcode == EAI_SYSTEM) {
1078 moonbr_io_errmsg();
1079 lua_pushnil(L);
1080 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1081 } else {
1082 lua_pushnil(L);
1083 lua_pushstring(L, gai_strerror(errcode));
1085 return 2;
1087 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1088 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1090 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1091 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1093 addrinfo = res;
1094 moonbr_io_tcpconnect_found:
1095 sock = socket(
1096 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1097 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
1098 addrinfo->ai_protocol
1099 );
1100 if (sock < 0) {
1101 moonbr_io_errmsg();
1102 freeaddrinfo(res);
1103 lua_pushnil(L);
1104 lua_pushstring(L, errmsg);
1105 return 2;
1107 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1108 freeaddrinfo(res);
1109 if (!nonblocking && errno == EINTR) {
1110 moonbr_io_errmsg();
1111 close(sock);
1112 lua_pushnil(L);
1113 lua_pushstring(L, errmsg);
1114 return 2;
1115 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
1116 moonbr_io_errmsg();
1117 lua_pushnil(L);
1118 lua_pushstring(L, errmsg);
1119 return 2;
1121 } else {
1122 freeaddrinfo(res);
1124 moonbr_io_pushhandle(L, sock);
1125 return 1;
1128 static int moonbr_io_tcpconnect(lua_State *L) {
1129 return moonbr_io_tcpconnect_impl(L, 0);
1132 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1133 return moonbr_io_tcpconnect_impl(L, 1);
1136 static int moonbr_io_locallisten(lua_State *L) {
1137 moonbr_io_listener_t *listener;
1138 const char *path;
1139 struct stat sb;
1140 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1141 const int path_maxlen = sizeof(struct sockaddr_un) - (
1142 (void *)sockaddr.sun_path - (void *)&sockaddr
1143 ) - 1; /* one byte for termination */
1144 int sock;
1145 path = luaL_checkstring(L, 1);
1146 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1147 strcpy(sockaddr.sun_path, path);
1148 if (stat(path, &sb) == 0) {
1149 if (S_ISSOCK(sb.st_mode)) unlink(path);
1151 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1152 listener->fd = -1;
1153 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1154 sock = socket(
1155 PF_LOCAL,
1156 SOCK_STREAM | SOCK_CLOEXEC,
1158 );
1159 if (sock < 0) {
1160 moonbr_io_errmsg();
1161 lua_pushnil(L);
1162 lua_pushstring(L, errmsg);
1163 return 2;
1165 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1166 moonbr_io_errmsg();
1167 close(sock);
1168 lua_pushnil(L);
1169 lua_pushstring(L, errmsg);
1170 return 2;
1172 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1173 moonbr_io_errmsg();
1174 close(sock);
1175 lua_pushnil(L);
1176 lua_pushstring(L, errmsg);
1177 return 2;
1179 listener->fd = sock;
1180 listener->addrfam = AF_LOCAL;
1181 listener->nonblocking = -1;
1182 return 1;
1185 static int moonbr_io_tcplisten(lua_State *L) {
1186 moonbr_io_listener_t *listener;
1187 const char *host, *port;
1188 struct addrinfo hints = { 0, };
1189 struct addrinfo *res, *addrinfo;
1190 int errcode;
1191 int sock;
1192 host = luaL_optstring(L, 1, NULL);
1193 port = luaL_checkstring(L, 2);
1194 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1195 listener->fd = -1;
1196 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1197 hints.ai_family = AF_UNSPEC;
1198 hints.ai_socktype = SOCK_STREAM;
1199 hints.ai_protocol = IPPROTO_TCP;
1200 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1201 errcode = getaddrinfo(host, port, &hints, &res);
1202 if (errcode) {
1203 freeaddrinfo(res);
1204 if (errcode == EAI_SYSTEM) {
1205 moonbr_io_errmsg();
1206 lua_pushnil(L);
1207 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1208 } else {
1209 lua_pushnil(L);
1210 lua_pushstring(L, gai_strerror(errcode));
1212 return 2;
1214 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1215 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1217 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1218 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1220 addrinfo = res;
1221 moonbr_io_tcpconnect_found:
1222 listener->addrfam = addrinfo->ai_family;
1223 sock = socket(
1224 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1225 addrinfo->ai_socktype | SOCK_CLOEXEC,
1226 addrinfo->ai_protocol
1227 );
1228 if (sock < 0) {
1229 moonbr_io_errmsg();
1230 freeaddrinfo(res);
1231 lua_pushnil(L);
1232 lua_pushstring(L, errmsg);
1233 return 2;
1236 static const int reuseval = 1;
1237 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1238 moonbr_io_errmsg();
1239 freeaddrinfo(res);
1240 close(sock);
1241 lua_pushnil(L);
1242 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1243 return 2;
1246 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1247 moonbr_io_errmsg();
1248 freeaddrinfo(res);
1249 close(sock);
1250 lua_pushnil(L);
1251 lua_pushstring(L, errmsg);
1252 return 2;
1254 freeaddrinfo(res);
1255 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1256 moonbr_io_errmsg();
1257 close(sock);
1258 lua_pushnil(L);
1259 lua_pushstring(L, errmsg);
1260 return 2;
1262 listener->fd = sock;
1263 listener->nonblocking = -1;
1264 return 1;
1267 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1268 moonbr_io_listener_t *listener;
1269 int fd;
1270 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1271 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1272 if (listener->nonblocking != nonblocking) {
1273 int flags;
1274 flags = fcntl(listener->fd, F_GETFL, 0);
1275 if (flags == -1) {
1276 moonbr_io_errmsg();
1277 close(listener->fd);
1278 listener->fd = -1;
1279 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1281 if (nonblocking) flags |= O_NONBLOCK;
1282 else flags &= ~O_NONBLOCK;
1283 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1284 moonbr_io_errmsg();
1285 close(listener->fd);
1286 listener->fd = -1;
1287 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1289 listener->nonblocking = nonblocking;
1291 while (1) {
1292 #if defined(__linux__) && !defined(_GNU_SOURCE)
1293 fd = accept(listener->fd, NULL, NULL);
1294 if (fd != -1) {
1295 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
1296 moonbr_io_errmsg();
1297 close(listener->fd);
1298 listener->fd = -1;
1299 close(fd);
1300 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1303 #else
1304 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1305 #endif
1306 if (fd < 0) {
1307 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1308 lua_pushboolean(L, 0);
1309 lua_pushliteral(L, "No incoming connection pending");
1310 return 2;
1311 } else if (errno != EINTR) {
1312 moonbr_io_errmsg();
1313 lua_pushnil(L);
1314 lua_pushstring(L, errmsg);
1315 return 2;
1317 } else {
1318 moonbr_io_pushhandle(L, fd);
1319 return 1;
1324 static int moonbr_io_accept(lua_State *L) {
1325 return moonbr_io_accept_impl(L, 0);
1328 static int moonbr_io_accept_nb(lua_State *L) {
1329 return moonbr_io_accept_impl(L, 1);
1332 static int moonbr_io_unlisten(lua_State *L) {
1333 moonbr_io_listener_t *listener;
1334 struct sockaddr_un addr;
1335 socklen_t addrlen;
1336 struct stat sb;
1337 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1338 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1339 addrlen = sizeof(addr);
1340 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1341 if (close(listener->fd)) {
1342 moonbr_io_errmsg();
1343 listener->fd = -1;
1344 if (addrlen && addrlen <= sizeof(addr)) {
1345 if (stat(addr.sun_path, &sb) == 0) {
1346 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1349 lua_pushnil(L);
1350 lua_pushstring(L, errmsg);
1351 return 2;
1353 listener->fd = -1;
1354 if (addrlen && addrlen <= sizeof(addr)) {
1355 if (stat(addr.sun_path, &sb) == 0) {
1356 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1359 lua_pushboolean(L, 1);
1360 return 1;
1363 static int moonbr_io_listenergc(lua_State *L) {
1364 moonbr_io_listener_t *listener;
1365 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1366 if (listener->fd >= 0) close(listener->fd);
1367 listener->fd = -1;
1368 return 0;
1371 static int moonbr_io_exec(lua_State *L) {
1372 char **argv;
1373 int i, argc;
1374 int sockin[2], sockout[2], sockerr[2];
1375 volatile int errorcond = 0;
1376 volatile char errmsgbuf[MOONBR_IO_MAXSTRERRORLEN] = MOONBR_IO_STRERROR_R_MSG;
1377 moonbr_io_child_t *child;
1378 argc = lua_gettop(L);
1379 argv = lua_newuserdata(L, (argc + 1) * sizeof(char *));
1380 for (i=0; i<argc; i++) argv[i] = (char *)luaL_checkstring(L, i+1);
1381 argv[argc] = NULL;
1382 child = lua_newuserdata(L, sizeof(moonbr_io_child_t));
1383 child->pid = 0;
1384 lua_newtable(L);
1385 lua_setuservalue(L, -2);
1386 luaL_setmetatable(L, MOONBR_IO_CHILD_MT_REGKEY);
1387 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockin)) {
1388 moonbr_io_errmsg();
1389 lua_pushnil(L);
1390 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1391 return 2;
1393 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockout)) {
1394 moonbr_io_errmsg();
1395 close(sockin[0]);
1396 close(sockin[1]);
1397 lua_pushnil(L);
1398 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1399 return 2;
1401 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, sockerr)) {
1402 moonbr_io_errmsg();
1403 close(sockin[0]);
1404 close(sockin[1]);
1405 close(sockout[0]);
1406 close(sockout[1]);
1407 lua_pushnil(L);
1408 lua_pushfstring(L, "Could not create socket pair: %s", errmsg);
1409 return 2;
1411 child->pid = vfork();
1412 if (child->pid == -1) {
1413 moonbr_io_errmsg();
1414 close(sockin[0]);
1415 close(sockin[1]);
1416 close(sockout[0]);
1417 close(sockout[1]);
1418 close(sockerr[0]);
1419 close(sockerr[1]);
1420 lua_pushnil(L);
1421 lua_pushfstring(L, "Could not fork: %s", errmsg);
1422 return 2;
1424 if (!child->pid) {
1425 if (dup2(sockin[1], 0) == -1) goto moonbr_io_exec_error1;
1426 if (dup2(sockout[1], 1) == -1) goto moonbr_io_exec_error1;
1427 if (dup2(sockerr[1], 2) == -1) goto moonbr_io_exec_error1;
1428 closefrom(3);
1429 if (fcntl(0, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1430 if (fcntl(1, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1431 if (fcntl(2, F_SETFD, 0) == -1) goto moonbr_io_exec_error1;
1432 if (execvp(argv[0], argv)) {
1433 errorcond = 2;
1434 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1435 _exit(0);
1437 moonbr_io_exec_error1:
1438 errorcond = 1;
1439 strerror_r(errno, (char *)errmsgbuf, MOONBR_IO_MAXSTRERRORLEN);
1440 _exit(0);
1442 close(sockin[1]);
1443 close(sockout[1]);
1444 close(sockerr[1]);
1445 if (errorcond) {
1446 int status;
1447 close(sockin[0]);
1448 close(sockout[0]);
1449 close(sockerr[0]);
1450 while (waitpid(child->pid, &status, 0) == -1) {
1451 if (errno != EINTR) {
1452 moonbr_io_errmsg();
1453 luaL_error(L, "Error in waitpid call after unsuccessful exec: %s", errmsg);
1456 child->pid = 0;
1457 lua_pushnil(L);
1458 if (errorcond == 2) lua_pushfstring(L, "Could not execute: %s", errmsgbuf);
1459 else lua_pushfstring(L, "Error in fork: %s", errmsgbuf);
1460 return 2;
1462 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1463 lua_pushlightuserdata(L, &sockin[0]);
1464 if (lua_pcall(L, 1, 1, 0)) {
1465 if (sockin[0] != -1) close(sockin[0]);
1466 close(sockout[0]);
1467 close(sockerr[0]);
1468 goto moonbr_io_exec_error2;
1470 lua_setfield(L, -2, "stdin");
1471 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1472 lua_pushlightuserdata(L, &sockout[0]);
1473 if (lua_pcall(L, 1, 1, 0)) {
1474 if (sockout[0] != -1) close(sockout[0]);
1475 close(sockerr[0]);
1476 goto moonbr_io_exec_error2;
1478 lua_setfield(L, -2, "stdout");
1479 lua_pushcfunction(L, moonbr_io_pushhandle_impl);
1480 lua_pushlightuserdata(L, &sockerr[0]);
1481 if (lua_pcall(L, 1, 1, 0)) {
1482 if (sockerr[0] != -1) close(sockerr[0]);
1483 goto moonbr_io_exec_error2;
1485 lua_setfield(L, -2, "stderr");
1486 return 1;
1487 moonbr_io_exec_error2:
1489 int status;
1490 while (waitpid(child->pid, &status, 0) == -1) {
1491 if (errno != EINTR) {
1492 moonbr_io_errmsg();
1493 luaL_error(L, "Error in waitpid call after error creating socket handles: %s", errmsg);
1497 child->pid = 0;
1498 return lua_error(L);
1501 static int moonbr_io_childindex(lua_State *L) {
1502 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1503 luaL_checkany(L, 2);
1504 lua_getuservalue(L, 1);
1505 lua_pushvalue(L, 2);
1506 lua_gettable(L, -2);
1507 if (lua_isnil(L, -1)) {
1508 luaL_getmetatable(L, MOONBR_IO_CHILD_PT_REGKEY);
1509 lua_pushvalue(L, 2);
1510 lua_gettable(L, -2);
1512 return 1;
1515 static int moonbr_io_childnewindex(lua_State *L) {
1516 luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1517 luaL_checkany(L, 2);
1518 luaL_checkany(L, 3);
1519 lua_getuservalue(L, 1);
1520 lua_pushvalue(L, 2);
1521 lua_pushvalue(L, 3);
1522 lua_settable(L, -3);
1523 return 0;
1526 static int moonbr_io_childgc(lua_State *L) {
1527 moonbr_io_child_t *child;
1528 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1529 if (child->pid) {
1530 int status;
1531 if (kill(child->pid, SIGKILL)) {
1532 moonbr_io_errmsg();
1533 luaL_error(L, "Error in kill call during garbage collection: %s", errmsg);
1535 while (waitpid(child->pid, &status, 0) == -1) {
1536 if (errno != EINTR) {
1537 moonbr_io_errmsg();
1538 luaL_error(L, "Error in waitpid call during garbage collection: %s", errmsg);
1542 return 0;
1545 static int moonbr_io_kill(lua_State *L) {
1546 moonbr_io_child_t *child;
1547 int sig;
1548 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1549 sig = luaL_optinteger(L, 2, SIGTERM);
1550 if (!child->pid) luaL_error(L, "Attempt to kill an already collected child process");
1551 if (kill(child->pid, sig)) {
1552 moonbr_io_errmsg();
1553 luaL_error(L, "Error in kill call: %s", errmsg);
1555 lua_settop(L, 1);
1556 return 1;
1559 static int moonbr_io_wait_impl(lua_State *L, int nonblocking) {
1560 moonbr_io_child_t *child;
1561 pid_t waitedpid;
1562 int status;
1563 child = luaL_checkudata(L, 1, MOONBR_IO_CHILD_MT_REGKEY);
1564 if (!child->pid) luaL_error(L, "Attempt to wait for an already collected child process");
1565 while ((waitedpid = waitpid(child->pid, &status, nonblocking ? WNOHANG : 0)) == -1) {
1566 if (errno != EINTR) {
1567 moonbr_io_errmsg();
1568 luaL_error(L, "Error in waitpid call: %s", errmsg);
1571 if (!waitedpid) {
1572 lua_pushboolean(L, 0);
1573 lua_pushliteral(L, "Process is still running");
1574 return 2;
1575 } else {
1576 child->pid = 0;
1577 if (WIFEXITED(status)) {
1578 lua_pushinteger(L, WEXITSTATUS(status));
1579 } else if (WIFSIGNALED(status)) {
1580 lua_pushinteger(L, -WTERMSIG(status));
1581 } else {
1582 luaL_error(L, "Unexpected status value returned by waitpid call");
1584 return 1;
1588 static int moonbr_io_wait(lua_State *L) {
1589 return moonbr_io_wait_impl(L, 0);
1592 static int moonbr_io_wait_nb(lua_State *L) {
1593 return moonbr_io_wait_impl(L, 1);
1596 #if LUA_VERSION_NUM >= 503
1597 static int moonbr_io_wait_cont(lua_State *L, int status, lua_KContext ctx) {
1598 #else
1599 static int moonbr_io_wait_cont(lua_State *L) {
1600 #endif
1601 #if !(LUA_VERSION_NUM >= 503)
1602 int ctx = 0;
1603 lua_getctx(L, &ctx);
1604 #endif
1605 while (1) {
1606 lua_pushcfunction(L, moonbr_io_wait_nb);
1607 lua_pushvalue(L, 1);
1608 lua_call(L, 1, 1);
1609 if (!lua_isnil(L, -1)) break;
1610 lua_pushvalue(L, 2);
1611 lua_callk(L, 0, 0, ctx, moonbr_io_wait_cont);
1613 return 1;
1616 static int moonbr_io_wait_call(lua_State *L) {
1617 lua_settop(L, 2);
1618 #if LUA_VERSION_NUM >= 503
1619 return moonbr_io_wait_cont(L, 0, 0);
1620 #else
1621 return moonbr_io_wait_cont(L);
1622 #endif
1625 moonbr_io_yield_wrapper(moonbr_io_wait_yield, moonbr_io_wait_call);
1627 #ifdef MOONBR_IO_USE_TLS
1628 #define moonbr_io_poll_tls() \
1629 if (!handle->tlshandshake) { \
1630 lua_pushboolean(L, 1); \
1631 return 1; \
1632 } \
1633 if (handle->tlshandshake == TLS_WANT_POLLIN) { \
1634 if (fd < 0) { \
1635 lua_pushboolean(L, 1); \
1636 return 1; \
1637 } \
1638 FD_SET(fd, &readfds); \
1639 if (fd+1 > nfds) nfds = fd+1; \
1640 continue; \
1641 } \
1642 if (handle->tlshandshake == TLS_WANT_POLLOUT) { \
1643 if (fd < 0) { \
1644 lua_pushboolean(L, 1); \
1645 return 1; \
1646 } \
1647 FD_SET(fd, &writefds); \
1648 if (fd+1 > nfds) nfds = fd+1; \
1649 continue; \
1650 } \
1651 while (0)
1652 #endif
1654 static int moonbr_io_poll(lua_State *L) {
1655 moonbr_io_handle_t *handle;
1656 moonbr_io_listener_t *listener;
1657 int fd, isnum;
1658 int nfds = 0;
1659 fd_set readfds, writefds, exceptfds;
1660 struct timeval timeout = {0, };
1661 int status;
1662 FD_ZERO(&readfds);
1663 FD_ZERO(&writefds);
1664 FD_ZERO(&exceptfds);
1665 if (!lua_isnoneornil(L, 1)) {
1666 luaL_checktype(L, 1, LUA_TTABLE);
1667 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1668 if (lua_toboolean(L, -1)) {
1669 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1670 if (handle) {
1671 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1672 fd = handle->fd;
1673 #if MOONBR_IO_USE_TLS
1674 moonbr_io_poll_tls();
1675 #endif
1676 if (
1677 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1678 handle->readbufin != handle->readbufout /* data pending in buffer */
1679 ) {
1680 lua_pushboolean(L, 1);
1681 return 1;
1683 } else {
1684 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1685 if (listener) {
1686 fd = listener->fd;
1687 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1688 } else {
1689 fd = lua_tointegerx(L, -2, &isnum);
1690 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1693 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1694 FD_SET(fd, &readfds);
1695 if (fd+1 > nfds) nfds = fd+1;
1699 if (!lua_isnoneornil(L, 2)) {
1700 luaL_checktype(L, 2, LUA_TTABLE);
1701 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1702 if (lua_toboolean(L, -1)) {
1703 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1704 if (handle) {
1705 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1706 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1707 fd = handle->fd;
1708 #if MOONBR_IO_USE_TLS
1709 moonbr_io_poll_tls();
1710 #endif
1711 } else {
1712 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1713 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1714 fd = lua_tointegerx(L, -2, &isnum);
1715 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1717 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1718 FD_SET(fd, &writefds);
1719 if (fd+1 > nfds) nfds = fd+1;
1723 if (!lua_isnoneornil(L, 3)) {
1724 lua_Number n;
1725 n = lua_tonumberx(L, 3, &isnum);
1726 if (isnum && n<0) {
1727 lua_pushboolean(L, 0);
1728 lua_pushliteral(L, "Negative timeout");
1729 return 2;
1730 } else if (isnum && n>=0 && n<100000000) {
1731 timeout.tv_sec = n;
1732 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1733 } else {
1734 luaL_argcheck(L, 0, 3, "not a valid timeout");
1736 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1737 } else {
1738 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1740 if (status == -1) {
1741 if (errno == EINTR) {
1742 lua_pushnil(L);
1743 lua_pushliteral(L, "Signal received while polling file descriptors");
1744 return 2;
1745 } else {
1746 moonbr_io_errmsg();
1747 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1749 } else if (status == 0) {
1750 lua_pushboolean(L, 0);
1751 lua_pushliteral(L, "Timeout while polling file descriptors");
1752 return 2;
1753 } else {
1754 lua_pushboolean(L, 1);
1755 return 1;
1759 static int moonbr_io_timeref(lua_State *L) {
1760 lua_Number sub;
1761 struct timespec tp;
1762 sub = luaL_optnumber(L, 1, 0);
1763 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1764 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1766 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1767 return 1;
1770 #ifdef MOONBR_IO_USE_TLS
1772 #define moonbr_io_tlsconf_string(name, field, func) \
1773 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1774 lua_getfield(L, 1, (field)); \
1775 valuetype = lua_type(L, -1); \
1776 if (valuetype != LUA_TNIL) { \
1777 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1778 value = lua_tostring(L, -1); \
1779 if (func(tlsconf, value)) { \
1780 lua_pushnil(L); \
1781 lua_pushfstring(L, "Could not set " name " \"%s\"", value); \
1782 return 2; \
1783 } \
1784 } \
1785 lua_pop(L, 1);
1787 #define moonbr_io_tlsconf_binary(name, field, func) \
1788 /* NOTE: use valuetype = lua_getfield(...) for LUA_VERSION_NUM >= 503 */ \
1789 lua_getfield(L, 1, (field)); \
1790 valuetype = lua_type(L, -1); \
1791 if (valuetype != LUA_TNIL) { \
1792 luaL_argcheck(L, valuetype == LUA_TSTRING, 1, "field \"" field "\" is not a string"); \
1793 value = lua_tolstring(L, -1, &valuelen); \
1794 if (func(tlsconf, (void *)value, valuelen)) { \
1795 lua_pushnil(L); \
1796 lua_pushliteral(L, "Could not set " name); \
1797 return 2; \
1798 } \
1799 } \
1800 lua_pop(L, 1);
1802 static int moonbr_io_tlsconf(lua_State *L) {
1803 struct tls_config *tlsconf;
1804 int valuetype;
1805 const char *value;
1806 size_t valuelen;
1807 luaL_checktype(L, 1, LUA_TTABLE);
1808 tlsconf = tls_config_new();
1809 if (!tlsconf) {
1810 return luaL_error(L, "Could not allocate memory for TLS configuration");
1812 lua_pushlightuserdata(L, tlsconf);
1813 luaL_setmetatable(L, MOONBR_IO_TLSCONF_MT_REGKEY);
1814 lua_pushvalue(L, 1);
1815 lua_setuservalue(L, -2);
1816 #if LUA_VERSION_NUM >= 503
1817 if (lua_getfield(L, 1, "mode") == LUA_TSTRING) value = lua_tostring(L, -1);
1818 #else
1819 lua_getfield(L, 1, "mode");
1820 if (lua_type(L, -1) == LUA_TSTRING) value = lua_tostring(L, -1);
1821 #endif
1822 else value = "";
1823 if (strcmp(value, "server") && strcmp(value, "client")) {
1824 luaL_argcheck(L, 0, 1, "field \"mode\" must be set to \"server\" or \"client\"");
1826 lua_pop(L, 1);
1827 moonbr_io_tlsconf_string("CA file", "ca_file", tls_config_set_ca_file);
1828 moonbr_io_tlsconf_string("CA path", "ca_path", tls_config_set_ca_path);
1829 moonbr_io_tlsconf_binary("CA", "ca_mem", tls_config_set_ca_mem);
1830 moonbr_io_tlsconf_string("certificate file", "cert_file", tls_config_set_cert_file);
1831 moonbr_io_tlsconf_binary("certificate", "cert_mem", tls_config_set_cert_mem);
1832 moonbr_io_tlsconf_string("key file", "key_file", tls_config_set_key_file);
1833 moonbr_io_tlsconf_binary("key", "key_mem", tls_config_set_key_mem);
1834 #if LUA_VERSION_NUM >= 503
1835 valuetype = lua_getfield(L, 1, "verify_client");
1836 #else
1837 lua_getfield(L, 1, "verify_client");
1838 #endif
1839 if (lua_toboolean(L, -1)) {
1840 #if LUA_VERSION_NUM >= 503
1841 if (valuetype == LUA_TSTRING) value = lua_tostring(L, -1);
1842 #else
1843 if (lua_type(L, -1) == LUA_TSTRING) value = lua_tostring(L, -1);
1844 #endif
1845 else value = "";
1846 if (!strcmp(value, "required")) {
1847 tls_config_verify_client(tlsconf);
1848 } else if (!strcmp(value, "optional")) {
1849 tls_config_verify_client_optional(tlsconf);
1850 } else {
1851 luaL_argcheck(L, 0, 1, "field \"verify_client\" must be set to \"required\", \"optional\", or be false or nil");
1854 lua_pop(L, 1);
1855 return 1;
1858 static int moonbr_io_tlsconfindex(lua_State *L) {
1859 struct tls_config *tlsconf;
1860 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
1861 luaL_checkany(L, 2);
1862 #if LUA_VERSION_NUM >= 503
1863 if (lua_getuservalue(L, 1) == LUA_TNIL) {
1864 #else
1865 lua_getuservalue(L, 1);
1866 if (lua_isnil(L, -1)) {
1867 #endif
1868 return luaL_error(L, "Attempt to use a destroyed TLS configuration");
1870 lua_pushvalue(L, 2);
1871 lua_gettable(L, -2);
1872 return 1;
1875 static int moonbr_io_tlsconfgc(lua_State *L) {
1876 struct tls_config *tlsconf;
1877 tlsconf = luaL_checkudata(L, 1, MOONBR_IO_TLSCONF_MT_REGKEY);
1878 #if LUA_VERSION_NUM >= 503
1879 if (lua_getuservalue(L, 1) == LUA_TNIL) return 0;
1880 #else
1881 lua_getuservalue(L, 1);
1882 if (lua_isnil(L, -1)) return 0;
1883 #endif
1884 tls_config_free(tlsconf);
1885 lua_pushnil(L);
1886 lua_setuservalue(L, 1);
1887 return 0;
1890 static int moonbr_io_starttls(lua_State *L) {
1891 moonbr_io_handle_t *handle;
1892 struct tls_config *tlsconf;
1893 const char *mode;
1894 const char *servername;
1895 struct tls *tls, *tls2;
1896 int is_server = 0;
1897 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
1898 if (lua_type(L, 2) == LUA_TTABLE) {
1899 lua_pushcfunction(L, moonbr_io_tlsconf);
1900 lua_pushvalue(L, 2);
1901 lua_call(L, 1, 2);
1902 if (lua_isnil(L, -2)) return 2;
1903 lua_pop(L, 1);
1904 lua_replace(L, 2);
1906 tlsconf = luaL_checkudata(L, 2, MOONBR_IO_TLSCONF_MT_REGKEY);
1907 if (handle->closed) return luaL_error(L, "Attempt to start TLS on a closed I/O handle");
1908 if (handle->finished) return luaL_error(L, "Attempt to start TLS on a finished I/O handle");
1909 #ifdef MOONBR_IO_USE_TLS
1910 if (handle->tls) return luaL_error(L, "Attempt to start TLS twice");
1911 #endif
1912 if (handle->readbufin || handle->writebufin) {
1913 return luaL_error(L, "Attempt to start TLS on an I/O handle with non-empty buffers");
1915 lua_getfield(L, 2, "mode");
1916 mode = lua_tostring(L, -1);
1917 if (mode && !strcmp(mode, "server")) {
1918 lua_pop(L, 1);
1919 tls = tls_server();
1920 is_server = 1;
1921 } else if (mode && !strcmp(mode, "client")) {
1922 lua_pop(L, 1);
1923 servername = luaL_checkstring(L, 3);
1924 tls = tls_client();
1925 } else {
1926 /* shouldn't happen unless table has been modified */
1927 lua_pop(L, 1);
1928 return luaL_error(L, "Field \"mode\" of TLS configuration is neither set to \"server\" nor \"client\"");
1930 if (!tls) {
1931 return luaL_error(L, "Could not allocate memory for TLS context");
1933 if (tls_configure(tls, tlsconf)) goto moonbr_io_starttls_error;
1934 if (is_server) {
1935 if (tls_accept_socket(tls, &tls2, handle->fd)) goto moonbr_io_starttls_error;
1936 handle->servertls = tls;
1937 handle->tls = tls2;
1938 } else {
1939 if (tls_connect_socket(tls, handle->fd, servername)) goto moonbr_io_starttls_error;
1940 handle->tls = tls;
1942 lua_settop(L, 1);
1943 return 1;
1944 moonbr_io_starttls_error:
1945 lua_pushnil(L);
1946 lua_pushstring(L, tls_error(tls));
1947 tls_free(tls);
1948 return 2;
1951 #endif
1953 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1954 {"read", moonbr_io_read},
1955 {"read_nb", moonbr_io_read_nb},
1956 {"read_call", moonbr_io_read_call},
1957 {"read_yield", moonbr_io_read_yield},
1958 {"drain", moonbr_io_drain},
1959 {"drain_nb", moonbr_io_drain_nb},
1960 {"drain_call", moonbr_io_drain_call},
1961 {"drain_yield", moonbr_io_drain_yield},
1962 {"write", moonbr_io_write},
1963 {"write_nb", moonbr_io_write_nb},
1964 {"write_call", moonbr_io_write_call},
1965 {"write_yield", moonbr_io_write_yield},
1966 {"flush", moonbr_io_flush},
1967 {"flush_nb", moonbr_io_flush_nb},
1968 {"flush_call", moonbr_io_flush_call},
1969 {"flush_yield", moonbr_io_flush_yield},
1970 {"finish", moonbr_io_finish},
1971 {"close", moonbr_io_close},
1972 {"reset", moonbr_io_reset},
1973 #ifdef MOONBR_IO_USE_TLS
1974 {"starttls", moonbr_io_starttls},
1975 #endif
1976 {NULL, NULL}
1977 };
1979 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1980 {"__index", moonbr_io_handleindex},
1981 {"__newindex", moonbr_io_handlenewindex},
1982 {"__gc", moonbr_io_handlegc},
1983 {NULL, NULL}
1984 };
1986 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1987 {"accept", moonbr_io_accept},
1988 {"accept_nb", moonbr_io_accept_nb},
1989 {"close", moonbr_io_unlisten},
1990 {NULL, NULL}
1991 };
1993 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1994 {"__gc", moonbr_io_listenergc},
1995 {NULL, NULL}
1996 };
1998 static const struct luaL_Reg moonbr_io_child_methods[] = {
1999 {"kill", moonbr_io_kill},
2000 {"wait", moonbr_io_wait},
2001 {"wait_nb", moonbr_io_wait_nb},
2002 {"wait_call", moonbr_io_wait_call},
2003 {"wait_yield", moonbr_io_wait_yield},
2004 {NULL, NULL}
2005 };
2007 static const struct luaL_Reg moonbr_io_child_metamethods[] = {
2008 {"__index", moonbr_io_childindex},
2009 {"__newindex", moonbr_io_childnewindex},
2010 {"__gc", moonbr_io_childgc},
2011 {NULL, NULL}
2012 };
2014 static const struct luaL_Reg moonbr_io_module_funcs[] = {
2015 {"localconnect", moonbr_io_localconnect},
2016 {"localconnect_nb", moonbr_io_localconnect_nb},
2017 {"tcpconnect", moonbr_io_tcpconnect},
2018 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
2019 {"locallisten", moonbr_io_locallisten},
2020 {"tcplisten", moonbr_io_tcplisten},
2021 {"exec", moonbr_io_exec},
2022 {"poll", moonbr_io_poll},
2023 {"timeref", moonbr_io_timeref},
2024 #ifdef MOONBR_IO_USE_TLS
2025 {"tlsconf", moonbr_io_tlsconf},
2026 #endif
2027 {NULL, NULL}
2028 };
2030 #ifdef MOONBR_IO_USE_TLS
2031 static const struct luaL_Reg moonbr_io_tlsconf_metamethods[] = {
2032 {"__index", moonbr_io_tlsconfindex},
2033 {"__gc", moonbr_io_tlsconfgc},
2034 {NULL, NULL}
2035 };
2036 #endif
2038 int luaopen_moonbridge_io(lua_State *L) {
2040 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
2042 lua_newtable(L); // module
2044 lua_newtable(L); // public metatable
2045 lua_newtable(L); // handle methods
2046 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
2047 lua_pushvalue(L, -1);
2048 lua_setfield(L, -4, "handle_pt");
2049 lua_setfield(L, -2, "__index");
2050 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
2052 lua_newtable(L); // handle metatable
2053 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
2054 lua_pushvalue(L, -1);
2055 lua_setfield(L, -3, "handle_mt");
2056 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
2058 lua_newtable(L); // listener metatable
2059 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
2060 lua_newtable(L); // listener methods
2061 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
2062 lua_pushvalue(L, -1);
2063 lua_setfield(L, -4, "listener_pt");
2064 lua_setfield(L, -2, "__index");
2065 lua_pushvalue(L, -1);
2066 lua_setfield(L, -3, "listener_mt");
2067 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
2069 lua_newtable(L); // child methods
2070 luaL_setfuncs(L, moonbr_io_child_methods, 0);
2071 lua_pushvalue(L, -1);
2072 lua_setfield(L, -3, "child_pt");
2073 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_PT_REGKEY);
2074 lua_newtable(L); // child metatable
2075 luaL_setfuncs(L, moonbr_io_child_metamethods, 0);
2076 lua_pushvalue(L, -1);
2077 lua_setfield(L, -3, "child_mt");
2078 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_CHILD_MT_REGKEY);
2080 #ifdef MOONBR_IO_USE_TLS
2081 if(tls_init()) {
2082 return luaL_error(L, "Could not initialize TLS library");
2084 lua_newtable(L); // tlsconf metatable
2085 luaL_setfuncs(L, moonbr_io_tlsconf_metamethods, 0);
2086 lua_pushvalue(L, -1);
2087 lua_setfield(L, -3, "tlsconf_mt");
2088 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_TLSCONF_MT_REGKEY);
2089 #endif
2091 moonbr_io_pushhandle(L, 0);
2092 lua_setfield(L, -2, "stdin");
2093 moonbr_io_pushhandle(L, 1);
2094 lua_setfield(L, -2, "stdout");
2095 moonbr_io_pushhandle(L, 2);
2096 lua_setfield(L, -2, "stderr");
2098 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
2099 return 1;

Impressum / About Us