Skip to content

Commit 11fa7e4

Browse files
authored
fix issue #177 #178 (#190)
`Get()` and `EachKey()` will panic dealing with invalid parameters in some cases because of array out of bounds. This pr try to fix #177 and #178
1 parent 1112445 commit 11fa7e4

File tree

2 files changed

+29
-14
lines changed

2 files changed

+29
-14
lines changed

parser.go

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -267,19 +267,23 @@ func searchKeys(data []byte, keys ...string) int {
267267
keyUnesc = ku
268268
}
269269

270-
if equalStr(&keyUnesc, keys[level-1]) {
271-
lastMatched = true
272-
273-
// if key level match
274-
if keyLevel == level-1 {
275-
keyLevel++
276-
// If we found all keys in path
277-
if keyLevel == lk {
278-
return i + 1
270+
if level <= len(keys) {
271+
if equalStr(&keyUnesc, keys[level-1]) {
272+
lastMatched = true
273+
274+
// if key level match
275+
if keyLevel == level-1 {
276+
keyLevel++
277+
// If we found all keys in path
278+
if keyLevel == lk {
279+
return i + 1
280+
}
279281
}
282+
} else {
283+
lastMatched = false
280284
}
281285
} else {
282-
lastMatched = false
286+
return -1
283287
}
284288
} else {
285289
i--
@@ -490,10 +494,11 @@ func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]str
490494
if len(p) < level+1 || pathFlags&bitwiseFlags[pi+1] != 0 || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) {
491495
continue
492496
}
493-
494-
aIdx, _ := strconv.Atoi(p[level][1 : len(p[level])-1])
495-
arrIdxFlags |= bitwiseFlags[aIdx+1]
496-
pIdxFlags |= bitwiseFlags[pi+1]
497+
if len(p[level]) >= 2 {
498+
aIdx, _ := strconv.Atoi(p[level][1 : len(p[level])-1])
499+
arrIdxFlags |= bitwiseFlags[aIdx+1]
500+
pIdxFlags |= bitwiseFlags[pi+1]
501+
}
497502
}
498503

499504
if arrIdxFlags > 0 {

parser_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,13 @@ var getTests = []GetTest{
814814
isFound: true,
815815
data: `1`,
816816
},
817+
{
818+
// Issue #178: Crash in searchKeys
819+
desc: `invalid json`,
820+
json: `{{{"":`,
821+
path: []string{"a", "b"},
822+
isFound: false,
823+
},
817824
}
818825

819826
var getIntTests = []GetTest{
@@ -1479,6 +1486,7 @@ func TestEachKey(t *testing.T) {
14791486
{"arrInt", "[3]"},
14801487
{"arrInt", "[5]"}, // Should not find last key
14811488
{"nested"},
1489+
{"arr", "["}, // issue#177 Invalid arguments
14821490
}
14831491

14841492
keysFound := 0
@@ -1525,6 +1533,8 @@ func TestEachKey(t *testing.T) {
15251533
if string(value) != `{"a":"test", "b":2, "nested3":{"a":"test3","b":4}, "c": "unknown"}` {
15261534
t.Error("Should find 9 key", string(value))
15271535
}
1536+
case 10:
1537+
t.Errorf("Found key #10 that should not be found")
15281538
default:
15291539
t.Errorf("Should find only 9 keys, got %v key", idx)
15301540
}

0 commit comments

Comments
 (0)