1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-01-08 10:45:04 +02:00
imgproxy/imagemeta/svg.go

61 lines
1.0 KiB
Go
Raw Normal View History

2019-12-25 11:06:15 +02:00
package imagemeta
import (
2020-09-22 14:03:05 +02:00
"bytes"
2020-02-11 15:28:13 +02:00
"encoding/xml"
2020-11-11 18:13:48 +02:00
"fmt"
"io"
2020-11-11 18:13:48 +02:00
"strings"
2021-09-30 16:23:30 +02:00
"github.com/imgproxy/imgproxy/v3/config"
2020-11-11 18:13:48 +02:00
"golang.org/x/text/encoding/charmap"
)
2020-02-11 15:28:13 +02:00
type svgHeader struct {
XMLName xml.Name
}
2020-11-11 18:13:48 +02:00
func xmlCharsetReader(charset string, input io.Reader) (io.Reader, error) {
if strings.EqualFold(charset, "iso-8859-1") {
return charmap.ISO8859_1.NewDecoder().Reader(input), nil
}
return nil, fmt.Errorf("Unknown SVG charset: %s", charset)
}
2020-02-11 15:28:13 +02:00
func IsSVG(r io.Reader) (bool, error) {
2021-05-13 15:58:44 +02:00
maxBytes := config.MaxSvgCheckBytes
2020-02-11 15:28:13 +02:00
var h svgHeader
buf := make([]byte, 0, maxBytes)
b := make([]byte, 1024)
2020-09-22 14:03:05 +02:00
rr := bytes.NewReader(buf)
2020-02-11 15:28:13 +02:00
for {
n, err := r.Read(b)
if err != nil && err != io.EOF {
return false, err
}
if n <= 0 {
return false, nil
}
buf = append(buf, b[:n]...)
2020-09-22 14:03:05 +02:00
rr.Reset(buf)
2020-02-11 15:28:13 +02:00
2020-09-22 14:03:05 +02:00
dec := xml.NewDecoder(rr)
dec.Strict = false
2020-11-11 18:13:48 +02:00
dec.CharsetReader = xmlCharsetReader
2020-11-20 12:26:01 +02:00
if dec.Decode(&h); h.XMLName.Local == "svg" {
2020-02-11 15:28:13 +02:00
return true, nil
}
if len(buf) >= maxBytes {
break
}
}
2020-02-11 15:28:13 +02:00
return false, nil
}