Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

svg.gno

25.39 Kb · 731 lines
  1package safe
  2
  3import (
  4	"chain/markdown"
  5	"errors"
  6	"strconv"
  7	"strings"
  8)
  9
 10// AssertSVG checks an engine's raw SVG output with a strict allowlist
 11// (SA-M3; it replaced a substring blacklist that namespace prefixes, URL
 12// whitespace and CSS escapes could slip past). The document is tokenized
 13// as XML and must be well formed:
 14//
 15//   - only the elements in svgElements, without a namespace prefix: no
 16//     script, style, foreignObject, image, a, animation (set, animate*) or
 17//     anything else that can run code, load a resource or redefine the page;
 18//   - only the attributes in svgAttributeList, without a prefix except
 19//     xlink:href and the two fixed xmlns declarations; event handlers and
 20//     style= are therefore impossible;
 21//   - attribute values hold no control character, backslash, '<', ':' or
 22//     non-allowlisted entity, so no URL scheme (javascript:, data:, http:)
 23//     can be spelled, however it is split or escaped; url() must be
 24//     url(#id) and href must be #id;
 25//   - (v2, WP-J J-4) no CSS <image> function that takes a URL as a string:
 26//     no value may contain image(, image-set(, cross-fade( or element(
 27//     (ASCII case-insensitive, Go lower-casing, so also -webkit-image-set(),
 28//     İmage(), …), and mask must be exactly "none" or "url(#id)";
 29//   - no comments, CDATA, doctype, entities or processing instructions.
 30//
 31// The frontend shows art only through <img>, which never runs scripts; this
 32// check is the defence in depth for every other place a data: URI ends up
 33// (wallets, explorers, indexers; RA M-7, design §5.4).
 34//
 35// v2 (mainnet plan §2.1, M-2) accepts exactly the documents v1 accepts,
 36// except the J-4 rule above, and returns the same error texts, at ~3k
 37// instead of ~30k gas per byte: one table-driven pass proves ordinary
 38// tokens clean, and every token it cannot prove clean goes through v1's
 39// checks unchanged (checkAttr, checkChars), so the first error found is
 40// v1's; the J-4 checks (checkCSSValue) run on a value only after v1's checks
 41// passed it. UTF-8 validity is one native MatchCharsetN call for ASCII
 42// documents, and long d/points values are skipped with native probes.
 43// Proof: v1's tests, the differential corpus zz_svg_corpus_test.gno (v2 =
 44// the TypeScript twin; v1 = v2 except on J-4 documents, listed by case) and
 45// the gas filetests z_svg_gas_*.
 46func AssertSVG(svg string, maxBytes int) error {
 47	if len(svg) == 0 {
 48		return errors.New("svg: empty")
 49	}
 50	if len(svg) > maxBytes {
 51		return errors.New("svg: larger than " + strconv.Itoa(maxBytes) + " bytes")
 52	}
 53	if !validUTF8(svg) {
 54		return errors.New("svg: invalid UTF-8")
 55	}
 56	if !strings.HasPrefix(svg, "<svg") || !strings.HasSuffix(svg, "</svg>") {
 57		return errors.New("svg: must start with <svg and end with </svg>")
 58	}
 59	return scanSVG(svg)
 60}
 61
 62const (
 63	svgNS   = "http://www.w3.org/2000/svg"
 64	xlinkNS = "http://www.w3.org/1999/xlink"
 65)
 66
 67// svgElements are the drawing elements an engine may use.
 68var svgElements = map[string]bool{
 69	"svg": true, "g": true, "defs": true, "symbol": true, "use": true,
 70	"title": true, "desc": true,
 71	"path": true, "rect": true, "circle": true, "ellipse": true,
 72	"line": true, "polyline": true, "polygon": true,
 73	"text": true, "tspan": true,
 74	"linearGradient": true, "radialGradient": true, "stop": true,
 75	"clipPath": true, "mask": true, "pattern": true,
 76	"filter": true, "feGaussianBlur": true, "feOffset": true, "feBlend": true,
 77	"feColorMatrix": true, "feComposite": true, "feFlood": true, "feMerge": true,
 78	"feMergeNode": true, "feMorphology": true, "feTurbulence": true,
 79	"feDisplacementMap": true, "feComponentTransfer": true, "feFuncR": true,
 80	"feFuncG": true, "feFuncB": true, "feFuncA": true,
 81}
 82
 83// svgAttributeList holds the geometry, paint and filter attributes (the v1
 84// set, reordered: the first six have the fixed ids below). Absent on
 85// purpose: style, on*, src, every animation attribute (attributeName, to,
 86// from, by, begin), and every prefixed name except xlink:href. An
 87// attribute's id is its index + 1 (frontend chain/assertSvg.ts uses the
 88// same list).
 89var svgAttributeList = []string{
 90	"xmlns", "xmlns:xlink", "href", "xlink:href", "d", "points",
 91	"id", "class", "version", "viewBox", "preserveAspectRatio",
 92	"x", "y", "x1", "y1", "x2", "y2", "cx", "cy", "r", "rx", "ry", "fx", "fy", "fr",
 93	"width", "height", "pathLength", "transform",
 94	"fill", "fill-opacity", "fill-rule",
 95	"stroke", "stroke-width", "stroke-opacity", "stroke-linecap",
 96	"stroke-linejoin", "stroke-dasharray", "stroke-dashoffset", "stroke-miterlimit",
 97	"opacity", "color", "visibility", "display",
 98	"clip-path", "clip-rule", "mask", "filter",
 99	"shape-rendering", "vector-effect", "paint-order", "mix-blend-mode",
100	"font-family", "font-size", "font-weight", "font-style",
101	"text-anchor", "dominant-baseline", "letter-spacing",
102	"textLength", "lengthAdjust", "dx", "dy", "rotate",
103	"gradientUnits", "gradientTransform", "spreadMethod",
104	"offset", "stop-color", "stop-opacity",
105	"patternUnits", "patternContentUnits", "patternTransform",
106	"clipPathUnits", "maskUnits", "maskContentUnits",
107	"filterUnits", "primitiveUnits", "result", "in", "in2",
108	"stdDeviation", "mode", "type", "values", "operator",
109	"k1", "k2", "k3", "k4", "radius",
110	"flood-color", "flood-opacity", "baseFrequency", "numOctaves",
111	"seed", "stitchTiles", "scale", "xChannelSelector", "yChannelSelector",
112	"tableValues", "slope", "intercept", "amplitude", "exponent",
113}
114
115const (
116	idXmlns = 1 + iota
117	idXmlnsXlink
118	idHref
119	idXlinkHref
120	idD
121	idPoints
122	idMask = 47 // "mask" (J-4: none or url(#id) only); checked in init
123)
124
125// svgAttrIDs maps an allowlisted attribute to its id (1..len); 0 = not allowed.
126var svgAttrIDs = map[string]int{}
127
128func init() {
129	if len(svgAttributeList) > 127 {
130		panic("safe: svgAttributeList outgrew the two-word seen mask")
131	}
132	for i, a := range svgAttributeList {
133		svgAttrIDs[a] = i + 1
134	}
135	if svgAttrIDs["mask"] != idMask {
136		panic("safe: idMask is not the id of mask")
137	}
138}
139
140// Byte classes, generated (256-byte tables indexed by the byte):
141//   - textClass: 0 plain, 1 '<', 2 '&', 3 byte >= 0x80, 4 control or DEL
142//     (not \t \n \r);
143//   - valueClass: 0 plain, 1 '"', 2 '\'', 3 'u', 'U' (url() check) or '('
144//     (J-4 function check), 4 '&', 5 byte >= 0x80, 6 '<', '>', ':', '\',
145//     control or DEL;
146//   - nameFirst / nameRest: XML name characters as v1 reads them (ASCII
147//     letters, '_', ':'; then also digits, '-', '.');
148//   - spaceClass: ' ', \t, \n, \r.
149//
150// valuePlainLo/Hi is valueClass 0 as a MatchCharsetN bitmap.
151const (
152	textClass = "\x04\x04\x04\x04\x04\x04\x04\x04\x04\x00\x00\x04\x04\x00\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03"
153	valueClass = "\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x00\x00\x01\x00\x00\x00\x04\x02\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x06\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05"
154	nameFirst = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
155	nameRest = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
156	spaceClass = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
157	valuePlainLo = 0xabfffe3b00000000
158	valuePlainHi = 0x7fdfffffefdfffff
159)
160
161func svgErr(msg string) error { return errors.New("svg: " + msg) }
162
163// validUTF8 is utf8.ValidString: an ASCII document passes one native call;
164// otherwise s is valid exactly when decoding to runes and re-encoding gives
165// s back (an invalid byte decodes to U+FFFD, which re-encodes as EF BF BD,
166// never as the byte itself).
167func validUTF8(s string) bool {
168	if markdown.MatchCharsetN(s, ^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0), 0, len(s)) {
169		return true
170	}
171	return string([]rune(s)) == s
172}
173
174// plainRun returns the end of the run of valueClass-0 bytes that starts at
175// i, found with native probes (doubling, then bisection); i when the run is
176// shorter than the first probe.
177func plainRun(s string, i int) int {
178	lim := len(s) - i
179	lo, hi := 0, 32
180	for {
181		if hi > lim {
182			hi = lim
183		}
184		if !markdown.MatchCharsetN(s[i:i+hi], valuePlainLo, valuePlainHi, valuePlainLo, valuePlainHi, 0, hi) {
185			break
186		}
187		lo = hi
188		if hi == lim {
189			return i + lo
190		}
191		hi *= 2
192	}
193	if lo == 0 {
194		return i
195	}
196	for hi-lo > 1 {
197		mid := (lo + hi) / 2
198		if markdown.MatchCharsetN(s[i:i+mid], valuePlainLo, valuePlainHi, valuePlainLo, valuePlainHi, 0, mid) {
199			lo = mid
200		} else {
201			hi = mid
202		}
203	}
204	return i + lo
205}
206
207// entityAt reports whether one of the five XML entities starts at s[i]. An
208// entity holds no '<' or quote, so matching against the whole document is
209// the same as v1's match against the text run or attribute value. The '&'
210// lies before the '<' of the final "</svg>", so i+6 <= len(s).
211func entityAt(s string, i int) bool {
212	switch s[i+1] {
213	case 'a':
214		return s[i:i+5] == "&amp;" || s[i:i+6] == "&apos;"
215	case 'l':
216		return s[i:i+4] == "&lt;"
217	case 'g':
218		return s[i:i+4] == "&gt;"
219	case 'q':
220		return s[i:i+6] == "&quot;"
221	}
222	return false
223}
224
225// scanSVG is v1's parser as one pass. s starts with "<svg" and ends with
226// "</svg>", so every '<' is at most at len(s)-6 and the last byte is '>':
227// the table loops stop at one of them and need no bounds check, and no
228// token can start inside the final "/svg>" except through its '<'.
229func scanSVG(s string) error {
230	n := len(s)
231	// Every element needs at least 3 bytes ("<g>"), so the depth stays
232	// below n/3: the stack never grows (append would copy it).
233	stack := make([]string, n/3+1)
234	depth := 0
235	i := 0
236	rootDone := false
237	for i < n {
238		if rootDone {
239			return svgErr("content after the root element")
240		}
241		if s[i] != '<' {
242			// character data: printable characters, whitespace and the
243			// five XML entities only (v1 text + checkChars)
244			if depth == 0 {
245				return svgErr("text outside the root element")
246			}
247			start := i
248			for {
249				for textClass[s[i]] == 0 {
250					i++
251				}
252				k := textClass[s[i]]
253				if k == 1 {
254					break
255				}
256				if k == 2 && entityAt(s, i) {
257					i++
258					continue
259				}
260				if k == 3 && !(s[i] == 0xc2 && s[i+1] < 0xa0) { // not a C1 control
261					i++
262					continue
263				}
264				for i < n && s[i] != '<' {
265					i++
266				}
267				if err := checkChars(s[start:i], true); err != nil {
268					return err
269				}
270				break
271			}
272			continue
273		}
274		c := s[i+1]
275		if c == '!' {
276			return svgErr("comments, CDATA, doctype and entity declarations are not allowed")
277		}
278		if c == '?' {
279			return svgErr("processing instructions are not allowed")
280		}
281		if c == '/' {
282			i += 2
283			start := i
284			if nameFirst[s[i]] != 0 {
285				i++
286				for nameRest[s[i]] != 0 {
287					i++
288				}
289			}
290			name := s[start:i]
291			for spaceClass[s[i]] != 0 {
292				i++
293			}
294			if s[i] != '>' {
295				return svgErr("malformed closing tag")
296			}
297			i++
298			if depth == 0 || stack[depth-1] != name {
299				return svgErr("mismatched closing tag </" + name + ">")
300			}
301			depth--
302			if depth == 0 {
303				rootDone = true
304			}
305			continue
306		}
307		// open tag
308		i++
309		start := i
310		if nameFirst[s[i]] != 0 {
311			i++
312			for nameRest[s[i]] != 0 {
313				i++
314			}
315		}
316		name := s[start:i]
317		if name == "" {
318			return svgErr("malformed tag")
319		}
320		if !svgElements[name] { // no allowed element holds ':'
321			return svgErr("element <" + name + "> is not allowed")
322		}
323		first := depth == 0
324		selfClosed := false
325		var seenLo, seenHi uint64
326		for {
327			sp := false
328			if spaceClass[s[i]] != 0 {
329				sp = true
330				i++
331				for spaceClass[s[i]] != 0 {
332					i++
333				}
334			}
335			c := s[i]
336			if c == '>' {
337				i++
338				stack[depth] = name
339				depth++
340				break
341			}
342			if c == '/' {
343				if s[i+1] != '>' {
344					return svgErr("malformed tag <" + name + ">")
345				}
346				i += 2
347				selfClosed = true
348				break
349			}
350			if !sp {
351				return svgErr("attributes must be separated by whitespace in <" + name + ">")
352			}
353			astart := i
354			if nameFirst[s[i]] != 0 {
355				i++
356				for nameRest[s[i]] != 0 {
357					i++
358				}
359			}
360			attr := s[astart:i]
361			if attr == "" {
362				return svgErr("malformed attribute in <" + name + ">")
363			}
364			// A name outside the allowlist (id 0) fails after its value is
365			// read, as in v1, so it can never be a duplicate.
366			id := svgAttrIDs[attr]
367			if id > 0 {
368				if id < 64 {
369					b := uint64(1) << uint(id)
370					if seenLo&b != 0 {
371						return svgErr("duplicate attribute " + attr)
372					}
373					seenLo |= b
374				} else {
375					b := uint64(1) << uint(id-64)
376					if seenHi&b != 0 {
377						return svgErr("duplicate attribute " + attr)
378					}
379					seenHi |= b
380				}
381			}
382			for spaceClass[s[i]] != 0 {
383				i++
384			}
385			if s[i] != '=' {
386				return svgErr("attribute " + attr + " needs a value")
387			}
388			i++
389			for spaceClass[s[i]] != 0 {
390				i++
391			}
392			q := s[i]
393			if q != '"' && q != '\'' {
394				return svgErr("attribute " + attr + " must be quoted")
395			}
396			qk := byte(1)
397			if q == '\'' {
398				qk = 2
399			}
400			i++
401			vstart := i
402			if id == idD || id == idPoints {
403				i = plainRun(s, i)
404			}
405			// mask (J-4) always takes the v1 path, then checkCSSValue
406			slow := id == idMask
407			chk := 0 // 1: url() check, 2: a CSS image function (J-4)
408			for {
409				for valueClass[s[i]] == 0 {
410					i++
411				}
412				k := valueClass[s[i]]
413				if k == qk {
414					break
415				}
416				if k <= 2 { // the other quote
417					i++
418					continue
419				}
420				if k == 3 {
421					if s[i] != '(' {
422						chk |= 1
423					} else if e, p := s[i-1]|0x20, s[i-2]|0x20; ((e == 'e' && (p == 'g' || p == 'd')) ||
424						(e == 't' && (p == 'e' || p == 'n'))) && cssImageFuncBefore(s, vstart, i) {
425						// prefilter: every word ends in "ge", "de", "et" or "nt"
426						// (rotate(, translate(, scale( … never call it)
427						chk |= 2
428					}
429					i++
430					continue
431				}
432				if k == 4 && entityAt(s, i) {
433					i++
434					continue
435				}
436				if k == 5 && !(s[i] == 0xc2 && s[i+1] < 0xa0) { // not a C1 control
437					i++
438					continue
439				}
440				slow = true
441				break
442			}
443			if slow {
444				for i < n && s[i] != q {
445					i++
446				}
447				if i >= n {
448					return svgErr("unterminated value of " + attr)
449				}
450				val := s[vstart:i]
451				i++
452				if err := checkAttr(name, attr, val); err != nil {
453					return err
454				}
455				if err := checkCSSValue(id, attr, val); err != nil {
456					return err
457				}
458				continue
459			}
460			// clean value: checkChars and the ':' '\' '<' rule pass
461			val := s[vstart:i]
462			i++
463			if id == 0 {
464				return svgErr("attribute " + attr + " is not allowed")
465			}
466			if id <= idXlinkHref {
467				if id == idXmlns {
468					return svgErr("xmlns must be " + svgNS) // a clean value holds no ':'
469				}
470				if id == idXmlnsXlink {
471					return svgErr("xmlns:xlink must be " + xlinkNS)
472				}
473				if !isFragment(val) {
474					return svgErr("references must stay inside the document (#id)")
475				}
476				continue
477			}
478			if chk != 0 {
479				if chk&1 != 0 {
480					if err := checkURLRefsLowered(val); err != nil {
481						return err
482					}
483				}
484				if chk&2 != 0 {
485					return svgErr("attribute " + attr + cssImageFuncErr)
486				}
487			}
488		}
489		if first && name != "svg" {
490			return svgErr("the root element must be <svg>")
491		}
492		if selfClosed && depth == 0 {
493			rootDone = true
494		}
495	}
496	if depth != 0 {
497		return svgErr("unclosed element <" + stack[depth-1] + ">")
498	}
499	if !rootDone {
500		return svgErr("no root element")
501	}
502	return nil
503}
504
505// checkAttr is v1's attribute check, unchanged: allowlist, the two xmlns
506// values, characters, ':' '\' '<', href, url().
507func checkAttr(elem, attr, val string) error {
508	if svgAttrIDs[attr] == 0 {
509		return svgErr("attribute " + attr + " is not allowed")
510	}
511	switch attr {
512	case "xmlns":
513		if val != svgNS {
514			return svgErr("xmlns must be " + svgNS)
515		}
516		return nil
517	case "xmlns:xlink":
518		if val != xlinkNS {
519			return svgErr("xmlns:xlink must be " + xlinkNS)
520		}
521		return nil
522	}
523	if err := checkChars(val, false); err != nil {
524		return svgErr("attribute " + attr + ": " + err.Error())
525	}
526	if strings.ContainsAny(val, ":\\<") {
527		return svgErr("attribute " + attr + " contains a forbidden character (':', '\\' or '<')")
528	}
529	if attr == "href" || attr == "xlink:href" {
530		if !isFragment(val) {
531			return svgErr("references must stay inside the document (#id)")
532		}
533		return nil
534	}
535	return checkURLRefs(val)
536}
537
538// checkCSSValue is the J-4 rule (v2 only), run on a value v1's checks
539// passed: no CSS function that takes an image URL as a string (a
540// protocol-relative or path URL needs no ':' and no url(), and browsers
541// fetch it when the SVG is inlined or opened as a document), and mask is
542// exactly "none" or "url(#id)" (the one allowlisted attribute whose CSS
543// property takes an <image>).
544func checkCSSValue(id int, attr, val string) error {
545	for i := 0; i < len(val); i++ {
546		if val[i] == '(' && cssImageFuncBefore(val, 0, i) {
547			return svgErr("attribute " + attr + cssImageFuncErr)
548		}
549	}
550	if id == idMask && val != "none" &&
551		!(len(val) >= 7 && val[:5] == "url(#" && val[len(val)-1] == ')' && isFragment(val[4:len(val)-1])) {
552		return svgErr("mask must be none or url(#id)")
553	}
554	return nil
555}
556
557const cssImageFuncErr = " uses a CSS image function (image, image-set, cross-fade, element)"
558
559// cssImageFuncs are the CSS functions that take an image URL as a string
560// (J-4); with the '(' after them, a value may not contain them.
561var cssImageFuncs = []string{"image", "image-set", "cross-fade", "element"}
562
563// cssImageFuncBefore reports whether s[start:p] (p is a '(') ends with one
564// of cssImageFuncs after Go's strings.ToLower: ASCII letters fold, and the
565// only non-ASCII rune lowering to a letter of these words is U+0130 ('i';
566// U+212A lowers to 'k', which none holds). Every other byte compares exactly.
567func cssImageFuncBefore(s string, start, p int) bool {
568	for _, w := range cssImageFuncs {
569		j := p
570		k := len(w) - 1
571		for ; k >= 0; k-- {
572			c := w[k]
573			if j > start && (s[j-1] == c || (c >= 'a' && c <= 'z' && s[j-1]|0x20 == c)) {
574				j--
575				continue
576			}
577			if c == 'i' && j-1 > start && s[j-2] == 0xc4 && s[j-1] == 0xb0 { // U+0130
578				j -= 2
579				continue
580			}
581			break
582		}
583		if k < 0 {
584			return true
585		}
586	}
587	return false
588}
589
590// checkURLRefs is v1's url() rule: every url( must hold #id.
591func checkURLRefs(val string) error {
592	low := strings.ToLower(val)
593	for {
594		k := strings.Index(low, "url")
595		if k < 0 {
596			return nil
597		}
598		rest := strings.TrimLeft(low[k+3:], " ")
599		if !strings.HasPrefix(rest, "(") {
600			low = low[k+3:]
601			continue
602		}
603		rest = strings.TrimLeft(rest[1:], " ")
604		end := strings.IndexByte(rest, ')')
605		if end < 0 || !isFragment(strings.TrimRight(rest[:end], " ")) {
606			return svgErr("references must stay inside the document (url(#id))")
607		}
608		low = rest[end:]
609	}
610}
611
612// checkURLRefsLowered is checkURLRefs without strings.ToLower: it scans val
613// once and compares case-insensitively. The url() rule only looks at ASCII
614// bytes ("url", '(', ')', ' ', fragment characters); the only non-ASCII
615// runes Go's ToLower maps to ASCII are U+0130 (to 'i') and U+212A (to 'k'),
616// so fragmentLowered accepts their UTF-8 forms as fragment characters.
617// Every other non-ASCII byte fails a match either way. val is valid UTF-8.
618func checkURLRefsLowered(val string) error {
619	n := len(val)
620	p := 0
621	for {
622		k := -1
623		for j := p; j+2 < n; j++ {
624			if val[j]|0x20 == 'u' && val[j+1]|0x20 == 'r' && val[j+2]|0x20 == 'l' {
625				k = j
626				break
627			}
628		}
629		if k < 0 {
630			return nil
631		}
632		r := k + 3
633		for r < n && val[r] == ' ' {
634			r++
635		}
636		if r >= n || val[r] != '(' {
637			p = k + 3
638			continue
639		}
640		r++
641		for r < n && val[r] == ' ' {
642			r++
643		}
644		e := r
645		for e < n && val[e] != ')' {
646			e++
647		}
648		if e >= n {
649			return svgErr("references must stay inside the document (url(#id))")
650		}
651		t := e
652		for t > r && val[t-1] == ' ' {
653			t--
654		}
655		if !fragmentLowered(val[r:t]) {
656			return svgErr("references must stay inside the document (url(#id))")
657		}
658		p = e
659	}
660}
661
662// fragmentLowered is isFragment(strings.ToLower(v)) for valid UTF-8 v.
663func fragmentLowered(v string) bool {
664	if len(v) < 2 || v[0] != '#' {
665		return false
666	}
667	for i := 1; i < len(v); i++ {
668		c := v[i]
669		if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.' {
670			continue
671		}
672		if c == 0xe2 && i+2 < len(v) && v[i+1] == 0x84 && v[i+2] == 0xaa { // U+212A KELVIN SIGN -> 'k'
673			i += 2
674			continue
675		}
676		if c == 0xc4 && i+1 < len(v) && v[i+1] == 0xb0 { // U+0130 -> 'i'
677			i++
678			continue
679		}
680		return false
681	}
682	return true
683}
684
685// checkChars allows printable characters and the five XML entities; text
686// (character data) may also hold whitespace, attribute values only spaces.
687func checkChars(s string, isText bool) error {
688	for i := 0; i < len(s); i++ {
689		c := s[i]
690		switch {
691		case c == '&':
692			ok := false
693			for _, e := range []string{"&amp;", "&lt;", "&gt;", "&quot;", "&apos;"} {
694				if strings.HasPrefix(s[i:], e) {
695					ok = true
696					break
697				}
698			}
699			if !ok {
700				return svgErr("only &amp; &lt; &gt; &quot; &apos; entities are allowed")
701			}
702		case c == 0x7f || (c < 0x20 && !(isText && isSpace(c))):
703			return svgErr("control characters are not allowed")
704		case c == '>' && !isText:
705			return svgErr("'>' in an attribute value")
706		}
707	}
708	for _, r := range s {
709		if r >= 0x80 && r <= 0x9f {
710			return svgErr("control characters are not allowed")
711		}
712	}
713	return nil
714}
715
716func isFragment(v string) bool {
717	if len(v) < 2 || v[0] != '#' {
718		return false
719	}
720	for i := 1; i < len(v); i++ {
721		c := v[i]
722		if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.') {
723			return false
724		}
725	}
726	return true
727}
728
729func isSpace(c byte) bool {
730	return c == ' ' || c == '\t' || c == '\n' || c == '\r'
731}