htparser: Improved shutdown behavior further.
[ashd.git] / src / plaintcp.c
index cf46b29..7d36a1d 100644 (file)
@@ -22,6 +22,7 @@
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
+#include <fcntl.h>
 #include <errno.h>
 #include <string.h>
 
@@ -64,10 +65,11 @@ int listensock4(int port)
        close(fd);
        return(-1);
     }
-    if(listen(fd, 16) < 0) {
+    if(listen(fd, 128) < 0) {
        close(fd);
        return(-1);
     }
+    fcntl(fd, F_SETFD, FD_CLOEXEC);
     return(fd);
 }
 
@@ -88,10 +90,11 @@ int listensock6(int port)
        close(fd);
        return(-1);
     }
-    if(listen(fd, 16) < 0) {
+    if(listen(fd, 128) < 0) {
        close(fd);
        return(-1);
     }
+    fcntl(fd, F_SETFD, FD_CLOEXEC);
     return(fd);
 }
 
@@ -165,13 +168,14 @@ void servetcp(struct muth *muth, va_list args)
 static void listenloop(struct muth *muth, va_list args)
 {
     vavar(struct tcpport *, tcp);
-    int ns;
+    int i, ns;
     struct sockaddr_storage name;
     socklen_t namelen;
     
     while(1) {
        namelen = sizeof(name);
-       block(tcp->fd, EV_READ, 0);
+       if(block(tcp->fd, EV_READ, 0) == 0)
+           goto out;
        ns = accept(tcp->fd, (struct sockaddr *)&name, &namelen);
        if(ns < 0) {
            flog(LOG_ERR, "accept: %s", strerror(errno));
@@ -183,6 +187,10 @@ static void listenloop(struct muth *muth, va_list args)
 out:
     close(tcp->fd);
     free(tcp);
+    for(i = 0; i < listeners.d; i++) {
+       if(listeners.b[i] == muth)
+           bufdel(listeners, i);
+    }
 }
 
 void handleplain(int argc, char **argp, char **argv)
@@ -212,7 +220,7 @@ void handleplain(int argc, char **argp, char **argv)
     omalloc(tcp);
     tcp->fd = fd;
     tcp->sport = port;
-    mustart(listenloop, tcp);
+    bufadd(listeners, mustart(listenloop, tcp));
     if((fd = listensock4(port)) < 0) {
        if(errno != EADDRINUSE) {
            flog(LOG_ERR, "could not listen on IPv4 (port %i): %s", port, strerror(errno));
@@ -222,6 +230,6 @@ void handleplain(int argc, char **argp, char **argv)
        omalloc(tcp);
        tcp->fd = fd;
        tcp->sport = port;
-       mustart(listenloop, tcp);
+       bufadd(listeners, mustart(listenloop, tcp));
     }
 }