moonbridge
changeset 112:e99265c3372d
New function moonbridge_io.locallisten(path) to listen on local (unix domain) sockets
author | jbe |
---|---|
date | Thu Apr 09 18:59:53 2015 +0200 (2015-04-09) |
parents | bff286e7496e |
children | 113185a57b06 |
files | moonbridge_io.c |
line diff
1.1 --- a/moonbridge_io.c Thu Apr 09 18:49:37 2015 +0200 1.2 +++ b/moonbridge_io.c Thu Apr 09 18:59:53 2015 +0200 1.3 @@ -747,6 +747,49 @@ 1.4 return moonbr_io_tcpconnect_impl(L, 1); 1.5 } 1.6 1.7 +static int moonbr_io_locallisten(lua_State *L) { 1.8 + moonbr_io_listener_t *listener; 1.9 + const char *path; 1.10 + struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL }; 1.11 + const int path_maxlen = sizeof(struct sockaddr_un) - ( 1.12 + (void *)sockaddr.sun_path - (void *)&sockaddr 1.13 + ) - 1; /* one byte for termination */ 1.14 + int sock; 1.15 + path = luaL_checkstring(L, 1); 1.16 + if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen); 1.17 + strcpy(sockaddr.sun_path, path); 1.18 + listener = lua_newuserdata(L, sizeof(moonbr_io_listener_t)); 1.19 + luaL_setmetatable(L, MOONBR_IO_LISTENER_MT_REGKEY); 1.20 + sock = socket( 1.21 + PF_LOCAL, 1.22 + SOCK_STREAM | SOCK_CLOEXEC, 1.23 + 0 1.24 + ); 1.25 + if (sock < 0) { 1.26 + moonbr_io_errmsg(); 1.27 + lua_pushnil(L); 1.28 + lua_pushstring(L, errmsg); 1.29 + return 2; 1.30 + } 1.31 + if (bind(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) { 1.32 + moonbr_io_errmsg(); 1.33 + close(sock); 1.34 + lua_pushnil(L); 1.35 + lua_pushstring(L, errmsg); 1.36 + return 2; 1.37 + } 1.38 + if (listen(sock, MOONBR_IO_LISTEN_BACKLOG)) { 1.39 + moonbr_io_errmsg(); 1.40 + close(sock); 1.41 + lua_pushnil(L); 1.42 + lua_pushstring(L, errmsg); 1.43 + return 2; 1.44 + } 1.45 + listener->fd = sock; 1.46 + listener->nonblocking = -1; 1.47 + return 1; 1.48 +} 1.49 + 1.50 static int moonbr_io_tcplisten(lua_State *L) { 1.51 moonbr_io_listener_t *listener; 1.52 const char *host, *port; 1.53 @@ -1021,6 +1064,7 @@ 1.54 {"localconnect_nb", moonbr_io_localconnect_nb}, 1.55 {"tcpconnect", moonbr_io_tcpconnect}, 1.56 {"tcpconnect_nb", moonbr_io_tcpconnect_nb}, 1.57 + {"locallisten", moonbr_io_locallisten}, 1.58 {"tcplisten", moonbr_io_tcplisten}, 1.59 {"poll", moonbr_io_poll}, 1.60 {NULL, NULL}