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