From 457b761d9301b1904c414a8e8ba908f74b9ab959 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gustaf=20Alh=C3=A4ll?= <gustaf@hanicef.me>
Date: Wed, 18 Dec 2024 15:02:17 +0100
Subject: [PATCH] Fix segfault when sending excessively large netcmds

---
 src/netcode/net_command.c | 28 ++++++++++++++++++++--------
 1 file changed, 20 insertions(+), 8 deletions(-)

diff --git a/src/netcode/net_command.c b/src/netcode/net_command.c
index f29a1a792..5b876df62 100644
--- a/src/netcode/net_command.c
+++ b/src/netcode/net_command.c
@@ -64,6 +64,12 @@ void SendNetXCmd(netxcmd_t id, const void *param, size_t nparam)
 	{
 		textcmdbuf_t *buf = textcmdbuf;
 
+		if (2+nparam > MAXTEXTCMD)
+		{
+			CONS_Alert(CONS_ERROR, M_GetText("packet too large to fit NetXCmd, cannot add netcmd %d! (size: %s, max: %d)\n"), id, sizeu1(2+nparam), MAXTEXTCMD);
+			return;
+		}
+
 		// for future reference: if (cv_debug) != debug disabled.
 		CONS_Alert(CONS_NOTICE, M_GetText("NetXCmd buffer full, delaying netcmd %d... (size: %d, needed: %s)\n"), id, localtextcmd[0], sizeu1(nparam));
 		if (buf == NULL)
@@ -79,16 +85,16 @@ void SendNetXCmd(netxcmd_t id, const void *param, size_t nparam)
 			buf = buf->next;
 
 		if (buf->cmd[0]+2+nparam > MAXTEXTCMD)
-		{
-			WriteNetXCmd(buf->cmd, id, param, nparam);
-		}
-		else
 		{
 			buf->next = Z_Malloc(sizeof(textcmdbuf_t), PU_STATIC, NULL);
 			buf->next->cmd[0] = 0;
 			buf->next->next = NULL;
 			WriteNetXCmd(buf->next->cmd, id, param, nparam);
 		}
+		else
+		{
+			WriteNetXCmd(buf->cmd, id, param, nparam);
+		}
 		return;
 	}
 	WriteNetXCmd(localtextcmd, id, param, nparam);
@@ -101,6 +107,12 @@ void SendNetXCmd2(netxcmd_t id, const void *param, size_t nparam)
 	{
 		textcmdbuf_t *buf = textcmdbuf2;
 
+		if (2+nparam > MAXTEXTCMD)
+		{
+			CONS_Alert(CONS_ERROR, M_GetText("packet too large to fit NetXCmd, cannot add netcmd %d! (size: %s, max: %d)\n"), id, sizeu1(2+nparam), MAXTEXTCMD);
+			return;
+		}
+
 		// for future reference: if (cv_debug) != debug disabled.
 		CONS_Alert(CONS_NOTICE, M_GetText("NetXCmd buffer full, delaying netcmd %d... (size: %d, needed: %s)\n"), id, localtextcmd2[0], sizeu1(nparam));
 		if (buf == NULL)
@@ -116,16 +128,16 @@ void SendNetXCmd2(netxcmd_t id, const void *param, size_t nparam)
 			buf = buf->next;
 
 		if (buf->cmd[0]+2+nparam > MAXTEXTCMD)
-		{
-			WriteNetXCmd(buf->cmd, id, param, nparam);
-		}
-		else
 		{
 			buf->next = Z_Malloc(sizeof(textcmdbuf_t), PU_STATIC, NULL);
 			buf->next->cmd[0] = 0;
 			buf->next->next = NULL;
 			WriteNetXCmd(buf->next->cmd, id, param, nparam);
 		}
+		else
+		{
+			WriteNetXCmd(buf->cmd, id, param, nparam);
+		}
 		return;
 	}
 	WriteNetXCmd(localtextcmd2, id, param, nparam);
-- 
GitLab