diff --git a/signature.go b/signature.go index f9ca3c4..9427541 100644 --- a/signature.go +++ b/signature.go @@ -1,5 +1,7 @@ package filesig +import "regexp" + var ( AVIF = []byte{0x00, 0x00, 0x00} BMP = []byte{0x42, 0x4D} @@ -32,4 +34,7 @@ var ( ZIP_1 = []byte{0x50, 0x4B, 0x05, 0x06} ZIP_2 = []byte{0x50, 0x4B, 0x07, 0x08} WEBP = []byte{0x52, 0x49, 0x46, 0x46} + + HtmlCommentRegex = regexp.MustCompile(`(?i)`) + SvgRegex = regexp.MustCompile(`(?i)^\s*(?:<\?xml[^>]*>\s*)?(?:]*>\s*)?]*>[^*]*<\/svg>\s*$`) ) diff --git a/validator.go b/validator.go index 84e4838..d599a5c 100644 --- a/validator.go +++ b/validator.go @@ -211,3 +211,14 @@ func IsMp4(r io.ReadSeeker) bool { return validMpFour1 == 0 && validMpFour2 == 0 } + +// IsSvg function will return true if File is a valid SVG +func IsSvg(r io.ReadSeeker) bool { + buff, err := io.ReadAll(r) + if err != nil { + return false + } + r.Seek(0, io.SeekStart) + + return SvgRegex.Match(HtmlCommentRegex.ReplaceAll(buff, []byte{})) +} diff --git a/validator_test.go b/validator_test.go index 41f1696..83cb1f9 100644 --- a/validator_test.go +++ b/validator_test.go @@ -395,3 +395,20 @@ func TestGenericMultipleCompareBuffer(t *testing.T) { t.Error("error: one of buffer type is invalid") } } + +func TestIsSvg(t *testing.T) { + buff, err := os.Open("./tmp/sample-0.svg") + + if err != nil { + t.Error("error: SVG file not found") + } + + defer func() { + buff.Close() + }() + + valid := IsSvg(buff) + if !valid { + t.Error("error: buffer not valid SVG file") + } +}