oficina / estilo Public

Clone
git clone https://amadan.net/oficina/estilo

Plain git — no account needed to clone.

Download

Download this file

1// Package typeface reads what an app needs to know about an uploaded font
2// file before it keeps it: the family and style names, weight, italic,
3// whether it is variable, its outline kind, its embedding flags and a
4// SHA-256 ref. It also says whether the app's own layout and PDF engines
5// may use the face (Pictures) and sets the headers for serving it.
6//
7// It takes TTF, OTF, WOFF and WOFF2 and nothing else. It reads the table
8// directory, the head, name, OS/2 and fvar tables, and the outline
9// structure (outlines.go); bounds-checks every offset against the bytes
10// it has; refuses tables that overlap; and believes no length it has not
11// checked. It has no storage and no routes: the app gives it bytes.
12package typeface
13
14import (
15 "cmp"
16 "crypto/sha256"
17 "encoding/binary"
18 "encoding/hex"
19 "errors"
20 "fmt"
21 "net/http"
22 "slices"
23 "strings"
24 "unicode"
25 "unicode/utf16"
26
27 "golang.org/x/text/encoding/charmap"
28)
29
30// Limits on what a person may keep. Inspect enforces MaxBytes; the other
31// two are for the app that keeps the faces.
32const (
33 MaxBytes = 10 << 20
34 MaxFacesPerFamily = 16
35 MaxFamilies = 32
36)
37
38// maxUnpacked caps how much a WOFF or WOFF2 may unpack to, so a small file
39// that expands enormously is refused rather than unpacked.
40const maxUnpacked = 4 * MaxBytes
41
42// maxNameRunes caps a family or style name. Real ones are a few words.
43const maxNameRunes = 256
44
45// Format is the file's container.
46type Format string
47
48const (
49 TTF Format = "ttf"
50 OTF Format = "otf"
51 WOFF Format = "woff"
52 WOFF2 Format = "woff2"
53)
54
55// Outline is the kind of glyph outlines the face carries.
56type Outline string
57
58const (
59 TrueType Outline = "truetype"
60 CFF Outline = "cff"
61)
62
63// Face is what Inspect learned about one font file.
64type Face struct {
65 Ref string // lowercase hex SHA-256 of the file as given
66 Format Format // the container
67 Outline Outline // TrueType (glyf) or CFF outlines
68 Family string // name ID 16, else 1
69 Style string // name ID 17, else 2
70 Weight int // OS/2 usWeightClass, 1..1000
71 WeightMin int // = Weight unless variable
72 WeightMax int // = Weight unless variable
73 Italic bool // OS/2 fsSelection bit 0 or head macStyle bit 1
74 Variable bool // fvar present (any axis)
75 FSType uint16 // OS/2 fsType, the embedding flags
76}
77
78// The errors Inspect returns wrap one of these, so a caller can tell a
79// file that is not a font it takes from one that is too big from one that
80// is broken.
81var (
82 ErrNotAFont = errors.New("typeface: not a TTF, OTF, WOFF or WOFF2 file")
83 ErrTooBig = errors.New("typeface: font file too big")
84 ErrMalformed = errors.New("typeface: malformed font file")
85)
86
87func malformed(format string, args ...any) error {
88 return fmt.Errorf("%w: "+format, append([]any{ErrMalformed}, args...)...)
89}
90
91// Signatures: the first four bytes of the file, and an sfnt's version.
92const (
93 sigTrueType = 0x00010000
94 sigTrue = 0x74727565 // 'true', Apple's TrueType
95 sigOTTO = 0x4F54544F // 'OTTO', CFF outlines
96 sigTTCF = 0x74746366 // 'ttcf', a collection
97 sigWOFF = 0x774F4646 // 'wOFF'
98 sigWOFF2 = 0x774F4632 // 'wOF2'
99)
100
101// fontTables is an sfnt after unwrapping: its version, the tags it has,
102// and the bytes of the tables Inspect reads.
103type fontTables struct {
104 version uint32
105 has map[string]bool
106 data map[string][]byte
107 transformed map[string]bool // a WOFF2's transformed glyf, loca or hmtx
108}
109
110// wanted are the only tables whose bytes Inspect reads: the ones it
111// describes the face from, and the ones checkOutlines reads.
112func wanted(tag string) bool {
113 switch tag {
114 case "head", "name", "OS/2", "fvar",
115 "maxp", "hhea", "hmtx", "glyf", "loca", "CFF ", "CFF2":
116 return true
117 }
118 return false
119}
120
121// Inspect reads a font file. It refuses anything over MaxBytes
122// (ErrTooBig), anything that is not TTF, OTF, WOFF or WOFF2 (ErrNotAFont)
123// and anything it cannot read in full (ErrMalformed).
124func Inspect(data []byte) (Face, error) {
125 if len(data) > MaxBytes {
126 return Face{}, fmt.Errorf("%w: %d bytes, the limit is %d", ErrTooBig, len(data), MaxBytes)
127 }
128 if len(data) < 4 {
129 return Face{}, ErrNotAFont
130 }
131 var (
132 format Format
133 ft fontTables
134 err error
135 )
136 switch binary.BigEndian.Uint32(data) {
137 case sigTrueType, sigTrue:
138 format = TTF
139 ft, err = readSFNT(data)
140 case sigOTTO:
141 format = OTF
142 ft, err = readSFNT(data)
143 case sigWOFF:
144 format = WOFF
145 ft, err = readWOFF(data)
146 case sigWOFF2:
147 format = WOFF2
148 ft, err = readWOFF2(data)
149 case sigTTCF:
150 return Face{}, fmt.Errorf("%w: font collections are not taken", ErrNotAFont)
151 default:
152 return Face{}, ErrNotAFont
153 }
154 if err != nil {
155 return Face{}, err
156 }
157 f, err := describe(ft)
158 if err != nil {
159 return Face{}, err
160 }
161 sum := sha256.Sum256(data)
162 f.Ref = hex.EncodeToString(sum[:])
163 f.Format = format
164 return f, nil
165}
166
167// checkFlavor refuses a WOFF or WOFF2 wrapping something other than a
168// single TrueType or CFF sfnt.
169func checkFlavor(flavor uint32) error {
170 switch flavor {
171 case sigTrueType, sigTrue, sigOTTO:
172 return nil
173 case sigTTCF:
174 return fmt.Errorf("%w: font collections are not taken", ErrNotAFont)
175 }
176 return malformed("unknown flavor %#08x", flavor)
177}
178
179// readSFNT reads a bare sfnt's table directory. Every table, read or not,
180// must lie inside the file, and no tag may appear twice.
181func readSFNT(data []byte) (fontTables, error) {
182 if len(data) < 12 {
183 return fontTables{}, malformed("sfnt header cut short")
184 }
185 n := int(binary.BigEndian.Uint16(data[4:]))
186 if n == 0 {
187 return fontTables{}, malformed("no tables")
188 }
189 if 12+16*n > len(data) {
190 return fontTables{}, malformed("table directory cut short: %d tables", n)
191 }
192 ft := fontTables{version: binary.BigEndian.Uint32(data), has: map[string]bool{}, data: map[string][]byte{}}
193 spans := make([]span, 0, n)
194 for i := 0; i < n; i++ {
195 rec := data[12+16*i:]
196 tag := string(rec[:4])
197 off := uint64(binary.BigEndian.Uint32(rec[8:]))
198 length := uint64(binary.BigEndian.Uint32(rec[12:]))
199 if off+length > uint64(len(data)) {
200 return fontTables{}, malformed("table %q runs past the end of the file", tag)
201 }
202 if ft.has[tag] {
203 return fontTables{}, malformed("table %q appears twice", tag)
204 }
205 ft.has[tag] = true
206 spans = append(spans, span{tag, off, length})
207 if wanted(tag) {
208 ft.data[tag] = data[off : off+length]
209 }
210 }
211 if err := disjoint(spans, uint64(12+16*n), uint64(len(data))); err != nil {
212 return fontTables{}, err
213 }
214 return ft, nil
215}
216
217// span is where one table's bytes lie in a file.
218type span struct {
219 tag string
220 off, length uint64
221}
222
223// disjoint refuses tables whose bytes overlap one another or the header
224// and directory before them (the first `header` bytes), and tables whose
225// lengths sum past the file's size. Each table is in bounds already; this
226// is what stops a reader that copies every table from copying the same
227// bytes once per table that names them.
228func disjoint(spans []span, header, size uint64) error {
229 var sum uint64
230 for _, s := range spans {
231 if sum += s.length; sum > size {
232 return malformed("tables sum to more than the file's %d bytes", size)
233 }
234 }
235 sorted := slices.Clone(spans)
236 slices.SortFunc(sorted, func(a, b span) int {
237 return cmp.Or(cmp.Compare(a.off, b.off), cmp.Compare(a.length, b.length))
238 })
239 end, last := header, ""
240 for _, s := range sorted {
241 if s.length == 0 {
242 continue
243 }
244 if s.off < end {
245 if last == "" {
246 return malformed("table %q overlaps the table directory", s.tag)
247 }
248 return malformed("tables %q and %q overlap", last, s.tag)
249 }
250 end, last = s.off+s.length, s.tag
251 }
252 return nil
253}
254
255// describe turns the tables into a Face (all but Ref and Format).
256func describe(ft fontTables) (Face, error) {
257 var f Face
258 // Outlines must be there, and pass checkOutlines once head is read.
259 if ft.version == sigOTTO {
260 if !ft.has["CFF "] && !ft.has["CFF2"] {
261 return Face{}, malformed("OTTO with no CFF or CFF2 table")
262 }
263 f.Outline = CFF
264 } else {
265 if !ft.has["glyf"] || !ft.has["loca"] {
266 return Face{}, malformed("TrueType with no glyf or loca table")
267 }
268 f.Outline = TrueType
269 }
270
271 head, ok := ft.data["head"]
272 if !ok {
273 return Face{}, malformed("no head table")
274 }
275 if len(head) < 54 || binary.BigEndian.Uint32(head[12:]) != 0x5F0F3CF5 {
276 return Face{}, malformed("head table is not one")
277 }
278 macStyle := binary.BigEndian.Uint16(head[44:])
279 if err := checkOutlines(ft, f.Outline); err != nil {
280 return Face{}, err
281 }
282
283 os2, ok := ft.data["OS/2"]
284 if !ok {
285 return Face{}, malformed("no OS/2 table")
286 }
287 if len(os2) < 64 {
288 return Face{}, malformed("OS/2 table cut short")
289 }
290 f.Weight = clampWeight(int(binary.BigEndian.Uint16(os2[4:])))
291 if f.Weight == 0 {
292 f.Weight = 400 // unset: the weight a browser assumes
293 }
294 f.FSType = binary.BigEndian.Uint16(os2[8:])
295 fsSelection := binary.BigEndian.Uint16(os2[62:])
296 f.Italic = fsSelection&0x0001 != 0 || macStyle&0x0002 != 0
297 f.WeightMin, f.WeightMax = f.Weight, f.Weight
298
299 name, ok := ft.data["name"]
300 if !ok {
301 return Face{}, malformed("no name table")
302 }
303 names, err := readNames(name)
304 if err != nil {
305 return Face{}, err
306 }
307 f.Family = firstOf(names, 16, 1)
308 f.Style = firstOf(names, 17, 2)
309 if f.Family == "" {
310 return Face{}, malformed("no family name")
311 }
312
313 // Any fvar makes the face variable; only a wght axis widens its
314 // weight range.
315 if fv, ok := ft.data["fvar"]; ok {
316 f.Variable = true
317 lo, hi, hasWght, err := weightAxis(fv)
318 if err != nil {
319 return Face{}, err
320 }
321 if hasWght {
322 f.WeightMin, f.WeightMax = lo, hi
323 }
324 }
325 return f, nil
326}
327
328// clampWeight keeps a weight within CSS's 1..1000, leaving 0 for unset.
329func clampWeight(w int) int {
330 return min(max(w, 0), 1000)
331}
332
333// weightAxis reads fvar and returns the 'wght' axis's range, if it has one.
334func weightAxis(fv []byte) (lo, hi int, ok bool, err error) {
335 if len(fv) < 16 {
336 return 0, 0, false, malformed("fvar header cut short")
337 }
338 axesAt := int(binary.BigEndian.Uint16(fv[4:]))
339 count := int(binary.BigEndian.Uint16(fv[8:]))
340 size := int(binary.BigEndian.Uint16(fv[10:]))
341 if size < 20 {
342 return 0, 0, false, malformed("fvar axis records of %d bytes", size)
343 }
344 if axesAt+count*size > len(fv) {
345 return 0, 0, false, malformed("fvar axes run past the table")
346 }
347 for i := 0; i < count; i++ {
348 a := fv[axesAt+i*size:]
349 if string(a[:4]) != "wght" {
350 continue
351 }
352 minV := fixed(binary.BigEndian.Uint32(a[4:]))
353 maxV := fixed(binary.BigEndian.Uint32(a[12:]))
354 lo, hi = max(clampWeight(minV), 1), max(clampWeight(maxV), 1)
355 if lo > hi {
356 return 0, 0, false, malformed("wght axis runs from %d down to %d", lo, hi)
357 }
358 return lo, hi, true, nil
359 }
360 return 0, 0, false, nil
361}
362
363// fixed rounds a 16.16 fixed-point number to the nearest integer.
364func fixed(v uint32) int {
365 return int((int64(int32(v)) + 0x8000) >> 16)
366}
367
368// nameKey is a name record's identity: which name, on which platform,
369// encoding and language.
370type nameKey struct{ platform, encoding, language, id uint16 }
371
372// readNames decodes the name records Inspect can use: platform 3
373// (Windows) and platform 0 (Unicode) in UTF-16BE, platform 1 (Mac) in
374// Mac Roman. Other records are skipped; every record must still lie
375// inside the table.
376func readNames(t []byte) (map[nameKey]string, error) {
377 if len(t) < 6 {
378 return nil, malformed("name table cut short")
379 }
380 count := int(binary.BigEndian.Uint16(t[2:]))
381 storage := int(binary.BigEndian.Uint16(t[4:]))
382 if 6+12*count > len(t) {
383 return nil, malformed("name records run past the table")
384 }
385 out := map[nameKey]string{}
386 for i := 0; i < count; i++ {
387 r := t[6+12*i:]
388 k := nameKey{
389 platform: binary.BigEndian.Uint16(r[0:]),
390 encoding: binary.BigEndian.Uint16(r[2:]),
391 language: binary.BigEndian.Uint16(r[4:]),
392 id: binary.BigEndian.Uint16(r[6:]),
393 }
394 length := int(binary.BigEndian.Uint16(r[8:]))
395 off := storage + int(binary.BigEndian.Uint16(r[10:]))
396 if off+length > len(t) {
397 return nil, malformed("name record %d runs past the table", i)
398 }
399 if k.id != 1 && k.id != 2 && k.id != 16 && k.id != 17 {
400 continue
401 }
402 raw := t[off : off+length]
403 var s string
404 switch {
405 case k.platform == 3 && (k.encoding == 0 || k.encoding == 1 || k.encoding == 10),
406 k.platform == 0:
407 s = utf16BE(raw)
408 case k.platform == 1 && k.encoding == 0:
409 b, err := charmap.Macintosh.NewDecoder().Bytes(raw)
410 if err != nil {
411 continue
412 }
413 s = string(b)
414 default:
415 continue
416 }
417 s = clean(s)
418 if len([]rune(s)) > maxNameRunes {
419 return nil, malformed("name %d is longer than %d characters", k.id, maxNameRunes)
420 }
421 out[k] = s
422 }
423 return out, nil
424}
425
426func utf16BE(b []byte) string {
427 u := make([]uint16, len(b)/2)
428 for i := range u {
429 u[i] = binary.BigEndian.Uint16(b[2*i:])
430 }
431 return string(utf16.Decode(u))
432}
433
434// clean drops control characters and surrounding space.
435func clean(s string) string {
436 s = strings.Map(func(r rune) rune {
437 if unicode.IsControl(r) {
438 return -1
439 }
440 return r
441 }, s)
442 return strings.TrimSpace(s)
443}
444
445// firstOf returns the best non-empty name among ids, tried in order. For
446// one id the platforms go Windows, then Mac, then Unicode; English (US
447// on Windows, language 0 on Mac) before any other language.
448func firstOf(names map[nameKey]string, ids ...uint16) string {
449 for _, id := range ids {
450 best, rank := "", 0
451 for k, s := range names {
452 if k.id != id || s == "" {
453 continue
454 }
455 r := nameRank(k)
456 // Ties between other languages go to the lowest key, so the
457 // answer does not depend on map order.
458 if r > rank || (r == rank && rank > 0 && s < best) {
459 best, rank = s, r
460 }
461 }
462 if best != "" {
463 return best
464 }
465 }
466 return ""
467}
468
469func nameRank(k nameKey) int {
470 switch {
471 case k.platform == 3 && k.language == 0x0409:
472 return 6
473 case k.platform == 3:
474 return 5
475 case k.platform == 1 && k.language == 0:
476 return 4
477 case k.platform == 1:
478 return 3
479 case k.platform == 0:
480 return 2
481 }
482 return 1
483}
484
485// Pictures reports whether the app's own layout and PDF engines may use
486// the face: a static, TrueType-outline, bare sfnt (not WOFF or WOFF2)
487// whose fsType allows embedding a subset of it. fsType 0 (installable),
488// 0x0004 (preview and print) and 0x0008 (editable) allow it; the
489// restricted-licence bit (0x0002), no-subsetting (0x0100, since the PDF
490// embeds subsets) and bitmap-only (0x0200) do not, even alongside a less
491// restrictive bit.
492func (f Face) Pictures() bool {
493 return !f.Variable &&
494 f.Outline == TrueType &&
495 (f.Format == TTF || f.Format == OTF) &&
496 f.FSType&0x0002 == 0 &&
497 f.FSType&0x0100 == 0 &&
498 f.FSType&0x0200 == 0
499}
500
501// ContentType is the face's media type.
502func (f Face) ContentType() string {
503 return contentType(f.Format)
504}
505
506func contentType(f Format) string {
507 switch f {
508 case TTF:
509 return "font/ttf"
510 case OTF:
511 return "font/otf"
512 case WOFF:
513 return "font/woff"
514 case WOFF2:
515 return "font/woff2"
516 }
517 return "application/octet-stream"
518}
519
520// Headers sets the headers for serving a font file by its ref: its media
521// type, no sniffing, a year's immutable caching in the browser only (the
522// ref is the file's hash, so its bytes never change; private, because a
523// person's fonts are theirs and shared caches should not keep them) and a
524// policy that lets it load nothing.
525func Headers(w http.ResponseWriter, f Format) {
526 h := w.Header()
527 h.Set("Content-Type", contentType(f))
528 h.Set("X-Content-Type-Options", "nosniff")
529 h.Set("Cache-Control", "private, max-age=31536000, immutable")
530 h.Set("Content-Security-Policy", "default-src 'none'")
531}
532