Skip to content

Commit

Permalink
Try and fix backslash escaping. Throw syntax exception on invalid jso…
Browse files Browse the repository at this point in the history
…n sooner
  • Loading branch information
dkulp committed Dec 6, 2022
1 parent d9da808 commit 631c21e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
14 changes: 7 additions & 7 deletions src/main/java/org/codehaus/jettison/json/JSONObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ public JSONObject(JSONTokener x) throws JSONException {
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
case '{':
throw x.syntaxError("Expected a key");
default:
x.back();
key = x.nextValue().toString();
Expand Down Expand Up @@ -1041,15 +1043,13 @@ public static String quote(String string, boolean escapeForwardSlashAlways) {
c = string.charAt(i);
switch (c) {
case '\\':
// Escape a backslash, but only if it isn't already escaped
if (i == len - 1 || string.charAt(i + 1) != '\\') {
sb.append('\\');
}
sb.append(c);
sb.append("\\\\");
//if (i < (len - 1) && string.charAt(i+1) == '\\') {
// i++;
//}
break;
case '"':
sb.append('\\');
sb.append(c);
sb.append("\\\"");
break;
case '/':
if (escapeForwardSlashAlways || i > 0 && string.charAt(i - 1) == '<') {
Expand Down
9 changes: 7 additions & 2 deletions src/test/java/org/codehaus/jettison/json/JSONObjectTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,11 @@ public void testMissingIsNull() throws Exception {
public void testSlashEscapingTurnedOnByDefault() throws Exception {
JSONObject obj = new JSONObject();
obj.put("key", "http://example.com/foo");
assertEquals(obj.toString(), "{\"key\":\"http:\\/\\/example.com\\/foo\"}");
assertEquals("{\"key\":\"http:\\/\\/example.com\\/foo\"}", obj.toString());

obj = new JSONObject();
obj.put("key", "\\\\");
assertEquals("{\"key\":\"\\\\\\\\\"}", obj.toString());
}

public void testForwardSlashEscapingModifiedfBySetter() throws Exception {
Expand Down Expand Up @@ -183,13 +187,14 @@ public void testFuzzerTestCase() throws Exception, JSONException {
fail("Failure expected");
} catch (JSONException ex) {
// expected
assertTrue(ex.getMessage().contains("Expected a key"));
}
}

public void testFuzzerTestCase2() throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append("{");
sb.append("{\"key\":");
}
try {
new JSONObject(sb.toString());
Expand Down

0 comments on commit 631c21e

Please sign in to comment.