From 54c0f743dd6971bf8636c13600a6d4e2ef10106f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Viktor=20S=C3=B6derqvist?= <viktor.soderqvist@est.tech>
Date: Tue, 27 Aug 2024 16:11:33 +0200
Subject: [PATCH] Connection minor fixes (#953)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

1. Remove redundant connIncrRefs/connDecrRefs

    In socket.c, the reference counter is incremented before calling
callHandler, but the same reference counter is also incremented inside
callHandler before calling the actual callback.

        static inline int callHandler(connection *conn, ConnectionCallbackFunc handler) {
            connIncrRefs(conn);
            if (handler) handler(conn);
            connDecrRefs(conn);
            ...
        }

    This commit removes the redundant incr/decr calls in socket.c

2. Correct return value of connRead for TLS when peer closed

    According to comments in connection.h, connRead returns 0 when the peer
has closed the connection. This patch corrects the return value for TLS
connections. (Without this patch, it returns -1 which means error.)

    There is an observable difference in what is logged in the verbose
level: "Client closed connection" vs "Reading from client: (null)".

---------

Signed-off-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
---
 src/socket.c | 2 --
 src/tls.c    | 2 +-
 2 files changed, 1 insertion(+), 3 deletions(-)

diff --git a/src/socket.c b/src/socket.c
index 295569da0..7344d66ad 100644
--- a/src/socket.c
+++ b/src/socket.c
@@ -203,9 +203,7 @@ static int connSocketAccept(connection *conn, ConnectionCallbackFunc accept_hand
     if (conn->state != CONN_STATE_ACCEPTING) return C_ERR;
     conn->state = CONN_STATE_CONNECTED;
 
-    connIncrRefs(conn);
     if (!callHandler(conn, accept_handler)) ret = C_ERR;
-    connDecrRefs(conn);
 
     return ret;
 }
diff --git a/src/tls.c b/src/tls.c
index 7b57fce6f..b4ba1adc9 100644
--- a/src/tls.c
+++ b/src/tls.c
@@ -570,7 +570,7 @@ static int updateStateAfterSSLIO(tls_connection *conn, int ret_value, int update
         } else {
             if (ssl_err == SSL_ERROR_ZERO_RETURN || ((ssl_err == SSL_ERROR_SYSCALL && !errno))) {
                 conn->c.state = CONN_STATE_CLOSED;
-                return -1;
+                return 0;
             } else {
                 conn->c.state = CONN_STATE_ERROR;
                 return -1;