diff options
Diffstat (limited to 'src/socket.c')
-rw-r--r-- | src/socket.c | 49 |
1 files changed, 37 insertions, 12 deletions
diff --git a/src/socket.c b/src/socket.c index e9b8584..2689c0f 100644 --- a/src/socket.c +++ b/src/socket.c @@ -10,6 +10,26 @@ #include "socket.h" #include "utils.h" +static int socket_setopts(int sockfd); + + +static int socket_setopts(int sockfd) +{ + int s, enable = 1; + + s = fcntl(sockfd, F_GETFL, 0); + if (s < 0) + return 1; + s |= O_CLOEXEC; + if (fcntl(sockfd, F_SETFL, s) == -1) + return 1; + + s = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)); + if (s) + return 1; + + return 0; +} int socket_nonblock(const psocket *psock) { @@ -40,7 +60,7 @@ int socket_init_in(const char *addr, int socket_bind_in(psocket *psock, struct addrinfo **results) { - int s = 1, fd = -1, rv, reuse_enable = 1; + int s = 1, fd = -1, rv; struct addrinfo *rp = NULL; assert(psock && results && *results); @@ -59,7 +79,10 @@ int socket_bind_in(psocket *psock, struct addrinfo **results) if (!rp) goto finalise; - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_enable, sizeof(int)); + s = socket_setopts(fd); + if (s) + goto finalise; + psock->fd = fd; psock->addr_len = rp->ai_addrlen; psock->addr = *rp->ai_addr; @@ -79,7 +102,7 @@ int socket_listen_in(psocket *psock) { assert(psock); - return listen(psock->fd, POTD_BACKLOG); + return listen(psock->fd, POTD_BACKLOG) != 0; } int socket_accept_in(const psocket *psock, psocket *client_psock) @@ -94,7 +117,8 @@ int socket_accept_in(const psocket *psock, psocket *client_psock) &client_psock->addr_len); if (fd < 0) return 1; - if (socket_nonblock(psock)) { + if (socket_nonblock(psock)) + { close(fd); return 1; } @@ -105,7 +129,7 @@ int socket_accept_in(const psocket *psock, psocket *client_psock) int socket_connect_in(psocket *psock, struct addrinfo **results) { - int s = 1, fd = -1, rv, reuse_enable = 1; + int s = 1, fd = -1, rv; struct addrinfo *rp = NULL; assert(psock && results && *results); @@ -124,7 +148,9 @@ int socket_connect_in(psocket *psock, struct addrinfo **results) if (!rp) goto finalise; - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_enable, sizeof(int)); + if (socket_setopts(fd)) + goto finalise; + psock->fd = fd; psock->addr_len = rp->ai_addrlen; psock->addr = *(rp->ai_addr); @@ -158,24 +184,23 @@ int socket_addrtostr_in(const psocket *psock, int socket_reconnect_in(psocket *psock) { int rv; - int reuse_enable = 1; assert(psock); if (psock->fd >= 0) - return -1; + return 1; psock->fd = socket(psock->family, psock->socktype, psock->protocol); if (psock->fd < 0) - return -2; + return 1; rv = connect(psock->fd, &psock->addr, psock->addr_len); if (rv) { socket_close(psock); - return -3; + return 1; } - if (setsockopt(psock->fd, SOL_SOCKET, SO_REUSEADDR, &reuse_enable, sizeof(int)) < 0) { + if (socket_setopts(psock->fd)) { socket_close(psock); - return -4; + return 1; } return socket_nonblock(psock); |