diff options
Diffstat (limited to 'src/util.c')
-rw-r--r-- | src/util.c | 42 |
1 files changed, 15 insertions, 27 deletions
@@ -23,49 +23,37 @@ #include "fcgy.h" -int util_socket(int d, int t, int p, uint32_t flags) { - int r = socket(d, t, p), - fd = r; +/* Only sets the flags, can't unset anything currently. */ +int util_fd_flags(int fd, uint32_t flags) { + int r; - if(r >= 0 && flags & FCGY_NONBLOCK) { - r = fcntl(fd, F_GETFL); - if(r >= 0) - r = fcntl(fd, F_SETFL, r|O_NONBLOCK); - } + if(flags & FCGY_NONBLOCK) + if((r = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, r|O_NONBLOCK) < 0) + return -1; - if(r >= 0 && flags & FCGY_CLOEXEC) { - r = fcntl(fd, F_GETFD); - if(r >= 0) - r = fcntl(fd, F_SETFD, r|FD_CLOEXEC); - } + if(flags & FCGY_CLOEXEC) + if((r = fcntl(fd, F_GETFD)) < 0 || fcntl(fd, F_SETFD, r|FD_CLOEXEC) < 0) + return -1; - if(r < 0) { - if(fd >= 0) - close(fd); - return r; - } - return fd; + return 0; } int util_serversock(int domain, void *addr, socklen_t addrlen, uint32_t flags) { - int fd = util_socket(domain, SOCK_STREAM, 0, flags); + int fd = socket(domain, SOCK_STREAM, 0); if(fd < 0) return fd; int r = 1; - if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof(int)) < 0) { - close(fd); - return -1; - } - #ifdef IPV6_V6ONLY /* Can fail, ignore error */ - r = 1; setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &r, sizeof(int)); #endif - if(bind(fd, addr, addrlen) < 0 || listen(fd, 64) < 0) { + if(util_fd_flags(fd, flags) < 0 + || setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &r, sizeof(int)) < 0 + || bind(fd, addr, addrlen) < 0 + || listen(fd, 64) < 0) { close(fd); return -1; } |