moonbridge

view moonbridge_io.c @ 248:4c9102fb77eb

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

Impressum / About Us