From c56a64ff4df7eecb6c88ff929497bcd0d65934f2 Mon Sep 17 00:00:00 2001
From: Jon Shallow <supjps-libcoap@jpshallow.com>
Date: Fri, 22 Apr 2022 13:15:39 +0100
Subject: [PATCH] coap_session.c: Balance SESSIONS_ADD and SESSIONS_DELETE
 usage

Upstream-Status: Backport [https://github.com/obgm/libcoap/commit/7e20aa9ef17277f39203334404e6c776b1171a7d]
Signed-off-by: Alex Kiernan <alex.kiernan@gmail.com>
Signed-off-by: Alex Kiernan <alexk@zuma.ai>
---
 src/coap_session.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/coap_session.c b/src/coap_session.c
index 77cae598f0af..536e57573361 100644
--- a/src/coap_session.c
+++ b/src/coap_session.c
@@ -813,6 +813,12 @@ coap_session_create_client(
   return session;
 
 error:
+  /*
+   * Need to add in the session as coap_session_release()
+   * will call SESSIONS_DELETE in coap_session_free().
+   */
+  if (session)
+    SESSIONS_ADD(ctx->sessions, session);
   coap_session_release(session);
   return NULL;
 }
@@ -1133,11 +1139,17 @@ coap_session_t *coap_new_server_session(
   if (session) {
     coap_log(LOG_DEBUG, "***%s: new incoming session\n",
              coap_session_str(session));
+    /* Returned session may already have been released and is now NULL */
     session = coap_session_accept(session);
   }
   return session;
 
 error:
+  /*
+   * Need to add in the session as coap_session_release()
+   * will call SESSIONS_DELETE in coap_session_free().
+   */
+  SESSIONS_ADD(ep->sessions, session);
   coap_session_free(session);
   return NULL;
 }
-- 
2.35.1

