From 40912fb84b83626bd90d1ebb4f1b5394ae5703e4 Mon Sep 17 00:00:00 2001 From: AllenX2018 Date: Fri, 13 Mar 2020 15:26:22 +0800 Subject: [PATCH] fix issue #177 #178 --- parser.go | 33 +++++++++++++++++++-------------- parser_test.go | 10 ++++++++++ 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/parser.go b/parser.go index 513125f9..69021985 100644 --- a/parser.go +++ b/parser.go @@ -261,19 +261,23 @@ func searchKeys(data []byte, keys ...string) int { keyUnesc = ku } - if equalStr(&keyUnesc, keys[level-1]) { - lastMatched = true - - // if key level match - if keyLevel == level-1 { - keyLevel++ - // If we found all keys in path - if keyLevel == lk { - return i + 1 + if level <= len(keys) { + if equalStr(&keyUnesc, keys[level-1]) { + lastMatched = true + + // if key level match + if keyLevel == level-1 { + keyLevel++ + // If we found all keys in path + if keyLevel == lk { + return i + 1 + } } + } else { + lastMatched = false } } else { - lastMatched = false + return -1 } } else { i-- @@ -484,10 +488,11 @@ func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]str if len(p) < level+1 || pathFlags&bitwiseFlags[pi+1] != 0 || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) { continue } - - aIdx, _ := strconv.Atoi(p[level][1 : len(p[level])-1]) - arrIdxFlags |= bitwiseFlags[aIdx+1] - pIdxFlags |= bitwiseFlags[pi+1] + if len(p[level]) >= 2 { + aIdx, _ := strconv.Atoi(p[level][1 : len(p[level])-1]) + arrIdxFlags |= bitwiseFlags[aIdx+1] + pIdxFlags |= bitwiseFlags[pi+1] + } } if arrIdxFlags > 0 { diff --git a/parser_test.go b/parser_test.go index 18045f1e..d2bb1c52 100644 --- a/parser_test.go +++ b/parser_test.go @@ -802,6 +802,13 @@ var getTests = []GetTest{ isFound: true, data: `1`, }, + { + // Issue #178: Crash in searchKeys + desc: `invalid json`, + json: `{{{"":`, + path: []string{"a", "b"}, + isFound: false, + }, } var getIntTests = []GetTest{ @@ -1467,6 +1474,7 @@ func TestEachKey(t *testing.T) { {"arrInt", "[3]"}, {"arrInt", "[5]"}, // Should not find last key {"nested"}, + {"arr", "["}, // issue#177 Invalid arguments } keysFound := 0 @@ -1513,6 +1521,8 @@ func TestEachKey(t *testing.T) { if string(value) != `{"a":"test", "b":2, "nested3":{"a":"test3","b":4}, "c": "unknown"}` { t.Error("Should find 9 key", string(value)) } + case 10: + t.Errorf("Found key #10 that should not be found") default: t.Errorf("Should find only 9 keys, got %v key", idx) }