Skip to content

Commit

Permalink
fix issue #177 #178 (#190)
Browse files Browse the repository at this point in the history
`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
  • Loading branch information
AllenX2018 committed Mar 21, 2020
1 parent 1112445 commit 11fa7e4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 14 deletions.
33 changes: 19 additions & 14 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,19 +267,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--
Expand Down Expand Up @@ -490,10 +494,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 {
Expand Down
10 changes: 10 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,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{
Expand Down Expand Up @@ -1479,6 +1486,7 @@ func TestEachKey(t *testing.T) {
{"arrInt", "[3]"},
{"arrInt", "[5]"}, // Should not find last key
{"nested"},
{"arr", "["}, // issue#177 Invalid arguments
}

keysFound := 0
Expand Down Expand Up @@ -1525,6 +1533,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)
}
Expand Down

0 comments on commit 11fa7e4

Please sign in to comment.