moonbridge
changeset 111:bff286e7496e
Added function moonbridge_io.localconnect(pathname) to connect to local (unix domain) socket
author | jbe |
---|---|
date | Thu Apr 09 18:49:37 2015 +0200 (2015-04-09) |
parents | 0daa33d9a147 |
children | e99265c3372d |
files | moonbridge_io.c |
line diff
1.1 --- a/moonbridge_io.c Thu Apr 09 18:46:06 2015 +0200 1.2 +++ b/moonbridge_io.c Thu Apr 09 18:49:37 2015 +0200 1.3 @@ -5,6 +5,7 @@ 1.4 #include <errno.h> 1.5 #include <string.h> 1.6 #include <sys/socket.h> 1.7 +#include <sys/un.h> 1.8 #include <sys/select.h> 1.9 #include <fcntl.h> 1.10 #include <netinet/in.h> 1.11 @@ -625,6 +626,53 @@ 1.12 return 0; 1.13 } 1.14 1.15 +static int moonbr_io_localconnect_impl(lua_State *L, int nonblocking) { 1.16 + const char *path; 1.17 + struct sockaddr_un sockaddr = { .sun_family = AF_LOCAL }; 1.18 + const int path_maxlen = sizeof(struct sockaddr_un) - ( 1.19 + (void *)sockaddr.sun_path - (void *)&sockaddr 1.20 + ) - 1; /* one byte for termination */ 1.21 + int sock; 1.22 + path = luaL_checkstring(L, 1); 1.23 + if (strlen(path) > path_maxlen) luaL_error(L, "Path too long; only %i characters allowed", path_maxlen); 1.24 + strcpy(sockaddr.sun_path, path); 1.25 + sock = socket( 1.26 + PF_LOCAL, 1.27 + SOCK_STREAM | SOCK_CLOEXEC | (nonblocking ? SOCK_NONBLOCK : 0), 1.28 + 0 1.29 + ); 1.30 + if (sock < 0) { 1.31 + moonbr_io_errmsg(); 1.32 + lua_pushnil(L); 1.33 + lua_pushstring(L, errmsg); 1.34 + return 2; 1.35 + } 1.36 + if (connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) { 1.37 + if (!nonblocking && errno == EINTR) { 1.38 + moonbr_io_errmsg(); 1.39 + close(sock); 1.40 + lua_pushnil(L); 1.41 + lua_pushstring(L, errmsg); 1.42 + return 2; 1.43 + } else if (!(nonblocking && (errno == EINPROGRESS || errno == EINTR))) { 1.44 + moonbr_io_errmsg(); 1.45 + lua_pushnil(L); 1.46 + lua_pushstring(L, errmsg); 1.47 + return 2; 1.48 + } 1.49 + } 1.50 + moonbr_io_pushhandle(L, sock); 1.51 + return 1; 1.52 +} 1.53 + 1.54 +static int moonbr_io_localconnect(lua_State *L) { 1.55 + return moonbr_io_localconnect_impl(L, 0); 1.56 +} 1.57 + 1.58 +static int moonbr_io_localconnect_nb(lua_State *L) { 1.59 + return moonbr_io_localconnect_impl(L, 1); 1.60 +} 1.61 + 1.62 static int moonbr_io_tcpconnect_impl(lua_State *L, int nonblocking) { 1.63 const char *host, *port; 1.64 struct addrinfo hints = { 0, }; 1.65 @@ -969,6 +1017,8 @@ 1.66 }; 1.67 1.68 static const struct luaL_Reg moonbr_io_module_funcs[] = { 1.69 + {"localconnect", moonbr_io_localconnect}, 1.70 + {"localconnect_nb", moonbr_io_localconnect_nb}, 1.71 {"tcpconnect", moonbr_io_tcpconnect}, 1.72 {"tcpconnect_nb", moonbr_io_tcpconnect_nb}, 1.73 {"tcplisten", moonbr_io_tcplisten},