From c20a8be23f698d7d89b7ccf8d328971cf4709b9f Mon Sep 17 00:00:00 2001 From: Colm O hEigeartaigh Date: Fri, 3 Mar 2023 12:01:09 +0000 Subject: [PATCH] Fixing issue 60 --- .../org/codehaus/jettison/json/JSONArray.java | 26 ++++++++++++------- .../codehaus/jettison/json/JSONArrayTest.java | 15 +++++++++++ 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/codehaus/jettison/json/JSONArray.java b/src/main/java/org/codehaus/jettison/json/JSONArray.java index 11acd9a..7038de7 100644 --- a/src/main/java/org/codehaus/jettison/json/JSONArray.java +++ b/src/main/java/org/codehaus/jettison/json/JSONArray.java @@ -182,22 +182,30 @@ public JSONArray(String string) throws JSONException { * @throws JSONException If there is a syntax error. */ public JSONArray(Collection collection) throws JSONException { + this(collection, 0); + } + + private JSONArray(Collection collection, int recursionDepth) throws JSONException { + if (recursionDepth > JSONObject.getGlobalRecursionDepthLimit()) { + throw new JSONException("JSONArray has reached recursion depth limit of " + + JSONObject.getGlobalRecursionDepthLimit()); + } + this.myArrayList = (collection == null) ? new ArrayList() : new ArrayList(collection); // ensure a pure hierarchy of JSONObjects and JSONArrays for (ListIterator iter = myArrayList.listIterator(); iter.hasNext();) { - Object e = iter.next(); - if (e instanceof Collection) { - iter.set(new JSONArray((Collection) e)); - } - if (e instanceof Map) { - iter.set(new JSONObject((Map) e)); - } - } + Object e = iter.next(); + if (e instanceof Collection) { + iter.set(new JSONArray((Collection) e, recursionDepth + 1)); + } + if (e instanceof Map) { + iter.set(new JSONObject((Map) e)); + } + } } - /** * Get the object value associated with an index. * @param index diff --git a/src/test/java/org/codehaus/jettison/json/JSONArrayTest.java b/src/test/java/org/codehaus/jettison/json/JSONArrayTest.java index 88333f3..6e36506 100644 --- a/src/test/java/org/codehaus/jettison/json/JSONArrayTest.java +++ b/src/test/java/org/codehaus/jettison/json/JSONArrayTest.java @@ -2,6 +2,9 @@ import junit.framework.TestCase; +import java.util.ArrayList; +import java.util.List; + public class JSONArrayTest extends TestCase { public void testInvalidArraySequence() throws Exception { try { @@ -67,6 +70,18 @@ public void testInfiniteLoop2() { public void testIssue52() throws JSONException { JSONObject.setGlobalRecursionDepthLimit(10); new JSONArray("[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {a:10}]"); + JSONObject.setGlobalRecursionDepthLimit(500); + } + + // https://github.com/jettison-json/jettison/issues/60 + public void testIssue60() throws JSONException { + List list = new ArrayList<>(); + list.add(list); + try { + new JSONArray(list); + } catch (JSONException ex) { + assertEquals(ex.getMessage(), "JSONArray has reached recursion depth limit of 500"); + } } }