moonbridge

view moonbridge_io.c @ 130:ee98e12427a9

Modified termination sequence handling
author jbe
date Wed Apr 15 00:54:17 2015 +0200 (2015-04-15)
parents df08e63dc44b
children 293e666a41e0
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 if (!reset) {
437 if (handle->writeleft) {
438 lua_pushcfunction(L, moonbr_io_flush);
439 lua_pushvalue(L, 1);
440 if (lua_pcall(L, 1, 2, 0)) {
441 handle->closed = 1;
442 close(handle->fd);
443 handle->fd = -1;
444 lua_error(L);
445 }
446 handle->closed = 1;
447 if (!lua_toboolean(L, -2)) {
448 close(handle->fd);
449 handle->fd = -1;
450 return 2;
451 }
452 } else {
453 handle->closed = 1;
454 moonbr_io_handle_set_linger(L, handle, -1);
455 }
456 } else {
457 handle->closed = 1;
458 }
459 if (handle->fd >= 0) {
460 if (close(handle->fd)) {
461 moonbr_io_errmsg();
462 handle->fd = -1;
463 lua_pushnil(L);
464 lua_pushstring(L, errmsg);
465 return 2;
466 }
467 handle->fd = -1;
468 }
469 lua_pushboolean(L, 1);
470 return 1;
472 }
474 static int moonbr_io_close(lua_State *L) {
475 return moonbr_io_close_impl(L, 0);
476 }
478 static int moonbr_io_reset(lua_State *L) {
479 return moonbr_io_close_impl(L, 1);
480 }
482 static int moonbr_io_handlegc(lua_State *L) {
483 moonbr_io_handle_t *handle;
484 handle = luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
485 if (handle->fd >= 0) {
486 lua_pushcfunction(L, moonbr_io_close);
487 lua_pushvalue(L, 1);
488 lua_pushinteger(L, 0);
489 lua_call(L, 2, 0);
490 }
491 return 0;
492 }
494 void moonbr_io_closehandle(lua_State *L, int idx, int reset) {
495 moonbr_io_handle_t *handle;
496 handle = luaL_checkudata(L, idx, MOONBR_IO_HANDLE_MT_REGKEY);
497 if (!handle->closed) {
498 lua_pushcfunction(L, reset ? moonbr_io_reset : moonbr_io_close);
499 lua_pushvalue(L, idx < 0 ? idx-1 : idx);
500 lua_call(L, 1, 0);
501 }
502 }
504 void moonbr_io_pushhandle(lua_State *L, int fd) {
505 moonbr_io_handle_t *handle;
506 struct sockaddr addr;
507 socklen_t addrlen;
508 handle = lua_newuserdata(L, sizeof(moonbr_io_handle_t));
509 handle->fd = fd;
510 addrlen = sizeof(addr);
511 if (getsockname(fd, &addr, &addrlen)) {
512 if (errno != ENOTSOCK) {
513 moonbr_io_errmsg();
514 luaL_error(L, "Unexpected error when examining socket: %s", errmsg);
515 }
516 handle->issock = 0;
517 } else {
518 handle->issock = 1;
519 handle->addrfam = addr.sa_family;
520 }
521 handle->finished = 0;
522 handle->closed = 0;
523 handle->nonblocking = -1;
524 handle->nopush = -1;
525 handle->readerr = 0;
526 handle->readbufin = 0;
527 handle->readbufout = 0;
528 handle->writeerr = 0;
529 handle->writeleft = 0;
530 handle->writeqin = 0;
531 handle->writeqout = 0;
532 handle->writeqoff = 0;
533 handle->writebufin = 0;
534 handle->writebufout = 0;
535 moonbr_io_handle_set_linger(L, handle, 0);
536 luaL_getmetatable(L, MOONBR_IO_HANDLE_MT_REGKEY);
537 lua_setmetatable(L, -2);
538 lua_newtable(L); // uservalue
539 lua_newtable(L);
540 lua_setfield(L, -2, "writequeue");
541 lua_newtable(L); // public
542 if (handle->addrfam == AF_INET6) {
543 struct sockaddr_in6 addr_in6;
544 char addrstrbuf[INET6_ADDRSTRLEN];
545 const char *addrstr;
546 addrlen = sizeof(addr_in6);
547 if (getsockname(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
548 moonbr_io_errmsg();
549 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
550 }
551 if (addrlen > sizeof(addr_in6)) {
552 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
553 }
554 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
555 if (!addrstr) {
556 moonbr_io_errmsg();
557 luaL_error(L, "Could not format local IP address: %s", errmsg);
558 } else {
559 lua_pushstring(L, addrstr);
560 lua_setfield(L, -2, "local_ip6");
561 }
562 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
563 lua_setfield(L, -2, "local_tcpport");
564 if (getpeername(fd, (struct sockaddr *)&addr_in6, &addrlen)) {
565 moonbr_io_errmsg();
566 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
567 }
568 if (addrlen > sizeof(addr_in6)) {
569 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
570 }
571 addrstr = inet_ntop(AF_INET6, addr_in6.sin6_addr.s6_addr, addrstrbuf, sizeof(addrstrbuf));
572 if (!addrstr) {
573 moonbr_io_errmsg();
574 luaL_error(L, "Could not format remote IP address: %s", errmsg);
575 } else {
576 lua_pushstring(L, addrstr);
577 lua_setfield(L, -2, "remote_ip6");
578 }
579 lua_pushinteger(L, ntohs(addr_in6.sin6_port));
580 lua_setfield(L, -2, "remote_tcpport");
581 } else if (handle->addrfam == AF_INET) {
582 struct sockaddr_in addr_in;
583 char addrstrbuf[INET_ADDRSTRLEN];
584 const char *addrstr;
585 addrlen = sizeof(addr_in);
586 if (getsockname(fd, (struct sockaddr *)&addr_in, &addrlen)) {
587 moonbr_io_errmsg();
588 luaL_error(L, "Could not determine local IP address/port: %s", errmsg);
589 }
590 if (addrlen > sizeof(addr_in)) {
591 luaL_error(L, "Could not determine local IP address/port: buffer size exceeded");
592 }
593 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
594 if (!addrstr) {
595 moonbr_io_errmsg();
596 luaL_error(L, "Could not format local IP address: %s", errmsg);
597 } else {
598 lua_pushstring(L, addrstr);
599 lua_setfield(L, -2, "local_ip4");
600 }
601 lua_pushinteger(L, ntohs(addr_in.sin_port));
602 lua_setfield(L, -2, "local_tcpport");
603 if (getpeername(fd, (struct sockaddr *)&addr_in, &addrlen)) {
604 moonbr_io_errmsg();
605 luaL_error(L, "Could not determine remote IP address/port: %s", errmsg);
606 }
607 if (addrlen > sizeof(addr_in)) {
608 luaL_error(L, "Could not determine remote IP address/port: buffer size exceeded");
609 }
610 addrstr = inet_ntop(AF_INET, &addr_in.sin_addr.s_addr, addrstrbuf, sizeof(addrstrbuf));
611 if (!addrstr) {
612 moonbr_io_errmsg();
613 luaL_error(L, "Could not format remote IP address: %s", errmsg);
614 } else {
615 lua_pushstring(L, addrstr);
616 lua_setfield(L, -2, "remote_ip4");
617 }
618 lua_pushinteger(L, ntohs(addr_in.sin_port));
619 lua_setfield(L, -2, "remote_tcpport");
620 }
621 luaL_getmetatable(L, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
622 lua_setmetatable(L, -2);
623 lua_setfield(L, -2, "public");
624 lua_setuservalue(L, -2);
625 }
627 static int moonbr_io_handleindex(lua_State *L) {
628 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
629 lua_getuservalue(L, 1);
630 lua_getfield(L, -1, "public");
631 lua_pushvalue(L, 2);
632 lua_gettable(L, -2);
633 return 1;
634 }
636 static int moonbr_io_handlenewindex(lua_State *L) {
637 luaL_checkudata(L, 1, MOONBR_IO_HANDLE_MT_REGKEY);
638 lua_getuservalue(L, 1);
639 lua_getfield(L, -1, "public");
640 lua_pushvalue(L, 2);
641 lua_pushvalue(L, 3);
642 lua_settable(L, -3);
643 return 0;
644 }
646 static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) {
647 const char *path;
648 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
649 const int path_maxlen = sizeof(struct sockaddr_un) - (
650 (void *)sockaddr.sun_path - (void *)&sockaddr
651 ) - 1; /* one byte for termination */
652 int sock;
653 path = luaL_checkstring(L, 1);
654 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
655 strcpy(sockaddr.sun_path, path);
656 sock = socket(
657 PF_LOCAL,
658 SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
659 0
660 );
661 if (sock < 0) {
662 moonbr_io_errmsg();
663 lua_pushnil(L);
664 lua_pushstring(L, errmsg);
665 return 2;
666 }
667 if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
668 if (!nonblocking && errno == EINTR) {
669 moonbr_io_errmsg();
670 close(sock);
671 lua_pushnil(L);
672 lua_pushstring(L, errmsg);
673 return 2;
674 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
675 moonbr_io_errmsg();
676 lua_pushnil(L);
677 lua_pushstring(L, errmsg);
678 return 2;
679 }
680 }
681 moonbr_io_pushhandle(L, sock);
682 return 1;
683 }
685 static int moonbr_io_localconnect(lua_State *L) {
686 return moonbr_io_localconnect_impl(L, 0);
687 }
689 static int moonbr_io_localconnect_nb(lua_State *L) {
690 return moonbr_io_localconnect_impl(L, 1);
691 }
693 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) {
694 const char *host, *port;
695 struct addrinfo hints = { 0, };
696 struct addrinfo *res, *addrinfo;
697 int errcode;
698 int sock;
699 host = luaL_checkstring(L, 1);
700 port = luaL_checkstring(L, 2);
701 hints.ai_family = AF_UNSPEC;
702 hints.ai_socktype = SOCK_STREAM;
703 hints.ai_protocol = IPPROTO_TCP;
704 hints.ai_flags = AI_ADDRCONFIG;
705 errcode = getaddrinfo(host, port, &hints, &res);
706 if (errcode) {
707 freeaddrinfo(res);
708 if (errcode == EAI_SYSTEM) {
709 moonbr_io_errmsg();
710 lua_pushnil(L);
711 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
712 } else {
713 lua_pushnil(L);
714 lua_pushstring(L, gai_strerror(errcode));
715 }
716 return 2;
717 }
718 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
719 if (addrinfo->ai_family == PF_INET6) goto moonbr_io_tcpconnect_found;
720 }
721 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
722 if (addrinfo->ai_family == PF_INET) goto moonbr_io_tcpconnect_found;
723 }
724 addrinfo = res;
725 moonbr_io_tcpconnect_found:
726 sock = socket(
727 addrinfo->ai_family,
728 addrinfo->ai_socktype | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0),
729 addrinfo->ai_protocol
730 );
731 if (sock < 0) {
732 moonbr_io_errmsg();
733 freeaddrinfo(res);
734 lua_pushnil(L);
735 lua_pushstring(L, errmsg);
736 return 2;
737 }
738 if (connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
739 freeaddrinfo(res);
740 if (!nonblocking && errno == EINTR) {
741 moonbr_io_errmsg();
742 close(sock);
743 lua_pushnil(L);
744 lua_pushstring(L, errmsg);
745 return 2;
746 } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) {
747 moonbr_io_errmsg();
748 lua_pushnil(L);
749 lua_pushstring(L, errmsg);
750 return 2;
751 }
752 } else {
753 freeaddrinfo(res);
754 }
755 moonbr_io_pushhandle(L, sock);
756 return 1;
757 }
759 static int moonbr_io_tcpconnect(lua_State *L) {
760 return moonbr_io_tcpconnect_impl(L, 0);
761 }
763 static int moonbr_io_tcpconnect_nb(lua_State *L) {
764 return moonbr_io_tcpconnect_impl(L, 1);
765 }
767 static int moonbr_io_locallisten(lua_State *L) {
768 moonbr_io_listener_t *listener;
769 const char *path;
770 struct stat sb;
771 struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL };
772 const int path_maxlen = sizeof(struct sockaddr_un) - (
773 (void *)sockaddr.sun_path - (void *)&sockaddr
774 ) - 1; /* one byte for termination */
775 int sock;
776 path = luaL_checkstring(L, 1);
777 if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen);
778 strcpy(sockaddr.sun_path, path);
779 if (stat(path, &sb) == 0) {
780 if (S_ISSOCK(sb.st_mode)) unlink(path);
781 }
782 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
783 listener->fd = -1;
784 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
785 sock = socket(
786 PF_LOCAL,
787 SOCK_STREAM | SOCK_CLOEXEC,
788 0
789 );
790 if (sock < 0) {
791 moonbr_io_errmsg();
792 lua_pushnil(L);
793 lua_pushstring(L, errmsg);
794 return 2;
795 }
796 if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) {
797 moonbr_io_errmsg();
798 close(sock);
799 lua_pushnil(L);
800 lua_pushstring(L, errmsg);
801 return 2;
802 }
803 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
804 moonbr_io_errmsg();
805 close(sock);
806 lua_pushnil(L);
807 lua_pushstring(L, errmsg);
808 return 2;
809 }
810 listener->fd = sock;
811 listener->addrfam = AF_LOCAL;
812 listener->nonblocking = -1;
813 return 1;
814 }
816 static int moonbr_io_tcplisten(lua_State *L) {
817 moonbr_io_listener_t *listener;
818 const char *host, *port;
819 struct addrinfo hints = { 0, };
820 struct addrinfo *res, *addrinfo;
821 int errcode;
822 int sock;
823 host = luaL_optstring(L, 1, NULL);
824 port = luaL_checkstring(L, 2);
825 listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t));
826 listener->fd = -1;
827 luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY);
828 hints.ai_family = AF_UNSPEC;
829 hints.ai_socktype = SOCK_STREAM;
830 hints.ai_protocol = IPPROTO_TCP;
831 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
832 errcode = getaddrinfo(host, port, &hints, &res);
833 if (errcode) {
834 freeaddrinfo(res);
835 if (errcode == EAI_SYSTEM) {
836 moonbr_io_errmsg();
837 lua_pushnil(L);
838 lua_pushfstring(L, "%s: %s", gai_strerror(errcode), errmsg);
839 } else {
840 lua_pushnil(L);
841 lua_pushstring(L, gai_strerror(errcode));
842 }
843 return 2;
844 }
845 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
846 if (addrinfo->ai_family == PF_INET6) goto moonbr_io_tcpconnect_found;
847 }
848 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
849 if (addrinfo->ai_family == PF_INET) goto moonbr_io_tcpconnect_found;
850 }
851 addrinfo = res;
852 moonbr_io_tcpconnect_found:
853 listener->addrfam = addrinfo->ai_family;
854 sock = socket(
855 addrinfo->ai_family,
856 addrinfo->ai_socktype | SOCK_CLOEXEC,
857 addrinfo->ai_protocol
858 );
859 if (sock < 0) {
860 moonbr_io_errmsg();
861 freeaddrinfo(res);
862 lua_pushnil(L);
863 lua_pushstring(L, errmsg);
864 return 2;
865 }
866 {
867 static const int reuseval = 1;
868 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval))) {
869 moonbr_io_errmsg();
870 freeaddrinfo(res);
871 close(sock);
872 lua_pushnil(L);
873 lua_pushfstring(L, "Error while setting SO_REUSEADDR with setsockopt: %s", errmsg);
874 return 2;
875 }
876 }
877 if (bind(sock, addrinfo->ai_addr, addrinfo->ai_addrlen)) {
878 moonbr_io_errmsg();
879 freeaddrinfo(res);
880 close(sock);
881 lua_pushnil(L);
882 lua_pushstring(L, errmsg);
883 return 2;
884 }
885 freeaddrinfo(res);
886 if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) {
887 moonbr_io_errmsg();
888 close(sock);
889 lua_pushnil(L);
890 lua_pushstring(L, errmsg);
891 return 2;
892 }
893 listener->fd = sock;
894 listener->nonblocking = -1;
895 return 1;
896 }
898 static int moonbr_io_accept_impl(lua_State *L, int nonblocking) {
899 moonbr_io_listener_t *listener;
900 int fd;
901 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
902 if (listener->fd < 0) luaL_error(L, "Attempt to use a closed listener");
903 if (listener->nonblocking != nonblocking) {
904 int flags;
905 flags = fcntl(listener->fd, F_GETFL, 0);
906 if (flags == -1) {
907 moonbr_io_errmsg();
908 close(listener->fd);
909 listener->fd = -1;
910 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
911 }
912 if (nonblocking) flags |= O_NONBLOCK;
913 else flags &= ~O_NONBLOCK;
914 if (fcntl(listener->fd, F_SETFL, flags) == -1) {
915 moonbr_io_errmsg();
916 close(listener->fd);
917 listener->fd = -1;
918 luaL_error(L, "Unexpected error in fcntl call: %s", errmsg);
919 }
920 listener->nonblocking = nonblocking;
921 }
922 while (1) {
923 fd = accept4(listener->fd, NULL, NULL, SOCK_CLOEXEC);
924 if (fd < 0) {
925 if (nonblocking && (errno == EAGAIN || errno == EWOULDBLOCK)) {
926 lua_pushboolean(L, 0);
927 lua_pushliteral(L, "No incoming connection pending");
928 return 2;
929 } else if (errno != EINTR) {
930 moonbr_io_errmsg();
931 lua_pushnil(L);
932 lua_pushstring(L, errmsg);
933 return 2;
934 }
935 } else {
936 moonbr_io_pushhandle(L, fd);
937 return 1;
938 }
939 }
940 }
942 static int moonbr_io_accept(lua_State *L) {
943 return moonbr_io_accept_impl(L, 0);
944 }
946 static int moonbr_io_accept_nb(lua_State *L) {
947 return moonbr_io_accept_impl(L, 1);
948 }
950 static int moonbr_io_unlisten(lua_State *L) {
951 moonbr_io_listener_t *listener;
952 struct sockaddr_un addr;
953 socklen_t addrlen;
954 struct stat sb;
955 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
956 if (listener->fd < 0) luaL_error(L, "Attempt to close a closed listener");
957 addrlen = sizeof(addr);
958 if (getsockname(listener->fd, (struct sockaddr *)&addr, &addrlen)) addrlen = 0;
959 if (close(listener->fd)) {
960 moonbr_io_errmsg();
961 listener->fd = -1;
962 if (addrlen && addrlen <= sizeof(addr)) {
963 if (stat(addr.sun_path, &sb) == 0) {
964 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
965 }
966 }
967 lua_pushnil(L);
968 lua_pushstring(L, errmsg);
969 return 2;
970 }
971 listener->fd = -1;
972 if (addrlen && addrlen <= sizeof(addr)) {
973 if (stat(addr.sun_path, &sb) == 0) {
974 if (S_ISSOCK(sb.st_mode)) unlink(addr.sun_path);
975 }
976 }
977 lua_pushboolean(L, 1);
978 return 1;
979 }
981 static int moonbr_io_listenergc(lua_State *L) {
982 moonbr_io_listener_t *listener;
983 listener = luaL_checkudata(L, 1, MOONBR_IO_LISTENER_MT_REGKEY);
984 if (listener->fd >= 0) close(listener->fd);
985 listener->fd = -1;
986 return 0;
987 }
989 static int moonbr_io_poll(lua_State *L) {
990 moonbr_io_handle_t *handle;
991 moonbr_io_listener_t *listener;
992 int fd, isnum;
993 int nfds = 0;
994 fd_set readfds, writefds, exceptfds;
995 struct timeval timeout = {0, };
996 int status;
997 FD_ZERO(&readfds);
998 FD_ZERO(&writefds);
999 FD_ZERO(&exceptfds);
1000 if (!lua_isnoneornil(L, 1)) {
1001 luaL_checktype(L, 1, LUA_TTABLE);
1002 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
1003 if (lua_toboolean(L, -1)) {
1004 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1005 if (handle) {
1006 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1007 fd = handle->fd;
1008 if (
1009 fd < 0 || /* fake EOF to simulate shutdown if fd < 0 */
1010 handle->readbufin != handle->readbufout /* data pending in buffer */
1011 ) {
1012 lua_pushboolean(L, 1);
1013 return 1;
1015 } else {
1016 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1017 if (listener) {
1018 fd = listener->fd;
1019 if (fd < 0) luaL_error(L, "Attempt to poll a closed listener");
1020 } else {
1021 fd = lua_tointegerx(L, -2, &isnum);
1022 if (!isnum) luaL_error(L, "Expected integer (file descriptor), I/O handle, or listener in table key");
1025 FD_SET(fd, &readfds);
1026 if (fd+1 > nfds) nfds = fd+1;
1030 if (!lua_isnoneornil(L, 2)) {
1031 luaL_checktype(L, 2, LUA_TTABLE);
1032 for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
1033 if (lua_toboolean(L, -1)) {
1034 handle = luaL_testudata(L, -2, MOONBR_IO_HANDLE_MT_REGKEY);
1035 if (handle) {
1036 if (handle->closed) luaL_error(L, "Attempt to poll a closed connection");
1037 if (handle->finished) luaL_error(L, "Attempt to write-poll a finished connection");
1038 fd = handle->fd;
1039 } else {
1040 listener = luaL_testudata(L, -2, MOONBR_IO_LISTENER_MT_REGKEY);
1041 if (listener) luaL_error(L, "Attempt to write-poll a listener");
1042 fd = lua_tointegerx(L, -2, &isnum);
1043 if (!isnum) luaL_error(L, "Expected integer (file descriptor) or I/O handle in table key");
1045 FD_SET(fd, &writefds);
1046 if (fd+1 > nfds) nfds = fd+1;
1050 if (!lua_isnoneornil(L, 3)) {
1051 lua_Number n;
1052 n = lua_tonumberx(L, 3, &isnum);
1053 if (isnum && n>=0 && n<100000000) {
1054 timeout.tv_sec = n;
1055 timeout.tv_usec = 1e6 * (n - timeout.tv_sec);
1056 } else {
1057 luaL_argcheck(L, 0, 3, "not a valid timeout");
1059 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
1060 } else {
1061 status = select(nfds, &readfds, &writefds, &exceptfds, NULL);
1063 if (status == -1) {
1064 if (errno == EINTR) {
1065 lua_pushboolean(L, 0);
1066 lua_pushliteral(L, "Signal received while polling file descriptors");
1067 return 2;
1068 } else {
1069 moonbr_io_errmsg();
1070 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
1072 } else if (status == 0) {
1073 lua_pushboolean(L, 0);
1074 lua_pushliteral(L, "Timeout while polling file descriptors");
1075 return 2;
1076 } else {
1077 lua_pushboolean(L, 1);
1078 return 1;
1082 static int moonbr_io_timeref(lua_State *L) {
1083 lua_Number sub;
1084 struct timespec tp;
1085 sub = luaL_optnumber(L, 1, 0);
1086 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
1087 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
1089 lua_pushnumber(L, tp.tv_sec + tp.tv_nsec / 1.0e9 - sub);
1090 return 1;
1093 static const struct luaL_Reg moonbr_io_handle_methods[] = {
1094 {"read", moonbr_io_read},
1095 {"read_nb", moonbr_io_read_nb},
1096 {"drain", moonbr_io_drain},
1097 {"drain_nb", moonbr_io_drain_nb},
1098 {"write", moonbr_io_write},
1099 {"write_nb", moonbr_io_write_nb},
1100 {"flush", moonbr_io_flush},
1101 {"flush_nb", moonbr_io_flush_nb},
1102 {"finish", moonbr_io_finish},
1103 {"close", moonbr_io_close},
1104 {"reset", moonbr_io_reset},
1105 {NULL, NULL}
1106 };
1108 static const struct luaL_Reg moonbr_io_handle_metamethods[] = {
1109 {"__index", moonbr_io_handleindex},
1110 {"__newindex", moonbr_io_handlenewindex},
1111 {"__gc", moonbr_io_handlegc},
1112 {NULL, NULL}
1113 };
1115 static const struct luaL_Reg moonbr_io_listener_methods[] = {
1116 {"accept", moonbr_io_accept},
1117 {"accept_nb", moonbr_io_accept_nb},
1118 {"close", moonbr_io_unlisten},
1119 {NULL, NULL}
1120 };
1122 static const struct luaL_Reg moonbr_io_listener_metamethods[] = {
1123 {"__gc", moonbr_io_listenergc},
1124 {NULL, NULL}
1125 };
1127 static const struct luaL_Reg moonbr_io_module_funcs[] = {
1128 {"localconnect", moonbr_io_localconnect},
1129 {"localconnect_nb", moonbr_io_localconnect_nb},
1130 {"tcpconnect", moonbr_io_tcpconnect},
1131 {"tcpconnect_nb", moonbr_io_tcpconnect_nb},
1132 {"locallisten", moonbr_io_locallisten},
1133 {"tcplisten", moonbr_io_tcplisten},
1134 {"poll", moonbr_io_poll},
1135 {"timeref", moonbr_io_timeref},
1136 {NULL, NULL}
1137 };
1139 int luaopen_moonbridge_io(lua_State *L) {
1141 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
1143 lua_newtable(L); // module
1145 lua_newtable(L); // public metatable
1146 lua_newtable(L); // handle methods
1147 luaL_setfuncs(L, moonbr_io_handle_methods, 0);
1148 lua_pushvalue(L, -1);
1149 lua_setfield(L, -4, "prototype_handle");
1150 lua_setfield(L, -2, "__index");
1151 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_PUBLIC_MT_REGKEY);
1153 lua_newtable(L); // handle metatable
1154 luaL_setfuncs(L, moonbr_io_handle_metamethods, 0);
1155 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_HANDLE_MT_REGKEY);
1157 lua_newtable(L); // listener metatable
1158 luaL_setfuncs(L, moonbr_io_listener_metamethods, 0);
1159 lua_newtable(L); // listener methods
1160 luaL_setfuncs(L, moonbr_io_listener_methods, 0);
1161 lua_pushvalue(L, -1);
1162 lua_setfield(L, -4, "prototype_listener");
1163 lua_setfield(L, -2, "__index");
1164 lua_setfield(L, LUA_REGISTRYINDEX, MOONBR_IO_LISTENER_MT_REGKEY);
1166 luaL_setfuncs(L, moonbr_io_module_funcs, 0);
1167 return 1;

Impressum / About Us