From a876319c1e72742c0c69da204590479f90ddc038 Mon Sep 17 00:00:00 2001 From: Mark Atwood Date: Tue, 1 Dec 2026 09:15:37 -0800 Subject: [PATCH] fix: call listen() once before the accept loop server-psk-nonblocking.c and server-psk-threaded.c bound the listening socket and then ran wolfSSL_Init(), wolfSSL_CTX_new(), the PSK callback setup, wolfSSL_CTX_set_cipher_list() and wolfSSL_CTX_SetTmpDH_file() before reaching listen(), which sat inside the accept loop. A TCP connect to a bound-but-not-listening port is refused immediately, so a client arriving in that window gets ECONNREFUSED. Measured on an idle box, the port stayed unlistened for a median of 19.5 ms and 20.3 ms respectively; after the move it is 4.4 ms for both. server-psk.c already calls listen() directly after bind(). Calling it once per accept iteration was a no-op after the first pass, and the O_NONBLOCK fcntl applies to the accepted connfd, not to listenfd, so the nonblocking behaviour is unchanged. --- psk/server-psk-nonblocking.c | 12 ++++++------ psk/server-psk-threaded.c | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/psk/server-psk-nonblocking.c b/psk/server-psk-nonblocking.c index cfbdabca1..6b4ed2cc2 100644 --- a/psk/server-psk-nonblocking.c +++ b/psk/server-psk-nonblocking.c @@ -146,6 +146,12 @@ int main() return 1; } + /* listen to the socket */ + if (listen(listenfd, LISTENQ) < 0) { + printf("Fatal error : listen error\n"); + return 1; + } + wolfSSL_Init(); if ((ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())) == NULL) { @@ -180,12 +186,6 @@ int main() for ( ; ; ) { WOLFSSL* ssl; - /* listen to the socket */ - if (listen(listenfd, LISTENQ) < 0) { - printf("Fatal error : listen error\n"); - return 1; - } - cliLen = sizeof(cliAddr); connfd = accept(listenfd, (struct sockaddr *) &cliAddr, &cliLen); if (connfd < 0) { diff --git a/psk/server-psk-threaded.c b/psk/server-psk-threaded.c index c2682e056..444bbf4f3 100644 --- a/psk/server-psk-threaded.c +++ b/psk/server-psk-threaded.c @@ -188,6 +188,12 @@ int main() return 1; } + /* listen to the socket */ + if (listen(listenfd, LISTENQ) < 0) { + printf("Fatal error : listen error"); + return 1; + } + wolfSSL_Init(); if ((ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())) == NULL) { @@ -221,12 +227,6 @@ int main() /* main loop for accepting and responding to clients */ for ( ; ; ) { - /* listen to the socket */ - if (listen(listenfd, LISTENQ) < 0) { - printf("Fatal error : listen error"); - return 1; - } - cliLen = sizeof(cliAddr); connfd = accept(listenfd, (struct sockaddr *) &cliAddr, &cliLen); if (connfd < 0) {