From 52a5b1714bdfbbb6a8ee5bc8088a1b09f7883623 Mon Sep 17 00:00:00 2001 From: Paul Bardea Date: Thu, 15 Dec 2016 15:36:45 -0800 Subject: [PATCH 1/3] Resolve crash when string ends in backslash The problem was that the parser would read beyond a backslash even if it was the last character, so rather than reporting it as invalid JSON and throwing an error it would try to read beyond the string and crash. This fix just adds a check to ensure that the parser doesn't read out of bounds. --- Sources/JSONParser.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/JSONParser.swift b/Sources/JSONParser.swift index 31ddaa9b..7da25928 100644 --- a/Sources/JSONParser.swift +++ b/Sources/JSONParser.swift @@ -237,6 +237,7 @@ public struct JSONParser { switch input[loc] { case Literal.BACKSLASH: loc = (loc + 1) + if loc >= input.count { continue } switch input[loc] { case Literal.DOUBLE_QUOTE: stringDecodingBuffer.append(Literal.DOUBLE_QUOTE) case Literal.BACKSLASH: stringDecodingBuffer.append(Literal.BACKSLASH) From 6b3881a6845f5826e3ef948129dd9d6d6a7c1b69 Mon Sep 17 00:00:00 2001 From: Paul Bardea Date: Thu, 15 Dec 2016 15:37:24 -0800 Subject: [PATCH 2/3] Add test for parsing string ending in backslash Add a test that tests if the parser will crash if the string ends in a backslash --- Tests/JSONParserTests.swift | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Tests/JSONParserTests.swift b/Tests/JSONParserTests.swift index c459acbe..5223bebb 100644 --- a/Tests/JSONParserTests.swift +++ b/Tests/JSONParserTests.swift @@ -482,4 +482,15 @@ class JSONParserTests: XCTestCase { } } } + + func testThatParserRejectsStringEndingInBackslash() { + let invalidJSONString = "[\"\\" + do { + _ = try JSONParser.parse(invalidJSONString) + } catch JSONParser.Error.endOfStreamUnexpected { + // do nothing - this is the expected error + } catch { + XCTFail("Unexpected error: \(error)") + } + } } From 356f4c37224897417828d4a9ebcd1aaf74d4dbc5 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 17 Jan 2017 19:33:49 -0500 Subject: [PATCH 3/3] Prefer guard ... else { continue } to if ... { continue } --- Sources/JSONParser.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/JSONParser.swift b/Sources/JSONParser.swift index 7da25928..6047ca0b 100644 --- a/Sources/JSONParser.swift +++ b/Sources/JSONParser.swift @@ -237,7 +237,7 @@ public struct JSONParser { switch input[loc] { case Literal.BACKSLASH: loc = (loc + 1) - if loc >= input.count { continue } + guard loc < input.count else { continue } switch input[loc] { case Literal.DOUBLE_QUOTE: stringDecodingBuffer.append(Literal.DOUBLE_QUOTE) case Literal.BACKSLASH: stringDecodingBuffer.append(Literal.BACKSLASH)