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 // CDXXML matches a CycloneDX XML BOM file.
134 // https://cyclonedx.org/docs/1.7/xml/
135 func CDXXML(raw []byte, _ uint32) bool {
136 // xmlns is missing the version suffix because there are too many past versions
137 // and probably future versions to come.
138 return xml(raw, xmlSig{[]byte("<bom"), []byte(`xmlns="http://cyclonedx.org/schema/bom/`)})
139 }
140
141 // VCard matches a Virtual Contact File.
142 func VCard(raw []byte, _ uint32) bool {
143 return ciPrefix(raw, []byte("BEGIN:VCARD\n"), []byte("BEGIN:VCARD\r\n"))
144 }
145
146 // ICalendar matches a iCalendar file.
147 func ICalendar(raw []byte, _ uint32) bool {
148 return ciPrefix(raw, []byte("BEGIN:VCALENDAR\n"), []byte("BEGIN:VCALENDAR\r\n"))
149 }
150
151 const (
152 snone = 0
153 scws = scan.CompactWS
154 sfw = scan.FullWord
155 scwsfw = scan.CompactWS | scan.FullWord
156 )
157
158 func phpPageF(raw []byte, _ uint32) bool {
159 return ciPrefix(raw,
160 []byte("<?PHP"),
161 []byte("<?\n"),
162 []byte("<?\r"),
163 []byte("<? "),
164 )
165 }
166 func phpScriptF(raw []byte, _ uint32) bool {
167 return shebang(raw,
168 shebangSig{[]byte("/usr/local/bin/php"), snone},
169 shebangSig{[]byte("/usr/bin/php"), snone},
170 shebangSig{[]byte("/usr/bin/env php"), scws},
171 shebangSig{[]byte("/usr/bin/env -S php"), scws},
172 )
173 }
174
175 // Js matches a Javascript file.
176 func Js(raw []byte, _ uint32) bool {
177 return shebang(raw,
178 shebangSig{[]byte("/bin/node"), snone},
179 shebangSig{[]byte("/usr/bin/node"), snone},
180 shebangSig{[]byte("/bin/nodejs"), snone},
181 shebangSig{[]byte("/usr/bin/nodejs"), snone},
182 shebangSig{[]byte("/usr/bin/env node"), scws},
183 shebangSig{[]byte("/usr/bin/env -S node"), scws},
184 shebangSig{[]byte("/usr/bin/env nodejs"), scws},
185 shebangSig{[]byte("/usr/bin/env -S nodejs"), scws},
186 )
187 }
188
189 // Lua matches a Lua programming language file.
190 func Lua(raw []byte, _ uint32) bool {
191 return shebang(raw,
192 shebangSig{[]byte("/usr/bin/lua"), sfw},
193 shebangSig{[]byte("/usr/local/bin/lua"), sfw},
194 shebangSig{[]byte("/usr/bin/env lua"), scwsfw},
195 shebangSig{[]byte("/usr/bin/env -S lua"), scwsfw},
196 )
197 }
198
199 // Perl matches a Perl programming language file.
200 func Perl(raw []byte, _ uint32) bool {
201 return shebang(raw,
202 shebangSig{[]byte("/usr/bin/perl"), sfw},
203 shebangSig{[]byte("/usr/bin/env perl"), scwsfw},
204 shebangSig{[]byte("/usr/bin/env -S perl"), scwsfw},
205 )
206 }
207
208 // Python matches a Python programming language file.
209 func Python(raw []byte, _ uint32) bool {
210 return shebang(raw,
211 shebangSig{[]byte("/usr/bin/python"), snone},
212 shebangSig{[]byte("/usr/local/bin/python"), snone},
213 shebangSig{[]byte("/usr/bin/env python"), scws},
214 shebangSig{[]byte("/usr/bin/env -S python"), scws},
215 shebangSig{[]byte("/usr/bin/python2"), snone},
216 shebangSig{[]byte("/usr/local/bin/python2"), snone},
217 shebangSig{[]byte("/usr/bin/env python2"), scws},
218 shebangSig{[]byte("/usr/bin/env -S python2"), scws},
219 shebangSig{[]byte("/usr/bin/python3"), snone},
220 shebangSig{[]byte("/usr/local/bin/python3"), snone},
221 shebangSig{[]byte("/usr/bin/env python3"), scws},
222 shebangSig{[]byte("/usr/bin/env -S python3"), scws},
223 )
224
225 }
226
227 // Ruby matches a Ruby programming language file.
228 func Ruby(raw []byte, _ uint32) bool {
229 return shebang(raw,
230 shebangSig{[]byte("/usr/bin/ruby"), snone},
231 shebangSig{[]byte("/usr/local/bin/ruby"), snone},
232 shebangSig{[]byte("/usr/bin/env ruby"), scws},
233 shebangSig{[]byte("/usr/bin/env -S ruby"), scws},
234 )
235 }
236
237 // Tcl matches a Tcl programming language file.
238 func Tcl(raw []byte, _ uint32) bool {
239 return shebang(raw,
240 shebangSig{[]byte("/usr/bin/tcl"), snone},
241 shebangSig{[]byte("/usr/local/bin/tcl"), snone},
242 shebangSig{[]byte("/usr/bin/env tcl"), scws},
243 shebangSig{[]byte("/usr/bin/env -S tcl"), scws},
244 shebangSig{[]byte("/usr/bin/tclsh"), snone},
245 shebangSig{[]byte("/usr/local/bin/tclsh"), snone},
246 shebangSig{[]byte("/usr/bin/env tclsh"), scws},
247 shebangSig{[]byte("/usr/bin/env -S tclsh"), scws},
248 shebangSig{[]byte("/usr/bin/wish"), snone},
249 shebangSig{[]byte("/usr/local/bin/wish"), snone},
250 shebangSig{[]byte("/usr/bin/env wish"), scws},
251 shebangSig{[]byte("/usr/bin/env -S wish"), scws},
252 )
253 }
254
255 // Rtf matches a Rich Text Format file.
256 func Rtf(raw []byte, _ uint32) bool {
257 return bytes.HasPrefix(raw, []byte("{\\rtf"))
258 }
259
260 // Shell matches a shell script file.
261 func Shell(raw []byte, _ uint32) bool {
262 return shebang(raw,
263 shebangSig{[]byte("/bin/sh"), sfw},
264 shebangSig{[]byte("/bin/bash"), sfw},
265 shebangSig{[]byte("/usr/local/bin/bash"), sfw},
266 shebangSig{[]byte("/usr/bin/env bash"), scwsfw},
267 shebangSig{[]byte("/usr/bin/env -S bash"), scwsfw},
268 shebangSig{[]byte("/bin/csh"), sfw},
269 shebangSig{[]byte("/usr/local/bin/csh"), sfw},
270 shebangSig{[]byte("/usr/bin/env csh"), scwsfw},
271 shebangSig{[]byte("/usr/bin/env -S csh"), scwsfw},
272 shebangSig{[]byte("/bin/dash"), sfw},
273 shebangSig{[]byte("/usr/local/bin/dash"), sfw},
274 shebangSig{[]byte("/usr/bin/env dash"), scwsfw},
275 shebangSig{[]byte("/usr/bin/env -S dash"), scwsfw},
276 shebangSig{[]byte("/bin/ksh"), sfw},
277 shebangSig{[]byte("/usr/local/bin/ksh"), sfw},
278 shebangSig{[]byte("/usr/bin/env ksh"), scwsfw},
279 shebangSig{[]byte("/usr/bin/env -S ksh"), scwsfw},
280 shebangSig{[]byte("/bin/tcsh"), sfw},
281 shebangSig{[]byte("/usr/local/bin/tcsh"), sfw},
282 shebangSig{[]byte("/usr/bin/env tcsh"), scwsfw},
283 shebangSig{[]byte("/usr/bin/env -S tcsh"), scwsfw},
284 shebangSig{[]byte("/bin/zsh"), sfw},
285 shebangSig{[]byte("/usr/local/bin/zsh"), sfw},
286 shebangSig{[]byte("/usr/bin/env zsh"), scwsfw},
287 shebangSig{[]byte("/usr/bin/env -S zsh"), scwsfw},
288 )
289 }
290
291 // Text matches a plain text file.
292 //
293 // TODO: This function does not parse BOM-less UTF16 and UTF32 files. Not really
294 // sure it should. libmagic also requires a BOM for UTF16 and UTF32.
295 func Text(raw []byte, _ uint32) bool {
296 // First look for BOM.
297 if cset := charset.FromBOM(raw); cset != "" {
298 return true
299 }
300 // Binary data bytes as defined here: https://mimesniff.spec.whatwg.org/#binary-data-byte
301 for i := 0; i < min(len(raw), 4096); i++ {
302 b := raw[i]
303 if b <= 0x08 ||
304 b == 0x0B ||
305 0x0E <= b && b <= 0x1A ||
306 0x1C <= b && b <= 0x1F {
307 return false
308 }
309 }
310 return true
311 }
312
313 // XHTML matches an XHTML file. This check depends on the XML check to have passed.
314 func XHTML(raw []byte, limit uint32) bool {
315 raw = raw[:min(len(raw), 1024)]
316 b := scan.Bytes(raw)
317 i, _ := b.Search([]byte("<!DOCTYPE HTML"), scan.CompactWS|scan.IgnoreCase)
318 if i != -1 {
319 return true
320 }
321 i, _ = b.Search([]byte("<HTML XMLNS="), scan.CompactWS|scan.IgnoreCase)
322 return i != -1
323 }
324
325 // Php matches a PHP: Hypertext Preprocessor file.
326 func Php(raw []byte, limit uint32) bool {
327 if res := phpPageF(raw, limit); res {
328 return res
329 }
330 return phpScriptF(raw, limit)
331 }
332
333 // JSON matches a JavaScript Object Notation file.
334 func JSON(raw []byte, limit uint32) bool {
335 // #175 A single JSON string, number or bool is not considered JSON.
336 // JSON objects and arrays are reported as JSON.
337 return jsonHelper(raw, limit, json.QueryNone, json.TokObject|json.TokArray)
338 }
339
340 // GeoJSON matches a RFC 7946 GeoJSON file.
341 //
342 // GeoJSON detection implies searching for key:value pairs like: `"type": "Feature"`
343 // in the input.
344 func GeoJSON(raw []byte, limit uint32) bool {
345 return jsonHelper(raw, limit, json.QueryGeo, json.TokObject)
346 }
347
348 // HAR matches a HAR Spec file.
349 // Spec: http://www.softwareishard.com/blog/har-12-spec/
350 func HAR(raw []byte, limit uint32) bool {
351 return jsonHelper(raw, limit, json.QueryHAR, json.TokObject)
352 }
353
354 // GLTF matches a GL Transmission Format (JSON) file.
355 // Visit [glTF specification] and [IANA glTF entry] for more details.
356 //
357 // [glTF specification]: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html
358 // [IANA glTF entry]: https://www.iana.org/assignments/media-types/model/gltf+json
359 func GLTF(raw []byte, limit uint32) bool {
360 return jsonHelper(raw, limit, json.QueryGLTF, json.TokObject)
361 }
362
363 // CDXJSON matches a CycloneDX JSON BOM file.
364 // https://cyclonedx.org/docs/1.7/json/
365 func CDXJSON(raw []byte, limit uint32) bool {
366 return jsonHelper(raw, limit, json.QueryCDX, json.TokObject)
367 }
368
369 // jsonHelper parses raw and tries to match the q query against it. wantToks
370 // ensures we're not wasting time parsing an input that would not pass anyway,
371 // ex: the input is a valid JSON array, but we're looking for a JSON object.
372 func jsonHelper(raw scan.Bytes, limit uint32, q string, wantToks ...int) bool {
373 firstNonWS := raw.FirstNonWS()
374
375 hasTargetTok := false
376 for _, t := range wantToks {
377 hasTargetTok = hasTargetTok || (t&json.TokArray > 0 && firstNonWS == '[')
378 hasTargetTok = hasTargetTok || (t&json.TokObject > 0 && firstNonWS == '{')
379 }
380 if !hasTargetTok {
381 return false
382 }
383 lraw := len(raw)
384 parsed, inspected, _, querySatisfied := json.Parse(q, raw)
385 if !querySatisfied {
386 return false
387 }
388
389 // If the full file content was provided, check that the whole input was parsed.
390 if limit == 0 || lraw < int(limit) {
391 return parsed == lraw
392 }
393
394 // If a section of the file was provided, check if all of it was inspected.
395 // In other words, check that if there was a problem parsing, that problem
396 // occurred after the last byte in the input.
397 return inspected == lraw && lraw > 0
398 }
399
400 // NdJSON matches a Newline delimited JSON file. All complete lines from raw
401 // must be valid JSON documents meaning they contain one of the valid JSON data
402 // types.
403 func NdJSON(raw []byte, limit uint32) bool {
404 lCount, objOrArr := 0, 0
405
406 s := scan.Bytes(raw)
407 var l scan.Bytes
408 for len(s) != 0 {
409 l = s.Line()
410 parsed, inspected, firstToken, _ := json.Parse(json.QueryNone, l)
411 // Only the last line may be truncated by the read limit; for it, it is
412 // enough that the parser inspected all of it. Every other line must be a
413 // complete, valid JSON document, otherwise a single JSON document spread
414 // over multiple lines would be mistaken for NDJSON. #803
415 if len(s) == 0 {
416 if inspected != len(l) {
417 return false
418 }
419 } else if parsed != len(l) {
420 return false
421 }
422 if firstToken == json.TokArray || firstToken == json.TokObject {
423 objOrArr++
424 }
425 lCount++
426 }
427
428 return lCount > 1 && objOrArr > 0
429 }
430
431 // Svg matches a SVG file.
432 func Svg(raw []byte, limit uint32) bool {
433 return svgWithoutXMLDeclaration(raw) || svgWithXMLDeclaration(raw)
434 }
435
436 // svgWithoutXMLDeclaration matches a SVG image that does not have an XML header.
437 // Example:
438 //
439 // <!-- xml comment ignored -->
440 // <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
441 // <rect fill="#fff" stroke="#000" x="-70" y="-70" width="390" height="390"/>
442 // </svg>
443 func svgWithoutXMLDeclaration(s scan.Bytes) bool {
444 for scan.ByteIsWS(s.Peek()) {
445 s.Advance(1)
446 }
447 for mkup.SkipAComment(&s) {
448 }
449 if !bytes.HasPrefix(s, []byte("<svg")) {
450 return false
451 }
452
453 targetName, targetVal := []byte("xmlns"), []byte("http://www.w3.org/2000/svg")
454 var aName, aVal []byte
455 hasMore := true
456 for hasMore {
457 aName, aVal, hasMore = mkup.GetAnAttribute(&s)
458 if bytes.Equal(aName, targetName) && bytes.Equal(aVal, targetVal) {
459 return true
460 }
461 if !hasMore {
462 return false
463 }
464 }
465 return false
466 }
467
468 // svgWithXMLDeclaration matches a SVG image that has an XML header.
469 // Example:
470 //
471 // <?xml version="1.0" encoding="UTF-8" standalone="no"?>
472 // <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">
473 // <rect fill="#fff" stroke="#000" x="-70" y="-70" width="390" height="390"/>
474 // </svg>
475 func svgWithXMLDeclaration(s scan.Bytes) bool {
476 for scan.ByteIsWS(s.Peek()) {
477 s.Advance(1)
478 }
479 if !bytes.HasPrefix(s, []byte("<?xml")) {
480 return false
481 }
482
483 // version is a required attribute for XML.
484 hasVersion := false
485 var aName []byte
486 hasMore := true
487 for hasMore {
488 aName, _, hasMore = mkup.GetAnAttribute(&s)
489 if bytes.Equal(aName, []byte("version")) {
490 hasVersion = true
491 break
492 }
493 if !hasMore {
494 break
495 }
496 }
497 if len(s) > 4096 {
498 s = s[:4096]
499 }
500 return hasVersion && bytes.Contains(s, []byte("<svg"))
501 }
502
503 // Srt matches a SubRip file.
504 func Srt(raw []byte, _ uint32) bool {
505 s := scan.Bytes(raw)
506 line := s.Line()
507
508 // First line must be 1.
509 if len(line) != 1 || line[0] != '1' {
510 return false
511 }
512 line = s.Line()
513 // Timestamp format (e.g: 00:02:16,612 --> 00:02:19,376) limits second line
514 // length to exactly 29 characters.
515 if len(line) != 29 {
516 return false
517 }
518 // Decimal separator of fractional seconds in the timestamps must be a
519 // comma, not a period.
520 if bytes.IndexByte(line, '.') != -1 {
521 return false
522 }
523 sep := []byte(" --> ")
524 i := bytes.Index(line, sep)
525 if i == -1 {
526 return false
527 }
528 const layout = "15:04:05,000"
529 t0, err := time.Parse(layout, string(line[:i]))
530 if err != nil {
531 return false
532 }
533 t1, err := time.Parse(layout, string(line[i+len(sep):]))
534 if err != nil {
535 return false
536 }
537 if t0.After(t1) {
538 return false
539 }
540
541 line = s.Line()
542 // A third line must exist and not be empty. This is the actual subtitle text.
543 return len(line) != 0
544 }
545
546 // Vtt matches a Web Video Text Tracks (WebVTT) file. See
547 // https://www.iana.org/assignments/media-types/text/vtt.
548 func Vtt(raw []byte, limit uint32) bool {
549 // Prefix match.
550 prefixes := [][]byte{
551 {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0A}, // UTF-8 BOM, "WEBVTT" and a line feed
552 {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0D}, // UTF-8 BOM, "WEBVTT" and a carriage return
553 {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x20}, // UTF-8 BOM, "WEBVTT" and a space
554 {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x09}, // UTF-8 BOM, "WEBVTT" and a horizontal tab
555 {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0A}, // "WEBVTT" and a line feed
556 {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0D}, // "WEBVTT" and a carriage return
557 {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x20}, // "WEBVTT" and a space
558 {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x09}, // "WEBVTT" and a horizontal tab
559 }
560 for _, p := range prefixes {
561 if bytes.HasPrefix(raw, p) {
562 return true
563 }
564 }
565
566 // Exact match.
567 return bytes.Equal(raw, []byte{0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) || // UTF-8 BOM and "WEBVTT"
568 bytes.Equal(raw, []byte{0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) // "WEBVTT"
569 }
570
571 type rfc822Hint struct {
572 h []byte
573 matchFlags scan.Flags
574 }
575
576 // The hints come from libmagic, but the implementation is bit different. libmagic
577 // only checks if the file starts with the hint, while we additionally look for
578 // a secondary hint in the first few lines of input.
579 func RFC822(raw []byte, limit uint32) bool {
580 b := scan.Bytes(raw)
581
582 // Keep hints here to avoid instantiating them several times in lineHasRFC822Hint.
583 // The alternative is to make them a package level var, but then they'd go
584 // on the heap.
585 // Some of the hints are IgnoreCase, some not. I selected based on what libmagic
586 // does and based on personal observations from sample files.
587 hints := []rfc822Hint{
588 // Enron dataset has Message-ID, Message-Id and Message-id.
589 {[]byte("Message-ID: "), scan.IgnoreCase},
590 {[]byte("From: "), 0},
591 {[]byte("To: "), 0},
592 {[]byte("CC: "), scan.IgnoreCase},
593 {[]byte("Date: "), 0},
594 {[]byte("Subject: "), 0},
595 {[]byte("Received: "), 0},
596 {[]byte("Relay-Version: "), 0},
597 {[]byte("#! rnews"), 0},
598 {[]byte("N#! rnews"), 0},
599 {[]byte("Forward to"), 0},
600 {[]byte("Pipe to"), 0},
601 {[]byte("DELIVERED-TO: "), scan.IgnoreCase},
602 {[]byte("RETURN-PATH: "), scan.IgnoreCase},
603 {[]byte("Content-Type: "), 0},
604 {[]byte("Content-Transfer-Encoding: "), 0},
605 }
606 if !lineHasRFC822Hint(b.Line(), hints) {
607 return false
608 }
609 for i := 0; i < 20; i++ {
610 if lineHasRFC822Hint(b.Line(), hints) {
611 return true
612 }
613 }
614
615 return false
616 }
617
618 func lineHasRFC822Hint(b scan.Bytes, hints []rfc822Hint) bool {
619 for _, h := range hints {
620 if b.Match(h.h, h.matchFlags) > -1 {
621 return true
622 }
623 }
624 return false
625 }
626
627 func GEDCOM(raw []byte, limit uint32) bool {
628 // Skip if empty
629 if len(raw) == 0 {
630 return false
631 }
632
633 // GEDCOM header fits within first 4KB
634 searchLimit := min(len(raw), 4096)
635 raw = raw[:searchLimit]
636
637 b := scan.Bytes(raw)
638
639 // Skip BOM if present: UTF-8, UTF-16BE, UTF-16LE
640 for _, bom := range [][]byte{
641 {0xEF, 0xBB, 0xBF}, // UTF-8
642 {0xFE, 0xFF}, // UTF-16BE
643 {0xFF, 0xFE}, // UTF-16LE
644 } {
645 if bytes.HasPrefix(b, bom) {
646 b.Advance(len(bom))
647 break // Only one BOM can exist at the start
648 }
649 }
650
651 b.TrimLWS()
652
653 firstLine := b.Line()
654 if !bytes.Equal(firstLine, []byte("0 HEAD")) {
655 return false
656 }
657
658 // "1 GEDC" is mandatory in the header
659 for i := 0; i < 10; i++ {
660 line := b.Line()
661 if bytes.Equal(line, []byte("1 GEDC")) {
662 return true
663 }
664 }
665 return false
666 }