Skip to content

Commit

Permalink
Add depth gaurd for serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
saintentropy committed Nov 29, 2023
1 parent 8f8e28b commit 106f644
Showing 1 changed file with 63 additions and 3 deletions.
66 changes: 63 additions & 3 deletions src/Libraries/CoreNodes/Data.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
using Dynamo.Events;
using Dynamo.Logging;
using Dynamo.Session;
using System.Globalization;
using System.Text;

namespace DSCore
{
Expand Down Expand Up @@ -188,8 +190,9 @@ private static object DynamoJObjectToNative(JObject jObject)
/// <returns name="json">A JSON string where primitive types (e.g. double, int, boolean), Lists, and Dictionary's will be turned into the associated JSON type.</returns>
public static string StringifyJSON([ArbitraryDimensionArrayImport] object values)
{
return JsonConvert.SerializeObject(values,
new JsonConverter[]
var settings = new JsonSerializerSettings()
{
Converters = new JsonConverter[]
{
new DictConverter(),
new DesignScriptGeometryConverter(),
Expand All @@ -198,9 +201,66 @@ public static string StringifyJSON([ArbitraryDimensionArrayImport] object values
#if _WINDOWS
new PNGImageConverter(),
#endif
});
}
};

StringBuilder sb = new StringBuilder(256);
using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture))
{
using (var jsonWriter = new MaxDepthJsonTextWriter(writer))
{
JsonSerializer.Create(settings).Serialize(jsonWriter, values);
}
return writer.ToString();
}
}

/// <summary>
/// Subclass of JsonTextWriter that limits a maximum supported object depth to prevent circular reference crashes when serializing arbitrary .NET objects types.
/// </summary>
private class MaxDepthJsonTextWriter : JsonTextWriter
{
private readonly int maxDepth = 15;
private int depth = 0;

public MaxDepthJsonTextWriter(TextWriter writer) : base(writer) { }

public override void WriteStartArray()
{
base.WriteStartArray();
depth++;
CheckDepth();
}

public override void WriteEndArray()
{
base.WriteEndArray();
depth--;
CheckDepth();
}

public override void WriteStartObject()
{
base.WriteStartObject();
depth++;
CheckDepth();
}

public override void WriteEndObject()
{
base.WriteEndObject();
depth--;
CheckDepth();
}

private void CheckDepth()
{
if (depth > maxDepth)
{
throw new JsonSerializationException(string.Format("Depth {0} Exceeds MaxDepth {1} at path \"{2}\"", depth, maxDepth, Path));
}
}
}

#region Converters
/// <summary>
Expand Down

0 comments on commit 106f644

Please sign in to comment.