moonbridge

view moonbridge_io.c @ 137:46ebdc5bf825

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

Impressum / About Us