Debian Codegraph @

internal/json/parser.go

raw symbols SCIP
1 package json
2
3 import (
4 "bytes"
5 "sync"
6 )
7
8 const (
9 QueryNone = "json"
10 QueryGeo = "geo"
11 QueryHAR = "har"
12 QueryGLTF = "gltf"
13 QueryCDX = "cdx"
14 maxRecursion = 4096
15 )
16
17 var queries = map[string][]query{
18 QueryNone: nil,
19 QueryGeo: {{
20 SearchPath: [][]byte{[]byte("type")},
21 SearchVals: [][]byte{
22 []byte(`"Feature"`),
23 []byte(`"FeatureCollection"`),
24 []byte(`"Point"`),
25 []byte(`"LineString"`),
26 []byte(`"Polygon"`),
27 []byte(`"MultiPoint"`),
28 []byte(`"MultiLineString"`),
29 []byte(`"MultiPolygon"`),
30 []byte(`"GeometryCollection"`),
31 },
32 }},
33 QueryHAR: {{
34 SearchPath: [][]byte{[]byte("log"), []byte("version")},
35 }, {
36 SearchPath: [][]byte{[]byte("log"), []byte("creator")},
37 }, {
38 SearchPath: [][]byte{[]byte("log"), []byte("entries")},
39 }},
40 QueryGLTF: {{
41 SearchPath: [][]byte{[]byte("asset"), []byte("version")},
42 SearchVals: [][]byte{[]byte(`"1.0"`), []byte(`"2.0"`)},
43 }},
44 QueryCDX: {{
45 SearchPath: [][]byte{[]byte("bomFormat")},
46 SearchVals: [][]byte{[]byte(`"CycloneDX"`)},
47 }},
48 }
49
50 var parserPool = sync.Pool{
51 New: func() any {
52 return &parserState{maxRecursion: maxRecursion}
53 },
54 }
55
56 // parserState holds the state of JSON parsing. The number of inspected bytes,
57 // the current path inside the JSON object, etc.
58 type parserState struct {
59 // ib represents the number of inspected bytes.
60 // Because mimetype limits itself to only reading the header of the file,
61 // it means sometimes the input JSON can be truncated. In that case, we want
62 // to still detect it as JSON, even if it's invalid/truncated.
63 // When ib == len(input) it means the JSON was valid (at least the header).
64 ib int
65 maxRecursion int
66 // currPath keeps a track of the JSON keys parsed up.
67 // It works only for JSON objects. JSON arrays are ignored
68 // mainly because the functionality is not needed.
69 currPath [][]byte
70 // firstToken stores the first JSON token encountered in input.
71 firstToken int
72 // querySatisfied is true if both path and value of any queries passed to
73 // consumeAny are satisfied.
74 querySatisfied bool
75 }
76
77 // query holds information about a combination of {"key": "val"} that we're trying
78 // to search for inside the JSON.
79 type query struct {
80 // SearchPath represents the whole path to look for inside the JSON.
81 // ex: [][]byte{[]byte("foo"), []byte("bar")} matches {"foo": {"bar": "baz"}}
82 SearchPath [][]byte
83 // SearchVals represents values to look for when the SearchPath is found.
84 // Each SearchVal element is tried until one of them matches (logical OR.)
85 SearchVals [][]byte
86 }
87
88 func eq(path1, path2 [][]byte) bool {
89 if len(path1) != len(path2) {
90 return false
91 }
92 for i := range path1 {
93 if !bytes.Equal(path1[i], path2[i]) {
94 return false
95 }
96 }
97 return true
98 }
99
100 // Parse will take out a parser from the pool depending on queryType and tries
101 // to parse raw bytes as JSON.
102 func Parse(queryType string, raw []byte) (parsed, inspected, firstToken int, querySatisfied bool) {
103 p := parserPool.Get().(*parserState)
104 defer func() {
105 // Avoid hanging on to too much memory in extreme input cases.
106 if len(p.currPath) > 128 {
107 p.currPath = nil
108 }
109 parserPool.Put(p)
110 }()
111 p.reset()
112
113 qs := queries[queryType]
114 got := p.consumeAny(raw, qs, 0)
115 return got, p.ib, p.firstToken, p.querySatisfied
116 }
117
118 func (p *parserState) reset() {
119 p.ib = 0
120 p.currPath = p.currPath[0:0]
121 p.firstToken = TokInvalid
122 p.querySatisfied = false
123 }
124
125 func (p *parserState) consumeSpace(b []byte) (n int) {
126 for len(b) > 0 && isSpace(b[0]) {
127 b = b[1:]
128 n++
129 p.ib++
130 }
131 return n
132 }
133
134 func (p *parserState) consumeConst(b, cnst []byte) int {
135 lb := len(b)
136 for i, c := range cnst {
137 if lb > i && b[i] == c {
138 p.ib++
139 } else {
140 return 0
141 }
142 }
143 return len(cnst)
144 }
145
146 func (p *parserState) consumeString(b []byte) (n int) {
147 var c byte
148 for len(b[n:]) > 0 {
149 c, n = b[n], n+1
150 p.ib++
151 switch c {
152 case '\\':
153 if len(b[n:]) == 0 {
154 return 0
155 }
156 switch b[n] {
157 case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
158 n++
159 p.ib++
160 continue
161 case 'u':
162 n++
163 p.ib++
164 for j := 0; j < 4 && len(b[n:]) > 0; j++ {
165 if !isXDigit(b[n]) {
166 return 0
167 }
168 n++
169 p.ib++
170 }
171 continue
172 default:
173 return 0
174 }
175 case '"':
176 return n
177 default:
178 continue
179 }
180 }
181 return 0
182 }
183
184 func (p *parserState) consumeNumber(b []byte) (n int) {
185 got := false
186 var i int
187
188 if len(b) == 0 {
189 goto out
190 }
191 if b[0] == '-' {
192 b, i = b[1:], i+1
193 p.ib++
194 }
195
196 for len(b) > 0 {
197 if !isDigit(b[0]) {
198 break
199 }
200 got = true
201 b, i = b[1:], i+1
202 p.ib++
203 }
204 if len(b) == 0 {
205 goto out
206 }
207 if b[0] == '.' {
208 b, i = b[1:], i+1
209 p.ib++
210 }
211 for len(b) > 0 {
212 if !isDigit(b[0]) {
213 break
214 }
215 got = true
216 b, i = b[1:], i+1
217 p.ib++
218 }
219 if len(b) == 0 {
220 goto out
221 }
222 if got && (b[0] == 'e' || b[0] == 'E') {
223 b, i = b[1:], i+1
224 p.ib++
225 got = false
226 if len(b) == 0 {
227 goto out
228 }
229 if b[0] == '+' || b[0] == '-' {
230 b, i = b[1:], i+1
231 p.ib++
232 }
233 for len(b) > 0 {
234 if !isDigit(b[0]) {
235 break
236 }
237 got = true
238 b, i = b[1:], i+1
239 p.ib++
240 }
241 }
242 out:
243 if got {
244 return i
245 }
246 return 0
247 }
248
249 // openArray is used instead of an inline []byte{'['} to avoid mem alllocs.
250 var openArray = []byte{'['}
251
252 func (p *parserState) consumeArray(b []byte, qs []query, lvl int) (n int) {
253 p.appendPath(openArray, qs)
254 if len(b) == 0 {
255 return 0
256 }
257
258 for n < len(b) {
259 n += p.consumeSpace(b[n:])
260 if len(b[n:]) == 0 {
261 return 0
262 }
263 if b[n] == ']' {
264 p.ib++
265 p.popLastPath(qs)
266 return n + 1
267 }
268 innerParsed := p.consumeAny(b[n:], qs, lvl)
269 if innerParsed == 0 {
270 return 0
271 }
272 n += innerParsed
273 if len(b[n:]) == 0 {
274 return 0
275 }
276 switch b[n] {
277 case ',':
278 n += 1
279 p.ib++
280 continue
281 case ']':
282 p.ib++
283 return n + 1
284 default:
285 return 0
286 }
287 }
288 return 0
289 }
290
291 func queryPathMatch(qs []query, path [][]byte) int {
292 for i := range qs {
293 if eq(qs[i].SearchPath, path) {
294 return i
295 }
296 }
297 return -1
298 }
299
300 // appendPath will append a path fragment if queries is not empty.
301 // If we don't need query functionality (just checking if a JSON is valid),
302 // then we can skip keeping track of the path we're currently in.
303 func (p *parserState) appendPath(path []byte, qs []query) {
304 if len(qs) != 0 {
305 p.currPath = append(p.currPath, path)
306 }
307 }
308 func (p *parserState) popLastPath(qs []query) {
309 if len(qs) != 0 {
310 p.currPath = p.currPath[:len(p.currPath)-1]
311 }
312 }
313
314 func (p *parserState) consumeObject(b []byte, qs []query, lvl int) (n int) {
315 for n < len(b) {
316 n += p.consumeSpace(b[n:])
317 if len(b[n:]) == 0 {
318 return 0
319 }
320 if b[n] == '}' {
321 p.ib++
322 return n + 1
323 }
324 if b[n] != '"' {
325 return 0
326 } else {
327 n += 1
328 p.ib++
329 }
330 // queryMatched stores the index of the query satisfying the current path.
331 queryMatched := -1
332 if keyLen := p.consumeString(b[n:]); keyLen == 0 {
333 return 0
334 } else {
335 p.appendPath(b[n:n+keyLen-1], qs)
336 if !p.querySatisfied {
337 queryMatched = queryPathMatch(qs, p.currPath)
338 }
339 n += keyLen
340 }
341 n += p.consumeSpace(b[n:])
342 if len(b[n:]) == 0 {
343 return 0
344 }
345 if b[n] != ':' {
346 return 0
347 } else {
348 n += 1
349 p.ib++
350 }
351 n += p.consumeSpace(b[n:])
352 if len(b[n:]) == 0 {
353 return 0
354 }
355
356 if valLen := p.consumeAny(b[n:], qs, lvl); valLen == 0 {
357 return 0
358 } else {
359 if queryMatched != -1 {
360 q := qs[queryMatched]
361 if len(q.SearchVals) == 0 {
362 p.querySatisfied = true
363 }
364 for _, val := range q.SearchVals {
365 if bytes.Equal(val, bytes.TrimSpace(b[n:n+valLen])) {
366 p.querySatisfied = true
367 }
368 }
369 }
370 n += valLen
371 }
372 if len(b[n:]) == 0 {
373 return 0
374 }
375 switch b[n] {
376 case ',':
377 p.popLastPath(qs)
378 n++
379 p.ib++
380 continue
381 case '}':
382 p.popLastPath(qs)
383 p.ib++
384 return n + 1
385 default:
386 return 0
387 }
388 }
389 return 0
390 }
391
392 func (p *parserState) consumeAny(b []byte, qs []query, lvl int) (n int) {
393 // Avoid too much recursion.
394 if p.maxRecursion != 0 && lvl > p.maxRecursion {
395 return 0
396 }
397 if len(qs) == 0 {
398 p.querySatisfied = true
399 }
400 n += p.consumeSpace(b)
401 if len(b[n:]) == 0 {
402 return 0
403 }
404
405 var t, rv int
406 switch b[n] {
407 case '"':
408 n++
409 p.ib++
410 rv = p.consumeString(b[n:])
411 t = TokString
412 case '[':
413 n++
414 p.ib++
415 rv = p.consumeArray(b[n:], qs, lvl+1)
416 t = TokArray
417 case '{':
418 n++
419 p.ib++
420 rv = p.consumeObject(b[n:], qs, lvl+1)
421 t = TokObject
422 case 't':
423 rv = p.consumeConst(b[n:], []byte("true"))
424 t = TokTrue
425 case 'f':
426 rv = p.consumeConst(b[n:], []byte("false"))
427 t = TokFalse
428 case 'n':
429 rv = p.consumeConst(b[n:], []byte("null"))
430 t = TokNull
431 default:
432 rv = p.consumeNumber(b[n:])
433 t = TokNumber
434 }
435 if lvl == 0 {
436 p.firstToken = t
437 }
438 if rv <= 0 {
439 return n
440 }
441 n += rv
442 n += p.consumeSpace(b[n:])
443 return n
444 }
445
446 func isSpace(c byte) bool {
447 return c == ' ' || c == '\t' || c == '\r' || c == '\n'
448 }
449 func isDigit(c byte) bool {
450 return '0' <= c && c <= '9'
451 }
452
453 func isXDigit(c byte) bool {
454 if isDigit(c) {
455 return true
456 }
457 return ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
458 }
459
460 const (
461 TokInvalid = 0
462 TokNull = 1 << iota
463 TokTrue
464 TokFalse
465 TokNumber
466 TokString
467 TokArray
468 TokObject
469 TokComma
470 )