moonbridge
view moonbridge_io.c @ 147:43387f11b096
Do not pass moonbridge_io.block when invoking callback passed to _call I/O methods but only include it for _yield I/O methods
author | jbe |
---|---|
date | Thu May 07 22:16:15 2015 +0200 (2015-05-07) |
parents | 6dfe5b424b18 |
children | c51c38d991df |
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_block(lua_State *L) {
77 lua_pushlightuserdata(L, &moonbr_io_block_udata);
78 lua_insert(L, 1);
79 return lua_yield(L, lua_gettop(L));
80 }
82 #if LUA_VERSION_NUM >= 503
83 static int moonbr_io_cont_returnall(lua_State *L, int status, lua_KContext ctx) {
84 #else
85 static int moonbr_io_cont_returnall(lua_State *L) {
86 #endif
87 return lua_gettop(L);
88 }
90 #define moonbr_io_yield_wrapper(yieldfunc, callfunc) \
91 static int yieldfunc(lua_State *L) { \
92 int args; \
93 lua_pushcfunction(L, callfunc); \
94 lua_insert(L, 1); \
95 args = lua_gettop(L); \
96 lua_pushcfunction(L, moonbr_io_yield_block); \
97 lua_insert(L, 3); \
98 lua_callk(L, args, LUA_MULTRET, 0, moonbr_io_cont_returnall); \
99 return lua_gettop(L); \
100 }
102 static void moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
103 int flags;
104 if (handle->nonblocking == nonblocking) return;
105 flags = fcntl(handle->fd, F_GETFL, 0);
106 if (flags == -1) {
107 moonbr_io_errmsg();
108 close(handle->fd);
109 handle->fd = -1;
110 handle->closed = 1;
111 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
112 }
113 if (nonblocking) flags |= O_NONBLOCK;
114 else flags &= ~O_NONBLOCK;
115 if (fcntl(handle->fd, F_SETFL, flags) == -1) {
116 moonbr_io_errmsg();
117 close(handle->fd);
118 handle->fd = -1;
119 handle->closed = 1;
120 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
121 }
122 handle->nonblocking = nonblocking;
123 }
125 static void moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
126 struct linger lingerval = { 0, };
127 if (!handle->issock) return;
128 if (timeout >= 0) {
129 lingerval.l_onoff = 1;
130 lingerval.l_linger = timeout;
131 }
132 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) {
133 moonbr_io_errmsg();
134 close(handle->fd);
135 handle->fd = -1;
136 handle->closed = 1;
137 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
138 }
139 }
141 static inline void moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
142 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
143 if (
144 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
145 handle->nopush == nopush
146 ) return;
147 #if defined(TCP_NOPUSH)
148 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) {
149 #elif defined(TCP_CORK)
150 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) {
151 #endif
152 moonbr_io_errmsg();
153 close(handle->fd);
154 handle->fd = -1;
155 handle->closed = 1;
156 #if defined(TCP_NOPUSH)
157 luaL_error(L, "Unexpected error while setting TCP_NOPUSH with setsockopt: %s", errmsg);
158 #elif defined(TCP_CORK)
159 luaL_error(L, "Unexpected error while setting TCP_CORK with setsockopt: %s", errmsg);
160 #endif
161 }
162 handle->nopush = nopush;
163 #else
164 #warning Neither TCP_NOPUSH nor TCP_CORK is available
165 #endif
166 }
168 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
169 moonbr_io_handle_t *handle;
170 lua_Integer maxread;
171 const char *terminatorstr;
172 size_t terminatorlen;
173 char terminator = 0; /* initialize to avoid compiler warning */
174 luaL_Buffer luabuf;
175 size_t luabufcnt = 0;
176 int remaining;
177 char *terminatorpos;
178 ssize_t bytesread;
179 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
180 maxread = luaL_optinteger(L, 2, 0);
181 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
182 if (terminatorlen) {
183 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
184 terminator = terminatorstr[0];
185 }
186 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
187 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
188 if (handle->readerr) {
189 lua_pushnil(L);
190 lua_pushliteral(L, "Previous read error");
191 return 2;
192 }
193 if (handle->fd < 0) {
194 /* fake EOF to simulate shutdown */
195 if (!drain) lua_pushliteral(L, "");
196 else lua_pushinteger(L, 0);
197 lua_pushliteral(L, "eof");
198 return 2;
199 }
200 handle->readerr = 1;
201 moonbr_io_handle_set_nonblocking(L, handle, nonblocking);
202 if (!drain) luaL_buffinit(L, &luabuf);
203 while (1) {
204 remaining = -1;
205 terminatorpos = NULL;
206 if (
207 maxread > 0 &&
208 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
209 ) {
210 remaining = (size_t)maxread - luabufcnt;
211 terminatorpos = memchr(
212 handle->readbuf + handle->readbufout,
213 terminator,
214 remaining
215 );
216 } else if (terminatorlen) {
217 terminatorpos = memchr(
218 handle->readbuf + handle->readbufout,
219 terminator,
220 handle->readbufin - handle->readbufout
221 );
222 }
223 if (terminatorpos) remaining = 1 + (
224 terminatorpos - (handle->readbuf + handle->readbufout)
225 );
226 if (remaining >= 0) {
227 if (!drain) {
228 luaL_addlstring(
229 &luabuf,
230 handle->readbuf + handle->readbufout,
231 remaining
232 );
233 luaL_pushresult(&luabuf);
234 } else {
235 lua_pushinteger(L, luabufcnt + remaining);
236 }
237 if (terminatorpos) lua_pushliteral(L, "term");
238 else lua_pushliteral(L, "maxlen");
239 handle->readbufout += remaining;
240 if (handle->readbufout == handle->readbufin) {
241 handle->readbufin = 0;
242 handle->readbufout = 0;
243 }
244 handle->readerr = 0;
245 return 2;
246 }
247 if (!drain) luaL_addlstring(
248 &luabuf,
249 handle->readbuf + handle->readbufout,
250 handle->readbufin - handle->readbufout
251 );
252 luabufcnt += handle->readbufin - handle->readbufout;
253 handle->readbufout = 0;
254 do {
255 bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
256 } while (bytesread < 0 && (errno == EINTR));
257 if (
258 bytesread == 0 || (
259 nonblocking &&
260 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
261 )
262 ) {
263 handle->readbufin = 0;
264 if (!drain) luaL_pushresult(&luabuf);
265 else lua_pushinteger(L, luabufcnt);
266 if (bytesread == 0) lua_pushliteral(L, "eof");
267 else lua_pushliteral(L, "block");
268 handle->readerr = 0;
269 return 2;
270 }
271 if (bytesread < 0) {
272 moonbr_io_errmsg();
273 lua_pushnil(L);
274 lua_pushstring(L, errmsg);
275 return 2;
276 }
277 handle->readbufin = bytesread;
278 }
279 }
281 static int moonbr_io_read(lua_State *L) {
282 return moonbr_io_read_impl(L, 0, 0);
283 }
285 static int moonbr_io_read_nb(lua_State *L) {
286 return moonbr_io_read_impl(L, 1, 0);
287 }
289 static int moonbr_io_drain(lua_State *L) {
290 return moonbr_io_read_impl(L, 0, 1);
291 }
293 static int moonbr_io_drain_nb(lua_State *L) {
294 return moonbr_io_read_impl(L, 1, 1);
295 }
297 #if LUA_VERSION_NUM >= 503
298 static int moonbr_io_read_cont(lua_State *L, int status, lua_KContext ctx) {
299 #else
300 static int moonbr_io_read_cont(lua_State *L) {
301 #endif
302 lua_Integer remaining;
303 size_t len;
304 #if !(LUA_VERSION_NUM >= 503)
305 int ctx = 0;
306 lua_getctx(L, &ctx);
307 #endif
308 remaining = lua_tointeger(L, 3);
309 while (1) {
310 lua_pushcfunction(L, moonbr_io_read_nb);
311 lua_pushvalue(L, 1);
312 lua_pushvalue(L, 3);
313 lua_pushvalue(L, 4);
314 lua_call(L, 3, 2);
315 if (lua_isnil(L, -2)) return 2;
316 lua_insert(L, -2);
317 len = lua_rawlen(L, -1);
318 if (ctx == 0) {
319 lua_replace(L, 5);
320 ctx = 1;
321 } else if (ctx == 1) {
322 lua_pushvalue(L, 5);
323 lua_newtable(L);
324 lua_replace(L, 5);
325 lua_rawseti(L, 5, 2);
326 lua_rawseti(L, 5, 1);
327 ctx = 2;
328 } else {
329 lua_rawseti(L, 5, lua_rawlen(L, 5) + 1);
330 }
331 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
332 lua_pop(L, 1);
333 if (remaining >= 0 && len) {
334 remaining -= len;
335 lua_pushinteger(L, remaining);
336 lua_replace(L, 3);
337 }
338 lua_pushvalue(L, 2);
339 lua_pushvalue(L, 1);
340 lua_pushliteral(L, "r");
341 lua_callk(L, 2, 0, ctx, moonbr_io_read_cont);
342 }
343 if (ctx == 1) {
344 lua_pushvalue(L, 5);
345 } else {
346 luaL_Buffer buf;
347 lua_Integer i, chunkcount;
348 chunkcount = lua_rawlen(L, 5);
349 luaL_buffinit(L, &buf);
350 for (i=1; i<=chunkcount && i>0; i++) {
351 lua_rawgeti(L, 5, i);
352 luaL_addvalue(&buf);
353 }
354 luaL_pushresult(&buf);
355 }
356 lua_pushvalue(L, -2);
357 return 2;
358 }
360 static int moonbr_io_read_call(lua_State *L) {
361 lua_settop(L, 4);
362 lua_pushnil(L);
363 #if LUA_VERSION_NUM >= 503
364 return moonbr_io_read_cont(L, 0, 0);
365 #else
366 return moonbr_io_read_cont(L);
367 #endif
368 }
370 moonbr_io_yield_wrapper(moonbr_io_read_yield, moonbr_io_read_call);
372 #if LUA_VERSION_NUM >= 503
373 static int moonbr_io_drain_cont(lua_State *L, int status, lua_KContext ctx) {
374 #else
375 static int moonbr_io_drain_cont(lua_State *L) {
376 #endif
377 lua_Integer remaining, len;
378 size_t totallen = 0;
379 #if !(LUA_VERSION_NUM >= 503)
380 int ctx = 0;
381 lua_getctx(L, &ctx);
382 #endif
383 remaining = lua_tointeger(L, 3);
384 while (1) {
385 lua_pushcfunction(L, moonbr_io_drain_nb);
386 lua_pushvalue(L, 1);
387 lua_pushvalue(L, 3);
388 lua_pushvalue(L, 4);
389 lua_call(L, 3, 2);
390 if (lua_isnil(L, -2)) return 2;
391 lua_insert(L, -2);
392 len = lua_tointeger(L, -1);
393 lua_pop(L, 1);
394 totallen += len;
395 if (strcmp(lua_tostring(L, -1), "block") != 0) break;
396 lua_pop(L, 1);
397 if (remaining >= 0 && len) {
398 remaining -= len;
399 lua_pushinteger(L, remaining);
400 lua_replace(L, 3);
401 }
402 lua_pushvalue(L, 2);
403 lua_pushvalue(L, 1);
404 lua_pushliteral(L, "r");
405 lua_callk(L, 2, 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_pushvalue(L, 1);
584 lua_pushliteral(L, "w");
585 lua_callk(L, 2, 0, 0, moonbr_io_write_cont);
586 }
587 }
589 static int moonbr_io_write_call(lua_State *L) {
590 lua_pushcfunction(L, moonbr_io_write_nb);
591 lua_insert(L, 3);
592 lua_pushvalue(L, 1);
593 lua_insert(L, 4);
594 lua_call(L, lua_gettop(L) - 3, 2);
595 if (lua_isnil(L, -2)) return 2;
596 if (!lua_tointeger(L, -2)) {
597 lua_pushvalue(L, 1);
598 return 1;
599 }
600 #if LUA_VERSION_NUM >= 503
601 return moonbr_io_write_cont(L, 0, 0);
602 #else
603 return moonbr_io_write_cont(L);
604 #endif
605 }
607 moonbr_io_yield_wrapper(moonbr_io_write_yield, moonbr_io_write_call);
609 static int moonbr_io_flush_call(lua_State *L) {
610 lua_pushcfunction(L, moonbr_io_flush_nb);
611 lua_insert(L, 3);
612 lua_pushvalue(L, 1);
613 lua_insert(L, 4);
614 lua_call(L, lua_gettop(L) - 3, 2);
615 if (lua_isnil(L, -2)) return 2;
616 if (!lua_tointeger(L, -2)) {
617 lua_pushvalue(L, 1);
618 return 1;
619 }
620 #if LUA_VERSION_NUM >= 503
621 return moonbr_io_write_cont(L, 0, 0);
622 #else
623 return moonbr_io_write_cont(L);
624 #endif
625 }
627 moonbr_io_yield_wrapper(moonbr_io_flush_yield, moonbr_io_flush_call);
629 static int moonbr_io_finish(lua_State *L) {
630 moonbr_io_handle_t *handle;
631 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
632 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
633 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
634 if (handle->writeleft) {
635 lua_pushcfunction(L, moonbr_io_flush);
636 lua_pushvalue(L, 1);
637 if (lua_pcall(L, 1, 2, 0)) {
638 handle->finished = 1;
639 lua_error(L);
640 }
641 if (!lua_toboolean(L, -2)) {
642 handle->finished = 1;
643 return 2;
644 }
645 }
646 handle->finished = 1;
647 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
648 if (shutdown(handle->fd, SHUT_WR)) {
649 moonbr_io_errmsg();
650 lua_pushnil(L);
651 lua_pushstring(L, errmsg);
652 return 2;
653 }
654 } else {
655 if (close(handle->fd)) {
656 moonbr_io_errmsg();
657 handle->fd = -1;
658 lua_pushnil(L);
659 lua_pushstring(L, errmsg);
660 return 2;
661 }
662 handle->fd = -1; /* fake EOF on read */
663 }
664 lua_pushboolean(L, 1);
665 return 1;
666 }
668 static int moonbr_io_close_impl(lua_State *L, int reset) {
669 moonbr_io_handle_t *handle;
670 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
671 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
672 if (!reset) {
673 if (handle->writeleft) {
674 lua_pushcfunction(L, moonbr_io_flush);
675 lua_pushvalue(L, 1);
676 if (lua_pcall(L, 1, 2, 0)) {
677 handle->closed = 1;
678 close(handle->fd);
679 handle->fd = -1;
680 lua_error(L);
681 }
682 handle->closed = 1;
683 if (!lua_toboolean(L, -2)) {
684 close(handle->fd);
685 handle->fd = -1;
686 return 2;
687 }
688 } else {
689 handle->closed = 1;
690 moonbr_io_handle_set_linger(L, handle, -1);
691 }
692 } else {
693 handle->closed = 1;
694 }
695 if (handle->fd >= 0) {
696 if (close(handle->fd)) {
697 moonbr_io_errmsg();
698 handle->fd = -1;
699 lua_pushnil(L);
700 lua_pushstring(L, errmsg);
701 return 2;
702 }
703 handle->fd = -1;
704 }
705 lua_pushboolean(L, 1);
706 return 1;
708 }
710 static int moonbr_io_close(lua_State *L) {
711 return moonbr_io_close_impl(L, 0);
712 }
714 static int moonbr_io_reset(lua_State *L) {
715 return moonbr_io_close_impl(L, 1);
716 }
718 static int moonbr_io_handlegc(lua_State *L) {
719 moonbr_io_handle_t *handle;
720 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
721 if (handle->fd >= 0) {
722 lua_pushcfunction(L, moonbr_io_close);
723 lua_pushvalue(L, 1);
724 lua_pushinteger(L, 0);
725 lua_call(L, 2, 0);
726 }
727 return 0;
728 }
730 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
731 moonbr_io_handle_t *handle;
732 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
733 if (!handle->closed) {
734 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
735 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
736 lua_call(L, 1, 0);
737 }
738 }
740 void moonbr_io_pushhandle(lua_State *L, int fd) {
741 moonbr_io_handle_t *handle;
742 struct sockaddr addr;
743 socklen_t addrlen;
744 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
745 handle->fd = fd;
746 addrlen = sizeof(addr);
747 if (getsockname(fd, &addr, &addrlen)) {
748 if (errno != ENOTSOCK) {
749 moonbr_io_errmsg();
750 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
751 }
752 handle->issock = 0;
753 } else {
754 handle->issock = 1;
755 handle->addrfam = addr.sa_family;
756 }
757 handle->finished = 0;
758 handle->closed = 0;
759 handle->nonblocking = -1;
760 handle->nopush = -1;
761 handle->readerr = 0;
762 handle->readbufin = 0;
763 handle->readbufout = 0;
764 handle->writeerr = 0;
765 handle->writeleft = 0;
766 handle->flushedleft = 0;
767 handle->writeqin = 0;
768 handle->writeqout = 0;
769 handle->writeqoff = 0;
770 handle->writebufin = 0;
771 handle->writebufout = 0;
772 moonbr_io_handle_set_linger(L, handle, 0);
773 luaL_getmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
774 lua_setmetatable(L, -2);
775 lua_newtable(L); // uservalue
776 lua_newtable(L);
777 lua_setfield(L, -2, "writequeue");
778 lua_newtable(L); // public
779 if (handle->addrfam == AF_INET6) {
780 struct sockaddr_in6 addr_in6;
781 char addrstrbuf[INET6_ADDRSTRLEN];
782 const char *addrstr;
783 addrlen = sizeof(addr_in6);
784 if (getsockname(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
785 moonbr_io_errmsg();
786 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
787 }
788 if (addrlen > sizeof(addr_in6)) {
789 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
790 }
791 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
792 if (!addrstr) {
793 moonbr_io_errmsg();
794 luaL_error(L, "Could not format local IP address: %s", errmsg);
795 } else {
796 lua_pushstring(L, addrstr);
797 lua_setfield(L, -2, "local_ip6");
798 }
799 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
800 lua_setfield(L, -2, "local_tcpport");
801 if (getpeername(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
802 moonbr_io_errmsg();
803 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
804 }
805 if (addrlen > sizeof(addr_in6)) {
806 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
807 }
808 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
809 if (!addrstr) {
810 moonbr_io_errmsg();
811 luaL_error(L, "Could not format remote IP address: %s", errmsg);
812 } else {
813 lua_pushstring(L, addrstr);
814 lua_setfield(L, -2, "remote_ip6");
815 }
816 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
817 lua_setfield(L, -2, "remote_tcpport");
818 } else if (handle->addrfam == AF_INET) {
819 struct sockaddr_in addr_in;
820 char addrstrbuf[INET_ADDRSTRLEN];
821 const char *addrstr;
822 addrlen = sizeof(addr_in);
823 if (getsockname(fd, (struct sockaddr *)&addr_in, &addrlen)) {
824 moonbr_io_errmsg();
825 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
826 }
827 if (addrlen > sizeof(addr_in)) {
828 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
829 }
830 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
831 if (!addrstr) {
832 moonbr_io_errmsg();
833 luaL_error(L, "Could not format local IP address: %s", errmsg);
834 } else {
835 lua_pushstring(L, addrstr);
836 lua_setfield(L, -2, "local_ip4");
837 }
838 lua_pushinteger(L, ntohs(addr_in.sin_port));
839 lua_setfield(L, -2, "local_tcpport");
840 if (getpeername(fd, (struct sockaddr *)&addr_in, &addrlen)) {
841 moonbr_io_errmsg();
842 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
843 }
844 if (addrlen > sizeof(addr_in)) {
845 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
846 }
847 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
848 if (!addrstr) {
849 moonbr_io_errmsg();
850 luaL_error(L, "Could not format remote IP address: %s", errmsg);
851 } else {
852 lua_pushstring(L, addrstr);
853 lua_setfield(L, -2, "remote_ip4");
854 }
855 lua_pushinteger(L, ntohs(addr_in.sin_port));
856 lua_setfield(L, -2, "remote_tcpport");
857 }
858 luaL_getmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
859 lua_setmetatable(L, -2);
860 lua_setfield(L, -2, "public");
861 lua_setuservalue(L, -2);
862 }
864 static int moonbr_io_handleindex(lua_State *L) {
865 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
866 lua_getuservalue(L, 1);
867 lua_getfield(L, -1, "public");
868 lua_pushvalue(L, 2);
869 lua_gettable(L, -2);
870 return 1;
871 }
873 static int moonbr_io_handlenewindex(lua_State *L) {
874 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
875 lua_getuservalue(L, 1);
876 lua_getfield(L, -1, "public");
877 lua_pushvalue(L, 2);
878 lua_pushvalue(L, 3);
879 lua_settable(L, -3);
880 return 0;
881 }
883 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
884 const char *path;
885 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
886 const int path_maxlen = sizeof(struct sockaddr_un) - (
887 (void *)sockaddr.sun_path - (void *)&sockaddr
888 ) - 1; /* one byte for termination */
889 int sock;
890 path = luaL_checkstring(L, 1);
891 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
892 strcpy(sockaddr.sun_path, path);
893 sock = socket(
894 PF_LOCAL,
895 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
896 0
897 );
898 if (sock < 0) {
899 moonbr_io_errmsg();
900 lua_pushnil(L);
901 lua_pushstring(L, errmsg);
902 return 2;
903 }
904 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
905 if (!nonblocking && errno == EINTR) {
906 moonbr_io_errmsg();
907 close(sock);
908 lua_pushnil(L);
909 lua_pushstring(L, errmsg);
910 return 2;
911 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
912 moonbr_io_errmsg();
913 lua_pushnil(L);
914 lua_pushstring(L, errmsg);
915 return 2;
916 }
917 }
918 moonbr_io_pushhandle(L, sock);
919 return 1;
920 }
922 static int moonbr_io_localconnect(lua_State *L) {
923 return moonbr_io_localconnect_impl(L, 0);
924 }
926 static int moonbr_io_localconnect_nb(lua_State *L) {
927 return moonbr_io_localconnect_impl(L, 1);
928 }
930 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
931 const char *host, *port;
932 struct addrinfo hints = { 0, };
933 struct addrinfo *res, *addrinfo;
934 int errcode;
935 int sock;
936 host = luaL_checkstring(L, 1);
937 port = luaL_checkstring(L, 2);
938 hints.ai_family = AF_UNSPEC;
939 hints.ai_socktype = SOCK_STREAM;
940 hints.ai_protocol = IPPROTO_TCP;
941 hints.ai_flags = AI_ADDRCONFIG;
942 errcode = getaddrinfo(host, port, &hints, &res);
943 if (errcode) {
944 freeaddrinfo(res);
945 if (errcode == EAI_SYSTEM) {
946 moonbr_io_errmsg();
947 lua_pushnil(L);
948 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
949 } else {
950 lua_pushnil(L);
951 lua_pushstring(L, gai_strerror(errcode));
952 }
953 return 2;
954 }
955 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
956 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
957 }
958 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
959 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
960 }
961 addrinfo = res;
962 moonbr_io_tcpconnect_found:
963 sock = socket(
964 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
965 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
966 addrinfo->ai_protocol
967 );
968 if (sock < 0) {
969 moonbr_io_errmsg();
970 freeaddrinfo(res);
971 lua_pushnil(L);
972 lua_pushstring(L, errmsg);
973 return 2;
974 }
975 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
976 freeaddrinfo(res);
977 if (!nonblocking && errno == EINTR) {
978 moonbr_io_errmsg();
979 close(sock);
980 lua_pushnil(L);
981 lua_pushstring(L, errmsg);
982 return 2;
983 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
984 moonbr_io_errmsg();
985 lua_pushnil(L);
986 lua_pushstring(L, errmsg);
987 return 2;
988 }
989 } else {
990 freeaddrinfo(res);
991 }
992 moonbr_io_pushhandle(L, sock);
993 return 1;
994 }
996 static int moonbr_io_tcpconnect(lua_State *L) {
997 return moonbr_io_tcpconnect_impl(L, 0);
998 }
1000 static int moonbr_io_tcpconnect_nb(lua_State *L) {
1001 return moonbr_io_tcpconnect_impl(L, 1);
1002 }
1004 static int moonbr_io_locallisten(lua_State *L) {
1005 moonbr_io_listener_t *listener;
1006 const char *path;
1007 struct stat sb;
1008 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
1009 const int path_maxlen = sizeof(struct sockaddr_un) - (
1010 (void *)sockaddr.sun_path - (void *)&sockaddr
1011 ) - 1; /* one byte for termination */
1012 int sock;
1013 path = luaL_checkstring(L, 1);
1014 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
1015 strcpy(sockaddr.sun_path, path);
1016 if (stat(path, &sb) == 0) {
1017 if (S_ISSOCK(sb.st_mode)) unlink(path);
1018 }
1019 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1020 listener->fd = -1;
1021 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1022 sock = socket(
1023 PF_LOCAL,
1024 SOCK_STREAM | SOCK_CLOEXEC,
1025 0
1026 );
1027 if (sock < 0) {
1028 moonbr_io_errmsg();
1029 lua_pushnil(L);
1030 lua_pushstring(L, errmsg);
1031 return 2;
1032 }
1033 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
1034 moonbr_io_errmsg();
1035 close(sock);
1036 lua_pushnil(L);
1037 lua_pushstring(L, errmsg);
1038 return 2;
1039 }
1040 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1041 moonbr_io_errmsg();
1042 close(sock);
1043 lua_pushnil(L);
1044 lua_pushstring(L, errmsg);
1045 return 2;
1046 }
1047 listener->fd = sock;
1048 listener->addrfam = AF_LOCAL;
1049 listener->nonblocking = -1;
1050 return 1;
1051 }
1053 static int moonbr_io_tcplisten(lua_State *L) {
1054 moonbr_io_listener_t *listener;
1055 const char *host, *port;
1056 struct addrinfo hints = { 0, };
1057 struct addrinfo *res, *addrinfo;
1058 int errcode;
1059 int sock;
1060 host = luaL_optstring(L, 1, NULL);
1061 port = luaL_checkstring(L, 2);
1062 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
1063 listener->fd = -1;
1064 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
1065 hints.ai_family = AF_UNSPEC;
1066 hints.ai_socktype = SOCK_STREAM;
1067 hints.ai_protocol = IPPROTO_TCP;
1068 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1069 errcode = getaddrinfo(host, port, &hints, &res);
1070 if (errcode) {
1071 freeaddrinfo(res);
1072 if (errcode == EAI_SYSTEM) {
1073 moonbr_io_errmsg();
1074 lua_pushnil(L);
1075 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
1076 } else {
1077 lua_pushnil(L);
1078 lua_pushstring(L, gai_strerror(errcode));
1079 }
1080 return 2;
1081 }
1082 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1083 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
1084 }
1085 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1086 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
1087 }
1088 addrinfo = res;
1089 moonbr_io_tcpconnect_found:
1090 listener->addrfam = addrinfo->ai_family;
1091 sock = socket(
1092 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
1093 addrinfo->ai_socktype | SOCK_CLOEXEC,
1094 addrinfo->ai_protocol
1095 );
1096 if (sock < 0) {
1097 moonbr_io_errmsg();
1098 freeaddrinfo(res);
1099 lua_pushnil(L);
1100 lua_pushstring(L, errmsg);
1101 return 2;
1102 }
1103 {
1104 static const int reuseval = 1;
1105 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
1106 moonbr_io_errmsg();
1107 freeaddrinfo(res);
1108 close(sock);
1109 lua_pushnil(L);
1110 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
1111 return 2;
1112 }
1113 }
1114 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
1115 moonbr_io_errmsg();
1116 freeaddrinfo(res);
1117 close(sock);
1118 lua_pushnil(L);
1119 lua_pushstring(L, errmsg);
1120 return 2;
1121 }
1122 freeaddrinfo(res);
1123 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
1124 moonbr_io_errmsg();
1125 close(sock);
1126 lua_pushnil(L);
1127 lua_pushstring(L, errmsg);
1128 return 2;
1129 }
1130 listener->fd = sock;
1131 listener->nonblocking = -1;
1132 return 1;
1133 }
1135 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
1136 moonbr_io_listener_t *listener;
1137 int fd;
1138 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1139 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
1140 if (listener->nonblocking != nonblocking) {
1141 int flags;
1142 flags = fcntl(listener->fd, F_GETFL, 0);
1143 if (flags == -1) {
1144 moonbr_io_errmsg();
1145 close(listener->fd);
1146 listener->fd = -1;
1147 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1148 }
1149 if (nonblocking) flags |= O_NONBLOCK;
1150 else flags &= ~O_NONBLOCK;
1151 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
1152 moonbr_io_errmsg();
1153 close(listener->fd);
1154 listener->fd = -1;
1155 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
1156 }
1157 listener->nonblocking = nonblocking;
1158 }
1159 while (1) {
1160 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
1161 if (fd < 0) {
1162 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
1163 lua_pushboolean(L, 0);
1164 lua_pushliteral(L, "No incoming connection pending");
1165 return 2;
1166 } else if (errno != EINTR) {
1167 moonbr_io_errmsg();
1168 lua_pushnil(L);
1169 lua_pushstring(L, errmsg);
1170 return 2;
1171 }
1172 } else {
1173 moonbr_io_pushhandle(L, fd);
1174 return 1;
1175 }
1176 }
1177 }
1179 static int moonbr_io_accept(lua_State *L) {
1180 return moonbr_io_accept_impl(L, 0);
1181 }
1183 static int moonbr_io_accept_nb(lua_State *L) {
1184 return moonbr_io_accept_impl(L, 1);
1185 }
1187 static int moonbr_io_unlisten(lua_State *L) {
1188 moonbr_io_listener_t *listener;
1189 struct sockaddr_un addr;
1190 socklen_t addrlen;
1191 struct stat sb;
1192 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1193 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
1194 addrlen = sizeof(addr);
1195 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
1196 if (close(listener->fd)) {
1197 moonbr_io_errmsg();
1198 listener->fd = -1;
1199 if (addrlen && addrlen <= sizeof(addr)) {
1200 if (stat(addr.sun_path, &sb) == 0) {
1201 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1202 }
1203 }
1204 lua_pushnil(L);
1205 lua_pushstring(L, errmsg);
1206 return 2;
1207 }
1208 listener->fd = -1;
1209 if (addrlen && addrlen <= sizeof(addr)) {
1210 if (stat(addr.sun_path, &sb) == 0) {
1211 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
1212 }
1213 }
1214 lua_pushboolean(L, 1);
1215 return 1;
1216 }
1218 static int moonbr_io_listenergc(lua_State *L) {
1219 moonbr_io_listener_t *listener;
1220 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1221 if (listener->fd >= 0) close(listener->fd);
1222 listener->fd = -1;
1223 return 0;
1224 }
1226 static int moonbr_io_poll(lua_State *L) {
1227 moonbr_io_handle_t *handle;
1228 moonbr_io_listener_t *listener;
1229 int fd, isnum;
1230 int nfds = 0;
1231 fd_set readfds, writefds, exceptfds;
1232 struct timeval timeout = {0, };
1233 int status;
1234 FD_ZERO(&readfds);
1235 FD_ZERO(&writefds);
1236 FD_ZERO(&exceptfds);
1237 if (!lua_isnoneornil(L, 1)) {
1238 luaL_checktype(L, 1, LUA_TTABLE);
1239 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1240 if (lua_toboolean(L, -1)) {
1241 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1242 if (handle) {
1243 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1244 fd = handle->fd;
1245 if (
1246 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1247 handle->readbufin != handle->readbufout /* data pending in buffer */
1248 ) {
1249 lua_pushboolean(L, 1);
1250 return 1;
1251 }
1252 } else {
1253 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1254 if (listener) {
1255 fd = listener->fd;
1256 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1257 } else {
1258 fd = lua_tointegerx(L, -2, &isnum);
1259 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1260 }
1261 }
1262 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1263 FD_SET(fd, &readfds);
1264 if (fd+1 > nfds) nfds = fd+1;
1265 }
1266 }
1267 }
1268 if (!lua_isnoneornil(L, 2)) {
1269 luaL_checktype(L, 2, LUA_TTABLE);
1270 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1271 if (lua_toboolean(L, -1)) {
1272 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1273 if (handle) {
1274 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1275 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1276 fd = handle->fd;
1277 } else {
1278 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1279 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1280 fd = lua_tointegerx(L, -2, &isnum);
1281 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1282 }
1283 if (fd < 0 || fd >= FD_SETSIZE) luaL_error(L, "File descriptor out of valid range");
1284 FD_SET(fd, &writefds);
1285 if (fd+1 > nfds) nfds = fd+1;
1286 }
1287 }
1288 }
1289 if (!lua_isnoneornil(L, 3)) {
1290 lua_Number n;
1291 n = lua_tonumberx(L, 3, &isnum);
1292 if (isnum && n<0) {
1293 lua_pushboolean(L, 0);
1294 lua_pushliteral(L, "Negative timeout");
1295 return 2;
1296 } else if (isnum && n>=0 && n<100000000) {
1297 timeout.tv_sec = n;
1298 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1299 } else {
1300 luaL_argcheck(L, 0, 3, "not a valid timeout");
1301 }
1302 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1303 } else {
1304 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1305 }
1306 if (status == -1) {
1307 if (errno == EINTR) {
1308 lua_pushnil(L);
1309 lua_pushliteral(L, "Signal received while polling file descriptors");
1310 return 2;
1311 } else {
1312 moonbr_io_errmsg();
1313 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1314 }
1315 } else if (status == 0) {
1316 lua_pushboolean(L, 0);
1317 lua_pushliteral(L, "Timeout while polling file descriptors");
1318 return 2;
1319 } else {
1320 lua_pushboolean(L, 1);
1321 return 1;
1322 }
1323 }
1325 static int moonbr_io_timeref(lua_State *L) {
1326 lua_Number sub;
1327 struct timespec tp;
1328 sub = luaL_optnumber(L, 1, 0);
1329 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1330 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1331 }
1332 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1333 return 1;
1334 }
1336 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1337 {"read", moonbr_io_read},
1338 {"read_nb", moonbr_io_read_nb},
1339 {"read_call", moonbr_io_read_call},
1340 {"read_yield", moonbr_io_read_yield},
1341 {"drain", moonbr_io_drain},
1342 {"drain_nb", moonbr_io_drain_nb},
1343 {"drain_call", moonbr_io_drain_call},
1344 {"drain_yield", moonbr_io_drain_yield},
1345 {"write", moonbr_io_write},
1346 {"write_nb", moonbr_io_write_nb},
1347 {"write_call", moonbr_io_write_call},
1348 {"write_yield", moonbr_io_write_yield},
1349 {"flush", moonbr_io_flush},
1350 {"flush_nb", moonbr_io_flush_nb},
1351 {"flush_call", moonbr_io_flush_call},
1352 {"flush_yield", moonbr_io_flush_yield},
1353 {"finish", moonbr_io_finish},
1354 {"close", moonbr_io_close},
1355 {"reset", moonbr_io_reset},
1356 {NULL, NULL}
1357 };
1359 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1360 {"__index", moonbr_io_handleindex},
1361 {"__newindex", moonbr_io_handlenewindex},
1362 {"__gc", moonbr_io_handlegc},
1363 {NULL, NULL}
1364 };
1366 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1367 {"accept", moonbr_io_accept},
1368 {"accept_nb", moonbr_io_accept_nb},
1369 {"close", moonbr_io_unlisten},
1370 {NULL, NULL}
1371 };
1373 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1374 {"__gc", moonbr_io_listenergc},
1375 {NULL, NULL}
1376 };
1378 static const struct luaL_Reg moonbr_io_module_funcs[] = {
1379 {"localconnect", moonbr_io_localconnect},
1380 {"localconnect_nb", moonbr_io_localconnect_nb},
1381 {"tcpconnect", moonbr_io_tcpconnect},
1382 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
1383 {"locallisten", moonbr_io_locallisten},
1384 {"tcplisten", moonbr_io_tcplisten},
1385 {"poll", moonbr_io_poll},
1386 {"timeref", moonbr_io_timeref},
1387 {NULL, NULL}
1388 };
1390 int luaopen_moonbridge_io(lua_State *L) {
1392 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
1394 lua_newtable(L); // module
1396 lua_pushlightuserdata(L, &moonbr_io_block_udata);
1397 lua_setfield(L, -2, "block");
1399 lua_newtable(L); // public metatable
1400 lua_newtable(L); // handle methods
1401 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
1402 lua_pushvalue(L, -1);
1403 lua_setfield(L, -4, "handle_pt");
1404 lua_setfield(L, -2, "__index");
1405 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1407 lua_newtable(L); // handle metatable
1408 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
1409 lua_pushvalue(L, -1);
1410 lua_setfield(L, -3, "handle_mt");
1411 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
1413 lua_newtable(L); // listener metatable
1414 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
1415 lua_newtable(L); // listener methods
1416 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
1417 lua_pushvalue(L, -1);
1418 lua_setfield(L, -4, "listener_pt");
1419 lua_setfield(L, -2, "__index");
1420 lua_pushvalue(L, -1);
1421 lua_setfield(L, -3, "listener_mt");
1422 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
1424 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
1425 return 1;
1427 }