moonbridge

view moonbridge_io.c @ 122:3bbcd75eefcd

Make moonbridge_io.poll(...) return immediately if there is data pending in read buffers
author jbe
date Sat Apr 11 00:18:12 2015 +0200 (2015-04-11)
parents 74ec80b721b9
children df08e63dc44b
line source
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <stdint.h>
5 #include <errno.h>
6 #include <string.h>
7 #include <sys/socket.h>
8 #include <sys/un.h>
9 #include <sys/select.h>
10 #include <fcntl.h>
11 #include <netinet/in.h>
12 #include <netinet/tcp.h>
13 #include <arpa/inet.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <netdb.h>
17 #include <signal.h>
18 #include <time.h>
20 #include <lua.h>
21 #include <lauxlib.h>
22 #include <lualib.h>
24 #define MOONBR_IO_MAXSTRERRORLEN 80
25 #define MOONBR_IO_READBUFLEN 4096
26 #define MOONBR_IO_WRITEBUFLEN 4096
28 #define MOONBR_IO_LISTEN_BACKLOG 1024
30 #define moonbr_io_errmsg() \
31 char errmsg[MOONBR_IO_MAXSTRERRORLEN]; \
32 strerror_r(errno, errmsg, MOONBR_IO_MAXSTRERRORLEN)
34 #define MOONBR_IO_HANDLE_MT_REGKEY "moonbridge_io_handle"
35 #define MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY "moonbridge_io_handle_public"
36 #define MOONBR_IO_LISTENER_MT_REGKEY "moonbridge_io_listener"
38 typedef struct {
39 int fd;
40 int issock;
41 sa_family_t addrfam;
42 int finished;
43 int closed;
44 int nonblocking;
45 int nopush;
46 int readerr;
47 int readbufin;
48 int readbufout;
49 int writeerr;
50 size_t writeleft;
51 #if LUA_VERSION_NUM >= 503
52 lua_Integer writeqin;
53 lua_Integer writeqout;
54 #else
55 int writeqin;
56 int writeqout;
57 #endif
58 size_t writeqoff;
59 int writebufin;
60 int writebufout;
61 char readbuf[MOONBR_IO_READBUFLEN];
62 char writebuf[MOONBR_IO_WRITEBUFLEN];
63 } moonbr_io_handle_t;
65 typedef struct {
66 int fd;
67 sa_family_t addrfam;
68 int nonblocking;
69 } moonbr_io_listener_t;
71 static void moonbr_io_handle_set_nonblocking(lua_State *L, moonbr_io_handle_t *handle, int nonblocking) {
72 int flags;
73 if (handle->nonblocking == nonblocking) return;
74 flags = fcntl(handle->fd, F_GETFL, 0);
75 if (flags == -1) {
76 moonbr_io_errmsg();
77 close(handle->fd);
78 handle->fd = -1;
79 handle->closed = 1;
80 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
81 }
82 if (nonblocking) flags |= O_NONBLOCK;
83 else flags &= ~O_NONBLOCK;
84 if (fcntl(handle->fd, F_SETFL, flags) == -1) {
85 moonbr_io_errmsg();
86 close(handle->fd);
87 handle->fd = -1;
88 handle->closed = 1;
89 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
90 }
91 handle->nonblocking = nonblocking;
92 }
94 static void moonbr_io_handle_set_linger(lua_State *L, moonbr_io_handle_t *handle, int timeout) {
95 struct linger lingerval = { 0, };
96 if (!handle->issock) return;
97 if (timeout >= 0) {
98 lingerval.l_onoff = 1;
99 lingerval.l_linger = timeout;
100 }
101 if (setsockopt(handle->fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) {
102 moonbr_io_errmsg();
103 close(handle->fd);
104 handle->fd = -1;
105 handle->closed = 1;
106 luaL_error(L, "Unexpected error while setting SO_LINGER with setsockopt: %s", errmsg);
107 }
108 }
110 static void moonbr_io_handle_set_nopush(lua_State *L, moonbr_io_handle_t *handle, int nopush) {
111 #if defined(TCP_NOPUSH) || defined(TCP_CORK)
112 if (
113 !(handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) ||
114 handle->nopush == nopush
115 ) return;
116 #if defined(TCP_NOPUSH)
117 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_NOPUSH, &nopush, sizeof(nopush))) {
118 #elif defined(TCP_CORK)
119 if (setsockopt(handle->fd, IPPROTO_TCP, TCP_CORK, &nopush, sizeof(nopush))) {
120 #endif
121 moonbr_io_errmsg();
122 close(handle->fd);
123 handle->fd = -1;
124 handle->closed = 1;
125 #if defined(TCP_NOPUSH)
126 luaL_error(L, "Unexpected error while setting TCP_NOPUSH with setsockopt: %s", errmsg);
127 #elif defined(TCP_CORK)
128 luaL_error(L, "Unexpected error while setting TCP_CORK with setsockopt: %s", errmsg);
129 #endif
130 }
131 handle->nopush = nopush;
132 #else
133 #warning Neither TCP_NOPUSH nor TCP_CORK is available
134 #endif
135 }
137 static int moonbr_io_read_impl(lua_State *L, int nonblocking, int drain) {
138 moonbr_io_handle_t *handle;
139 lua_Integer maxread;
140 const char *terminatorstr;
141 size_t terminatorlen;
142 char terminator;
143 luaL_Buffer luabuf;
144 size_t luabufcnt = 0;
145 int remaining;
146 char *terminatorpos;
147 ssize_t bytesread;
148 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
149 maxread = luaL_optinteger(L, 2, 0);
150 terminatorstr = luaL_optlstring(L, 3, "", &terminatorlen);
151 if (terminatorlen) {
152 luaL_argcheck(L, terminatorlen == 1, 3, "single byte expected");
153 terminator = terminatorstr[0];
154 }
155 lua_settop(L, 1); /* return handle on drain, terminator string may be garbage collected */
156 if (handle->closed) luaL_error(L, "Attempt to read from a closed I/O handle");
157 if (handle->readerr) {
158 lua_pushnil(L);
159 lua_pushliteral(L, "Previous read error");
160 return 2;
161 }
162 handle->readerr = 1;
163 if (handle->fd < 0) goto moonbr_io_read_impl_eof; /* fake EOF to simulate shutdown */
164 moonbr_io_handle_set_nonblocking(L, handle, nonblocking);
165 if (!drain) luaL_buffinit(L, &luabuf);
166 while (1) {
167 remaining = -1;
168 if (
169 maxread > 0 &&
170 handle->readbufin - handle->readbufout >= (size_t)maxread - luabufcnt
171 ) {
172 remaining = maxread - luabufcnt;
173 } else if (terminatorlen) {
174 terminatorpos = memchr(
175 handle->readbuf + handle->readbufout,
176 terminator,
177 handle->readbufin - handle->readbufout
178 );
179 if (terminatorpos) remaining = 1 + (
180 terminatorpos - (handle->readbuf + handle->readbufout)
181 );
182 }
183 if (remaining >= 0) {
184 if (!drain) {
185 luaL_addlstring(
186 &luabuf,
187 handle->readbuf + handle->readbufout,
188 remaining
189 );
190 luaL_pushresult(&luabuf);
191 } else {
192 luaL_pushresult(&luabuf);
193 lua_pop(L, 1);
194 lua_pushinteger(L, luabufcnt + remaining);
195 }
196 handle->readbufout += remaining;
197 if (handle->readbufout == handle->readbufin) {
198 handle->readbufin = 0;
199 handle->readbufout =0;
200 }
201 handle->readerr = 0;
202 return 1;
203 }
204 if (!drain) luaL_addlstring(
205 &luabuf,
206 handle->readbuf + handle->readbufout,
207 handle->readbufin - handle->readbufout
208 );
209 luabufcnt += handle->readbufin - handle->readbufout;
210 do {
211 bytesread = read(handle->fd, handle->readbuf, MOONBR_IO_READBUFLEN);
212 } while (bytesread < 0 && (errno == EINTR));
213 if (
214 bytesread == 0 || (
215 nonblocking &&
216 bytesread < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)
217 )
218 ) {
219 handle->readbufin = 0;
220 handle->readbufout = 0;
221 if (!drain) {
222 luaL_pushresult(&luabuf);
223 if (!luabufcnt && bytesread == 0) {
224 lua_pop(L, 1);
225 moonbr_io_read_impl_eof:
226 lua_pushboolean(L, 0);
227 lua_pushliteral(L, "End of file");
228 handle->readerr = 0;
229 return 2;
230 }
231 } else {
232 if (!luabufcnt && bytesread == 0) lua_pushboolean(L, 1);
233 else lua_pushboolean(L, luabufcnt);
234 }
235 handle->readerr = 0;
236 return 1;
237 }
238 if (bytesread < 0) {
239 moonbr_io_errmsg();
240 lua_pushnil(L);
241 lua_pushstring(L, errmsg);
242 return 2;
243 }
244 handle->readbufin = bytesread;
245 handle->readbufout = 0;
246 }
247 }
249 static int moonbr_io_read(lua_State *L) {
250 return moonbr_io_read_impl(L, 0, 0);
251 }
253 static int moonbr_io_read_nb(lua_State *L) {
254 return moonbr_io_read_impl(L, 1, 0);
255 }
257 static int moonbr_io_drain(lua_State *L) {
258 return moonbr_io_read_impl(L, 0, 1);
259 }
261 static int moonbr_io_drain_nb(lua_State *L) {
262 return moonbr_io_read_impl(L, 1, 1);
263 }
265 static int moonbr_io_write_impl(lua_State *L, int nonblocking, int flush) {
266 moonbr_io_handle_t *handle;
267 int i, top;
268 const char *str;
269 size_t strlen;
270 ssize_t written;
271 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
272 if (handle->closed) luaL_error(L, "Attempt to write to a closed I/O handle");
273 if (handle->finished) luaL_error(L, "Attempt to write to a finished I/O handle");
274 if (handle->writeerr) {
275 lua_pushnil(L);
276 lua_pushliteral(L, "Previous write error");
277 return 2;
278 }
279 handle->writeerr = 1;
280 moonbr_io_handle_set_nonblocking(L, handle, nonblocking);
281 top = lua_gettop(L);
282 lua_getuservalue(L, 1);
283 lua_getfield(L, -1, "writequeue");
284 for (i=2; i<=top; i++) {
285 luaL_checklstring(L, i, &strlen);
286 lua_pushvalue(L, i);
287 lua_rawseti(L, -2, handle->writeqin++);
288 handle->writeleft += strlen;
289 }
290 while (handle->writeqout != handle->writeqin) {
291 lua_rawgeti(L, -1, handle->writeqout);
292 str = lua_tolstring(L, -1, &strlen);
293 while (handle->writeqoff < strlen) {
294 if (
295 strlen - handle->writeqoff <=
296 MOONBR_IO_WRITEBUFLEN - handle->writebufin
297 ) {
298 memcpy(
299 handle->writebuf + handle->writebufin,
300 str + handle->writeqoff,
301 strlen - handle->writeqoff
302 );
303 handle->writebufin += strlen - handle->writeqoff;
304 break;
305 } else {
306 moonbr_io_handle_set_nopush(L, handle, 1);
307 memcpy(
308 handle->writebuf + handle->writebufin,
309 str + handle->writeqoff,
310 MOONBR_IO_WRITEBUFLEN - handle->writebufin
311 );
312 handle->writeqoff += MOONBR_IO_WRITEBUFLEN - handle->writebufin;
313 while (handle->writebufout < MOONBR_IO_WRITEBUFLEN) {
314 written = write(
315 handle->fd,
316 handle->writebuf + handle->writebufout,
317 MOONBR_IO_WRITEBUFLEN - handle->writebufout
318 );
319 if (written < 0) {
320 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
321 goto moonbr_io_write_impl_block;
322 } else if (errno != EINTR) {
323 moonbr_io_errmsg();
324 lua_pushnil(L);
325 lua_pushstring(L, errmsg);
326 return 2;
327 }
328 } else {
329 handle->writebufout += written;
330 handle->writeleft -= written;
331 }
332 }
333 handle->writebufin = 0;
334 handle->writebufout = 0;
335 }
336 }
337 handle->writeqoff = 0;
338 lua_pop(L, 1);
339 lua_pushnil(L);
340 lua_rawseti(L, -2, handle->writeqout++);
341 }
342 if (flush) {
343 moonbr_io_handle_set_nopush(L, handle, 0);
344 while (handle->writebufout < handle->writebufin) {
345 written = write(
346 handle->fd,
347 handle->writebuf + handle->writebufout,
348 handle->writebufin - handle->writebufout
349 );
350 if (written < 0) {
351 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
352 goto moonbr_io_write_impl_block;
353 } else if (errno != EINTR) {
354 moonbr_io_errmsg();
355 lua_pushnil(L);
356 lua_pushstring(L, errmsg);
357 return 2;
358 }
359 } else {
360 handle->writebufout += written;
361 handle->writeleft -= written;
362 }
363 }
364 handle->writebufin = 0;
365 handle->writebufout = 0;
366 }
367 if (nonblocking) lua_pushinteger(L, 0);
368 else lua_pushvalue(L, 1);
369 handle->writeerr = 0;
370 return 1;
371 moonbr_io_write_impl_block:
372 lua_pushinteger(L, handle->writeleft);
373 handle->writeerr = 0;
374 return 1;
375 }
377 static int moonbr_io_write(lua_State *L) {
378 return moonbr_io_write_impl(L, 0, 0);
379 }
381 static int moonbr_io_write_nb(lua_State *L) {
382 return moonbr_io_write_impl(L, 1, 0);
383 }
385 static int moonbr_io_flush(lua_State *L) {
386 return moonbr_io_write_impl(L, 0, 1);
387 }
389 static int moonbr_io_flush_nb(lua_State *L) {
390 return moonbr_io_write_impl(L, 1, 1);
391 }
393 static int moonbr_io_finish(lua_State *L) {
394 moonbr_io_handle_t *handle;
395 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
396 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
397 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
398 if (handle->writeleft) {
399 lua_pushcfunction(L, moonbr_io_flush);
400 lua_pushvalue(L, 1);
401 if (lua_pcall(L, 1, 2, 0)) {
402 handle->finished = 1;
403 lua_error(L);
404 }
405 if (!lua_toboolean(L, -2)) {
406 handle->finished = 1;
407 return 2;
408 }
409 }
410 handle->finished = 1;
411 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
412 if (shutdown(handle->fd, SHUT_WR)) {
413 moonbr_io_errmsg();
414 lua_pushnil(L);
415 lua_pushstring(L, errmsg);
416 return 2;
417 }
418 } else {
419 if (close(handle->fd)) {
420 moonbr_io_errmsg();
421 handle->fd = -1;
422 lua_pushnil(L);
423 lua_pushstring(L, errmsg);
424 return 2;
425 }
426 handle->fd = -1; /* fake EOF on read */
427 }
428 lua_pushboolean(L, 1);
429 return 1;
430 }
432 static int moonbr_io_close_impl(lua_State *L, int reset) {
433 moonbr_io_handle_t *handle;
434 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
435 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
436 handle->closed = 1;
437 if (!reset) {
438 if (handle->writeleft) {
439 lua_pushcfunction(L, moonbr_io_flush);
440 lua_pushvalue(L, 1);
441 if (lua_pcall(L, 1, 2, 0)) {
442 close(handle->fd);
443 handle->fd = -1;
444 lua_error(L);
445 }
446 if (!lua_toboolean(L, -2)) {
447 close(handle->fd);
448 handle->fd = -1;
449 return 2;
450 }
451 }
452 moonbr_io_handle_set_linger(L, handle, -1);
453 }
454 if (handle->fd >= 0) {
455 if (close(handle->fd)) {
456 moonbr_io_errmsg();
457 handle->fd = -1;
458 lua_pushnil(L);
459 lua_pushstring(L, errmsg);
460 return 2;
461 }
462 handle->fd = -1;
463 }
464 lua_pushboolean(L, 1);
465 return 1;
467 }
469 static int moonbr_io_close(lua_State *L) {
470 return moonbr_io_close_impl(L, 0);
471 }
473 static int moonbr_io_reset(lua_State *L) {
474 return moonbr_io_close_impl(L, 1);
475 }
477 static int moonbr_io_handlegc(lua_State *L) {
478 moonbr_io_handle_t *handle;
479 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
480 if (handle->fd >= 0) {
481 lua_pushcfunction(L, moonbr_io_close);
482 lua_pushvalue(L, 1);
483 lua_pushinteger(L, 0);
484 lua_call(L, 2, 0);
485 }
486 return 0;
487 }
489 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
490 moonbr_io_handle_t *handle;
491 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
492 if (!handle->closed) {
493 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
494 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
495 lua_call(L, 1, 0);
496 }
497 }
499 void moonbr_io_pushhandle(lua_State *L, int fd) {
500 moonbr_io_handle_t *handle;
501 struct sockaddr addr;
502 socklen_t addrlen;
503 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
504 handle->fd = fd;
505 addrlen = sizeof(addr);
506 if (getsockname(fd, &addr, &addrlen)) {
507 if (errno != ENOTSOCK) {
508 moonbr_io_errmsg();
509 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
510 }
511 handle->issock = 0;
512 } else {
513 handle->issock = 1;
514 handle->addrfam = addr.sa_family;
515 }
516 handle->finished = 0;
517 handle->closed = 0;
518 handle->nonblocking = -1;
519 handle->nopush = -1;
520 handle->readerr = 0;
521 handle->readbufin = 0;
522 handle->readbufout = 0;
523 handle->writeerr = 0;
524 handle->writeleft = 0;
525 handle->writeqin = 0;
526 handle->writeqout = 0;
527 handle->writeqoff = 0;
528 handle->writebufin = 0;
529 handle->writebufout = 0;
530 moonbr_io_handle_set_linger(L, handle, 0);
531 luaL_getmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
532 lua_setmetatable(L, -2);
533 lua_newtable(L); // uservalue
534 lua_newtable(L);
535 lua_setfield(L, -2, "writequeue");
536 lua_newtable(L); // public
537 if (handle->addrfam == AF_INET6) {
538 struct sockaddr_in6 addr_in6;
539 char addrstrbuf[INET6_ADDRSTRLEN];
540 const char *addrstr;
541 addrlen = sizeof(addr_in6);
542 if (getsockname(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
543 moonbr_io_errmsg();
544 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
545 }
546 if (addrlen > sizeof(addr_in6)) {
547 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
548 }
549 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
550 if (!addrstr) {
551 moonbr_io_errmsg();
552 luaL_error(L, "Could not format local IP address: %s", errmsg);
553 } else {
554 lua_pushstring(L, addrstr);
555 lua_setfield(L, -2, "local_ip6");
556 }
557 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
558 lua_setfield(L, -2, "local_tcpport");
559 if (getpeername(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
560 moonbr_io_errmsg();
561 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
562 }
563 if (addrlen > sizeof(addr_in6)) {
564 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
565 }
566 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
567 if (!addrstr) {
568 moonbr_io_errmsg();
569 luaL_error(L, "Could not format remote IP address: %s", errmsg);
570 } else {
571 lua_pushstring(L, addrstr);
572 lua_setfield(L, -2, "remote_ip6");
573 }
574 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
575 lua_setfield(L, -2, "remote_tcpport");
576 } else if (handle->addrfam == AF_INET) {
577 struct sockaddr_in addr_in;
578 char addrstrbuf[INET_ADDRSTRLEN];
579 const char *addrstr;
580 addrlen = sizeof(addr_in);
581 if (getsockname(fd, (struct sockaddr *)&addr_in, &addrlen)) {
582 moonbr_io_errmsg();
583 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
584 }
585 if (addrlen > sizeof(addr_in)) {
586 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
587 }
588 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
589 if (!addrstr) {
590 moonbr_io_errmsg();
591 luaL_error(L, "Could not format local IP address: %s", errmsg);
592 } else {
593 lua_pushstring(L, addrstr);
594 lua_setfield(L, -2, "local_ip4");
595 }
596 lua_pushinteger(L, ntohs(addr_in.sin_port));
597 lua_setfield(L, -2, "local_tcpport");
598 if (getpeername(fd, (struct sockaddr *)&addr_in, &addrlen)) {
599 moonbr_io_errmsg();
600 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
601 }
602 if (addrlen > sizeof(addr_in)) {
603 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
604 }
605 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
606 if (!addrstr) {
607 moonbr_io_errmsg();
608 luaL_error(L, "Could not format remote IP address: %s", errmsg);
609 } else {
610 lua_pushstring(L, addrstr);
611 lua_setfield(L, -2, "remote_ip4");
612 }
613 lua_pushinteger(L, ntohs(addr_in.sin_port));
614 lua_setfield(L, -2, "remote_tcpport");
615 }
616 luaL_getmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
617 lua_setmetatable(L, -2);
618 lua_setfield(L, -2, "public");
619 lua_setuservalue(L, -2);
620 }
622 static int moonbr_io_handleindex(lua_State *L) {
623 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
624 lua_getuservalue(L, 1);
625 lua_getfield(L, -1, "public");
626 lua_pushvalue(L, 2);
627 lua_gettable(L, -2);
628 return 1;
629 }
631 static int moonbr_io_handlenewindex(lua_State *L) {
632 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
633 lua_getuservalue(L, 1);
634 lua_getfield(L, -1, "public");
635 lua_pushvalue(L, 2);
636 lua_pushvalue(L, 3);
637 lua_settable(L, -3);
638 return 0;
639 }
641 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
642 const char *path;
643 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
644 const int path_maxlen = sizeof(struct sockaddr_un) - (
645 (void *)sockaddr.sun_path - (void *)&sockaddr
646 ) - 1; /* one byte for termination */
647 int sock;
648 path = luaL_checkstring(L, 1);
649 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
650 strcpy(sockaddr.sun_path, path);
651 sock = socket(
652 PF_LOCAL,
653 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
654 0
655 );
656 if (sock < 0) {
657 moonbr_io_errmsg();
658 lua_pushnil(L);
659 lua_pushstring(L, errmsg);
660 return 2;
661 }
662 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
663 if (!nonblocking && errno == EINTR) {
664 moonbr_io_errmsg();
665 close(sock);
666 lua_pushnil(L);
667 lua_pushstring(L, errmsg);
668 return 2;
669 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
670 moonbr_io_errmsg();
671 lua_pushnil(L);
672 lua_pushstring(L, errmsg);
673 return 2;
674 }
675 }
676 moonbr_io_pushhandle(L, sock);
677 return 1;
678 }
680 static int moonbr_io_localconnect(lua_State *L) {
681 return moonbr_io_localconnect_impl(L, 0);
682 }
684 static int moonbr_io_localconnect_nb(lua_State *L) {
685 return moonbr_io_localconnect_impl(L, 1);
686 }
688 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
689 const char *host, *port;
690 struct addrinfo hints = { 0, };
691 struct addrinfo *res, *addrinfo;
692 int errcode;
693 int sock;
694 host = luaL_checkstring(L, 1);
695 port = luaL_checkstring(L, 2);
696 hints.ai_family = AF_UNSPEC;
697 hints.ai_socktype = SOCK_STREAM;
698 hints.ai_protocol = IPPROTO_TCP;
699 hints.ai_flags = AI_ADDRCONFIG;
700 errcode = getaddrinfo(host, port, &hints, &res);
701 if (errcode) {
702 freeaddrinfo(res);
703 if (errcode == EAI_SYSTEM) {
704 moonbr_io_errmsg();
705 lua_pushnil(L);
706 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
707 } else {
708 lua_pushnil(L);
709 lua_pushstring(L, gai_strerror(errcode));
710 }
711 return 2;
712 }
713 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
714 if (addrinfo->ai_family == PF_INET6) goto moonbr_io_tcpconnect_found;
715 }
716 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
717 if (addrinfo->ai_family == PF_INET) goto moonbr_io_tcpconnect_found;
718 }
719 addrinfo = res;
720 moonbr_io_tcpconnect_found:
721 sock = socket(
722 addrinfo->ai_family,
723 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
724 addrinfo->ai_protocol
725 );
726 if (sock < 0) {
727 moonbr_io_errmsg();
728 freeaddrinfo(res);
729 lua_pushnil(L);
730 lua_pushstring(L, errmsg);
731 return 2;
732 }
733 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
734 freeaddrinfo(res);
735 if (!nonblocking && errno == EINTR) {
736 moonbr_io_errmsg();
737 close(sock);
738 lua_pushnil(L);
739 lua_pushstring(L, errmsg);
740 return 2;
741 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
742 moonbr_io_errmsg();
743 lua_pushnil(L);
744 lua_pushstring(L, errmsg);
745 return 2;
746 }
747 } else {
748 freeaddrinfo(res);
749 }
750 moonbr_io_pushhandle(L, sock);
751 return 1;
752 }
754 static int moonbr_io_tcpconnect(lua_State *L) {
755 return moonbr_io_tcpconnect_impl(L, 0);
756 }
758 static int moonbr_io_tcpconnect_nb(lua_State *L) {
759 return moonbr_io_tcpconnect_impl(L, 1);
760 }
762 static int moonbr_io_locallisten(lua_State *L) {
763 moonbr_io_listener_t *listener;
764 const char *path;
765 struct stat sb;
766 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
767 const int path_maxlen = sizeof(struct sockaddr_un) - (
768 (void *)sockaddr.sun_path - (void *)&sockaddr
769 ) - 1; /* one byte for termination */
770 int sock;
771 path = luaL_checkstring(L, 1);
772 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
773 strcpy(sockaddr.sun_path, path);
774 if (stat(path, &sb) == 0) {
775 if (S_ISSOCK(sb.st_mode)) unlink(path);
776 }
777 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
778 listener->fd = -1;
779 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
780 sock = socket(
781 PF_LOCAL,
782 SOCK_STREAM | SOCK_CLOEXEC,
783 0
784 );
785 if (sock < 0) {
786 moonbr_io_errmsg();
787 lua_pushnil(L);
788 lua_pushstring(L, errmsg);
789 return 2;
790 }
791 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
792 moonbr_io_errmsg();
793 close(sock);
794 lua_pushnil(L);
795 lua_pushstring(L, errmsg);
796 return 2;
797 }
798 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
799 moonbr_io_errmsg();
800 close(sock);
801 lua_pushnil(L);
802 lua_pushstring(L, errmsg);
803 return 2;
804 }
805 listener->fd = sock;
806 listener->addrfam = AF_LOCAL;
807 listener->nonblocking = -1;
808 return 1;
809 }
811 static int moonbr_io_tcplisten(lua_State *L) {
812 moonbr_io_listener_t *listener;
813 const char *host, *port;
814 struct addrinfo hints = { 0, };
815 struct addrinfo *res, *addrinfo;
816 int errcode;
817 int sock;
818 host = luaL_optstring(L, 1, NULL);
819 port = luaL_checkstring(L, 2);
820 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
821 listener->fd = -1;
822 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
823 hints.ai_family = AF_UNSPEC;
824 hints.ai_socktype = SOCK_STREAM;
825 hints.ai_protocol = IPPROTO_TCP;
826 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
827 errcode = getaddrinfo(host, port, &hints, &res);
828 if (errcode) {
829 freeaddrinfo(res);
830 if (errcode == EAI_SYSTEM) {
831 moonbr_io_errmsg();
832 lua_pushnil(L);
833 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
834 } else {
835 lua_pushnil(L);
836 lua_pushstring(L, gai_strerror(errcode));
837 }
838 return 2;
839 }
840 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
841 if (addrinfo->ai_family == PF_INET6) goto moonbr_io_tcpconnect_found;
842 }
843 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
844 if (addrinfo->ai_family == PF_INET) goto moonbr_io_tcpconnect_found;
845 }
846 addrinfo = res;
847 moonbr_io_tcpconnect_found:
848 listener->addrfam = addrinfo->ai_family;
849 sock = socket(
850 addrinfo->ai_family,
851 addrinfo->ai_socktype | SOCK_CLOEXEC,
852 addrinfo->ai_protocol
853 );
854 if (sock < 0) {
855 moonbr_io_errmsg();
856 freeaddrinfo(res);
857 lua_pushnil(L);
858 lua_pushstring(L, errmsg);
859 return 2;
860 }
861 {
862 static const int reuseval = 1;
863 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
864 moonbr_io_errmsg();
865 freeaddrinfo(res);
866 close(sock);
867 lua_pushnil(L);
868 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
869 return 2;
870 }
871 }
872 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
873 moonbr_io_errmsg();
874 freeaddrinfo(res);
875 close(sock);
876 lua_pushnil(L);
877 lua_pushstring(L, errmsg);
878 return 2;
879 }
880 freeaddrinfo(res);
881 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
882 moonbr_io_errmsg();
883 close(sock);
884 lua_pushnil(L);
885 lua_pushstring(L, errmsg);
886 return 2;
887 }
888 listener->fd = sock;
889 listener->nonblocking = -1;
890 return 1;
891 }
893 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
894 moonbr_io_listener_t *listener;
895 int fd;
896 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
897 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
898 if (listener->nonblocking != nonblocking) {
899 int flags;
900 flags = fcntl(listener->fd, F_GETFL, 0);
901 if (flags == -1) {
902 moonbr_io_errmsg();
903 close(listener->fd);
904 listener->fd = -1;
905 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
906 }
907 if (nonblocking) flags |= O_NONBLOCK;
908 else flags &= ~O_NONBLOCK;
909 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
910 moonbr_io_errmsg();
911 close(listener->fd);
912 listener->fd = -1;
913 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
914 }
915 listener->nonblocking = nonblocking;
916 }
917 while (1) {
918 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
919 if (fd < 0) {
920 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
921 lua_pushboolean(L, 0);
922 lua_pushliteral(L, "No incoming connection pending");
923 return 2;
924 } else if (errno != EINTR) {
925 moonbr_io_errmsg();
926 lua_pushnil(L);
927 lua_pushstring(L, errmsg);
928 return 2;
929 }
930 } else {
931 moonbr_io_pushhandle(L, fd);
932 return 1;
933 }
934 }
935 }
937 static int moonbr_io_accept(lua_State *L) {
938 return moonbr_io_accept_impl(L, 0);
939 }
941 static int moonbr_io_accept_nb(lua_State *L) {
942 return moonbr_io_accept_impl(L, 1);
943 }
945 static int moonbr_io_unlisten(lua_State *L) {
946 moonbr_io_listener_t *listener;
947 struct sockaddr_un addr;
948 socklen_t addrlen;
949 struct stat sb;
950 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
951 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
952 addrlen = sizeof(addr);
953 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
954 if (close(listener->fd)) {
955 moonbr_io_errmsg();
956 listener->fd = -1;
957 if (addrlen && addrlen <= sizeof(addr)) {
958 if (stat(addr.sun_path, &sb) == 0) {
959 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
960 }
961 }
962 lua_pushnil(L);
963 lua_pushstring(L, errmsg);
964 return 2;
965 }
966 listener->fd = -1;
967 if (addrlen && addrlen <= sizeof(addr)) {
968 if (stat(addr.sun_path, &sb) == 0) {
969 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
970 }
971 }
972 lua_pushboolean(L, 1);
973 return 1;
974 }
976 static int moonbr_io_listenergc(lua_State *L) {
977 moonbr_io_listener_t *listener;
978 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
979 if (listener->fd >= 0) close(listener->fd);
980 listener->fd = -1;
981 return 0;
982 }
984 static int moonbr_io_poll(lua_State *L) {
985 moonbr_io_handle_t *handle;
986 moonbr_io_listener_t *listener;
987 int fd, isnum;
988 int nfds = 0;
989 fd_set readfds, writefds, exceptfds;
990 struct timeval timeout = {0, };
991 int status;
992 FD_ZERO(&readfds);
993 FD_ZERO(&writefds);
994 FD_ZERO(&exceptfds);
995 if (!lua_isnoneornil(L, 1)) {
996 luaL_checktype(L, 1, LUA_TTABLE);
997 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
998 if (lua_toboolean(L, -1)) {
999 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1000 if (handle) {
1001 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1002 fd = handle->fd;
1003 if (
1004 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1005 handle->readbufin != handle->readbufout /* data pending in buffer */
1006 ) {
1007 lua_pushboolean(L, 1);
1008 return 1;
1010 } else {
1011 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1012 if (listener) {
1013 fd = listener->fd;
1014 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1015 } else {
1016 fd = lua_tointegerx(L, -2, &isnum);
1017 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1020 FD_SET(fd, &readfds);
1021 if (fd+1 > nfds) nfds = fd+1;
1025 if (!lua_isnoneornil(L, 2)) {
1026 luaL_checktype(L, 2, LUA_TTABLE);
1027 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1028 if (lua_toboolean(L, -1)) {
1029 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1030 if (handle) {
1031 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1032 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1033 fd = handle->fd;
1034 } else {
1035 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1036 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1037 fd = lua_tointegerx(L, -2, &isnum);
1038 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1040 FD_SET(fd, &writefds);
1041 if (fd+1 > nfds) nfds = fd+1;
1045 if (!lua_isnoneornil(L, 3)) {
1046 lua_Number n;
1047 n = lua_tonumberx(L, 3, &isnum);
1048 if (isnum && n>=0 && n<100000000) {
1049 timeout.tv_sec = n;
1050 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1051 } else {
1052 luaL_argcheck(L, 0, 3, "not a valid timeout");
1054 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1055 } else {
1056 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1058 if (status == -1) {
1059 if (errno == EINTR) {
1060 lua_pushboolean(L, 0);
1061 lua_pushliteral(L, "Signal received while polling file descriptors");
1062 return 2;
1063 } else {
1064 moonbr_io_errmsg();
1065 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1067 } else if (status == 0) {
1068 lua_pushboolean(L, 0);
1069 lua_pushliteral(L, "Timeout while polling file descriptors");
1070 return 2;
1071 } else {
1072 lua_pushboolean(L, 1);
1073 return 1;
1077 static int moonbr_io_timeref(lua_State *L) {
1078 lua_Number sub;
1079 struct timespec tp;
1080 sub = luaL_optnumber(L, 1, 0);
1081 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1082 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1084 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1085 return 1;
1088 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1089 {"read", moonbr_io_read},
1090 {"read_nb", moonbr_io_read_nb},
1091 {"drain", moonbr_io_drain},
1092 {"drain_nb", moonbr_io_drain_nb},
1093 {"write", moonbr_io_write},
1094 {"write_nb", moonbr_io_write_nb},
1095 {"flush", moonbr_io_flush},
1096 {"flush_nb", moonbr_io_flush_nb},
1097 {"finish", moonbr_io_finish},
1098 {"close", moonbr_io_close},
1099 {"reset", moonbr_io_reset},
1100 {NULL, NULL}
1101 };
1103 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1104 {"__index", moonbr_io_handleindex},
1105 {"__newindex", moonbr_io_handlenewindex},
1106 {"__gc", moonbr_io_handlegc},
1107 {NULL, NULL}
1108 };
1110 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1111 {"accept", moonbr_io_accept},
1112 {"accept_nb", moonbr_io_accept_nb},
1113 {"close", moonbr_io_unlisten},
1114 {NULL, NULL}
1115 };
1117 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1118 {"__gc", moonbr_io_listenergc},
1119 {NULL, NULL}
1120 };
1122 static const struct luaL_Reg moonbr_io_module_funcs[] = {
1123 {"localconnect", moonbr_io_localconnect},
1124 {"localconnect_nb", moonbr_io_localconnect_nb},
1125 {"tcpconnect", moonbr_io_tcpconnect},
1126 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
1127 {"locallisten", moonbr_io_locallisten},
1128 {"tcplisten", moonbr_io_tcplisten},
1129 {"poll", moonbr_io_poll},
1130 {"timeref", moonbr_io_timeref},
1131 {NULL, NULL}
1132 };
1134 int luaopen_moonbridge_io(lua_State *L) {
1136 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
1138 lua_newtable(L); // module
1140 lua_newtable(L); // public metatable
1141 lua_newtable(L); // handle methods
1142 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
1143 lua_pushvalue(L, -1);
1144 lua_setfield(L, -4, "prototype_handle");
1145 lua_setfield(L, -2, "__index");
1146 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1148 lua_newtable(L); // handle metatable
1149 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
1150 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
1152 lua_newtable(L); // listener metatable
1153 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
1154 lua_newtable(L); // listener methods
1155 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
1156 lua_pushvalue(L, -1);
1157 lua_setfield(L, -4, "prototype_listener");
1158 lua_setfield(L, -2, "__index");
1159 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
1161 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
1162 return 1;

Impressum / About Us