From: Andre Date: Thu, 15 Jun 2006 06:06:44 +0000 (+0200) Subject: init_tcp_socket: close socket fd on errors X-Git-Tag: v0.2.14~62^2~2 X-Git-Url: http://git.tuebingen.mpg.de/?p=paraslash.git;a=commitdiff_plain;h=0b976cff31e330df80b7a278d5f9d3a0615a644c init_tcp_socket: close socket fd on errors The current code may leak the fd if bind fails, for example. This is a benign bug however, since all paraslash applications that call init_tcp_socket() terminate on errors anyway. But it is no good idea to rely on this, so close the fd on errors. This patch also gets rid of the do_bind() one-liner which was only called from init_tcp_socket(). --- diff --git a/net.c b/net.c index 6c4bbf98..850a9f39 100644 --- a/net.c +++ b/net.c @@ -304,14 +304,6 @@ static int setserversockopts(int socket_fd) return 1; } -static int do_bind(int socket_fd, struct sockaddr_in *my_addr) -{ - if (bind(socket_fd, (struct sockaddr *)my_addr, - sizeof(struct sockaddr)) == -1) - return -E_BIND; - return 1; -} - /** * prepare a structure for \p AF_UNIX socket addresses * @@ -500,22 +492,30 @@ int recv_cred_buffer(int fd, char *buf, size_t size) */ int init_tcp_socket(int port) { - int sockfd, ret; struct sockaddr_in my_addr; + int fd, ret = get_socket(); - if ((sockfd = get_socket()) < 0) - return sockfd; - ret = setserversockopts(sockfd); if (ret < 0) return ret; - init_sockaddr(&my_addr, port, NULL); - ret = do_bind(sockfd, &my_addr); + fd = ret; + ret = setserversockopts(fd); if (ret < 0) - return ret; - if (listen(sockfd, BACKLOG) == -1) - return -E_LISTEN; - PARA_INFO_LOG("listening on port %d, fd %d\n", port, sockfd); - return sockfd; + goto err; + init_sockaddr(&my_addr, port, NULL); + ret = -E_BIND; + if (bind(fd, (struct sockaddr *)&my_addr, + sizeof(struct sockaddr)) == -1) { + PARA_CRIT_LOG("bind error: %s\n", strerror(errno)); + goto err; + } + ret = -E_LISTEN; + if (listen(fd, BACKLOG) == -1) + goto err; + PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd); + return fd; +err: + close(fd); + return ret; } /**