Merge nixio 0.2
[project/luci.git] / libs / nixio / src / socket.c
index 9d46486..17c6afc 100644 (file)
  *  limitations under the License.
  */
 
-#include <lua.h>
-#include <lualib.h>
-#include <lauxlib.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
+#include "nixio.h"
 #include <unistd.h>
 #include <string.h>
 #include <errno.h>
-#include "nixio.h"
 
 
 /**
@@ -36,6 +31,9 @@ static int nixio_socket(lua_State *L) {
        const char *proto  = lua_tolstring(L, 3, NULL);
 
        nixio_sock *sock = lua_newuserdata(L, sizeof(nixio_sock));
+       if (!sock) {
+               return luaL_error(L, "out of memory");
+       }
 
        if (!strcmp(domain, "inet")) {
                sock->domain = AF_INET;
@@ -78,7 +76,7 @@ static int nixio_socket(lua_State *L) {
        sock->fd = socket(sock->domain, sock->type, sock->protocol);
 
        if (sock->fd < 0) {
-               return nixio__perror(L);
+               return nixio__perror_s(L);
        }
 
        return 1;
@@ -90,8 +88,18 @@ static int nixio_socket(lua_State *L) {
 static int nixio_sock_close(lua_State *L) {
        nixio_sock *sock = nixio__checksock(L);
        int sockfd = sock->fd;
+       int res;
        sock->fd = -1;
-       return nixio__pstatus(L, !close(sockfd));
+
+       do {
+#ifndef __WINNT__
+               res = close(sockfd);
+#else
+               res = closesocket(sockfd);
+#endif
+       } while (res == -1 && errno == EINTR);
+
+       return nixio__pstatus_s(L, !res);
 }
 
 /**
@@ -99,8 +107,15 @@ static int nixio_sock_close(lua_State *L) {
  */
 static int nixio_sock__gc(lua_State *L) {
        nixio_sock *sock = (nixio_sock*)luaL_checkudata(L, 1, NIXIO_META);
+       int res;
        if (sock && sock->fd != -1) {
-               close(sock->fd);
+               do {
+#ifndef __WINNT__
+                       res = close(sock->fd);
+#else
+                       res = closesocket(sock->fd);
+#endif
+               } while (res == -1 && errno == EINTR);
        }
        return 0;
 }
@@ -131,7 +146,7 @@ static int nixio_sock_shutdown(lua_State *L) {
                return luaL_argerror(L, 2, "supported values: both, read, write");
        }
 
-       return nixio__pstatus(L, !shutdown(sockfd, how));
+       return nixio__pstatus_s(L, !shutdown(sockfd, how));
 }
 
 /* module table */
@@ -144,17 +159,12 @@ static const luaL_reg R[] = {
 static const luaL_reg M[] = {
        {"close",               nixio_sock_close},
        {"shutdown",    nixio_sock_shutdown},
+       {"__gc",                nixio_sock__gc},
+       {"__tostring",  nixio_sock__tostring},
        {NULL,                  NULL}
 };
 
 void nixio_open_socket(lua_State *L) {
-       luaL_getmetatable(L, NIXIO_META);
-       lua_pushcfunction(L, nixio_sock__gc);
-       lua_setfield(L, -2, "__gc");
-       lua_pushcfunction(L, nixio_sock__tostring);
-       lua_setfield(L, -2, "__tostring");
-       lua_pop(L, 1);
-
        luaL_register(L, NULL, R);
 
        lua_pushvalue(L, -2);