2

Closed

Deserialize truncated array causes infinite loop in 4.5.7

description

I discovered this bug in our ASP.NET Web API application that incorporates JSON.NET.
http://aspnetwebstack.codeplex.com/
 
Because of networking issues, we were receiving incomplete JSON POSTs containing an array that was truncated. This sample reproduces the problem:
 
{"events":[{"code":64411,"prio
 
Investigation showed that Newtonsoft.Json.Serialization.JsonSerializerInternalReader.HandleError is looping indefinitely (stack trace attached)
 
private void HandleError(JsonReader reader, bool readPastError, int initialDepth)
{
  ClearErrorContext();
 
  if (readPastError)
  {
    reader.Skip();
 
    while (reader.Depth > (initialDepth + 1))
    {
      reader.Read();
    }
  }
}
 
This following test reproduces the problem and mimics the behaviour in ASP.NET Web API's JsonMediaTypeFormatter
http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/1ccfcdfc11da#src%2fSystem.Net.Http.Formatting%2fFormatting%2fJsonMediaTypeFormatter.cs
 
public class Tests
{
    [Test]
    public void Test()
    {
        const string input = "{\"events\":[{\"code\":64411,\"prio";
 
        const int maxDepth = 256;
        using(var jsonTextReader = new JsonTextReader(new StringReader(input)) { MaxDepth = maxDepth })
        {
            JsonSerializer jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings { MaxDepth = maxDepth });
            jsonSerializer.Error += (sender, e) =>
                                    {
                                        Exception exception = e.ErrorContext.Error;
                                        Trace.WriteLine(e.ErrorContext.Path + Environment.NewLine + exception);
                                        e.ErrorContext.Handled = true;
                                    };
            object obj = jsonSerializer.Deserialize(jsonTextReader, typeof(LogMessage));
        }
    }
}
 
public class LogMessage
{
    public string DeviceId { get; set; }
}
 
public class LogEvent
{
    public string Code { get; set; }
    public int Priority { get; set; }
}

file attachments

Closed Aug 2, 2012 at 8:57 AM by JamesNK
Fixed

comments