moonbridge

view moonbridge_io.c @ 136:ae23bcae95d1

Restored Linux compatibility regarding #include section
author jbe
date Thu Apr 16 22:12:34 2015 +0200 (2015-04-16)
parents 795bc86be569
children 46ebdc5bf825
line source
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <string.h>
5 #include <errno.h>
6 #include <unistd.h>
7 #include <signal.h>
8 #include <fcntl.h>
9 #include <sys/stat.h>
10 #include <sys/socket.h>
11 #include <sys/un.h>
12 #include <netinet/in.h>
13 #include <netinet/tcp.h>
14 #include <sys/select.h>
15 #include <time.h>
16 #include <netdb.h>
17 #include <arpa/inet.h>
19 #include <lua.h>
20 #include <lauxlib.h>
21 #include <lualib.h>
23 #define MOONBR_IO_MAXSTRERRORLEN 80
24 #define MOONBR_IO_READBUFLEN 4096
25 #define MOONBR_IO_WRITEBUFLEN 4096
27 #define MOONBR_IO_LISTEN_BACKLOG 1024
29 #define moonbr_io_errmsg() \
30 char errmsg[MOONBR_IO_MAXSTRERRORLEN]; \
31 strerror_r(errno, errmsg, MOONBR_IO_MAXSTRERRORLEN)
33 #define MOONBR_IO_HANDLE_MT_REGKEY "moonbridge_io_handle"
34 #define MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY "moonbridge_io_handle_public"
35 #define MOONBR_IO_LISTENER_MT_REGKEY "moonbridge_io_listener"
37 typedef struct {
38 int fd;
39 int issock;
40 sa_family_t addrfam;
41 int finished;
42 int closed;
43 int nonblocking;
44 int nopush;
45 int readerr;
46 int readbufin;
47 int readbufout;
48 int writeerr;
49 size_t writeleft;
50 size_t flushedleft;
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 inline 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 if (flush) handle->flushedleft = handle->writeleft;
291 while (handle->writeqout != handle->writeqin) {
292 lua_rawgeti(L, -1, handle->writeqout);
293 str = lua_tolstring(L, -1, &strlen);
294 while (handle->writeqoff < strlen) {
295 if (
296 strlen - handle->writeqoff <
297 MOONBR_IO_WRITEBUFLEN - handle->writebufin
298 ) {
299 memcpy(
300 handle->writebuf + handle->writebufin,
301 str + handle->writeqoff,
302 strlen - handle->writeqoff
303 );
304 handle->writebufin += strlen - handle->writeqoff;
305 break;
306 } else {
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 moonbr_io_handle_set_nopush(L, handle, 1);
315 written = write(
316 handle->fd,
317 handle->writebuf + handle->writebufout,
318 MOONBR_IO_WRITEBUFLEN - handle->writebufout
319 );
320 if (written < 0) {
321 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
322 goto moonbr_io_write_impl_block;
323 } else if (errno != EINTR) {
324 moonbr_io_errmsg();
325 lua_pushnil(L);
326 lua_pushstring(L, errmsg);
327 return 2;
328 }
329 } else {
330 handle->writebufout += written;
331 handle->writeleft -= written;
332 if (handle->flushedleft) {
333 if (written >= handle->flushedleft) {
334 handle->flushedleft = 0;
335 moonbr_io_handle_set_nopush(L, handle, 0);
336 } else {
337 handle->flushedleft -= written;
338 }
339 }
340 }
341 }
342 handle->writebufin = 0;
343 handle->writebufout = 0;
344 }
345 }
346 handle->writeqoff = 0;
347 lua_pop(L, 1);
348 lua_pushnil(L);
349 lua_rawseti(L, -2, handle->writeqout++);
350 }
351 while (handle->flushedleft) {
352 moonbr_io_handle_set_nopush(L, handle, 1);
353 written = write(
354 handle->fd,
355 handle->writebuf + handle->writebufout,
356 handle->writebufin - handle->writebufout
357 );
358 if (written < 0) {
359 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
360 goto moonbr_io_write_impl_block;
361 } else if (errno != EINTR) {
362 moonbr_io_errmsg();
363 lua_pushnil(L);
364 lua_pushstring(L, errmsg);
365 return 2;
366 }
367 } else {
368 handle->writebufout += written;
369 handle->writeleft -= written;
370 if (handle->flushedleft) {
371 if (written >= handle->flushedleft) {
372 handle->flushedleft = 0;
373 moonbr_io_handle_set_nopush(L, handle, 0);
374 } else {
375 handle->flushedleft -= written;
376 }
377 }
378 }
379 }
380 if (handle->writebufout == handle->writebufin) {
381 handle->writebufin = 0;
382 handle->writebufout = 0;
383 }
384 if (nonblocking) lua_pushinteger(L, 0);
385 else lua_pushvalue(L, 1);
386 handle->writeerr = 0;
387 return 1;
388 moonbr_io_write_impl_block:
389 lua_pushinteger(L, handle->writeleft);
390 handle->writeerr = 0;
391 return 1;
392 }
394 static int moonbr_io_write(lua_State *L) {
395 return moonbr_io_write_impl(L, 0, 0);
396 }
398 static int moonbr_io_write_nb(lua_State *L) {
399 return moonbr_io_write_impl(L, 1, 0);
400 }
402 static int moonbr_io_flush(lua_State *L) {
403 return moonbr_io_write_impl(L, 0, 1);
404 }
406 static int moonbr_io_flush_nb(lua_State *L) {
407 return moonbr_io_write_impl(L, 1, 1);
408 }
410 static int moonbr_io_finish(lua_State *L) {
411 moonbr_io_handle_t *handle;
412 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
413 if (handle->closed) luaL_error(L, "Attempt to finish a closed I/O handle");
414 if (handle->finished) luaL_error(L, "Attempt to finish a finished I/O handle");
415 if (handle->writeleft) {
416 lua_pushcfunction(L, moonbr_io_flush);
417 lua_pushvalue(L, 1);
418 if (lua_pcall(L, 1, 2, 0)) {
419 handle->finished = 1;
420 lua_error(L);
421 }
422 if (!lua_toboolean(L, -2)) {
423 handle->finished = 1;
424 return 2;
425 }
426 }
427 handle->finished = 1;
428 if (handle->addrfam == AF_INET6 || handle->addrfam == AF_INET) {
429 if (shutdown(handle->fd, SHUT_WR)) {
430 moonbr_io_errmsg();
431 lua_pushnil(L);
432 lua_pushstring(L, errmsg);
433 return 2;
434 }
435 } else {
436 if (close(handle->fd)) {
437 moonbr_io_errmsg();
438 handle->fd = -1;
439 lua_pushnil(L);
440 lua_pushstring(L, errmsg);
441 return 2;
442 }
443 handle->fd = -1; /* fake EOF on read */
444 }
445 lua_pushboolean(L, 1);
446 return 1;
447 }
449 static int moonbr_io_close_impl(lua_State *L, int reset) {
450 moonbr_io_handle_t *handle;
451 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
452 if (handle->closed) luaL_error(L, "Attempt to close a closed I/O handle");
453 if (!reset) {
454 if (handle->writeleft) {
455 lua_pushcfunction(L, moonbr_io_flush);
456 lua_pushvalue(L, 1);
457 if (lua_pcall(L, 1, 2, 0)) {
458 handle->closed = 1;
459 close(handle->fd);
460 handle->fd = -1;
461 lua_error(L);
462 }
463 handle->closed = 1;
464 if (!lua_toboolean(L, -2)) {
465 close(handle->fd);
466 handle->fd = -1;
467 return 2;
468 }
469 } else {
470 handle->closed = 1;
471 moonbr_io_handle_set_linger(L, handle, -1);
472 }
473 } else {
474 handle->closed = 1;
475 }
476 if (handle->fd >= 0) {
477 if (close(handle->fd)) {
478 moonbr_io_errmsg();
479 handle->fd = -1;
480 lua_pushnil(L);
481 lua_pushstring(L, errmsg);
482 return 2;
483 }
484 handle->fd = -1;
485 }
486 lua_pushboolean(L, 1);
487 return 1;
489 }
491 static int moonbr_io_close(lua_State *L) {
492 return moonbr_io_close_impl(L, 0);
493 }
495 static int moonbr_io_reset(lua_State *L) {
496 return moonbr_io_close_impl(L, 1);
497 }
499 static int moonbr_io_handlegc(lua_State *L) {
500 moonbr_io_handle_t *handle;
501 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
502 if (handle->fd >= 0) {
503 lua_pushcfunction(L, moonbr_io_close);
504 lua_pushvalue(L, 1);
505 lua_pushinteger(L, 0);
506 lua_call(L, 2, 0);
507 }
508 return 0;
509 }
511 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
512 moonbr_io_handle_t *handle;
513 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
514 if (!handle->closed) {
515 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
516 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
517 lua_call(L, 1, 0);
518 }
519 }
521 void moonbr_io_pushhandle(lua_State *L, int fd) {
522 moonbr_io_handle_t *handle;
523 struct sockaddr addr;
524 socklen_t addrlen;
525 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
526 handle->fd = fd;
527 addrlen = sizeof(addr);
528 if (getsockname(fd, &addr, &addrlen)) {
529 if (errno != ENOTSOCK) {
530 moonbr_io_errmsg();
531 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
532 }
533 handle->issock = 0;
534 } else {
535 handle->issock = 1;
536 handle->addrfam = addr.sa_family;
537 }
538 handle->finished = 0;
539 handle->closed = 0;
540 handle->nonblocking = -1;
541 handle->nopush = -1;
542 handle->readerr = 0;
543 handle->readbufin = 0;
544 handle->readbufout = 0;
545 handle->writeerr = 0;
546 handle->writeleft = 0;
547 handle->flushedleft = 0;
548 handle->writeqin = 0;
549 handle->writeqout = 0;
550 handle->writeqoff = 0;
551 handle->writebufin = 0;
552 handle->writebufout = 0;
553 moonbr_io_handle_set_linger(L, handle, 0);
554 luaL_getmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
555 lua_setmetatable(L, -2);
556 lua_newtable(L); // uservalue
557 lua_newtable(L);
558 lua_setfield(L, -2, "writequeue");
559 lua_newtable(L); // public
560 if (handle->addrfam == AF_INET6) {
561 struct sockaddr_in6 addr_in6;
562 char addrstrbuf[INET6_ADDRSTRLEN];
563 const char *addrstr;
564 addrlen = sizeof(addr_in6);
565 if (getsockname(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
566 moonbr_io_errmsg();
567 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
568 }
569 if (addrlen > sizeof(addr_in6)) {
570 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
571 }
572 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
573 if (!addrstr) {
574 moonbr_io_errmsg();
575 luaL_error(L, "Could not format local IP address: %s", errmsg);
576 } else {
577 lua_pushstring(L, addrstr);
578 lua_setfield(L, -2, "local_ip6");
579 }
580 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
581 lua_setfield(L, -2, "local_tcpport");
582 if (getpeername(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
583 moonbr_io_errmsg();
584 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
585 }
586 if (addrlen > sizeof(addr_in6)) {
587 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
588 }
589 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
590 if (!addrstr) {
591 moonbr_io_errmsg();
592 luaL_error(L, "Could not format remote IP address: %s", errmsg);
593 } else {
594 lua_pushstring(L, addrstr);
595 lua_setfield(L, -2, "remote_ip6");
596 }
597 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
598 lua_setfield(L, -2, "remote_tcpport");
599 } else if (handle->addrfam == AF_INET) {
600 struct sockaddr_in addr_in;
601 char addrstrbuf[INET_ADDRSTRLEN];
602 const char *addrstr;
603 addrlen = sizeof(addr_in);
604 if (getsockname(fd, (struct sockaddr *)&addr_in, &addrlen)) {
605 moonbr_io_errmsg();
606 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
607 }
608 if (addrlen > sizeof(addr_in)) {
609 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
610 }
611 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
612 if (!addrstr) {
613 moonbr_io_errmsg();
614 luaL_error(L, "Could not format local IP address: %s", errmsg);
615 } else {
616 lua_pushstring(L, addrstr);
617 lua_setfield(L, -2, "local_ip4");
618 }
619 lua_pushinteger(L, ntohs(addr_in.sin_port));
620 lua_setfield(L, -2, "local_tcpport");
621 if (getpeername(fd, (struct sockaddr *)&addr_in, &addrlen)) {
622 moonbr_io_errmsg();
623 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
624 }
625 if (addrlen > sizeof(addr_in)) {
626 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
627 }
628 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
629 if (!addrstr) {
630 moonbr_io_errmsg();
631 luaL_error(L, "Could not format remote IP address: %s", errmsg);
632 } else {
633 lua_pushstring(L, addrstr);
634 lua_setfield(L, -2, "remote_ip4");
635 }
636 lua_pushinteger(L, ntohs(addr_in.sin_port));
637 lua_setfield(L, -2, "remote_tcpport");
638 }
639 luaL_getmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
640 lua_setmetatable(L, -2);
641 lua_setfield(L, -2, "public");
642 lua_setuservalue(L, -2);
643 }
645 static int moonbr_io_handleindex(lua_State *L) {
646 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
647 lua_getuservalue(L, 1);
648 lua_getfield(L, -1, "public");
649 lua_pushvalue(L, 2);
650 lua_gettable(L, -2);
651 return 1;
652 }
654 static int moonbr_io_handlenewindex(lua_State *L) {
655 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
656 lua_getuservalue(L, 1);
657 lua_getfield(L, -1, "public");
658 lua_pushvalue(L, 2);
659 lua_pushvalue(L, 3);
660 lua_settable(L, -3);
661 return 0;
662 }
664 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
665 const char *path;
666 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
667 const int path_maxlen = sizeof(struct sockaddr_un) - (
668 (void *)sockaddr.sun_path - (void *)&sockaddr
669 ) - 1; /* one byte for termination */
670 int sock;
671 path = luaL_checkstring(L, 1);
672 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
673 strcpy(sockaddr.sun_path, path);
674 sock = socket(
675 PF_LOCAL,
676 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
677 0
678 );
679 if (sock < 0) {
680 moonbr_io_errmsg();
681 lua_pushnil(L);
682 lua_pushstring(L, errmsg);
683 return 2;
684 }
685 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
686 if (!nonblocking && errno == EINTR) {
687 moonbr_io_errmsg();
688 close(sock);
689 lua_pushnil(L);
690 lua_pushstring(L, errmsg);
691 return 2;
692 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
693 moonbr_io_errmsg();
694 lua_pushnil(L);
695 lua_pushstring(L, errmsg);
696 return 2;
697 }
698 }
699 moonbr_io_pushhandle(L, sock);
700 return 1;
701 }
703 static int moonbr_io_localconnect(lua_State *L) {
704 return moonbr_io_localconnect_impl(L, 0);
705 }
707 static int moonbr_io_localconnect_nb(lua_State *L) {
708 return moonbr_io_localconnect_impl(L, 1);
709 }
711 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
712 const char *host, *port;
713 struct addrinfo hints = { 0, };
714 struct addrinfo *res, *addrinfo;
715 int errcode;
716 int sock;
717 host = luaL_checkstring(L, 1);
718 port = luaL_checkstring(L, 2);
719 hints.ai_family = AF_UNSPEC;
720 hints.ai_socktype = SOCK_STREAM;
721 hints.ai_protocol = IPPROTO_TCP;
722 hints.ai_flags = AI_ADDRCONFIG;
723 errcode = getaddrinfo(host, port, &hints, &res);
724 if (errcode) {
725 freeaddrinfo(res);
726 if (errcode == EAI_SYSTEM) {
727 moonbr_io_errmsg();
728 lua_pushnil(L);
729 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
730 } else {
731 lua_pushnil(L);
732 lua_pushstring(L, gai_strerror(errcode));
733 }
734 return 2;
735 }
736 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
737 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
738 }
739 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
740 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
741 }
742 addrinfo = res;
743 moonbr_io_tcpconnect_found:
744 sock = socket(
745 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
746 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
747 addrinfo->ai_protocol
748 );
749 if (sock < 0) {
750 moonbr_io_errmsg();
751 freeaddrinfo(res);
752 lua_pushnil(L);
753 lua_pushstring(L, errmsg);
754 return 2;
755 }
756 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
757 freeaddrinfo(res);
758 if (!nonblocking && errno == EINTR) {
759 moonbr_io_errmsg();
760 close(sock);
761 lua_pushnil(L);
762 lua_pushstring(L, errmsg);
763 return 2;
764 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
765 moonbr_io_errmsg();
766 lua_pushnil(L);
767 lua_pushstring(L, errmsg);
768 return 2;
769 }
770 } else {
771 freeaddrinfo(res);
772 }
773 moonbr_io_pushhandle(L, sock);
774 return 1;
775 }
777 static int moonbr_io_tcpconnect(lua_State *L) {
778 return moonbr_io_tcpconnect_impl(L, 0);
779 }
781 static int moonbr_io_tcpconnect_nb(lua_State *L) {
782 return moonbr_io_tcpconnect_impl(L, 1);
783 }
785 static int moonbr_io_locallisten(lua_State *L) {
786 moonbr_io_listener_t *listener;
787 const char *path;
788 struct stat sb;
789 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
790 const int path_maxlen = sizeof(struct sockaddr_un) - (
791 (void *)sockaddr.sun_path - (void *)&sockaddr
792 ) - 1; /* one byte for termination */
793 int sock;
794 path = luaL_checkstring(L, 1);
795 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
796 strcpy(sockaddr.sun_path, path);
797 if (stat(path, &sb) == 0) {
798 if (S_ISSOCK(sb.st_mode)) unlink(path);
799 }
800 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
801 listener->fd = -1;
802 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
803 sock = socket(
804 PF_LOCAL,
805 SOCK_STREAM | SOCK_CLOEXEC,
806 0
807 );
808 if (sock < 0) {
809 moonbr_io_errmsg();
810 lua_pushnil(L);
811 lua_pushstring(L, errmsg);
812 return 2;
813 }
814 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
815 moonbr_io_errmsg();
816 close(sock);
817 lua_pushnil(L);
818 lua_pushstring(L, errmsg);
819 return 2;
820 }
821 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
822 moonbr_io_errmsg();
823 close(sock);
824 lua_pushnil(L);
825 lua_pushstring(L, errmsg);
826 return 2;
827 }
828 listener->fd = sock;
829 listener->addrfam = AF_LOCAL;
830 listener->nonblocking = -1;
831 return 1;
832 }
834 static int moonbr_io_tcplisten(lua_State *L) {
835 moonbr_io_listener_t *listener;
836 const char *host, *port;
837 struct addrinfo hints = { 0, };
838 struct addrinfo *res, *addrinfo;
839 int errcode;
840 int sock;
841 host = luaL_optstring(L, 1, NULL);
842 port = luaL_checkstring(L, 2);
843 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
844 listener->fd = -1;
845 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
846 hints.ai_family = AF_UNSPEC;
847 hints.ai_socktype = SOCK_STREAM;
848 hints.ai_protocol = IPPROTO_TCP;
849 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
850 errcode = getaddrinfo(host, port, &hints, &res);
851 if (errcode) {
852 freeaddrinfo(res);
853 if (errcode == EAI_SYSTEM) {
854 moonbr_io_errmsg();
855 lua_pushnil(L);
856 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
857 } else {
858 lua_pushnil(L);
859 lua_pushstring(L, gai_strerror(errcode));
860 }
861 return 2;
862 }
863 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
864 if (addrinfo->ai_family == AF_INET6) goto moonbr_io_tcpconnect_found;
865 }
866 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
867 if (addrinfo->ai_family == AF_INET) goto moonbr_io_tcpconnect_found;
868 }
869 addrinfo = res;
870 moonbr_io_tcpconnect_found:
871 listener->addrfam = addrinfo->ai_family;
872 sock = socket(
873 addrinfo->ai_family, /* NOTE: not correctly using PF_* but AF_* constants here */
874 addrinfo->ai_socktype | SOCK_CLOEXEC,
875 addrinfo->ai_protocol
876 );
877 if (sock < 0) {
878 moonbr_io_errmsg();
879 freeaddrinfo(res);
880 lua_pushnil(L);
881 lua_pushstring(L, errmsg);
882 return 2;
883 }
884 {
885 static const int reuseval = 1;
886 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
887 moonbr_io_errmsg();
888 freeaddrinfo(res);
889 close(sock);
890 lua_pushnil(L);
891 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
892 return 2;
893 }
894 }
895 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
896 moonbr_io_errmsg();
897 freeaddrinfo(res);
898 close(sock);
899 lua_pushnil(L);
900 lua_pushstring(L, errmsg);
901 return 2;
902 }
903 freeaddrinfo(res);
904 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
905 moonbr_io_errmsg();
906 close(sock);
907 lua_pushnil(L);
908 lua_pushstring(L, errmsg);
909 return 2;
910 }
911 listener->fd = sock;
912 listener->nonblocking = -1;
913 return 1;
914 }
916 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
917 moonbr_io_listener_t *listener;
918 int fd;
919 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
920 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
921 if (listener->nonblocking != nonblocking) {
922 int flags;
923 flags = fcntl(listener->fd, F_GETFL, 0);
924 if (flags == -1) {
925 moonbr_io_errmsg();
926 close(listener->fd);
927 listener->fd = -1;
928 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
929 }
930 if (nonblocking) flags |= O_NONBLOCK;
931 else flags &= ~O_NONBLOCK;
932 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
933 moonbr_io_errmsg();
934 close(listener->fd);
935 listener->fd = -1;
936 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
937 }
938 listener->nonblocking = nonblocking;
939 }
940 while (1) {
941 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
942 if (fd < 0) {
943 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
944 lua_pushboolean(L, 0);
945 lua_pushliteral(L, "No incoming connection pending");
946 return 2;
947 } else if (errno != EINTR) {
948 moonbr_io_errmsg();
949 lua_pushnil(L);
950 lua_pushstring(L, errmsg);
951 return 2;
952 }
953 } else {
954 moonbr_io_pushhandle(L, fd);
955 return 1;
956 }
957 }
958 }
960 static int moonbr_io_accept(lua_State *L) {
961 return moonbr_io_accept_impl(L, 0);
962 }
964 static int moonbr_io_accept_nb(lua_State *L) {
965 return moonbr_io_accept_impl(L, 1);
966 }
968 static int moonbr_io_unlisten(lua_State *L) {
969 moonbr_io_listener_t *listener;
970 struct sockaddr_un addr;
971 socklen_t addrlen;
972 struct stat sb;
973 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
974 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
975 addrlen = sizeof(addr);
976 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
977 if (close(listener->fd)) {
978 moonbr_io_errmsg();
979 listener->fd = -1;
980 if (addrlen && addrlen <= sizeof(addr)) {
981 if (stat(addr.sun_path, &sb) == 0) {
982 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
983 }
984 }
985 lua_pushnil(L);
986 lua_pushstring(L, errmsg);
987 return 2;
988 }
989 listener->fd = -1;
990 if (addrlen && addrlen <= sizeof(addr)) {
991 if (stat(addr.sun_path, &sb) == 0) {
992 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
993 }
994 }
995 lua_pushboolean(L, 1);
996 return 1;
997 }
999 static int moonbr_io_listenergc(lua_State *L) {
1000 moonbr_io_listener_t *listener;
1001 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
1002 if (listener->fd >= 0) close(listener->fd);
1003 listener->fd = -1;
1004 return 0;
1007 static int moonbr_io_poll(lua_State *L) {
1008 moonbr_io_handle_t *handle;
1009 moonbr_io_listener_t *listener;
1010 int fd, isnum;
1011 int nfds = 0;
1012 fd_set readfds, writefds, exceptfds;
1013 struct timeval timeout = {0, };
1014 int status;
1015 FD_ZERO(&readfds);
1016 FD_ZERO(&writefds);
1017 FD_ZERO(&exceptfds);
1018 if (!lua_isnoneornil(L, 1)) {
1019 luaL_checktype(L, 1, LUA_TTABLE);
1020 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1021 if (lua_toboolean(L, -1)) {
1022 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1023 if (handle) {
1024 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1025 fd = handle->fd;
1026 if (
1027 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1028 handle->readbufin != handle->readbufout /* data pending in buffer */
1029 ) {
1030 lua_pushboolean(L, 1);
1031 return 1;
1033 } else {
1034 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1035 if (listener) {
1036 fd = listener->fd;
1037 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1038 } else {
1039 fd = lua_tointegerx(L, -2, &isnum);
1040 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1043 FD_SET(fd, &readfds);
1044 if (fd+1 > nfds) nfds = fd+1;
1048 if (!lua_isnoneornil(L, 2)) {
1049 luaL_checktype(L, 2, LUA_TTABLE);
1050 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1051 if (lua_toboolean(L, -1)) {
1052 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1053 if (handle) {
1054 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1055 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1056 fd = handle->fd;
1057 } else {
1058 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1059 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1060 fd = lua_tointegerx(L, -2, &isnum);
1061 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1063 FD_SET(fd, &writefds);
1064 if (fd+1 > nfds) nfds = fd+1;
1068 if (!lua_isnoneornil(L, 3)) {
1069 lua_Number n;
1070 n = lua_tonumberx(L, 3, &isnum);
1071 if (isnum && n>=0 && n<100000000) {
1072 timeout.tv_sec = n;
1073 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1074 } else {
1075 luaL_argcheck(L, 0, 3, "not a valid timeout");
1077 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1078 } else {
1079 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1081 if (status == -1) {
1082 if (errno == EINTR) {
1083 lua_pushboolean(L, 0);
1084 lua_pushliteral(L, "Signal received while polling file descriptors");
1085 return 2;
1086 } else {
1087 moonbr_io_errmsg();
1088 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1090 } else if (status == 0) {
1091 lua_pushboolean(L, 0);
1092 lua_pushliteral(L, "Timeout while polling file descriptors");
1093 return 2;
1094 } else {
1095 lua_pushboolean(L, 1);
1096 return 1;
1100 static int moonbr_io_timeref(lua_State *L) {
1101 lua_Number sub;
1102 struct timespec tp;
1103 sub = luaL_optnumber(L, 1, 0);
1104 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1105 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1107 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1108 return 1;
1111 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1112 {"read", moonbr_io_read},
1113 {"read_nb", moonbr_io_read_nb},
1114 {"drain", moonbr_io_drain},
1115 {"drain_nb", moonbr_io_drain_nb},
1116 {"write", moonbr_io_write},
1117 {"write_nb", moonbr_io_write_nb},
1118 {"flush", moonbr_io_flush},
1119 {"flush_nb", moonbr_io_flush_nb},
1120 {"finish", moonbr_io_finish},
1121 {"close", moonbr_io_close},
1122 {"reset", moonbr_io_reset},
1123 {NULL, NULL}
1124 };
1126 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1127 {"__index", moonbr_io_handleindex},
1128 {"__newindex", moonbr_io_handlenewindex},
1129 {"__gc", moonbr_io_handlegc},
1130 {NULL, NULL}
1131 };
1133 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1134 {"accept", moonbr_io_accept},
1135 {"accept_nb", moonbr_io_accept_nb},
1136 {"close", moonbr_io_unlisten},
1137 {NULL, NULL}
1138 };
1140 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1141 {"__gc", moonbr_io_listenergc},
1142 {NULL, NULL}
1143 };
1145 static const struct luaL_Reg moonbr_io_module_funcs[] = {
1146 {"localconnect", moonbr_io_localconnect},
1147 {"localconnect_nb", moonbr_io_localconnect_nb},
1148 {"tcpconnect", moonbr_io_tcpconnect},
1149 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
1150 {"locallisten", moonbr_io_locallisten},
1151 {"tcplisten", moonbr_io_tcplisten},
1152 {"poll", moonbr_io_poll},
1153 {"timeref", moonbr_io_timeref},
1154 {NULL, NULL}
1155 };
1157 int luaopen_moonbridge_io(lua_State *L) {
1159 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
1161 lua_newtable(L); // module
1163 lua_newtable(L); // public metatable
1164 lua_newtable(L); // handle methods
1165 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
1166 lua_pushvalue(L, -1);
1167 lua_setfield(L, -4, "prototype_handle");
1168 lua_setfield(L, -2, "__index");
1169 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1171 lua_newtable(L); // handle metatable
1172 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
1173 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
1175 lua_newtable(L); // listener metatable
1176 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
1177 lua_newtable(L); // listener methods
1178 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
1179 lua_pushvalue(L, -1);
1180 lua_setfield(L, -4, "prototype_listener");
1181 lua_setfield(L, -2, "__index");
1182 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
1184 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
1185 return 1;

Impressum / About Us