Debian Codegraph @

internal/magic/text.go

raw symbols SCIP
1 package magic
2
3 import (
4 "bytes"
5 "time"
6
7 "github.com/gabriel-vasile/mimetype/internal/charset"
8 "github.com/gabriel-vasile/mimetype/internal/json"
9 mkup "github.com/gabriel-vasile/mimetype/internal/markup"
10 "github.com/gabriel-vasile/mimetype/internal/scan"
11 )
12
13 // HTML matches a Hypertext Markup Language file.
14 func HTML(raw []byte, _ uint32) bool {
15 return markup(raw,
16 []byte("<!DOCTYPE HTML"),
17 []byte("<HTML"),
18 []byte("<HEAD"),
19 []byte("<SCRIPT"),
20 []byte("<IFRAME"),
21 []byte("<H1"),
22 []byte("<DIV"),
23 []byte("<FONT"),
24 []byte("<TABLE"),
25 []byte("<A"),
26 []byte("<STYLE"),
27 []byte("<TITLE"),
28 []byte("<B"),
29 []byte("<BODY"),
30 []byte("<BR"),
31 []byte("<P"),
32 []byte("<!--"),
33 )
34 }
35
36 // XML matches an Extensible Markup Language file.
37 func XML(raw []byte, _ uint32) bool {
38 return markup(raw, []byte("<?XML"))
39 }
40
41 // Owl2 matches an Owl ontology file.
42 func Owl2(raw []byte, _ uint32) bool {
43 return xml(raw,
44 xmlSig{[]byte("<Ontology"), []byte(`xmlns="http://www.w3.org/2002/07/owl#"`)},
45 )
46 }
47
48 // Rss matches a Rich Site Summary file.
49 func Rss(raw []byte, _ uint32) bool {
50 return xml(raw,
51 xmlSig{[]byte("<rss"), []byte{}},
52 )
53 }
54
55 // Atom matches an Atom Syndication Format file.
56 func Atom(raw []byte, _ uint32) bool {
57 return xml(raw,
58 xmlSig{[]byte("<feed"), []byte(`xmlns="http://www.w3.org/2005/Atom"`)},
59 )
60 }
61
62 // Kml matches a Keyhole Markup Language file.
63 func Kml(raw []byte, _ uint32) bool {
64 return xml(raw,
65 xmlSig{[]byte("<kml"), []byte(`xmlns="http://www.opengis.net/kml/2.2"`)},
66 xmlSig{[]byte("<kml"), []byte(`xmlns="http://earth.google.com/kml/2.0"`)},
67 xmlSig{[]byte("<kml"), []byte(`xmlns="http://earth.google.com/kml/2.1"`)},
68 xmlSig{[]byte("<kml"), []byte(`xmlns="http://earth.google.com/kml/2.2"`)},
69 )
70 }
71
72 // Xliff matches a XML Localization Interchange File Format file.
73 func Xliff(raw []byte, _ uint32) bool {
74 return xml(raw,
75 xmlSig{[]byte("<xliff"), []byte(`xmlns="urn:oasis:names:tc:xliff:document:1.2"`)},
76 )
77 }
78
79 // Collada matches a COLLAborative Design Activity file.
80 func Collada(raw []byte, _ uint32) bool {
81 return xml(raw,
82 xmlSig{[]byte("<COLLADA"), []byte(`xmlns="http://www.collada.org/2005/11/COLLADASchema"`)},
83 )
84 }
85
86 // Gml matches a Geography Markup Language file.
87 func Gml(raw []byte, _ uint32) bool {
88 return xml(raw,
89 xmlSig{[]byte{}, []byte(`xmlns:gml="http://www.opengis.net/gml"`)},
90 xmlSig{[]byte{}, []byte(`xmlns:gml="http://www.opengis.net/gml/3.2"`)},
91 xmlSig{[]byte{}, []byte(`xmlns:gml="http://www.opengis.net/gml/3.3/exr"`)},
92 )
93 }
94
95 // Gpx matches a GPS Exchange Format file.
96 func Gpx(raw []byte, _ uint32) bool {
97 return xml(raw,
98 xmlSig{[]byte("<gpx"), []byte(`xmlns="http://www.topografix.com/GPX/1/1"`)},
99 )
100 }
101
102 // Tcx matches a Training Center XML file.
103 func Tcx(raw []byte, _ uint32) bool {
104 return xml(raw,
105 xmlSig{[]byte("<TrainingCenterDatabase"), []byte(`xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"`)},
106 )
107 }
108
109 // X3d matches an Extensible 3D Graphics file.
110 func X3d(raw []byte, _ uint32) bool {
111 return xml(raw,
112 xmlSig{[]byte("<X3D"), []byte(`xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance"`)},
113 )
114 }
115
116 // Amf matches an Additive Manufacturing XML file.
117 func Amf(raw []byte, _ uint32) bool {
118 return xml(raw, xmlSig{[]byte("<amf"), []byte{}})
119 }
120
121 // Threemf matches a 3D Manufacturing Format file.
122 func Threemf(raw []byte, _ uint32) bool {
123 return xml(raw,
124 xmlSig{[]byte("<model"), []byte(`xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"`)},
125 )
126 }
127
128 // Xfdf matches a XML Forms Data Format file.
129 func Xfdf(raw []byte, _ uint32) bool {
130 return xml(raw, xmlSig{[]byte("<xfdf"), []byte(`xmlns="http://ns.adobe.com/xfdf/"`)})
131 }
132
133 // VCard matches a Virtual Contact File.
134 func VCard(raw []byte, _ uint32) bool {
135 return ciPrefix(raw, []byte("BEGIN:VCARD\n"), []byte("BEGIN:VCARD\r\n"))
136 }
137
138 // ICalendar matches a iCalendar file.
139 func ICalendar(raw []byte, _ uint32) bool {
140 return ciPrefix(raw, []byte("BEGIN:VCALENDAR\n"), []byte("BEGIN:VCALENDAR\r\n"))
141 }
142 func phpPageF(raw []byte, _ uint32) bool {
143 return ciPrefix(raw,
144 []byte("<?PHP"),
145 []byte("<?\n"),
146 []byte("<?\r"),
147 []byte("<? "),
148 )
149 }
150 func phpScriptF(raw []byte, _ uint32) bool {
151 return shebang(raw,
152 scan.CompactWS,
153 []byte("/usr/local/bin/php"),
154 []byte("/usr/bin/php"),
155 []byte("/usr/bin/env php"),
156 []byte("/usr/bin/env -S php"),
157 )
158 }
159
160 // Js matches a Javascript file.
161 func Js(raw []byte, _ uint32) bool {
162 return shebang(raw,
163 scan.CompactWS,
164 []byte("/bin/node"),
165 []byte("/usr/bin/node"),
166 []byte("/bin/nodejs"),
167 []byte("/usr/bin/nodejs"),
168 []byte("/usr/bin/env node"),
169 []byte("/usr/bin/env -S node"),
170 []byte("/usr/bin/env nodejs"),
171 []byte("/usr/bin/env -S nodejs"),
172 )
173 }
174
175 // Lua matches a Lua programming language file.
176 func Lua(raw []byte, _ uint32) bool {
177 return shebang(raw,
178 scan.CompactWS|scan.FullWord,
179 []byte("/usr/bin/lua"),
180 []byte("/usr/local/bin/lua"),
181 []byte("/usr/bin/env lua"),
182 []byte("/usr/bin/env -S lua"),
183 )
184 }
185
186 // Perl matches a Perl programming language file.
187 func Perl(raw []byte, _ uint32) bool {
188 return shebang(raw,
189 scan.CompactWS|scan.FullWord,
190 []byte("/usr/bin/perl"),
191 []byte("/usr/bin/env perl"),
192 []byte("/usr/bin/env -S perl"),
193 )
194 }
195
196 // Python matches a Python programming language file.
197 func Python(raw []byte, _ uint32) bool {
198 return shebang(raw,
199 scan.CompactWS,
200 []byte("/usr/bin/python"),
201 []byte("/usr/local/bin/python"),
202 []byte("/usr/bin/env python"),
203 []byte("/usr/bin/env -S python"),
204 []byte("/usr/bin/python2"),
205 []byte("/usr/local/bin/python2"),
206 []byte("/usr/bin/env python2"),
207 []byte("/usr/bin/env -S python2"),
208 []byte("/usr/bin/python3"),
209 []byte("/usr/local/bin/python3"),
210 []byte("/usr/bin/env python3"),
211 []byte("/usr/bin/env -S python3"),
212 )
213
214 }
215
216 // Ruby matches a Ruby programming language file.
217 func Ruby(raw []byte, _ uint32) bool {
218 return shebang(raw,
219 scan.CompactWS,
220 []byte("/usr/bin/ruby"),
221 []byte("/usr/local/bin/ruby"),
222 []byte("/usr/bin/env ruby"),
223 []byte("/usr/bin/env -S ruby"),
224 )
225 }
226
227 // Tcl matches a Tcl programming language file.
228 func Tcl(raw []byte, _ uint32) bool {
229 return shebang(raw,
230 scan.CompactWS,
231 []byte("/usr/bin/tcl"),
232 []byte("/usr/local/bin/tcl"),
233 []byte("/usr/bin/env tcl"),
234 []byte("/usr/bin/env -S tcl"),
235 []byte("/usr/bin/tclsh"),
236 []byte("/usr/local/bin/tclsh"),
237 []byte("/usr/bin/env tclsh"),
238 []byte("/usr/bin/env -S tclsh"),
239 []byte("/usr/bin/wish"),
240 []byte("/usr/local/bin/wish"),
241 []byte("/usr/bin/env wish"),
242 []byte("/usr/bin/env -S wish"),
243 )
244 }
245
246 // Rtf matches a Rich Text Format file.
247 func Rtf(raw []byte, _ uint32) bool {
248 return bytes.HasPrefix(raw, []byte("{\\rtf"))
249 }
250
251 // Shell matches a shell script file.
252 func Shell(raw []byte, _ uint32) bool {
253 return shebang(raw,
254 scan.CompactWS|scan.FullWord,
255 []byte("/bin/sh"),
256 []byte("/bin/bash"),
257 []byte("/usr/local/bin/bash"),
258 []byte("/usr/bin/env bash"),
259 []byte("/usr/bin/env -S bash"),
260 []byte("/bin/csh"),
261 []byte("/usr/local/bin/csh"),
262 []byte("/usr/bin/env csh"),
263 []byte("/usr/bin/env -S csh"),
264 []byte("/bin/dash"),
265 []byte("/usr/local/bin/dash"),
266 []byte("/usr/bin/env dash"),
267 []byte("/usr/bin/env -S dash"),
268 []byte("/bin/ksh"),
269 []byte("/usr/local/bin/ksh"),
270 []byte("/usr/bin/env ksh"),
271 []byte("/usr/bin/env -S ksh"),
272 []byte("/bin/tcsh"),
273 []byte("/usr/local/bin/tcsh"),
274 []byte("/usr/bin/env tcsh"),
275 []byte("/usr/bin/env -S tcsh"),
276 []byte("/bin/zsh"),
277 []byte("/usr/local/bin/zsh"),
278 []byte("/usr/bin/env zsh"),
279 []byte("/usr/bin/env -S zsh"),
280 )
281 }
282
283 // Text matches a plain text file.
284 //
285 // TODO: This function does not parse BOM-less UTF16 and UTF32 files. Not really
286 // sure it should. libmagic also requires a BOM for UTF16 and UTF32.
287 func Text(raw []byte, _ uint32) bool {
288 // First look for BOM.
289 if cset := charset.FromBOM(raw); cset != "" {
290 return true
291 }
292 // Binary data bytes as defined here: https://mimesniff.spec.whatwg.org/#binary-data-byte
293 for i := 0; i < min(len(raw), 4096); i++ {
294 b := raw[i]
295 if b <= 0x08 ||
296 b == 0x0B ||
297 0x0E <= b && b <= 0x1A ||
298 0x1C <= b && b <= 0x1F {
299 return false
300 }
301 }
302 return true
303 }
304
305 // XHTML matches an XHTML file. This check depends on the XML check to have passed.
306 func XHTML(raw []byte, limit uint32) bool {
307 raw = raw[:min(len(raw), 1024)]
308 b := scan.Bytes(raw)
309 i, _ := b.Search([]byte("<!DOCTYPE HTML"), scan.CompactWS|scan.IgnoreCase)
310 if i != -1 {
311 return true
312 }
313 i, _ = b.Search([]byte("<HTML XMLNS="), scan.CompactWS|scan.IgnoreCase)
314 return i != -1
315 }
316
317 // Php matches a PHP: Hypertext Preprocessor file.
318 func Php(raw []byte, limit uint32) bool {
319 if res := phpPageF(raw, limit); res {
320 return res
321 }
322 return phpScriptF(raw, limit)
323 }
324
325 // JSON matches a JavaScript Object Notation file.
326 func JSON(raw []byte, limit uint32) bool {
327 // #175 A single JSON string, number or bool is not considered JSON.
328 // JSON objects and arrays are reported as JSON.
329 return jsonHelper(raw, limit, json.QueryNone, json.TokObject|json.TokArray)
330 }
331
332 // GeoJSON matches a RFC 7946 GeoJSON file.
333 //
334 // GeoJSON detection implies searching for key:value pairs like: `"type": "Feature"`
335 // in the input.
336 func GeoJSON(raw []byte, limit uint32) bool {
337 return jsonHelper(raw, limit, json.QueryGeo, json.TokObject)
338 }
339
340 // HAR matches a HAR Spec file.
341 // Spec: http://www.softwareishard.com/blog/har-12-spec/
342 func HAR(raw []byte, limit uint32) bool {
343 return jsonHelper(raw, limit, json.QueryHAR, json.TokObject)
344 }
345
346 // GLTF matches a GL Transmission Format (JSON) file.
347 // Visit [glTF specification] and [IANA glTF entry] for more details.
348 //
349 // [glTF specification]: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html
350 // [IANA glTF entry]: https://www.iana.org/assignments/media-types/model/gltf+json
351 func GLTF(raw []byte, limit uint32) bool {
352 return jsonHelper(raw, limit, json.QueryGLTF, json.TokObject)
353 }
354
355 // jsonHelper parses raw and tries to match the q query against it. wantToks
356 // ensures we're not wasting time parsing an input that would not pass anyway,
357 // ex: the input is a valid JSON array, but we're looking for a JSON object.
358 func jsonHelper(raw scan.Bytes, limit uint32, q string, wantToks ...int) bool {
359 firstNonWS := raw.FirstNonWS()
360
361 hasTargetTok := false
362 for _, t := range wantToks {
363 hasTargetTok = hasTargetTok || (t&json.TokArray > 0 && firstNonWS == '[')
364 hasTargetTok = hasTargetTok || (t&json.TokObject > 0 && firstNonWS == '{')
365 }
366 if !hasTargetTok {
367 return false
368 }
369 lraw := len(raw)
370 parsed, inspected, _, querySatisfied := json.Parse(q, raw)
371 if !querySatisfied {
372 return false
373 }
374
375 // If the full file content was provided, check that the whole input was parsed.
376 if limit == 0 || lraw < int(limit) {
377 return parsed == lraw
378 }
379
380 // If a section of the file was provided, check if all of it was inspected.
381 // In other words, check that if there was a problem parsing, that problem
382 // occurred after the last byte in the input.
383 return inspected == lraw && lraw > 0
384 }
385
386 // NdJSON matches a Newline delimited JSON file. All complete lines from raw
387 // must be valid JSON documents meaning they contain one of the valid JSON data
388 // types.
389 func NdJSON(raw []byte, limit uint32) bool {
390 lCount, objOrArr := 0, 0
391
392 s := scan.Bytes(raw)
393 var l scan.Bytes
394 for len(s) != 0 {
395 l = s.Line()
396 _, inspected, firstToken, _ := json.Parse(json.QueryNone, l)
397 if len(l) != inspected {
398 return false
399 }
400 if firstToken == json.TokArray || firstToken == json.TokObject {
401 objOrArr++
402 }
403 lCount++
404 }
405
406 return lCount > 1 && objOrArr > 0
407 }
408
409 // Svg matches a SVG file.
410 func Svg(raw []byte, limit uint32) bool {
411 return svgWithoutXMLDeclaration(raw) || svgWithXMLDeclaration(raw)
412 }
413
414 // svgWithoutXMLDeclaration matches a SVG image that does not have an XML header.
415 // Example:
416 //
417 // <!-- xml comment ignored -->
418 // <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
419 // <rect fill="#fff" stroke="#000" x="-70" y="-70" width="390" height="390"/>
420 // </svg>
421 func svgWithoutXMLDeclaration(s scan.Bytes) bool {
422 for scan.ByteIsWS(s.Peek()) {
423 s.Advance(1)
424 }
425 for mkup.SkipAComment(&s) {
426 }
427 if !bytes.HasPrefix(s, []byte("<svg")) {
428 return false
429 }
430
431 targetName, targetVal := []byte("xmlns"), []byte("http://www.w3.org/2000/svg")
432 var aName, aVal []byte
433 hasMore := true
434 for hasMore {
435 aName, aVal, hasMore = mkup.GetAnAttribute(&s)
436 if bytes.Equal(aName, targetName) && bytes.Equal(aVal, targetVal) {
437 return true
438 }
439 if !hasMore {
440 return false
441 }
442 }
443 return false
444 }
445
446 // svgWithXMLDeclaration matches a SVG image that has an XML header.
447 // Example:
448 //
449 // <?xml version="1.0" encoding="UTF-8" standalone="no"?>
450 // <svg width="391" height="391" viewBox="-70.5 -70.5 391 391" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
451 // <rect fill="#fff" stroke="#000" x="-70" y="-70" width="390" height="390"/>
452 // </svg>
453 func svgWithXMLDeclaration(s scan.Bytes) bool {
454 for scan.ByteIsWS(s.Peek()) {
455 s.Advance(1)
456 }
457 if !bytes.HasPrefix(s, []byte("<?xml")) {
458 return false
459 }
460
461 // version is a required attribute for XML.
462 hasVersion := false
463 var aName []byte
464 hasMore := true
465 for hasMore {
466 aName, _, hasMore = mkup.GetAnAttribute(&s)
467 if bytes.Equal(aName, []byte("version")) {
468 hasVersion = true
469 break
470 }
471 if !hasMore {
472 break
473 }
474 }
475 if len(s) > 4096 {
476 s = s[:4096]
477 }
478 return hasVersion && bytes.Contains(s, []byte("<svg"))
479 }
480
481 // Srt matches a SubRip file.
482 func Srt(raw []byte, _ uint32) bool {
483 s := scan.Bytes(raw)
484 line := s.Line()
485
486 // First line must be 1.
487 if len(line) != 1 || line[0] != '1' {
488 return false
489 }
490 line = s.Line()
491 // Timestamp format (e.g: 00:02:16,612 --> 00:02:19,376) limits second line
492 // length to exactly 29 characters.
493 if len(line) != 29 {
494 return false
495 }
496 // Decimal separator of fractional seconds in the timestamps must be a
497 // comma, not a period.
498 if bytes.IndexByte(line, '.') != -1 {
499 return false
500 }
501 sep := []byte(" --> ")
502 i := bytes.Index(line, sep)
503 if i == -1 {
504 return false
505 }
506 const layout = "15:04:05,000"
507 t0, err := time.Parse(layout, string(line[:i]))
508 if err != nil {
509 return false
510 }
511 t1, err := time.Parse(layout, string(line[i+len(sep):]))
512 if err != nil {
513 return false
514 }
515 if t0.After(t1) {
516 return false
517 }
518
519 line = s.Line()
520 // A third line must exist and not be empty. This is the actual subtitle text.
521 return len(line) != 0
522 }
523
524 // Vtt matches a Web Video Text Tracks (WebVTT) file. See
525 // https://www.iana.org/assignments/media-types/text/vtt.
526 func Vtt(raw []byte, limit uint32) bool {
527 // Prefix match.
528 prefixes := [][]byte{
529 {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0A}, // UTF-8 BOM, "WEBVTT" and a line feed
530 {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0D}, // UTF-8 BOM, "WEBVTT" and a carriage return
531 {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x20}, // UTF-8 BOM, "WEBVTT" and a space
532 {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x09}, // UTF-8 BOM, "WEBVTT" and a horizontal tab
533 {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0A}, // "WEBVTT" and a line feed
534 {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0D}, // "WEBVTT" and a carriage return
535 {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x20}, // "WEBVTT" and a space
536 {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x09}, // "WEBVTT" and a horizontal tab
537 }
538 for _, p := range prefixes {
539 if bytes.HasPrefix(raw, p) {
540 return true
541 }
542 }
543
544 // Exact match.
545 return bytes.Equal(raw, []byte{0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) || // UTF-8 BOM and "WEBVTT"
546 bytes.Equal(raw, []byte{0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) // "WEBVTT"
547 }
548
549 type rfc822Hint struct {
550 h []byte
551 matchFlags scan.Flags
552 }
553
554 // The hints come from libmagic, but the implementation is bit different. libmagic
555 // only checks if the file starts with the hint, while we additionally look for
556 // a secondary hint in the first few lines of input.
557 func RFC822(raw []byte, limit uint32) bool {
558 b := scan.Bytes(raw)
559
560 // Keep hints here to avoid instantiating them several times in lineHasRFC822Hint.
561 // The alternative is to make them a package level var, but then they'd go
562 // on the heap.
563 // Some of the hints are IgnoreCase, some not. I selected based on what libmagic
564 // does and based on personal observations from sample files.
565 hints := []rfc822Hint{
566 {[]byte("From: "), 0},
567 {[]byte("To: "), 0},
568 {[]byte("CC: "), scan.IgnoreCase},
569 {[]byte("Date: "), 0},
570 {[]byte("Subject: "), 0},
571 {[]byte("Received: "), 0},
572 {[]byte("Relay-Version: "), 0},
573 {[]byte("#! rnews"), 0},
574 {[]byte("N#! rnews"), 0},
575 {[]byte("Forward to"), 0},
576 {[]byte("Pipe to"), 0},
577 {[]byte("DELIVERED-TO: "), scan.IgnoreCase},
578 {[]byte("RETURN-PATH: "), scan.IgnoreCase},
579 {[]byte("Content-Type: "), 0},
580 {[]byte("Content-Transfer-Encoding: "), 0},
581 }
582 if !lineHasRFC822Hint(b.Line(), hints) {
583 return false
584 }
585 for i := 0; i < 20; i++ {
586 if lineHasRFC822Hint(b.Line(), hints) {
587 return true
588 }
589 }
590
591 return false
592 }
593
594 func lineHasRFC822Hint(b scan.Bytes, hints []rfc822Hint) bool {
595 for _, h := range hints {
596 if b.Match(h.h, h.matchFlags) > -1 {
597 return true
598 }
599 }
600 return false
601 }