From ba3ce49606271ec49188b8c73ff341b9f680f254 Mon Sep 17 00:00:00 2001
From: Quentin Armitage <quentin@armitage.org.uk>
Date: Wed, 28 Oct 2020 16:11:37 +0000
Subject: [PATCH 427/691] core: Fix a file descriptor leak when reloading

Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>
---
 lib/scheduler.c | 29 +++++++++++++++++++----------
 1 file changed, 19 insertions(+), 10 deletions(-)

diff --git a/lib/scheduler.c b/lib/scheduler.c
index f54e3b4..139b8e5 100644
--- a/lib/scheduler.c
+++ b/lib/scheduler.c
@@ -839,10 +839,24 @@ thread_destroy_list(thread_master_t *m, list_head_t *l)
 	thread_t *thread, *thread_tmp;
 
 	list_for_each_entry_safe(thread, thread_tmp, l, next) {
-		if (thread->event) {
-			thread_del_read(thread);
-			thread_del_write(thread);
+		/* The following thread types are relevant for the ready list */
+		if (thread->type == THREAD_READY_READ_FD ||
+		    thread->type == THREAD_READY_WRITE_FD ||
+		    thread->type == THREAD_READ_TIMEOUT ||
+		    thread->type == THREAD_WRITE_TIMEOUT ||
+		    thread->type == THREAD_READ_ERROR ||
+		    thread->type == THREAD_WRITE_ERROR) {
+			/* Do we have a thread_event, and does it need deleting? */
+			if (thread->event) {
+				thread_del_read(thread);
+				thread_del_write(thread);
+			}
+
+			/* Do we have a file descriptor that needs closing ? */
+			if (thread->u.f.close_on_reload)
+				thread_close_fd(thread);
 		}
+
 		list_head_del(&thread->next);
 		thread_add_unuse(m, thread);
 	}
@@ -856,14 +870,9 @@ thread_destroy_rb(thread_master_t *m, rb_root_cached_t *root)
 	rb_for_each_entry_safe_cached(thread, thread_tmp, root, n) {
 		rb_erase_cached(&thread->n, root);
 
+		/* The following are relevant for the read and write rb lists */
 		if (thread->type == THREAD_READ ||
-		    thread->type == THREAD_WRITE ||
-		    thread->type == THREAD_READY_READ_FD ||
-		    thread->type == THREAD_READY_WRITE_FD ||
-		    thread->type == THREAD_READ_TIMEOUT ||
-		    thread->type == THREAD_WRITE_TIMEOUT ||
-		    thread->type == THREAD_READ_ERROR ||
-		    thread->type == THREAD_WRITE_ERROR) {
+		    thread->type == THREAD_WRITE) {
 			/* Do we have a thread_event, and does it need deleting? */
 			if (thread->type == THREAD_READ)
 				thread_del_read(thread);
-- 
1.8.3.1

