Skip to content

Commit

Permalink
BinaryLog: escape characters in byte arrays
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
robertlong13 authored and meee1 committed Nov 17, 2023
1 parent c3af5c7 commit 5890d68
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion ExtLibs/Utilities/BinaryLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.IO;
using System.Runtime.InteropServices;
using uint8_t = System.Byte;
using System.Diagnostics;

namespace MissionPlanner.Utilities
{
Expand Down Expand Up @@ -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";
Expand Down

0 comments on commit 5890d68

Please sign in to comment.