// Package typeface reads what an app needs to know about an uploaded font // file before it keeps it: the family and style names, weight, italic, // whether it is variable, its outline kind, its embedding flags and a // SHA-256 ref. It also says whether the app's own layout and PDF engines // may use the face (Pictures) and sets the headers for serving it. // // It takes TTF, OTF, WOFF and WOFF2 and nothing else. It reads the table // directory, the head, name, OS/2 and fvar tables, and the outline // structure (outlines.go); bounds-checks every offset against the bytes // it has; refuses tables that overlap; and believes no length it has not // checked. It has no storage and no routes: the app gives it bytes. package typeface import ( "cmp" "crypto/sha256" "encoding/binary" "encoding/hex" "errors" "fmt" "net/http" "slices" "strings" "unicode" "unicode/utf16" "golang.org/x/text/encoding/charmap" ) // Limits on what a person may keep. Inspect enforces MaxBytes; the other // two are for the app that keeps the faces. const ( MaxBytes = 10 << 20 MaxFacesPerFamily = 16 MaxFamilies = 32 ) // maxUnpacked caps how much a WOFF or WOFF2 may unpack to, so a small file // that expands enormously is refused rather than unpacked. const maxUnpacked = 4 * MaxBytes // maxNameRunes caps a family or style name. Real ones are a few words. const maxNameRunes = 256 // Format is the file's container. type Format string const ( TTF Format = "ttf" OTF Format = "otf" WOFF Format = "woff" WOFF2 Format = "woff2" ) // Outline is the kind of glyph outlines the face carries. type Outline string const ( TrueType Outline = "truetype" CFF Outline = "cff" ) // Face is what Inspect learned about one font file. type Face struct { Ref string // lowercase hex SHA-256 of the file as given Format Format // the container Outline Outline // TrueType (glyf) or CFF outlines Family string // name ID 16, else 1 Style string // name ID 17, else 2 Weight int // OS/2 usWeightClass, 1..1000 WeightMin int // = Weight unless variable WeightMax int // = Weight unless variable Italic bool // OS/2 fsSelection bit 0 or head macStyle bit 1 Variable bool // fvar present (any axis) FSType uint16 // OS/2 fsType, the embedding flags } // The errors Inspect returns wrap one of these, so a caller can tell a // file that is not a font it takes from one that is too big from one that // is broken. var ( ErrNotAFont = errors.New("typeface: not a TTF, OTF, WOFF or WOFF2 file") ErrTooBig = errors.New("typeface: font file too big") ErrMalformed = errors.New("typeface: malformed font file") ) func malformed(format string, args ...any) error { return fmt.Errorf("%w: "+format, append([]any{ErrMalformed}, args...)...) } // Signatures: the first four bytes of the file, and an sfnt's version. const ( sigTrueType = 0x00010000 sigTrue = 0x74727565 // 'true', Apple's TrueType sigOTTO = 0x4F54544F // 'OTTO', CFF outlines sigTTCF = 0x74746366 // 'ttcf', a collection sigWOFF = 0x774F4646 // 'wOFF' sigWOFF2 = 0x774F4632 // 'wOF2' ) // fontTables is an sfnt after unwrapping: its version, the tags it has, // and the bytes of the tables Inspect reads. type fontTables struct { version uint32 has map[string]bool data map[string][]byte transformed map[string]bool // a WOFF2's transformed glyf, loca or hmtx } // wanted are the only tables whose bytes Inspect reads: the ones it // describes the face from, and the ones checkOutlines reads. func wanted(tag string) bool { switch tag { case "head", "name", "OS/2", "fvar", "maxp", "hhea", "hmtx", "glyf", "loca", "CFF ", "CFF2": return true } return false } // Inspect reads a font file. It refuses anything over MaxBytes // (ErrTooBig), anything that is not TTF, OTF, WOFF or WOFF2 (ErrNotAFont) // and anything it cannot read in full (ErrMalformed). func Inspect(data []byte) (Face, error) { if len(data) > MaxBytes { return Face{}, fmt.Errorf("%w: %d bytes, the limit is %d", ErrTooBig, len(data), MaxBytes) } if len(data) < 4 { return Face{}, ErrNotAFont } var ( format Format ft fontTables err error ) switch binary.BigEndian.Uint32(data) { case sigTrueType, sigTrue: format = TTF ft, err = readSFNT(data) case sigOTTO: format = OTF ft, err = readSFNT(data) case sigWOFF: format = WOFF ft, err = readWOFF(data) case sigWOFF2: format = WOFF2 ft, err = readWOFF2(data) case sigTTCF: return Face{}, fmt.Errorf("%w: font collections are not taken", ErrNotAFont) default: return Face{}, ErrNotAFont } if err != nil { return Face{}, err } f, err := describe(ft) if err != nil { return Face{}, err } sum := sha256.Sum256(data) f.Ref = hex.EncodeToString(sum[:]) f.Format = format return f, nil } // checkFlavor refuses a WOFF or WOFF2 wrapping something other than a // single TrueType or CFF sfnt. func checkFlavor(flavor uint32) error { switch flavor { case sigTrueType, sigTrue, sigOTTO: return nil case sigTTCF: return fmt.Errorf("%w: font collections are not taken", ErrNotAFont) } return malformed("unknown flavor %#08x", flavor) } // readSFNT reads a bare sfnt's table directory. Every table, read or not, // must lie inside the file, and no tag may appear twice. func readSFNT(data []byte) (fontTables, error) { if len(data) < 12 { return fontTables{}, malformed("sfnt header cut short") } n := int(binary.BigEndian.Uint16(data[4:])) if n == 0 { return fontTables{}, malformed("no tables") } if 12+16*n > len(data) { return fontTables{}, malformed("table directory cut short: %d tables", n) } ft := fontTables{version: binary.BigEndian.Uint32(data), has: map[string]bool{}, data: map[string][]byte{}} spans := make([]span, 0, n) for i := 0; i < n; i++ { rec := data[12+16*i:] tag := string(rec[:4]) off := uint64(binary.BigEndian.Uint32(rec[8:])) length := uint64(binary.BigEndian.Uint32(rec[12:])) if off+length > uint64(len(data)) { return fontTables{}, malformed("table %q runs past the end of the file", tag) } if ft.has[tag] { return fontTables{}, malformed("table %q appears twice", tag) } ft.has[tag] = true spans = append(spans, span{tag, off, length}) if wanted(tag) { ft.data[tag] = data[off : off+length] } } if err := disjoint(spans, uint64(12+16*n), uint64(len(data))); err != nil { return fontTables{}, err } return ft, nil } // span is where one table's bytes lie in a file. type span struct { tag string off, length uint64 } // disjoint refuses tables whose bytes overlap one another or the header // and directory before them (the first `header` bytes), and tables whose // lengths sum past the file's size. Each table is in bounds already; this // is what stops a reader that copies every table from copying the same // bytes once per table that names them. func disjoint(spans []span, header, size uint64) error { var sum uint64 for _, s := range spans { if sum += s.length; sum > size { return malformed("tables sum to more than the file's %d bytes", size) } } sorted := slices.Clone(spans) slices.SortFunc(sorted, func(a, b span) int { return cmp.Or(cmp.Compare(a.off, b.off), cmp.Compare(a.length, b.length)) }) end, last := header, "" for _, s := range sorted { if s.length == 0 { continue } if s.off < end { if last == "" { return malformed("table %q overlaps the table directory", s.tag) } return malformed("tables %q and %q overlap", last, s.tag) } end, last = s.off+s.length, s.tag } return nil } // describe turns the tables into a Face (all but Ref and Format). func describe(ft fontTables) (Face, error) { var f Face // Outlines must be there, and pass checkOutlines once head is read. if ft.version == sigOTTO { if !ft.has["CFF "] && !ft.has["CFF2"] { return Face{}, malformed("OTTO with no CFF or CFF2 table") } f.Outline = CFF } else { if !ft.has["glyf"] || !ft.has["loca"] { return Face{}, malformed("TrueType with no glyf or loca table") } f.Outline = TrueType } head, ok := ft.data["head"] if !ok { return Face{}, malformed("no head table") } if len(head) < 54 || binary.BigEndian.Uint32(head[12:]) != 0x5F0F3CF5 { return Face{}, malformed("head table is not one") } macStyle := binary.BigEndian.Uint16(head[44:]) if err := checkOutlines(ft, f.Outline); err != nil { return Face{}, err } os2, ok := ft.data["OS/2"] if !ok { return Face{}, malformed("no OS/2 table") } if len(os2) < 64 { return Face{}, malformed("OS/2 table cut short") } f.Weight = clampWeight(int(binary.BigEndian.Uint16(os2[4:]))) if f.Weight == 0 { f.Weight = 400 // unset: the weight a browser assumes } f.FSType = binary.BigEndian.Uint16(os2[8:]) fsSelection := binary.BigEndian.Uint16(os2[62:]) f.Italic = fsSelection&0x0001 != 0 || macStyle&0x0002 != 0 f.WeightMin, f.WeightMax = f.Weight, f.Weight name, ok := ft.data["name"] if !ok { return Face{}, malformed("no name table") } names, err := readNames(name) if err != nil { return Face{}, err } f.Family = firstOf(names, 16, 1) f.Style = firstOf(names, 17, 2) if f.Family == "" { return Face{}, malformed("no family name") } // Any fvar makes the face variable; only a wght axis widens its // weight range. if fv, ok := ft.data["fvar"]; ok { f.Variable = true lo, hi, hasWght, err := weightAxis(fv) if err != nil { return Face{}, err } if hasWght { f.WeightMin, f.WeightMax = lo, hi } } return f, nil } // clampWeight keeps a weight within CSS's 1..1000, leaving 0 for unset. func clampWeight(w int) int { return min(max(w, 0), 1000) } // weightAxis reads fvar and returns the 'wght' axis's range, if it has one. func weightAxis(fv []byte) (lo, hi int, ok bool, err error) { if len(fv) < 16 { return 0, 0, false, malformed("fvar header cut short") } axesAt := int(binary.BigEndian.Uint16(fv[4:])) count := int(binary.BigEndian.Uint16(fv[8:])) size := int(binary.BigEndian.Uint16(fv[10:])) if size < 20 { return 0, 0, false, malformed("fvar axis records of %d bytes", size) } if axesAt+count*size > len(fv) { return 0, 0, false, malformed("fvar axes run past the table") } for i := 0; i < count; i++ { a := fv[axesAt+i*size:] if string(a[:4]) != "wght" { continue } minV := fixed(binary.BigEndian.Uint32(a[4:])) maxV := fixed(binary.BigEndian.Uint32(a[12:])) lo, hi = max(clampWeight(minV), 1), max(clampWeight(maxV), 1) if lo > hi { return 0, 0, false, malformed("wght axis runs from %d down to %d", lo, hi) } return lo, hi, true, nil } return 0, 0, false, nil } // fixed rounds a 16.16 fixed-point number to the nearest integer. func fixed(v uint32) int { return int((int64(int32(v)) + 0x8000) >> 16) } // nameKey is a name record's identity: which name, on which platform, // encoding and language. type nameKey struct{ platform, encoding, language, id uint16 } // readNames decodes the name records Inspect can use: platform 3 // (Windows) and platform 0 (Unicode) in UTF-16BE, platform 1 (Mac) in // Mac Roman. Other records are skipped; every record must still lie // inside the table. func readNames(t []byte) (map[nameKey]string, error) { if len(t) < 6 { return nil, malformed("name table cut short") } count := int(binary.BigEndian.Uint16(t[2:])) storage := int(binary.BigEndian.Uint16(t[4:])) if 6+12*count > len(t) { return nil, malformed("name records run past the table") } out := map[nameKey]string{} for i := 0; i < count; i++ { r := t[6+12*i:] k := nameKey{ platform: binary.BigEndian.Uint16(r[0:]), encoding: binary.BigEndian.Uint16(r[2:]), language: binary.BigEndian.Uint16(r[4:]), id: binary.BigEndian.Uint16(r[6:]), } length := int(binary.BigEndian.Uint16(r[8:])) off := storage + int(binary.BigEndian.Uint16(r[10:])) if off+length > len(t) { return nil, malformed("name record %d runs past the table", i) } if k.id != 1 && k.id != 2 && k.id != 16 && k.id != 17 { continue } raw := t[off : off+length] var s string switch { case k.platform == 3 && (k.encoding == 0 || k.encoding == 1 || k.encoding == 10), k.platform == 0: s = utf16BE(raw) case k.platform == 1 && k.encoding == 0: b, err := charmap.Macintosh.NewDecoder().Bytes(raw) if err != nil { continue } s = string(b) default: continue } s = clean(s) if len([]rune(s)) > maxNameRunes { return nil, malformed("name %d is longer than %d characters", k.id, maxNameRunes) } out[k] = s } return out, nil } func utf16BE(b []byte) string { u := make([]uint16, len(b)/2) for i := range u { u[i] = binary.BigEndian.Uint16(b[2*i:]) } return string(utf16.Decode(u)) } // clean drops control characters and surrounding space. func clean(s string) string { s = strings.Map(func(r rune) rune { if unicode.IsControl(r) { return -1 } return r }, s) return strings.TrimSpace(s) } // firstOf returns the best non-empty name among ids, tried in order. For // one id the platforms go Windows, then Mac, then Unicode; English (US // on Windows, language 0 on Mac) before any other language. func firstOf(names map[nameKey]string, ids ...uint16) string { for _, id := range ids { best, rank := "", 0 for k, s := range names { if k.id != id || s == "" { continue } r := nameRank(k) // Ties between other languages go to the lowest key, so the // answer does not depend on map order. if r > rank || (r == rank && rank > 0 && s < best) { best, rank = s, r } } if best != "" { return best } } return "" } func nameRank(k nameKey) int { switch { case k.platform == 3 && k.language == 0x0409: return 6 case k.platform == 3: return 5 case k.platform == 1 && k.language == 0: return 4 case k.platform == 1: return 3 case k.platform == 0: return 2 } return 1 } // Pictures reports whether the app's own layout and PDF engines may use // the face: a static, TrueType-outline, bare sfnt (not WOFF or WOFF2) // whose fsType allows embedding a subset of it. fsType 0 (installable), // 0x0004 (preview and print) and 0x0008 (editable) allow it; the // restricted-licence bit (0x0002), no-subsetting (0x0100, since the PDF // embeds subsets) and bitmap-only (0x0200) do not, even alongside a less // restrictive bit. func (f Face) Pictures() bool { return !f.Variable && f.Outline == TrueType && (f.Format == TTF || f.Format == OTF) && f.FSType&0x0002 == 0 && f.FSType&0x0100 == 0 && f.FSType&0x0200 == 0 } // ContentType is the face's media type. func (f Face) ContentType() string { return contentType(f.Format) } func contentType(f Format) string { switch f { case TTF: return "font/ttf" case OTF: return "font/otf" case WOFF: return "font/woff" case WOFF2: return "font/woff2" } return "application/octet-stream" } // Headers sets the headers for serving a font file by its ref: its media // type, no sniffing, a year's immutable caching in the browser only (the // ref is the file's hash, so its bytes never change; private, because a // person's fonts are theirs and shared caches should not keep them) and a // policy that lets it load nothing. func Headers(w http.ResponseWriter, f Format) { h := w.Header() h.Set("Content-Type", contentType(f)) h.Set("X-Content-Type-Options", "nosniff") h.Set("Cache-Control", "private, max-age=31536000, immutable") h.Set("Content-Security-Policy", "default-src 'none'") }