From 53ad61a0fec71d840b319f3d240a5c25d4e026b2 Mon Sep 17 00:00:00 2001 From: Andrew Golledge Date: Thu, 7 Nov 2024 22:47:01 +0100 Subject: [PATCH] Avoid "index out of range" exceptions when empty error responses are returned. --- .../Sockets/MessageParsingTests.cs | 41 +++++++++++++++++++ NEventSocket/FreeSwitch/ApiResponse.cs | 2 +- NEventSocket/FreeSwitch/CommandReply.cs | 2 +- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/NEventSocket.Tests/Sockets/MessageParsingTests.cs b/NEventSocket.Tests/Sockets/MessageParsingTests.cs index 13cd8ed..afd9214 100644 --- a/NEventSocket.Tests/Sockets/MessageParsingTests.cs +++ b/NEventSocket.Tests/Sockets/MessageParsingTests.cs @@ -175,6 +175,27 @@ public void it_should_parse_Command_Reply_ERR() Console.WriteLine(reply); } + [Fact] + public void it_should_parse_empty_string_when_empty_Command_Reply_ERR() + { + var parser = new Parser(); + var rawInput = "Content-Type: command/reply\nReply-Text: -ERR\n\n"; + + foreach (char c in rawInput) + { + parser.Append(c); + } + + Assert.True(parser.Completed); + + var reply = new CommandReply(parser.ExtractMessage()); + Assert.NotNull(reply); + Assert.False(reply.Success); + Assert.Equal(string.Empty, reply.ErrorMessage); + + Console.WriteLine(reply); + } + [Fact] public void it_should_parse_Api_Response_OK() { @@ -216,6 +237,26 @@ public void it_should_parse_Api_Response_ERR() Console.WriteLine(response); } + [Fact] + public void it_should_parse_empty_string_when_empty_Api_Response_ERR() + { + var parser = new Parser(); + var rawInput = "Content-Type: api/response\nContent-Length: 4\n\n-ERR"; + + foreach (char c in rawInput) + { + parser.Append(c); + } + + Assert.True(parser.Completed); + + var response = new ApiResponse(parser.ExtractMessage()); + Assert.False(response.Success); + Assert.Equal(string.Empty, response.ErrorMessage); + + Console.WriteLine(response); + } + [Fact] public void it_should_treat_Api_Response_ERR_no_reply_as_Success() { diff --git a/NEventSocket/FreeSwitch/ApiResponse.cs b/NEventSocket/FreeSwitch/ApiResponse.cs index 0e46d0f..a366041 100644 --- a/NEventSocket/FreeSwitch/ApiResponse.cs +++ b/NEventSocket/FreeSwitch/ApiResponse.cs @@ -51,7 +51,7 @@ public string ErrorMessage { get { - return BodyText != null && BodyText.StartsWith("-ERR") + return BodyText != null && BodyText.StartsWith("-ERR ") ? BodyText.Substring(5, BodyText.Length - 5) : string.Empty; } diff --git a/NEventSocket/FreeSwitch/CommandReply.cs b/NEventSocket/FreeSwitch/CommandReply.cs index 25eef8a..dd82638 100644 --- a/NEventSocket/FreeSwitch/CommandReply.cs +++ b/NEventSocket/FreeSwitch/CommandReply.cs @@ -56,7 +56,7 @@ public string ErrorMessage { get { - return ReplyText != null && ReplyText.StartsWith("-ERR") + return ReplyText != null && ReplyText.StartsWith("-ERR ") ? ReplyText.Substring(5, ReplyText.Length - 5) : string.Empty; }