From 4ff4e8169c5f73e37a17df482916752bc0b17d1f Mon Sep 17 00:00:00 2001
From: dormando <dormando@rydia.net>
Date: Thu, 21 Mar 2024 12:41:01 -0700
Subject: [PATCH] crawler: fix potential memory corruption

if the client closes during the finalization stages of the dump we can
crash attempting to write a final END/EN to the client buffer.

---
 crawler.c | 17 +++++++++++------
 1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/crawler.c b/crawler.c
index e360081..a56538b 100644
--- a/crawler.c
+++ b/crawler.c
@@ -291,9 +291,11 @@ static void crawler_metadump_eval(crawler_module_t *cm, item *it, uint32_t hv, i
 
 static void crawler_metadump_finalize(crawler_module_t *cm) {
     if (cm->c.c != NULL) {
-        lru_crawler_write(&cm->c); // empty the write buffer
-        memcpy(cm->c.buf, "END\r\n", 5);
-        cm->c.bufused += 5;
+        // flush any pending data.
+        if (lru_crawler_write(&cm->c) == 0) {
+            memcpy(cm->c.buf, "END\r\n", 5);
+            cm->c.bufused += 5;
+        }
     }
 }
 
@@ -328,9 +330,11 @@ static void crawler_mgdump_eval(crawler_module_t *cm, item *it, uint32_t hv, int
 
 static void crawler_mgdump_finalize(crawler_module_t *cm) {
     if (cm->c.c != NULL) {
-        lru_crawler_write(&cm->c); // empty the write buffer
-        memcpy(cm->c.buf, "EN\r\n", 4);
-        cm->c.bufused += 4;
+        // flush any pending data.
+        if (lru_crawler_write(&cm->c) == 0) {
+            memcpy(cm->c.buf, "EN\r\n", 4);
+            cm->c.bufused += 4;
+        }
     }
 }
 
@@ -350,6 +354,7 @@ static int lru_crawler_write(crawler_client_t *c) {
 
         if (ret < 0) {
             // fatal.
+            lru_crawler_close_client(c);
             return -1;
         }
 
-- 
2.27.0

