From 5890d68fa93fe6ea0d8be8208e282140f1bb0fe2 Mon Sep 17 00:00:00 2001 From: Bob Long Date: Fri, 17 Nov 2023 16:56:33 +1100 Subject: [PATCH] BinaryLog: escape characters in byte arrays Some byte arrays in logs are raw binary data, containing problematic characters (like newlines and other unprintables). Others are printable strings meant to be displayed. This allows both to be handled. --- ExtLibs/Utilities/BinaryLog.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/ExtLibs/Utilities/BinaryLog.cs b/ExtLibs/Utilities/BinaryLog.cs index 4e96254420..70babfc3c3 100644 --- a/ExtLibs/Utilities/BinaryLog.cs +++ b/ExtLibs/Utilities/BinaryLog.cs @@ -7,6 +7,7 @@ using System.IO; using System.Runtime.InteropServices; using uint8_t = System.Byte; +using System.Diagnostics; namespace MissionPlanner.Utilities { @@ -158,7 +159,18 @@ public string ReadMessage(Stream br, long length) if (a.IsNumber()) return (((IConvertible)a).ToString(CultureInfo.InvariantCulture)); else if (a is System.Byte[]) - return System.Text.Encoding.ASCII.GetString(a as byte[]).Trim('\0'); + { + var str = Encoding.ASCII.GetString(a as byte[]).Trim('\0'); + // Escape \ as \\ + str = str.Replace("\\", "\\\\"); + // Escape certain whitespace characters + str = str.Replace("\n", "\\n"); + str = str.Replace("\r", "\\r"); + str = str.Replace("\t", "\\t"); + // Escape all other non-printable characters + str = str.Select(c => (c < 32 || c > 127) ? $"\\x{Convert.ToByte(c):X2}" : $"{c}").Aggregate((x, y) => $"{x}{y}"); + return str; + } else return a?.ToString(); })) + "\r\n";