moonbridge

view moonbridge_io.c @ 119:84aa2b8dcf79

Fixed bug regarding testing of valid file descriptor in moonbr_child_run function
author jbe
date Fri Apr 10 13:11:17 2015 +0200 (2015-04-10)
parents 118e320a7812
children 74ec80b721b9
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 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
862 moonbr_io_errmsg();
863 freeaddrinfo(res);
864 close(sock);
865 lua_pushnil(L);
866 lua_pushstring(L, errmsg);
867 return 2;
868 }
869 freeaddrinfo(res);
870 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
871 moonbr_io_errmsg();
872 close(sock);
873 lua_pushnil(L);
874 lua_pushstring(L, errmsg);
875 return 2;
876 }
877 listener->fd = sock;
878 listener->nonblocking = -1;
879 return 1;
880 }
882 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
883 moonbr_io_listener_t *listener;
884 int fd;
885 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
886 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
887 if (listener->nonblocking != nonblocking) {
888 int flags;
889 flags = fcntl(listener->fd, F_GETFL, 0);
890 if (flags == -1) {
891 moonbr_io_errmsg();
892 close(listener->fd);
893 listener->fd = -1;
894 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
895 }
896 if (nonblocking) flags |= O_NONBLOCK;
897 else flags &= ~O_NONBLOCK;
898 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
899 moonbr_io_errmsg();
900 close(listener->fd);
901 listener->fd = -1;
902 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
903 }
904 listener->nonblocking = nonblocking;
905 }
906 while (1) {
907 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
908 if (fd < 0) {
909 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
910 lua_pushboolean(L, 0);
911 lua_pushliteral(L, "No incoming connection pending");
912 return 2;
913 } else if (errno != EINTR) {
914 moonbr_io_errmsg();
915 lua_pushnil(L);
916 lua_pushstring(L, errmsg);
917 return 2;
918 }
919 } else {
920 moonbr_io_pushhandle(L, fd);
921 return 1;
922 }
923 }
924 }
926 static int moonbr_io_accept(lua_State *L) {
927 return moonbr_io_accept_impl(L, 0);
928 }
930 static int moonbr_io_accept_nb(lua_State *L) {
931 return moonbr_io_accept_impl(L, 1);
932 }
934 static int moonbr_io_unlisten(lua_State *L) {
935 moonbr_io_listener_t *listener;
936 struct sockaddr_un addr;
937 socklen_t addrlen;
938 struct stat sb;
939 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
940 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
941 addrlen = sizeof(addr);
942 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
943 if (close(listener->fd)) {
944 moonbr_io_errmsg();
945 listener->fd = -1;
946 if (addrlen && addrlen <= sizeof(addr)) {
947 if (stat(addr.sun_path, &sb) == 0) {
948 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
949 }
950 }
951 lua_pushnil(L);
952 lua_pushstring(L, errmsg);
953 return 2;
954 }
955 listener->fd = -1;
956 if (addrlen && addrlen <= sizeof(addr)) {
957 if (stat(addr.sun_path, &sb) == 0) {
958 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
959 }
960 }
961 lua_pushboolean(L, 1);
962 return 1;
963 }
965 static int moonbr_io_listenergc(lua_State *L) {
966 moonbr_io_listener_t *listener;
967 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
968 if (listener->fd >= 0) close(listener->fd);
969 listener->fd = -1;
970 return 0;
971 }
973 static int moonbr_io_poll(lua_State *L) {
974 moonbr_io_handle_t *handle;
975 moonbr_io_listener_t *listener;
976 int fd, isnum;
977 int nfds = 0;
978 fd_set readfds, writefds, exceptfds;
979 struct timeval timeout = {0, };
980 int status;
981 FD_ZERO(&readfds);
982 FD_ZERO(&writefds);
983 FD_ZERO(&exceptfds);
984 if (!lua_isnoneornil(L, 1)) {
985 luaL_checktype(L, 1, LUA_TTABLE);
986 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
987 if (lua_toboolean(L, -1)) {
988 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
989 if (handle) {
990 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
991 fd = handle->fd;
992 if (fd < 0) { /* fake EOF to simulate shutdown */
993 lua_pushboolean(L, 1);
994 return 1;
995 }
996 } else {
997 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
998 if (listener) {
999 fd = listener->fd;
1000 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1001 } else {
1002 fd = lua_tointegerx(L, -2, &isnum);
1003 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1006 FD_SET(fd, &readfds);
1007 if (fd+1 > nfds) nfds = fd+1;
1011 if (!lua_isnoneornil(L, 2)) {
1012 luaL_checktype(L, 2, LUA_TTABLE);
1013 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1014 if (lua_toboolean(L, -1)) {
1015 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1016 if (handle) {
1017 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1018 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1019 fd = handle->fd;
1020 } else {
1021 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1022 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1023 fd = lua_tointegerx(L, -2, &isnum);
1024 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1026 FD_SET(fd, &writefds);
1027 if (fd+1 > nfds) nfds = fd+1;
1031 if (!lua_isnoneornil(L, 3)) {
1032 lua_Number n;
1033 n = lua_tonumberx(L, 3, &isnum);
1034 if (isnum && n>=0 && n<100000000) {
1035 timeout.tv_sec = n;
1036 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1037 } else {
1038 luaL_argcheck(L, 0, 3, "not a valid timeout");
1040 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1041 } else {
1042 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1044 if (status == -1) {
1045 if (errno == EINTR) {
1046 lua_pushboolean(L, 0);
1047 lua_pushliteral(L, "Signal received while polling file descriptors");
1048 return 2;
1049 } else {
1050 moonbr_io_errmsg();
1051 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1053 } else if (status == 0) {
1054 lua_pushboolean(L, 0);
1055 lua_pushliteral(L, "Timeout while polling file descriptors");
1056 return 2;
1057 } else {
1058 lua_pushboolean(L, 1);
1059 return 1;
1063 static int moonbr_io_timeref(lua_State *L) {
1064 lua_Number sub;
1065 struct timespec tp;
1066 sub = luaL_optnumber(L, 1, 0);
1067 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1068 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1070 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1071 return 1;
1074 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1075 {"read", moonbr_io_read},
1076 {"read_nb", moonbr_io_read_nb},
1077 {"drain", moonbr_io_drain},
1078 {"drain_nb", moonbr_io_drain_nb},
1079 {"write", moonbr_io_write},
1080 {"write_nb", moonbr_io_write_nb},
1081 {"flush", moonbr_io_flush},
1082 {"flush_nb", moonbr_io_flush_nb},
1083 {"finish", moonbr_io_finish},
1084 {"close", moonbr_io_close},
1085 {"reset", moonbr_io_reset},
1086 {NULL, NULL}
1087 };
1089 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1090 {"__index", moonbr_io_handleindex},
1091 {"__newindex", moonbr_io_handlenewindex},
1092 {"__gc", moonbr_io_handlegc},
1093 {NULL, NULL}
1094 };
1096 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1097 {"accept", moonbr_io_accept},
1098 {"accept_nb", moonbr_io_accept_nb},
1099 {"close", moonbr_io_unlisten},
1100 {NULL, NULL}
1101 };
1103 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1104 {"__gc", moonbr_io_listenergc},
1105 {NULL, NULL}
1106 };
1108 static const struct luaL_Reg moonbr_io_module_funcs[] = {
1109 {"localconnect", moonbr_io_localconnect},
1110 {"localconnect_nb", moonbr_io_localconnect_nb},
1111 {"tcpconnect", moonbr_io_tcpconnect},
1112 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
1113 {"locallisten", moonbr_io_locallisten},
1114 {"tcplisten", moonbr_io_tcplisten},
1115 {"poll", moonbr_io_poll},
1116 {"timeref", moonbr_io_timeref},
1117 {NULL, NULL}
1118 };
1120 int luaopen_moonbridge_io(lua_State *L) {
1122 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
1124 lua_newtable(L); // module
1126 lua_newtable(L); // public metatable
1127 lua_newtable(L); // handle methods
1128 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
1129 lua_pushvalue(L, -1);
1130 lua_setfield(L, -4, "prototype_handle");
1131 lua_setfield(L, -2, "__index");
1132 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1134 lua_newtable(L); // handle metatable
1135 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
1136 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
1138 lua_newtable(L); // listener metatable
1139 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
1140 lua_newtable(L); // listener methods
1141 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
1142 lua_pushvalue(L, -1);
1143 lua_setfield(L, -4, "prototype_listener");
1144 lua_setfield(L, -2, "__index");
1145 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
1147 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
1148 return 1;

Impressum / About Us