moonbridge

view moonbridge_io.c @ 148:c51c38d991df

Reverted previous commit (but changes to Makefile)
author jbe
date Thu May 07 22:22:21 2015 +0200 (2015-05-07)
parents 43387f11b096
children c820130f55d7
line source
2 #if defined(__linux__)
3 #define _GNU_SOURCE
4 #endif
5 #include <stdlib.h>
6 #include <stdint.h>
7 #include <string.h>
8 #include <errno.h>
9 #include <unistd.h>
10 #include <signal.h>
11 #include <fcntl.h>
12 #include <sys/stat.h>
13 #include <sys/socket.h>
14 #include <sys/un.h>
15 #include <netinet/in.h>
16 #include <netinet/tcp.h>
17 #include <sys/select.h>
18 #include <time.h>
19 #include <netdb.h>
20 #include <arpa/inet.h>
22 #include <lua.h>
23 #include <lauxlib.h>
24 #include <lualib.h>
26 #define MOONBR_IO_MAXSTRERRORLEN 80
27 #define MOONBR_IO_READBUFLEN 4096
28 #define MOONBR_IO_WRITEBUFLEN 4096
30 #define MOONBR_IO_LISTEN_BACKLOG 1024
32 #define moonbr_io_errmsg() \
33 char errmsg[MOONBR_IO_MAXSTRERRORLEN]; \
34 strerror_r(errno, errmsg, MOONBR_IO_MAXSTRERRORLEN)
36 #define MOONBR_IO_HANDLE_MT_REGKEY "moonbridge_io_handle"
37 #define MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY "moonbridge_io_handle_public"
38 #define MOONBR_IO_LISTENER_MT_REGKEY "moonbridge_io_listener"
40 char moonbr_io_block_udata = 0;
42 typedef struct {
43 int fd;
44 int issock;
45 sa_family_t addrfam;
46 int finished;
47 int closed;
48 int nonblocking;
49 int nopush;
50 int readerr;
51 int readbufin;
52 int readbufout;
53 int writeerr;
54 size_t writeleft;
55 size_t flushedleft;
56 #if LUA_VERSION_NUM >= 503
57 lua_Integer writeqin;
58 lua_Integer writeqout;
59 #else
60 int writeqin;
61 int writeqout;
62 #endif
63 size_t writeqoff;
64 int writebufin;
65 int writebufout;
66 char readbuf[MOONBR_IO_READBUFLEN];
67 char writebuf[MOONBR_IO_WRITEBUFLEN];
68 } moonbr_io_handle_t;
70 typedef struct {
71 int fd;
72 sa_family_t addrfam;
73 int nonblocking;
74 } moonbr_io_listener_t;
76 static int moonbr_io_yield(lua_State *L) {
77 return lua_yield(L, 0);
78 }
80 #if LUA_VERSION_NUM >= 503
81 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
82 #else
83 static int moonbr_io_cont_returnall(lua_State *L) {
84 #endif
85 return lua_gettop(L);
86 }
88 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
89 static int yieldfunc(lua_State *L) { \
90 int args; \
91 lua_pushcfunction(L, callfunc); \
92 lua_insert(L, 1); \
93 args = lua_gettop(L); \
94 lua_pushcfunction(L, moonbr_io_yield); \
95 lua_insert(L, 3); \
96 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
97 return lua_gettop(L); \
98 }
100 static void moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
101 int flags;
102 if (handle->nonblocking == nonblocking) return;
103 flags = fcntl(handle->fd, F_GETFL, 0);
104 if (flags == -1) {
105 moonbr_io_errmsg();
106 close(handle->fd);
107 handle->fd = -1;
108 handle->closed = 1;
109 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
110 }
111 if (nonblocking) flags |= O_NONBLOCK;
112 else flags &= ~O_NONBLOCK;
113 if (fcntl(handle->fd, F_SETFL, flags) == -1) {
114 moonbr_io_errmsg();
115 close(handle->fd);
116 handle->fd = -1;
117 handle->closed = 1;
118 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
119 }
120 handle->nonblocking = nonblocking;
121 }
123 static void moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
124 struct linger lingerval = { 0, };
125 if (!handle->issock) return;
126 if (timeout >= 0) {
127 lingerval.l_onoff = 1;
128 lingerval.l_linger = timeout;
129 }
130 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) {
131 moonbr_io_errmsg();
132 close(handle->fd);
133 handle->fd = -1;
134 handle->closed = 1;
135 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
136 }
137 }
139 static inline void moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
140 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
141 if (
142 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
143 handle->nopush == nopush
144 ) return;
145 #if defined(TCP_NOPUSH)
146 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) {
147 #elif defined(TCP_CORK)
148 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) {
149 #endif
150 moonbr_io_errmsg();
151 close(handle->fd);
152 handle->fd = -1;
153 handle->closed = 1;
154 #if defined(TCP_NOPUSH)
155 luaL_error(L, "Unexpected error while setting TCP_NOPUSH with setsockopt: %s", errmsg);
156 #elif defined(TCP_CORK)
157 luaL_error(L, "Unexpected error while setting TCP_CORK with setsockopt: %s", errmsg);
158 #endif
159 }
160 handle->nopush = nopush;
161 #else
162 #warning Neither TCP_NOPUSH nor TCP_CORK is available
163 #endif
164 }
166 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
167 moonbr_io_handle_t *handle;
168 lua_Integer maxread;
169 const char *terminatorstr;
170 size_t terminatorlen;
171 char terminator = 0; /* initialize to avoid compiler warning */
172 luaL_Buffer luabuf;
173 size_t luabufcnt = 0;
174 int remaining;
175 char *terminatorpos;
176 ssize_t bytesread;
177 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
178 maxread = luaL_optinteger(L, 2, 0);
179 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
180 if (terminatorlen) {
181 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
182 terminator = terminatorstr[0];
183 }
184 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
185 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
186 if (handle->readerr) {
187 lua_pushnil(L);
188 lua_pushliteral(L, "Previous read error");
189 return 2;
190 }
191 if (handle->fd < 0) {
192 /* fake EOF to simulate shutdown */
193 if (!drain) lua_pushliteral(L, "");
194 else lua_pushinteger(L, 0);
195 lua_pushliteral(L, "eof");
196 return 2;
197 }
198 handle->readerr = 1;
199 moonbr_io_handle_set_nonblocking(L, handle, nonblocking);
200 if (!drain) luaL_buffinit(L, &luabuf);
201 while (1) {
202 remaining = -1;
203 terminatorpos = NULL;
204 if (
205 maxread > 0 &&
206 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
207 ) {
208 remaining = (size_t)maxread - luabufcnt;
209 terminatorpos = memchr(
210 handle->readbuf + handle->readbufout,
211 terminator,
212 remaining
213 );
214 } else if (terminatorlen) {
215 terminatorpos = memchr(
216 handle->readbuf + handle->readbufout,
217 terminator,
218 handle->readbufin - handle->readbufout
219 );
220 }
221 if (terminatorpos) remaining = 1 + (
222 terminatorpos - (handle->readbuf + handle->readbufout)
223 );
224 if (remaining >= 0) {
225 if (!drain) {
226 luaL_addlstring(
227 &luabuf,
228 handle->readbuf + handle->readbufout,
229 remaining
230 );
231 luaL_pushresult(&luabuf);
232 } else {
233 lua_pushinteger(L, luabufcnt + remaining);
234 }
235 if (terminatorpos) lua_pushliteral(L, "term");
236 else lua_pushliteral(L, "maxlen");
237 handle->readbufout += remaining;
238 if (handle->readbufout == handle->readbufin) {
239 handle->readbufin = 0;
240 handle->readbufout = 0;
241 }
242 handle->readerr = 0;
243 return 2;
244 }
245 if (!drain) luaL_addlstring(
246 &luabuf,
247 handle->readbuf + handle->readbufout,
248 handle->readbufin - handle->readbufout
249 );
250 luabufcnt += handle->readbufin - handle->readbufout;
251 handle->readbufout = 0;
252 do {
253 bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
254 } while (bytesread < 0 && (errno == EINTR));
255 if (
256 bytesread == 0 || (
257 nonblocking &&
258 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
259 )
260 ) {
261 handle->readbufin = 0;
262 if (!drain) luaL_pushresult(&luabuf);
263 else lua_pushinteger(L, luabufcnt);
264 if (bytesread == 0) lua_pushliteral(L, "eof");
265 else lua_pushliteral(L, "block");
266 handle->readerr = 0;
267 return 2;
268 }
269 if (bytesread < 0) {
270 moonbr_io_errmsg();
271 lua_pushnil(L);
272 lua_pushstring(L, errmsg);
273 return 2;
274 }
275 handle->readbufin = bytesread;
276 }
277 }
279 static int moonbr_io_read(lua_State *L) {
280 return moonbr_io_read_impl(L, 0, 0);
281 }
283 static int moonbr_io_read_nb(lua_State *L) {
284 return moonbr_io_read_impl(L, 1, 0);
285 }
287 static int moonbr_io_drain(lua_State *L) {
288 return moonbr_io_read_impl(L, 0, 1);
289 }
291 static int moonbr_io_drain_nb(lua_State *L) {
292 return moonbr_io_read_impl(L, 1, 1);
293 }
295 #if LUA_VERSION_NUM >= 503
296 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
297 #else
298 static int moonbr_io_read_cont(lua_State *L) {
299 #endif
300 lua_Integer remaining;
301 size_t len;
302 #if !(LUA_VERSION_NUM >= 503)
303 int ctx = 0;
304 lua_getctx(L, &ctx);
305 #endif
306 remaining = lua_tointeger(L, 3);
307 while (1) {
308 lua_pushcfunction(L, moonbr_io_read_nb);
309 lua_pushvalue(L, 1);
310 lua_pushvalue(L, 3);
311 lua_pushvalue(L, 4);
312 lua_call(L, 3, 2);
313 if (lua_isnil(L, -2)) return 2;
314 lua_insert(L, -2);
315 len = lua_rawlen(L, -1);
316 if (ctx == 0) {
317 lua_replace(L, 5);
318 ctx = 1;
319 } else if (ctx == 1) {
320 lua_pushvalue(L, 5);
321 lua_newtable(L);
322 lua_replace(L, 5);
323 lua_rawseti(L, 5, 2);
324 lua_rawseti(L, 5, 1);
325 ctx = 2;
326 } else {
327 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
328 }
329 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
330 lua_pop(L, 1);
331 if (remaining >= 0 && len) {
332 remaining -= len;
333 lua_pushinteger(L, remaining);
334 lua_replace(L, 3);
335 }
336 lua_pushvalue(L, 2);
337 lua_pushlightuserdata(L, &moonbr_io_block_udata);
338 lua_pushvalue(L, 1);
339 lua_pushliteral(L, "r");
340 lua_callk(L, 3, 0, ctx, moonbr_io_read_cont);
341 }
342 if (ctx == 1) {
343 lua_pushvalue(L, 5);
344 } else {
345 luaL_Buffer buf;
346 lua_Integer i, chunkcount;
347 chunkcount = lua_rawlen(L, 5);
348 luaL_buffinit(L, &buf);
349 for (i=1; i<=chunkcount && i>0; i++) {
350 lua_rawgeti(L, 5, i);
351 luaL_addvalue(&buf);
352 }
353 luaL_pushresult(&buf);
354 }
355 lua_pushvalue(L, -2);
356 return 2;
357 }
359 static int moonbr_io_read_call(lua_State *L) {
360 lua_settop(L, 4);
361 lua_pushnil(L);
362 #if LUA_VERSION_NUM >= 503
363 return moonbr_io_read_cont(L, 0, 0);
364 #else
365 return moonbr_io_read_cont(L);
366 #endif
367 }
369 moonbr_io_yield_wrapper(moonbr_io_read_yield, moonbr_io_read_call);
371 #if LUA_VERSION_NUM >= 503
372 static int moonbr_io_drain_cont(lua_State *L, int status, lua_KContext ctx) {
373 #else
374 static int moonbr_io_drain_cont(lua_State *L) {
375 #endif
376 lua_Integer remaining, len;
377 size_t totallen = 0;
378 #if !(LUA_VERSION_NUM >= 503)
379 int ctx = 0;
380 lua_getctx(L, &ctx);
381 #endif
382 remaining = lua_tointeger(L, 3);
383 while (1) {
384 lua_pushcfunction(L, moonbr_io_drain_nb);
385 lua_pushvalue(L, 1);
386 lua_pushvalue(L, 3);
387 lua_pushvalue(L, 4);
388 lua_call(L, 3, 2);
389 if (lua_isnil(L, -2)) return 2;
390 lua_insert(L, -2);
391 len = lua_tointeger(L, -1);
392 lua_pop(L, 1);
393 totallen += len;
394 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
395 lua_pop(L, 1);
396 if (remaining >= 0 && len) {
397 remaining -= len;
398 lua_pushinteger(L, remaining);
399 lua_replace(L, 3);
400 }
401 lua_pushvalue(L, 2);
402 lua_pushlightuserdata(L, &moonbr_io_block_udata);
403 lua_pushvalue(L, 1);
404 lua_pushliteral(L, "r");
405 lua_callk(L, 3, 0, ctx, moonbr_io_drain_cont);
406 }
407 lua_pushinteger(L, totallen);
408 lua_pushvalue(L, -2);
409 return 2;
410 }
412 static int moonbr_io_drain_call(lua_State *L) {
413 #if LUA_VERSION_NUM >= 503
414 return moonbr_io_drain_cont(L, 0, 0);
415 #else
416 return moonbr_io_drain_cont(L);
417 #endif
418 }
420 moonbr_io_yield_wrapper(moonbr_io_drain_yield, moonbr_io_drain_call);
422 static int moonbr_io_write_impl(lua_State *L, int nonblocking, int flush) {
423 moonbr_io_handle_t *handle;
424 int i, top;
425 const char *str;
426 size_t strlen;
427 ssize_t written;
428 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
429 if (handle->closed) luaL_error(L, "Attempt to write to a closed I/O handle");
430 if (handle->finished) luaL_error(L, "Attempt to write to a finished I/O handle");
431 if (handle->writeerr) {
432 lua_pushnil(L);
433 lua_pushliteral(L, "Previous write error");
434 return 2;
435 }
436 handle->writeerr = 1;
437 moonbr_io_handle_set_nonblocking(L, handle, nonblocking);
438 top = lua_gettop(L);
439 lua_getuservalue(L, 1);
440 lua_getfield(L, -1, "writequeue");
441 for (i=2; i<=top; i++) {
442 luaL_checklstring(L, i, &strlen);
443 lua_pushvalue(L, i);
444 lua_rawseti(L, -2, handle->writeqin++);
445 handle->writeleft += strlen;
446 }
447 if (flush) handle->flushedleft = handle->writeleft;
448 while (handle->writeqout != handle->writeqin) {
449 lua_rawgeti(L, -1, handle->writeqout);
450 str = lua_tolstring(L, -1, &strlen);
451 while (handle->writeqoff < strlen) {
452 if (
453 strlen - handle->writeqoff <
454 MOONBR_IO_WRITEBUFLEN - handle->writebufin
455 ) {
456 memcpy(
457 handle->writebuf + handle->writebufin,
458 str + handle->writeqoff,
459 strlen - handle->writeqoff
460 );
461 handle->writebufin += strlen - handle->writeqoff;
462 break;
463 } else {
464 memcpy(
465 handle->writebuf + handle->writebufin,
466 str + handle->writeqoff,
467 MOONBR_IO_WRITEBUFLEN - handle->writebufin
468 );
469 handle->writeqoff += MOONBR_IO_WRITEBUFLEN - handle->writebufin;
470 while (handle->writebufout < MOONBR_IO_WRITEBUFLEN) {
471 moonbr_io_handle_set_nopush(L, handle, 1);
472 written = write(
473 handle->fd,
474 handle->writebuf + handle->writebufout,
475 MOONBR_IO_WRITEBUFLEN - handle->writebufout
476 );
477 if (written < 0) {
478 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
479 goto moonbr_io_write_impl_block;
480 } else if (errno != EINTR) {
481 moonbr_io_errmsg();
482 lua_pushnil(L);
483 lua_pushstring(L, errmsg);
484 return 2;
485 }
486 } else {
487 handle->writebufout += written;
488 handle->writeleft -= written;
489 if (handle->flushedleft) {
490 if (written >= handle->flushedleft) {
491 handle->flushedleft = 0;
492 moonbr_io_handle_set_nopush(L, handle, 0);
493 } else {
494 handle->flushedleft -= written;
495 }
496 }
497 }
498 }
499 handle->writebufin = 0;
500 handle->writebufout = 0;
501 }
502 }
503 handle->writeqoff = 0;
504 lua_pop(L, 1);
505 lua_pushnil(L);
506 lua_rawseti(L, -2, handle->writeqout++);
507 }
508 while (handle->flushedleft) {
509 moonbr_io_handle_set_nopush(L, handle, 1);
510 written = write(
511 handle->fd,
512 handle->writebuf + handle->writebufout,
513 handle->writebufin - handle->writebufout
514 );
515 if (written < 0) {
516 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
517 goto moonbr_io_write_impl_block;
518 } else if (errno != EINTR) {
519 moonbr_io_errmsg();
520 lua_pushnil(L);
521 lua_pushstring(L, errmsg);
522 return 2;
523 }
524 } else {
525 handle->writebufout += written;
526 handle->writeleft -= written;
527 if (handle->flushedleft) {
528 if (written >= handle->flushedleft) {
529 handle->flushedleft = 0;
530 moonbr_io_handle_set_nopush(L, handle, 0);
531 } else {
532 handle->flushedleft -= written;
533 }
534 }
535 }
536 }
537 if (handle->writebufout == handle->writebufin) {
538 handle->writebufin = 0;
539 handle->writebufout = 0;
540 }
541 if (nonblocking) lua_pushinteger(L, 0);
542 else lua_pushvalue(L, 1);
543 handle->writeerr = 0;
544 return 1;
545 moonbr_io_write_impl_block:
546 lua_pushinteger(L, handle->writeleft);
547 handle->writeerr = 0;
548 return 1;
549 }
551 static int moonbr_io_write(lua_State *L) {
552 return moonbr_io_write_impl(L, 0, 0);
553 }
555 static int moonbr_io_write_nb(lua_State *L) {
556 return moonbr_io_write_impl(L, 1, 0);
557 }
559 static int moonbr_io_flush(lua_State *L) {
560 return moonbr_io_write_impl(L, 0, 1);
561 }
563 static int moonbr_io_flush_nb(lua_State *L) {
564 return moonbr_io_write_impl(L, 1, 1);
565 }
567 #if LUA_VERSION_NUM >= 503
568 static int moonbr_io_write_cont(lua_State *L, int status, lua_KContext ctx) {
569 #else
570 static int moonbr_io_write_cont(lua_State *L) {
571 #endif
572 while (1) {
573 lua_pushcfunction(L, moonbr_io_write_nb);
574 lua_pushvalue(L, 1);
575 lua_call(L, 1, 2);
576 if (lua_isnil(L, -2)) return 2;
577 if (!lua_tointeger(L, -2)) {
578 lua_pushvalue(L, 1);
579 return 1;
580 }
581 lua_pop(L, 2);
582 lua_pushvalue(L, 2);
583 lua_pushlightuserdata(L, &moonbr_io_block_udata);
584 lua_pushvalue(L, 1);
585 lua_pushliteral(L, "w");
586 lua_callk(L, 3, 0, 0, moonbr_io_write_cont);
587 }
588 }
590 static int moonbr_io_write_call(lua_State *L) {
591 lua_pushcfunction(L, moonbr_io_write_nb);
592 lua_insert(L, 3);
593 lua_pushvalue(L, 1);
594 lua_insert(L, 4);
595 lua_call(L, lua_gettop(L) - 3, 2);
596 if (lua_isnil(L, -2)) return 2;
597 if (!lua_tointeger(L, -2)) {
598 lua_pushvalue(L, 1);
599 return 1;
600 }
601 #if LUA_VERSION_NUM >= 503
602 return moonbr_io_write_cont(L, 0, 0);
603 #else
604 return moonbr_io_write_cont(L);
605 #endif
606 }
608 moonbr_io_yield_wrapper(moonbr_io_write_yield, moonbr_io_write_call);
610 static int moonbr_io_flush_call(lua_State *L) {
611 lua_pushcfunction(L, moonbr_io_flush_nb);
612 lua_insert(L, 3);
613 lua_pushvalue(L, 1);
614 lua_insert(L, 4);
615 lua_call(L, lua_gettop(L) - 3, 2);
616 if (lua_isnil(L, -2)) return 2;
617 if (!lua_tointeger(L, -2)) {
618 lua_pushvalue(L, 1);
619 return 1;
620 }
621 #if LUA_VERSION_NUM >= 503
622 return moonbr_io_write_cont(L, 0, 0);
623 #else
624 return moonbr_io_write_cont(L);
625 #endif
626 }
628 moonbr_io_yield_wrapper(moonbr_io_flush_yield, moonbr_io_flush_call);
630 static int moonbr_io_finish(lua_State *L) {
631 moonbr_io_handle_t *handle;
632 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
633 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
634 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
635 if (handle->writeleft) {
636 lua_pushcfunction(L, moonbr_io_flush);
637 lua_pushvalue(L, 1);
638 if (lua_pcall(L, 1, 2, 0)) {
639 handle->finished = 1;
640 lua_error(L);
641 }
642 if (!lua_toboolean(L, -2)) {
643 handle->finished = 1;
644 return 2;
645 }
646 }
647 handle->finished = 1;
648 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
649 if (shutdown(handle->fd, SHUT_WR)) {
650 moonbr_io_errmsg();
651 lua_pushnil(L);
652 lua_pushstring(L, errmsg);
653 return 2;
654 }
655 } else {
656 if (close(handle->fd)) {
657 moonbr_io_errmsg();
658 handle->fd = -1;
659 lua_pushnil(L);
660 lua_pushstring(L, errmsg);
661 return 2;
662 }
663 handle->fd = -1; /* fake EOF on read */
664 }
665 lua_pushboolean(L, 1);
666 return 1;
667 }
669 static int moonbr_io_close_impl(lua_State *L, int reset) {
670 moonbr_io_handle_t *handle;
671 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
672 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
673 if (!reset) {
674 if (handle->writeleft) {
675 lua_pushcfunction(L, moonbr_io_flush);
676 lua_pushvalue(L, 1);
677 if (lua_pcall(L, 1, 2, 0)) {
678 handle->closed = 1;
679 close(handle->fd);
680 handle->fd = -1;
681 lua_error(L);
682 }
683 handle->closed = 1;
684 if (!lua_toboolean(L, -2)) {
685 close(handle->fd);
686 handle->fd = -1;
687 return 2;
688 }
689 } else {
690 handle->closed = 1;
691 moonbr_io_handle_set_linger(L, handle, -1);
692 }
693 } else {
694 handle->closed = 1;
695 }
696 if (handle->fd >= 0) {
697 if (close(handle->fd)) {
698 moonbr_io_errmsg();
699 handle->fd = -1;
700 lua_pushnil(L);
701 lua_pushstring(L, errmsg);
702 return 2;
703 }
704 handle->fd = -1;
705 }
706 lua_pushboolean(L, 1);
707 return 1;
709 }
711 static int moonbr_io_close(lua_State *L) {
712 return moonbr_io_close_impl(L, 0);
713 }
715 static int moonbr_io_reset(lua_State *L) {
716 return moonbr_io_close_impl(L, 1);
717 }
719 static int moonbr_io_handlegc(lua_State *L) {
720 moonbr_io_handle_t *handle;
721 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
722 if (handle->fd >= 0) {
723 lua_pushcfunction(L, moonbr_io_close);
724 lua_pushvalue(L, 1);
725 lua_pushinteger(L, 0);
726 lua_call(L, 2, 0);
727 }
728 return 0;
729 }
731 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
732 moonbr_io_handle_t *handle;
733 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
734 if (!handle->closed) {
735 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
736 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
737 lua_call(L, 1, 0);
738 }
739 }
741 void moonbr_io_pushhandle(lua_State *L, int fd) {
742 moonbr_io_handle_t *handle;
743 struct sockaddr addr;
744 socklen_t addrlen;
745 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
746 handle->fd = fd;
747 addrlen = sizeof(addr);
748 if (getsockname(fd, &addr, &addrlen)) {
749 if (errno != ENOTSOCK) {
750 moonbr_io_errmsg();
751 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
752 }
753 handle->issock = 0;
754 } else {
755 handle->issock = 1;
756 handle->addrfam = addr.sa_family;
757 }
758 handle->finished = 0;
759 handle->closed = 0;
760 handle->nonblocking = -1;
761 handle->nopush = -1;
762 handle->readerr = 0;
763 handle->readbufin = 0;
764 handle->readbufout = 0;
765 handle->writeerr = 0;
766 handle->writeleft = 0;
767 handle->flushedleft = 0;
768 handle->writeqin = 0;
769 handle->writeqout = 0;
770 handle->writeqoff = 0;
771 handle->writebufin = 0;
772 handle->writebufout = 0;
773 moonbr_io_handle_set_linger(L, handle, 0);
774 luaL_getmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
775 lua_setmetatable(L, -2);
776 lua_newtable(L); // uservalue
777 lua_newtable(L);
778 lua_setfield(L, -2, "writequeue");
779 lua_newtable(L); // public
780 if (handle->addrfam == AF_INET6) {
781 struct sockaddr_in6 addr_in6;
782 char addrstrbuf[INET6_ADDRSTRLEN];
783 const char *addrstr;
784 addrlen = sizeof(addr_in6);
785 if (getsockname(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
786 moonbr_io_errmsg();
787 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
788 }
789 if (addrlen > sizeof(addr_in6)) {
790 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
791 }
792 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
793 if (!addrstr) {
794 moonbr_io_errmsg();
795 luaL_error(L, "Could not format local IP address: %s", errmsg);
796 } else {
797 lua_pushstring(L, addrstr);
798 lua_setfield(L, -2, "local_ip6");
799 }
800 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
801 lua_setfield(L, -2, "local_tcpport");
802 if (getpeername(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
803 moonbr_io_errmsg();
804 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
805 }
806 if (addrlen > sizeof(addr_in6)) {
807 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
808 }
809 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
810 if (!addrstr) {
811 moonbr_io_errmsg();
812 luaL_error(L, "Could not format remote IP address: %s", errmsg);
813 } else {
814 lua_pushstring(L, addrstr);
815 lua_setfield(L, -2, "remote_ip6");
816 }
817 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
818 lua_setfield(L, -2, "remote_tcpport");
819 } else if (handle->addrfam == AF_INET) {
820 struct sockaddr_in addr_in;
821 char addrstrbuf[INET_ADDRSTRLEN];
822 const char *addrstr;
823 addrlen = sizeof(addr_in);
824 if (getsockname(fd, (struct sockaddr *)&addr_in, &addrlen)) {
825 moonbr_io_errmsg();
826 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
827 }
828 if (addrlen > sizeof(addr_in)) {
829 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
830 }
831 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
832 if (!addrstr) {
833 moonbr_io_errmsg();
834 luaL_error(L, "Could not format local IP address: %s", errmsg);
835 } else {
836 lua_pushstring(L, addrstr);
837 lua_setfield(L, -2, "local_ip4");
838 }
839 lua_pushinteger(L, ntohs(addr_in.sin_port));
840 lua_setfield(L, -2, "local_tcpport");
841 if (getpeername(fd, (struct sockaddr *)&addr_in, &addrlen)) {
842 moonbr_io_errmsg();
843 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
844 }
845 if (addrlen > sizeof(addr_in)) {
846 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
847 }
848 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
849 if (!addrstr) {
850 moonbr_io_errmsg();
851 luaL_error(L, "Could not format remote IP address: %s", errmsg);
852 } else {
853 lua_pushstring(L, addrstr);
854 lua_setfield(L, -2, "remote_ip4");
855 }
856 lua_pushinteger(L, ntohs(addr_in.sin_port));
857 lua_setfield(L, -2, "remote_tcpport");
858 }
859 luaL_getmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
860 lua_setmetatable(L, -2);
861 lua_setfield(L, -2, "public");
862 lua_setuservalue(L, -2);
863 }
865 static int moonbr_io_handleindex(lua_State *L) {
866 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
867 lua_getuservalue(L, 1);
868 lua_getfield(L, -1, "public");
869 lua_pushvalue(L, 2);
870 lua_gettable(L, -2);
871 return 1;
872 }
874 static int moonbr_io_handlenewindex(lua_State *L) {
875 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
876 lua_getuservalue(L, 1);
877 lua_getfield(L, -1, "public");
878 lua_pushvalue(L, 2);
879 lua_pushvalue(L, 3);
880 lua_settable(L, -3);
881 return 0;
882 }
884 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
885 const char *path;
886 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
887 const int path_maxlen = sizeof(struct sockaddr_un) - (
888 (void *)sockaddr.sun_path - (void *)&sockaddr
889 ) - 1; /* one byte for termination */
890 int sock;
891 path = luaL_checkstring(L, 1);
892 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
893 strcpy(sockaddr.sun_path, path);
894 sock = socket(
895 PF_LOCAL,
896 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
897 0
898 );
899 if (sock < 0) {
900 moonbr_io_errmsg();
901 lua_pushnil(L);
902 lua_pushstring(L, errmsg);
903 return 2;
904 }
905 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
906 if (!nonblocking && errno == EINTR) {
907 moonbr_io_errmsg();
908 close(sock);
909 lua_pushnil(L);
910 lua_pushstring(L, errmsg);
911 return 2;
912 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
913 moonbr_io_errmsg();
914 lua_pushnil(L);
915 lua_pushstring(L, errmsg);
916 return 2;
917 }
918 }
919 moonbr_io_pushhandle(L, sock);
920 return 1;
921 }
923 static int moonbr_io_localconnect(lua_State *L) {
924 return moonbr_io_localconnect_impl(L, 0);
925 }
927 static int moonbr_io_localconnect_nb(lua_State *L) {
928 return moonbr_io_localconnect_impl(L, 1);
929 }
931 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
932 const char *host, *port;
933 struct addrinfo hints = { 0, };
934 struct addrinfo *res, *addrinfo;
935 int errcode;
936 int sock;
937 host = luaL_checkstring(L, 1);
938 port = luaL_checkstring(L, 2);
939 hints.ai_family = AF_UNSPEC;
940 hints.ai_socktype = SOCK_STREAM;
941 hints.ai_protocol = IPPROTO_TCP;
942 hints.ai_flags = AI_ADDRCONFIG;
943 errcode = getaddrinfo(host, port, &hints, &res);
944 if (errcode) {
945 freeaddrinfo(res);
946 if (errcode == EAI_SYSTEM) {
947 moonbr_io_errmsg();
948 lua_pushnil(L);
949 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
950 } else {
951 lua_pushnil(L);
952 lua_pushstring(L, gai_strerror(errcode));
953 }
954 return 2;
955 }
956 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
957 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
958 }
959 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
960 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
961 }
962 addrinfo = res;
963 moonbr_io_tcpconnect_found:
964 sock = socket(
965 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
966 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
967 addrinfo->ai_protocol
968 );
969 if (sock < 0) {
970 moonbr_io_errmsg();
971 freeaddrinfo(res);
972 lua_pushnil(L);
973 lua_pushstring(L, errmsg);
974 return 2;
975 }
976 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
977 freeaddrinfo(res);
978 if (!nonblocking && errno == EINTR) {
979 moonbr_io_errmsg();
980 close(sock);
981 lua_pushnil(L);
982 lua_pushstring(L, errmsg);
983 return 2;
984 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
985 moonbr_io_errmsg();
986 lua_pushnil(L);
987 lua_pushstring(L, errmsg);
988 return 2;
989 }
990 } else {
991 freeaddrinfo(res);
992 }
993 moonbr_io_pushhandle(L, sock);
994 return 1;
995 }
997 static int moonbr_io_tcpconnect(lua_State *L) {
998 return moonbr_io_tcpconnect_impl(L, 0);
999 }
1001 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1002 return moonbr_io_tcpconnect_impl(L, 1);
1005 static int moonbr_io_locallisten(lua_State *L) {
1006 moonbr_io_listener_t *listener;
1007 const char *path;
1008 struct stat sb;
1009 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1010 const int path_maxlen = sizeof(struct sockaddr_un) - (
1011 (void *)sockaddr.sun_path - (void *)&sockaddr
1012 ) - 1; /* one byte for termination */
1013 int sock;
1014 path = luaL_checkstring(L, 1);
1015 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1016 strcpy(sockaddr.sun_path, path);
1017 if (stat(path, &sb) == 0) {
1018 if (S_ISSOCK(sb.st_mode)) unlink(path);
1020 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1021 listener->fd = -1;
1022 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1023 sock = socket(
1024 PF_LOCAL,
1025 SOCK_STREAM | SOCK_CLOEXEC,
1027 );
1028 if (sock < 0) {
1029 moonbr_io_errmsg();
1030 lua_pushnil(L);
1031 lua_pushstring(L, errmsg);
1032 return 2;
1034 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1035 moonbr_io_errmsg();
1036 close(sock);
1037 lua_pushnil(L);
1038 lua_pushstring(L, errmsg);
1039 return 2;
1041 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1042 moonbr_io_errmsg();
1043 close(sock);
1044 lua_pushnil(L);
1045 lua_pushstring(L, errmsg);
1046 return 2;
1048 listener->fd = sock;
1049 listener->addrfam = AF_LOCAL;
1050 listener->nonblocking = -1;
1051 return 1;
1054 static int moonbr_io_tcplisten(lua_State *L) {
1055 moonbr_io_listener_t *listener;
1056 const char *host, *port;
1057 struct addrinfo hints = { 0, };
1058 struct addrinfo *res, *addrinfo;
1059 int errcode;
1060 int sock;
1061 host = luaL_optstring(L, 1, NULL);
1062 port = luaL_checkstring(L, 2);
1063 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1064 listener->fd = -1;
1065 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1066 hints.ai_family = AF_UNSPEC;
1067 hints.ai_socktype = SOCK_STREAM;
1068 hints.ai_protocol = IPPROTO_TCP;
1069 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1070 errcode = getaddrinfo(host, port, &hints, &res);
1071 if (errcode) {
1072 freeaddrinfo(res);
1073 if (errcode == EAI_SYSTEM) {
1074 moonbr_io_errmsg();
1075 lua_pushnil(L);
1076 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1077 } else {
1078 lua_pushnil(L);
1079 lua_pushstring(L, gai_strerror(errcode));
1081 return 2;
1083 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1084 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1086 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1087 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1089 addrinfo = res;
1090 moonbr_io_tcpconnect_found:
1091 listener->addrfam = addrinfo->ai_family;
1092 sock = socket(
1093 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1094 addrinfo->ai_socktype | SOCK_CLOEXEC,
1095 addrinfo->ai_protocol
1096 );
1097 if (sock < 0) {
1098 moonbr_io_errmsg();
1099 freeaddrinfo(res);
1100 lua_pushnil(L);
1101 lua_pushstring(L, errmsg);
1102 return 2;
1105 static const int reuseval = 1;
1106 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1107 moonbr_io_errmsg();
1108 freeaddrinfo(res);
1109 close(sock);
1110 lua_pushnil(L);
1111 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1112 return 2;
1115 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1116 moonbr_io_errmsg();
1117 freeaddrinfo(res);
1118 close(sock);
1119 lua_pushnil(L);
1120 lua_pushstring(L, errmsg);
1121 return 2;
1123 freeaddrinfo(res);
1124 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1125 moonbr_io_errmsg();
1126 close(sock);
1127 lua_pushnil(L);
1128 lua_pushstring(L, errmsg);
1129 return 2;
1131 listener->fd = sock;
1132 listener->nonblocking = -1;
1133 return 1;
1136 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1137 moonbr_io_listener_t *listener;
1138 int fd;
1139 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1140 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1141 if (listener->nonblocking != nonblocking) {
1142 int flags;
1143 flags = fcntl(listener->fd, F_GETFL, 0);
1144 if (flags == -1) {
1145 moonbr_io_errmsg();
1146 close(listener->fd);
1147 listener->fd = -1;
1148 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1150 if (nonblocking) flags |= O_NONBLOCK;
1151 else flags &= ~O_NONBLOCK;
1152 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1153 moonbr_io_errmsg();
1154 close(listener->fd);
1155 listener->fd = -1;
1156 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1158 listener->nonblocking = nonblocking;
1160 while (1) {
1161 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1162 if (fd < 0) {
1163 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1164 lua_pushboolean(L, 0);
1165 lua_pushliteral(L, "No incoming connection pending");
1166 return 2;
1167 } else if (errno != EINTR) {
1168 moonbr_io_errmsg();
1169 lua_pushnil(L);
1170 lua_pushstring(L, errmsg);
1171 return 2;
1173 } else {
1174 moonbr_io_pushhandle(L, fd);
1175 return 1;
1180 static int moonbr_io_accept(lua_State *L) {
1181 return moonbr_io_accept_impl(L, 0);
1184 static int moonbr_io_accept_nb(lua_State *L) {
1185 return moonbr_io_accept_impl(L, 1);
1188 static int moonbr_io_unlisten(lua_State *L) {
1189 moonbr_io_listener_t *listener;
1190 struct sockaddr_un addr;
1191 socklen_t addrlen;
1192 struct stat sb;
1193 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1194 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1195 addrlen = sizeof(addr);
1196 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1197 if (close(listener->fd)) {
1198 moonbr_io_errmsg();
1199 listener->fd = -1;
1200 if (addrlen && addrlen <= sizeof(addr)) {
1201 if (stat(addr.sun_path, &sb) == 0) {
1202 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1205 lua_pushnil(L);
1206 lua_pushstring(L, errmsg);
1207 return 2;
1209 listener->fd = -1;
1210 if (addrlen && addrlen <= sizeof(addr)) {
1211 if (stat(addr.sun_path, &sb) == 0) {
1212 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1215 lua_pushboolean(L, 1);
1216 return 1;
1219 static int moonbr_io_listenergc(lua_State *L) {
1220 moonbr_io_listener_t *listener;
1221 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1222 if (listener->fd >= 0) close(listener->fd);
1223 listener->fd = -1;
1224 return 0;
1227 static int moonbr_io_poll(lua_State *L) {
1228 moonbr_io_handle_t *handle;
1229 moonbr_io_listener_t *listener;
1230 int fd, isnum;
1231 int nfds = 0;
1232 fd_set readfds, writefds, exceptfds;
1233 struct timeval timeout = {0, };
1234 int status;
1235 FD_ZERO(&readfds);
1236 FD_ZERO(&writefds);
1237 FD_ZERO(&exceptfds);
1238 if (!lua_isnoneornil(L, 1)) {
1239 luaL_checktype(L, 1, LUA_TTABLE);
1240 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1241 if (lua_toboolean(L, -1)) {
1242 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1243 if (handle) {
1244 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1245 fd = handle->fd;
1246 if (
1247 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1248 handle->readbufin != handle->readbufout /* data pending in buffer */
1249 ) {
1250 lua_pushboolean(L, 1);
1251 return 1;
1253 } else {
1254 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1255 if (listener) {
1256 fd = listener->fd;
1257 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1258 } else {
1259 fd = lua_tointegerx(L, -2, &isnum);
1260 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1263 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1264 FD_SET(fd, &readfds);
1265 if (fd+1 > nfds) nfds = fd+1;
1269 if (!lua_isnoneornil(L, 2)) {
1270 luaL_checktype(L, 2, LUA_TTABLE);
1271 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1272 if (lua_toboolean(L, -1)) {
1273 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1274 if (handle) {
1275 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1276 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1277 fd = handle->fd;
1278 } else {
1279 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1280 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1281 fd = lua_tointegerx(L, -2, &isnum);
1282 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1284 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1285 FD_SET(fd, &writefds);
1286 if (fd+1 > nfds) nfds = fd+1;
1290 if (!lua_isnoneornil(L, 3)) {
1291 lua_Number n;
1292 n = lua_tonumberx(L, 3, &isnum);
1293 if (isnum && n<0) {
1294 lua_pushboolean(L, 0);
1295 lua_pushliteral(L, "Negative timeout");
1296 return 2;
1297 } else if (isnum && n>=0 && n<100000000) {
1298 timeout.tv_sec = n;
1299 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1300 } else {
1301 luaL_argcheck(L, 0, 3, "not a valid timeout");
1303 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1304 } else {
1305 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1307 if (status == -1) {
1308 if (errno == EINTR) {
1309 lua_pushnil(L);
1310 lua_pushliteral(L, "Signal received while polling file descriptors");
1311 return 2;
1312 } else {
1313 moonbr_io_errmsg();
1314 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1316 } else if (status == 0) {
1317 lua_pushboolean(L, 0);
1318 lua_pushliteral(L, "Timeout while polling file descriptors");
1319 return 2;
1320 } else {
1321 lua_pushboolean(L, 1);
1322 return 1;
1326 static int moonbr_io_timeref(lua_State *L) {
1327 lua_Number sub;
1328 struct timespec tp;
1329 sub = luaL_optnumber(L, 1, 0);
1330 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1331 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1333 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1334 return 1;
1337 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1338 {"read", moonbr_io_read},
1339 {"read_nb", moonbr_io_read_nb},
1340 {"read_call", moonbr_io_read_call},
1341 {"read_yield", moonbr_io_read_yield},
1342 {"drain", moonbr_io_drain},
1343 {"drain_nb", moonbr_io_drain_nb},
1344 {"drain_call", moonbr_io_drain_call},
1345 {"drain_yield", moonbr_io_drain_yield},
1346 {"write", moonbr_io_write},
1347 {"write_nb", moonbr_io_write_nb},
1348 {"write_call", moonbr_io_write_call},
1349 {"write_yield", moonbr_io_write_yield},
1350 {"flush", moonbr_io_flush},
1351 {"flush_nb", moonbr_io_flush_nb},
1352 {"flush_call", moonbr_io_flush_call},
1353 {"flush_yield", moonbr_io_flush_yield},
1354 {"finish", moonbr_io_finish},
1355 {"close", moonbr_io_close},
1356 {"reset", moonbr_io_reset},
1357 {NULL, NULL}
1358 };
1360 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1361 {"__index", moonbr_io_handleindex},
1362 {"__newindex", moonbr_io_handlenewindex},
1363 {"__gc", moonbr_io_handlegc},
1364 {NULL, NULL}
1365 };
1367 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1368 {"accept", moonbr_io_accept},
1369 {"accept_nb", moonbr_io_accept_nb},
1370 {"close", moonbr_io_unlisten},
1371 {NULL, NULL}
1372 };
1374 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1375 {"__gc", moonbr_io_listenergc},
1376 {NULL, NULL}
1377 };
1379 static const struct luaL_Reg moonbr_io_module_funcs[] = {
1380 {"localconnect", moonbr_io_localconnect},
1381 {"localconnect_nb", moonbr_io_localconnect_nb},
1382 {"tcpconnect", moonbr_io_tcpconnect},
1383 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
1384 {"locallisten", moonbr_io_locallisten},
1385 {"tcplisten", moonbr_io_tcplisten},
1386 {"poll", moonbr_io_poll},
1387 {"timeref", moonbr_io_timeref},
1388 {NULL, NULL}
1389 };
1391 int luaopen_moonbridge_io(lua_State *L) {
1393 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
1395 lua_newtable(L); // module
1397 lua_pushlightuserdata(L, &moonbr_io_block_udata);
1398 lua_setfield(L, -2, "block");
1400 lua_newtable(L); // public metatable
1401 lua_newtable(L); // handle methods
1402 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
1403 lua_pushvalue(L, -1);
1404 lua_setfield(L, -4, "handle_pt");
1405 lua_setfield(L, -2, "__index");
1406 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1408 lua_newtable(L); // handle metatable
1409 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
1410 lua_pushvalue(L, -1);
1411 lua_setfield(L, -3, "handle_mt");
1412 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
1414 lua_newtable(L); // listener metatable
1415 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
1416 lua_newtable(L); // listener methods
1417 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
1418 lua_pushvalue(L, -1);
1419 lua_setfield(L, -4, "listener_pt");
1420 lua_setfield(L, -2, "__index");
1421 lua_pushvalue(L, -1);
1422 lua_setfield(L, -3, "listener_mt");
1423 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
1425 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
1426 return 1;

Impressum / About Us