typeface: inspect uploaded TTF, OTF, WOFF and WOFF2 font files
Inspect returns names, weight, style, variability, outline kind and embedding flags, refusing malformed, overlapping or oversize files; Pictures says whether a face may be subset into a PDF; Headers serves fonts privately with a deny-all CSP. Used first by Slides. Squashed from feat/typeface into main (discussion 42). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from feat/typeface into main.
10 files changed,
+2,210
−0
go.mod+1 −0go.sum+4 −0typeface/bounds_test.go+111 −0typeface/outlines.go+313 −0typeface/outlines_test.go+267 −0typeface/testdata/LICENSE-OFL-1.1.txt+91 −0typeface/testdata/LiberationSans-Regular.ttfbinarytypeface/typeface.go+531 −0typeface/typeface_test.go+628 −0typeface/woff.go+264 −0
CI passed — run details
CI log
=== modcache === all modules verified === vet === CGO_ENABLED=0 go vet ./... go: downloading github.com/andybalholm/brotli v1.2.7 CGO_ENABLED=0 go vet -tags browser ./... === fmt === === build === CGO_ENABLED=0 go build -buildvcs=false ./... === go-test === CGO_ENABLED=0 go test -count=1 ./... ok amadan.net/oficina/estilo.git/base 0.004s ok amadan.net/oficina/estilo.git/brand 0.003s ok amadan.net/oficina/estilo.git/busy 0.009s ok amadan.net/oficina/estilo.git/callui 0.004s ok amadan.net/oficina/estilo.git/chrome 4.916s ? amadan.net/oficina/estilo.git/cmd/oficina-notices [no test files] ok amadan.net/oficina/estilo.git/colophon 0.022s ok amadan.net/oficina/estilo.git/credits 0.005s ok amadan.net/oficina/estilo.git/credits/catalog 0.004s ok amadan.net/oficina/estilo.git/desk 0.004s ok amadan.net/oficina/estilo.git/googleimport 3.332s ok amadan.net/oficina/estilo.git/homeconnect 0.004s ok amadan.net/oficina/estilo.git/internal/lint 0.006s ? amadan.net/oficina/estilo.git/internal/tokencheck [no test files] ok amadan.net/oficina/estilo.git/menu 0.010s ok amadan.net/oficina/estilo.git/savestatus 0.112s ok amadan.net/oficina/estilo.git/side 0.135s ok amadan.net/oficina/estilo.git/sky 0.032s ok amadan.net/oficina/estilo.git/theme 0.013s ok amadan.net/oficina/estilo.git/typeface 0.322s === spacing === go run amadan.net/rastrillo/fiesta/cmd/fiesta@v1.7.0 spacing .
diff --git a/go.mod b/go.mod| index 9af7908..cb195d4 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -3,6 +3,7 @@ module amadan.net/oficina/estilo.git |
| go 1.25.0 |
| require ( |
| + github.com/andybalholm/brotli v1.2.7 |
| github.com/carlosframework/rastrillo v0.23.0 |
| golang.org/x/text v0.20.0 |
| ) |
diff --git a/go.sum b/go.sum| index be1533c..02e6bbf 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,3 +1,5 @@ |
| +github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A= |
| +github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= |
| github.com/carlosframework/rastrillo v0.23.0 h1:tKAAlwPt4Pg/rkqk7o6jvV12bbZ0r34oEVpuOlKfX7w= |
| github.com/carlosframework/rastrillo v0.23.0/go.mod h1:pZlrE5F5OhspvZFzef0DrfjHAjA8FXycb9J5/8vc8Tw= |
| github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 h1:UQ4AU+BGti3Sy/aLU8KVseYKNALcX9UXY6DfpwQ6J8E= |
| @@ -38,6 +40,8 @@ github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOF |
| github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= |
| +github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= |
| +github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= |
| golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= |
| golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= |
| golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= |
diff --git a/typeface/bounds_test.go b/typeface/bounds_test.go| new file mode 100644 |
| index 0000000..f304e86 |
| --- /dev/null |
| +++ b/typeface/bounds_test.go |
| @@ -0,0 +1,111 @@ |
| +package typeface |
| + |
| +import ( |
| + "bytes" |
| + "encoding/binary" |
| + "errors" |
| + "fmt" |
| + "testing" |
| +) |
| + |
| +// An sfnt whose directory points several tables at the same bytes passes |
| +// a per-table bounds check, yet a reader that copies each table (an |
| +// app renaming the font for its PDF, say) copies those bytes once per |
| +// table: a 10 MiB file became 4.8 GB to copy (final review, C1). Tables |
| +// may not overlap, nor sum past the file. |
| + |
| +// pointedAt is data with the directory entries of the given tags set to |
| +// the offset and length of the table at. |
| +func pointedAt(t *testing.T, data []byte, at string, tags ...string) []byte { |
| + t.Helper() |
| + out := bytes.Clone(data) |
| + n := int(binary.BigEndian.Uint16(out[4:])) |
| + var off, length uint32 |
| + found := false |
| + for i := 0; i < n; i++ { |
| + rec := out[12+16*i:] |
| + if string(rec[:4]) == at { |
| + off, length, found = binary.BigEndian.Uint32(rec[8:]), binary.BigEndian.Uint32(rec[12:]), true |
| + } |
| + } |
| + if !found { |
| + t.Fatalf("no %q table", at) |
| + } |
| + for i := 0; i < n; i++ { |
| + rec := out[12+16*i:] |
| + for _, tag := range tags { |
| + if string(rec[:4]) == tag { |
| + binary.BigEndian.PutUint32(rec[8:], off) |
| + binary.BigEndian.PutUint32(rec[12:], length) |
| + } |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// withFillers is Liberation plus n small tables named z000, z001, ... |
| +func withFillers(t *testing.T, n int) ([]byte, []string) { |
| + t.Helper() |
| + v, ts := tablesOf(t, liberation(t)) |
| + var tags []string |
| + for i := 0; i < n; i++ { |
| + tag := fmt.Sprintf("z%03d", i) |
| + tags = append(tags, tag) |
| + ts = append(ts, table{tag, []byte{0, 0, 0, 0}}) |
| + } |
| + return buildSFNT(v, ts), tags |
| +} |
| + |
| +func TestInspectRefusesTablesThatShareBytes(t *testing.T) { |
| + // One table over another: the sum still fits the file. |
| + two := pointedAt(t, liberation(t), "hhea", "gasp") |
| + |
| + // A hundred tables over glyf, the amplification itself. |
| + many, tags := withFillers(t, 100) |
| + many = pointedAt(t, many, "glyf", tags...) |
| + |
| + // A table inside the table directory. |
| + inDir := bytes.Clone(liberation(t)) |
| + binary.BigEndian.PutUint32(inDir[12+8:], 0) // the first table at offset 0 |
| + |
| + // WOFF: two identical tables whose compressed bytes are one range. |
| + v, ts := tablesOf(t, liberation(t)) |
| + same := bytes.Repeat([]byte("same"), 64) |
| + woff := buildWOFF(t, buildSFNT(v, append(ts, table{"zzz1", same}, table{"zzz2", same}))) |
| + { |
| + n := int(binary.BigEndian.Uint16(woff[12:])) |
| + var off []byte |
| + for i := 0; i < n; i++ { |
| + rec := woff[44+20*i:] |
| + switch string(rec[:4]) { |
| + case "zzz1": |
| + off = bytes.Clone(rec[4:8]) |
| + case "zzz2": |
| + copy(rec[4:8], off) |
| + } |
| + } |
| + } |
| + |
| + for _, c := range []struct { |
| + name string |
| + data []byte |
| + }{ |
| + {"two tables over one range", two}, |
| + {"a hundred tables over glyf", many}, |
| + {"a table over the directory", inDir}, |
| + {"a WOFF with two tables over one range", woff}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + f, err := Inspect(c.data) |
| + if !errors.Is(err, ErrMalformed) { |
| + t.Fatalf("Inspect = %+v, %v; want ErrMalformed", f, err) |
| + } |
| + t.Log(err) |
| + }) |
| + } |
| + |
| + // Tables that only touch, and empty ones, are fine. |
| + touching, _ := withFillers(t, 3) |
| + mustInspect(t, touching) |
| + mustInspect(t, buildSFNT(v, append(ts, table{"zero", nil}))) |
| +} |
diff --git a/typeface/outlines.go b/typeface/outlines.go| new file mode 100644 |
| index 0000000..6668e3d |
| --- /dev/null |
| +++ b/typeface/outlines.go |
| @@ -0,0 +1,313 @@ |
| +package typeface |
| + |
| +import "encoding/binary" |
| + |
| +// Outline checks: what Inspect can check about a face's glyphs cheaply, |
| +// before the file is kept. They read structure only, never a glyph's |
| +// instructions or charstrings: a TrueType face's loca must climb inside |
| +// glyf, each glyph must hold at least its header, and maxp's glyph count |
| +// must agree with loca and hmtx; a CFF or CFF2 table's header and |
| +// top-level INDEXes must parse inside the table, with as many |
| +// CharStrings as maxp has glyphs. Anything deeper is left to the |
| +// browser's own font sanitiser and to the app's parser when it draws. |
| +// |
| +// A WOFF2's transformed glyf, loca and hmtx are not rebuilt, so they are |
| +// not checked here. |
| + |
| +// checkOutlines runs the checks for the face's outline kind. |
| +func checkOutlines(ft fontTables, outline Outline) error { |
| + maxp := ft.data["maxp"] |
| + if len(maxp) < 6 { |
| + return malformed("no maxp table") |
| + } |
| + n := int(binary.BigEndian.Uint16(maxp[4:])) |
| + if n == 0 { |
| + return malformed("maxp counts no glyphs") |
| + } |
| + if outline == CFF { |
| + if b, ok := ft.data["CFF2"]; ok { |
| + return checkCFF2(b, n) |
| + } |
| + return checkCFF(ft.data["CFF "], n) |
| + } |
| + if err := checkMetrics(ft, n); err != nil { |
| + return err |
| + } |
| + return checkGlyf(ft, n) |
| +} |
| + |
| +// checkMetrics checks hhea's numberOfHMetrics against maxp and hmtx. |
| +func checkMetrics(ft fontTables, n int) error { |
| + hhea := ft.data["hhea"] |
| + if len(hhea) < 36 { |
| + return malformed("no hhea table") |
| + } |
| + m := int(binary.BigEndian.Uint16(hhea[34:])) |
| + if m == 0 || m > n { |
| + return malformed("%d horizontal metrics for %d glyphs", m, n) |
| + } |
| + if ft.transformed["hmtx"] { |
| + return nil |
| + } |
| + if need := 4*m + 2*(n-m); len(ft.data["hmtx"]) < need { |
| + return malformed("hmtx holds %d bytes, its metrics need %d", len(ft.data["hmtx"]), need) |
| + } |
| + return nil |
| +} |
| + |
| +// checkGlyf checks loca against glyf and maxp. |
| +func checkGlyf(ft fontTables, n int) error { |
| + if ft.transformed["glyf"] { |
| + return nil |
| + } |
| + head := ft.data["head"] // describe has checked its length |
| + size := 0 |
| + switch int16(binary.BigEndian.Uint16(head[50:])) { |
| + case 0: |
| + size = 2 |
| + case 1: |
| + size = 4 |
| + default: |
| + return malformed("indexToLocFormat is neither short nor long") |
| + } |
| + loca, glyf := ft.data["loca"], ft.data["glyf"] |
| + if len(loca) < size*(n+1) { |
| + return malformed("loca holds %d bytes, %d glyphs need %d", len(loca), n, size*(n+1)) |
| + } |
| + at := func(i int) uint64 { |
| + if size == 2 { |
| + return 2 * uint64(binary.BigEndian.Uint16(loca[2*i:])) |
| + } |
| + return uint64(binary.BigEndian.Uint32(loca[4*i:])) |
| + } |
| + prev := at(0) |
| + for i := 1; i <= n; i++ { |
| + next := at(i) |
| + if next < prev { |
| + return malformed("loca goes backwards at glyph %d", i-1) |
| + } |
| + if next > uint64(len(glyf)) { |
| + return malformed("glyph %d runs past glyf", i-1) |
| + } |
| + // A glyph with any bytes has at least its 10-byte header. |
| + if l := next - prev; l != 0 && l < 10 { |
| + return malformed("glyph %d is %d bytes, shorter than its header", i-1, l) |
| + } |
| + prev = next |
| + } |
| + return nil |
| +} |
| + |
| +// cffIndex is a CFF INDEX that readIndex has checked. |
| +type cffIndex struct { |
| + b []byte |
| + count, offSize int |
| + offsets, data int // where the offset array and the data begin |
| + end int // the first byte after the INDEX |
| +} |
| + |
| +// off is the INDEX's offset i (1-based, as stored). |
| +func (x cffIndex) off(i int) int { |
| + v := 0 |
| + for _, c := range x.b[x.offsets+i*x.offSize : x.offsets+(i+1)*x.offSize] { |
| + v = v<<8 | int(c) |
| + } |
| + return v |
| +} |
| + |
| +// item is the INDEX's item i. |
| +func (x cffIndex) item(i int) []byte { |
| + return x.b[x.data+x.off(i)-1 : x.data+x.off(i+1)-1] |
| +} |
| + |
| +// readIndex reads the INDEX at b[at:]. countSize is 2 in CFF and 4 in |
| +// CFF2. Offsets must start at 1 and never go back, and the data must lie |
| +// inside b. |
| +func readIndex(b []byte, at, countSize int) (cffIndex, error) { |
| + x := cffIndex{b: b} |
| + if at < 0 || at+countSize > len(b) { |
| + return x, malformed("CFF INDEX past the table") |
| + } |
| + if countSize == 4 { |
| + c := binary.BigEndian.Uint32(b[at:]) |
| + if c > uint32(len(b)) { |
| + return x, malformed("CFF INDEX of %d items in a %d-byte table", c, len(b)) |
| + } |
| + x.count = int(c) |
| + } else { |
| + x.count = int(binary.BigEndian.Uint16(b[at:])) |
| + } |
| + at += countSize |
| + if x.count == 0 { |
| + x.end = at |
| + return x, nil |
| + } |
| + if at >= len(b) { |
| + return x, malformed("CFF INDEX cut short") |
| + } |
| + x.offSize, x.offsets = int(b[at]), at+1 |
| + if x.offSize < 1 || x.offSize > 4 { |
| + return x, malformed("CFF INDEX offSize %d", x.offSize) |
| + } |
| + if (x.count+1)*x.offSize > len(b)-x.offsets { |
| + return x, malformed("CFF INDEX offsets past the table") |
| + } |
| + if x.off(0) != 1 { |
| + return x, malformed("CFF INDEX's first offset is not 1") |
| + } |
| + prev := 1 |
| + for i := 1; i <= x.count; i++ { |
| + o := x.off(i) |
| + if o < prev { |
| + return x, malformed("CFF INDEX offsets go back") |
| + } |
| + prev = o |
| + } |
| + x.data = x.offsets + (x.count+1)*x.offSize |
| + if prev-1 > len(b)-x.data { |
| + return x, malformed("CFF INDEX data past the table") |
| + } |
| + x.end = x.data + prev - 1 |
| + return x, nil |
| +} |
| + |
| +// charStringsAt reads a Top DICT and returns its CharStrings offset (the |
| +// operand before operator 17), or -1 when it names none. |
| +func charStringsAt(dict []byte) (int, error) { |
| + var last int64 |
| + have, at := false, -1 |
| + for i := 0; i < len(dict); { |
| + b := dict[i] |
| + switch { |
| + case b == 28: |
| + if i+3 > len(dict) { |
| + return 0, malformed("CFF DICT cut short") |
| + } |
| + last, have = int64(int16(binary.BigEndian.Uint16(dict[i+1:]))), true |
| + i += 3 |
| + case b == 29: |
| + if i+5 > len(dict) { |
| + return 0, malformed("CFF DICT cut short") |
| + } |
| + last, have = int64(int32(binary.BigEndian.Uint32(dict[i+1:]))), true |
| + i += 5 |
| + case b == 30: // a real: nibbles to an 0xf |
| + i++ |
| + for { |
| + if i >= len(dict) { |
| + return 0, malformed("CFF DICT real cut short") |
| + } |
| + c := dict[i] |
| + i++ |
| + if c&0x0f == 0x0f || c>>4 == 0x0f { |
| + break |
| + } |
| + } |
| + have = false |
| + case b >= 32 && b <= 246: |
| + last, have = int64(b)-139, true |
| + i++ |
| + case b >= 247 && b <= 254: |
| + if i+2 > len(dict) { |
| + return 0, malformed("CFF DICT cut short") |
| + } |
| + w := int64(b) |
| + if b <= 250 { |
| + last = (w-247)*256 + int64(dict[i+1]) + 108 |
| + } else { |
| + last = -(w-251)*256 - int64(dict[i+1]) - 108 |
| + } |
| + have = true |
| + i += 2 |
| + case b == 12: // two-byte operator |
| + i += 2 |
| + have = false |
| + case b <= 27: |
| + if b == 17 { |
| + if !have || last < 0 { |
| + return 0, malformed("CFF CharStrings with no offset") |
| + } |
| + at = int(last) |
| + } |
| + i++ |
| + have = false |
| + default: |
| + return 0, malformed("CFF DICT byte %d is reserved", b) |
| + } |
| + } |
| + return at, nil |
| +} |
| + |
| +// checkCharStrings checks the CharStrings INDEX at b[at:] holds n glyphs. |
| +func checkCharStrings(b []byte, at, countSize, n int) error { |
| + if at < 0 { |
| + return malformed("CFF names no CharStrings") |
| + } |
| + x, err := readIndex(b, at, countSize) |
| + if err != nil { |
| + return err |
| + } |
| + if x.count != n { |
| + return malformed("%d CharStrings for %d glyphs", x.count, n) |
| + } |
| + return nil |
| +} |
| + |
| +// checkCFF checks a CFF table: header, Name, Top DICT, String and Global |
| +// Subr INDEXes, and the CharStrings INDEX the one Top DICT names. |
| +func checkCFF(b []byte, n int) error { |
| + if len(b) < 4 || b[0] != 1 { |
| + return malformed("CFF header is not one") |
| + } |
| + hdrSize := int(b[2]) |
| + if hdrSize < 4 || hdrSize > len(b) || b[3] < 1 || b[3] > 4 { |
| + return malformed("CFF header is not one") |
| + } |
| + names, err := readIndex(b, hdrSize, 2) |
| + if err != nil { |
| + return err |
| + } |
| + if names.count != 1 { |
| + return malformed("CFF with %d fonts", names.count) |
| + } |
| + top, err := readIndex(b, names.end, 2) |
| + if err != nil { |
| + return err |
| + } |
| + if top.count != 1 { |
| + return malformed("CFF with %d Top DICTs", top.count) |
| + } |
| + strs, err := readIndex(b, top.end, 2) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := readIndex(b, strs.end, 2); err != nil { // Global Subrs |
| + return err |
| + } |
| + cs, err := charStringsAt(top.item(0)) |
| + if err != nil { |
| + return err |
| + } |
| + return checkCharStrings(b, cs, 2, n) |
| +} |
| + |
| +// checkCFF2 checks a CFF2 table: header, Top DICT, Global Subr INDEX, |
| +// and the CharStrings INDEX the Top DICT names. |
| +func checkCFF2(b []byte, n int) error { |
| + if len(b) < 5 || b[0] != 2 { |
| + return malformed("CFF2 header is not one") |
| + } |
| + hdrSize := int(b[2]) |
| + topLen := int(binary.BigEndian.Uint16(b[3:])) |
| + if hdrSize < 5 || hdrSize+topLen > len(b) { |
| + return malformed("CFF2 header is not one") |
| + } |
| + if _, err := readIndex(b, hdrSize+topLen, 4); err != nil { // Global Subrs |
| + return err |
| + } |
| + cs, err := charStringsAt(b[hdrSize : hdrSize+topLen]) |
| + if err != nil { |
| + return err |
| + } |
| + return checkCharStrings(b, cs, 4, n) |
| +} |
diff --git a/typeface/outlines_test.go b/typeface/outlines_test.go| new file mode 100644 |
| index 0000000..8afd9e4 |
| --- /dev/null |
| +++ b/typeface/outlines_test.go |
| @@ -0,0 +1,267 @@ |
| +package typeface |
| + |
| +import ( |
| + "bytes" |
| + "encoding/binary" |
| + "errors" |
| + "testing" |
| +) |
| + |
| +// Outlines are checked before a file is kept, as far as it is cheap to: |
| +// for TrueType, that loca's offsets climb and stay inside glyf, that each |
| +// glyph holds at least its header, and that maxp's glyph count agrees |
| +// with loca and hmtx; for CFF and CFF2, that the header and the top-level |
| +// INDEXes parse inside the table and the CharStrings count is maxp's. |
| +// Outline-table presence alone was taken as validation before (final |
| +// review, I1). A WOFF2's transformed glyf and loca are not rebuilt, so |
| +// they are not checked here; the browser's own sanitiser still is. |
| + |
| +// buildIndex is a CFF INDEX of items: a count of countSize bytes (2 in |
| +// CFF, 4 in CFF2), then 4-byte offsets and the data. |
| +func buildIndex(countSize int, items ...[]byte) []byte { |
| + var b []byte |
| + if countSize == 4 { |
| + b = binary.BigEndian.AppendUint32(b, uint32(len(items))) |
| + } else { |
| + b = binary.BigEndian.AppendUint16(b, uint16(len(items))) |
| + } |
| + if len(items) == 0 { |
| + return b |
| + } |
| + b = append(b, 4) |
| + off := uint32(1) |
| + b = binary.BigEndian.AppendUint32(b, off) |
| + for _, it := range items { |
| + off += uint32(len(it)) |
| + b = binary.BigEndian.AppendUint32(b, off) |
| + } |
| + for _, it := range items { |
| + b = append(b, it...) |
| + } |
| + return b |
| +} |
| + |
| +// charStrings is n glyphs, each a lone endchar. |
| +func charStrings(n int) [][]byte { |
| + out := make([][]byte, n) |
| + for i := range out { |
| + out[i] = []byte{14} |
| + } |
| + return out |
| +} |
| + |
| +// dictInt is a DICT operand in its five-byte form, so a DICT's length |
| +// does not depend on the numbers in it. |
| +func dictInt(v int32) []byte { |
| + return binary.BigEndian.AppendUint32([]byte{29}, uint32(v)) |
| +} |
| + |
| +// cffTable is a CFF table with one font of n glyphs: header, Name INDEX, |
| +// Top DICT INDEX (CharStrings only), empty String and Global Subr |
| +// INDEXes, then the CharStrings INDEX. |
| +func cffTable(n int) []byte { |
| + header := []byte{1, 0, 4, 4} |
| + name := buildIndex(2, []byte("Test")) |
| + empty := buildIndex(2) |
| + // The Top DICT INDEX's size is fixed (one item of 6 bytes), so the |
| + // CharStrings offset can be worked out before it is written. |
| + topLen := len(buildIndex(2, make([]byte, 6))) |
| + at := len(header) + len(name) + topLen + 2*len(empty) |
| + top := buildIndex(2, append(dictInt(int32(at)), 17)) |
| + b := append(append(append(header, name...), top...), empty...) |
| + b = append(b, empty...) |
| + return append(b, buildIndex(2, charStrings(n)...)...) |
| +} |
| + |
| +// cff2Table is a CFF2 table of n glyphs: header, Top DICT (CharStrings |
| +// only), an empty Global Subr INDEX, then the CharStrings INDEX. |
| +func cff2Table(n int) []byte { |
| + const headerSize, topLen = 5, 6 |
| + at := headerSize + topLen + 4 |
| + top := append(dictInt(int32(at)), 17) |
| + b := []byte{2, 0, headerSize} |
| + b = binary.BigEndian.AppendUint16(b, topLen) |
| + b = append(b, top...) |
| + b = append(b, buildIndex(4)...) |
| + return append(b, buildIndex(4, charStrings(n)...)...) |
| +} |
| + |
| +// numGlyphs is maxp's glyph count in tables ts. |
| +func numGlyphs(ts []table) int { |
| + return int(binary.BigEndian.Uint16(tableData(ts, "maxp")[4:])) |
| +} |
| + |
| +// otto is Liberation's other tables in an OTTO, with outlines cffTag |
| +// built by make for Liberation's glyph count, where glyf and loca were. |
| +func otto(t *testing.T, cffTag string, make func(n int) []byte) []byte { |
| + t.Helper() |
| + _, ts := tablesOf(t, liberation(t)) |
| + ts = withoutTable(ts, "glyf", "loca") |
| + return buildSFNT(sigOTTO, append(ts, table{cffTag, make(numGlyphs(ts))})) |
| +} |
| + |
| +// liberationWith is Liberation with table tag changed by edit. |
| +func liberationWith(t *testing.T, tag string, edit func(b []byte) []byte) []byte { |
| + t.Helper() |
| + v, ts := tablesOf(t, liberation(t)) |
| + return buildSFNT(v, withTable(ts, tag, edit(bytes.Clone(tableData(ts, tag))))) |
| +} |
| + |
| +// locaAt and setLoca read and write Liberation's long-format loca. |
| +func locaAt(b []byte, i int) uint32 { return binary.BigEndian.Uint32(b[4*i:]) } |
| +func setLoca(b []byte, i int, v uint32) { binary.BigEndian.PutUint32(b[4*i:], v) } |
| + |
| +// someGlyph is the first glyph after .notdef longer than n bytes. |
| +func someGlyph(t *testing.T, loca []byte, n uint32) int { |
| + t.Helper() |
| + for i := 1; 4*(i+2) <= len(loca); i++ { |
| + if locaAt(loca, i+1)-locaAt(loca, i) > n { |
| + return i |
| + } |
| + } |
| + t.Fatal("no glyph long enough") |
| + return 0 |
| +} |
| + |
| +func TestInspectReadsGenuineCFFAndCFF2(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + data []byte |
| + }{ |
| + {"cff", otto(t, "CFF ", cffTable)}, |
| + {"cff2", otto(t, "CFF2", cff2Table)}, |
| + {"woff of a cff", buildWOFF(t, otto(t, "CFF ", cffTable))}, |
| + {"woff2 of a cff2", buildWOFF2(t, otto(t, "CFF2", cff2Table))}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + if f := mustInspect(t, c.data); f.Outline != CFF { |
| + t.Errorf("Outline = %q", f.Outline) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A WOFF2's transformed glyf and loca are not rebuilt, so their bytes are |
| +// not checked: the file is taken on its other tables. |
| +func TestInspectTakesATransformedWOFF2Glyf(t *testing.T) { |
| + flavor, es, _ := woff2Parts(t, liberation(t)) |
| + var stream []byte |
| + _, ts := tablesOf(t, liberation(t)) |
| + for i := range es { |
| + switch es[i].tag { |
| + case "glyf": |
| + es[i].version, es[i].transform = 0, 64 |
| + stream = append(stream, make([]byte, 64)...) |
| + case "loca": |
| + es[i].version, es[i].transform = 0, 0 |
| + default: |
| + stream = append(stream, tableData(ts, es[i].tag)...) |
| + } |
| + } |
| + mustInspect(t, assembleWOFF2(flavor, es, brotliOf(stream))) |
| +} |
| + |
| +func TestInspectRefusesBrokenOutlines(t *testing.T) { |
| + _, ts := tablesOf(t, liberation(t)) |
| + loca := tableData(ts, "loca") |
| + glyfLen := uint32(len(tableData(ts, "glyf"))) |
| + g := someGlyph(t, loca, 16) |
| + |
| + backwards := liberationWith(t, "loca", func(b []byte) []byte { |
| + setLoca(b, g+1, locaAt(b, g)-2) |
| + return b |
| + }) |
| + pastGlyf := liberationWith(t, "loca", func(b []byte) []byte { |
| + setLoca(b, len(b)/4-1, glyfLen+4) |
| + return b |
| + }) |
| + shortGlyph := liberationWith(t, "loca", func(b []byte) []byte { |
| + setLoca(b, g+1, locaAt(b, g)+4) |
| + return b |
| + }) |
| + moreGlyphs := liberationWith(t, "maxp", func(b []byte) []byte { |
| + binary.BigEndian.PutUint16(b[4:], uint16(numGlyphs(ts)+10)) |
| + return b |
| + }) |
| + badLocFormat := liberationWith(t, "head", func(b []byte) []byte { |
| + binary.BigEndian.PutUint16(b[50:], 2) |
| + return b |
| + }) |
| + shortHmtx := liberationWith(t, "hmtx", func(b []byte) []byte { return b[:100] }) |
| + noMetrics := liberationWith(t, "hhea", func(b []byte) []byte { |
| + binary.BigEndian.PutUint16(b[34:], 0) |
| + return b |
| + }) |
| + tooManyMetrics := liberationWith(t, "hhea", func(b []byte) []byte { |
| + binary.BigEndian.PutUint16(b[34:], uint16(numGlyphs(ts)+1)) |
| + return b |
| + }) |
| + v, _ := tablesOf(t, liberation(t)) |
| + empty := buildSFNT(v, withTable(withTable(ts, "glyf", nil), "loca", nil)) |
| + noMaxp := buildSFNT(v, withoutTable(ts, "maxp")) |
| + |
| + cffWith := func(edit func(b []byte) []byte) []byte { |
| + return otto(t, "CFF ", func(n int) []byte { return edit(cffTable(n)) }) |
| + } |
| + stub := cffWith(func([]byte) []byte { return []byte{1, 0, 4, 1} }) |
| + fewerCharStrings := otto(t, "CFF ", func(n int) []byte { return cffTable(n - 1) }) |
| + cffCutShort := cffWith(func(b []byte) []byte { return b[:len(b)-1] }) |
| + cffBadVersion := cffWith(func(b []byte) []byte { b[0] = 3; return b }) |
| + cffTwoNames := cffWith(func(b []byte) []byte { |
| + binary.BigEndian.PutUint16(b[4:], 2) // the Name INDEX's count |
| + return b |
| + }) |
| + cffOffsetsBack := cffWith(func(b []byte) []byte { |
| + // The Name INDEX's second offset, before its first. |
| + binary.BigEndian.PutUint32(b[4+2+1+4:], 0) |
| + return b |
| + }) |
| + cffNoCharStrings := cffWith(func(b []byte) []byte { |
| + // The Top DICT's operator, 17, made a different one (15, |
| + // charset), so the DICT names no CharStrings. |
| + i := bytes.Index(b, []byte{17, 0, 0}) |
| + if i < 0 { |
| + t.Fatal("no CharStrings operator") |
| + } |
| + b[i] = 15 |
| + return b |
| + }) |
| + cff2CutShort := otto(t, "CFF2", func(n int) []byte { return cff2Table(n)[:12] }) |
| + cff2Fewer := otto(t, "CFF2", func(n int) []byte { return cff2Table(n - 1) }) |
| + |
| + for _, c := range []struct { |
| + name string |
| + data []byte |
| + }{ |
| + {"loca going backwards", backwards}, |
| + {"loca past the end of glyf", pastGlyf}, |
| + {"a glyph shorter than its header", shortGlyph}, |
| + {"maxp counting more glyphs than loca holds", moreGlyphs}, |
| + {"an indexToLocFormat that is neither", badLocFormat}, |
| + {"hmtx shorter than its metrics", shortHmtx}, |
| + {"no horizontal metrics", noMetrics}, |
| + {"more metrics than glyphs", tooManyMetrics}, |
| + {"an empty glyf and loca", empty}, |
| + {"no maxp", noMaxp}, |
| + {"a WOFF of a backwards loca", buildWOFF(t, backwards)}, |
| + {"a WOFF2 of a loca past glyf", buildWOFF2(t, pastGlyf)}, |
| + {"a stub CFF", stub}, |
| + {"a CFF with fewer CharStrings than glyphs", fewerCharStrings}, |
| + {"a CFF cut short", cffCutShort}, |
| + {"a CFF of an unknown version", cffBadVersion}, |
| + {"a CFF with two fonts", cffTwoNames}, |
| + {"a CFF INDEX whose offsets go back", cffOffsetsBack}, |
| + {"a CFF with no CharStrings", cffNoCharStrings}, |
| + {"a CFF2 cut short", cff2CutShort}, |
| + {"a CFF2 with fewer CharStrings than glyphs", cff2Fewer}, |
| + {"a WOFF2 of a stub CFF", buildWOFF2(t, stub)}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + f, err := Inspect(c.data) |
| + if !errors.Is(err, ErrMalformed) { |
| + t.Fatalf("Inspect = %+v, %v; want ErrMalformed", f, err) |
| + } |
| + t.Log(err) |
| + }) |
| + } |
| +} |
diff --git a/typeface/testdata/LICENSE-OFL-1.1.txt b/typeface/testdata/LICENSE-OFL-1.1.txt| new file mode 100644 |
| index 0000000..84619fc |
| --- /dev/null |
| +++ b/typeface/testdata/LICENSE-OFL-1.1.txt |
| @@ -0,0 +1,91 @@ |
| +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 |
| + |
| +PREAMBLE The goals of the Open Font License (OFL) are to stimulate |
| +worldwide development of collaborative font projects, to support the font |
| +creation efforts of academic and linguistic communities, and to provide |
| +a free and open framework in which fonts may be shared and improved in |
| +partnership with others. |
| + |
| +The OFL allows the licensed fonts to be used, studied, modified and |
| +redistributed freely as long as they are not sold by themselves. |
| +The fonts, including any derivative works, can be bundled, embedded, |
| +redistributed and/or sold with any software provided that any reserved |
| +names are not used by derivative works. The fonts and derivatives, |
| +however, cannot be released under any other type of license. The |
| +requirement for fonts to remain under this license does not apply to |
| +any document created using the fonts or their derivatives. |
| + |
| + |
| + |
| +DEFINITIONS |
| +"Font Software" refers to the set of files released by the Copyright |
| +Holder(s) under this license and clearly marked as such. |
| +This may include source files, build scripts and documentation. |
| + |
| +"Reserved Font Name" refers to any names specified as such after the |
| +copyright statement(s). |
| + |
| +"Original Version" refers to the collection of Font Software components |
| +as distributed by the Copyright Holder(s). |
| + |
| +"Modified Version" refers to any derivative made by adding to, deleting, |
| +or substituting ? in part or in whole ? |
| +any of the components of the Original Version, by changing formats or |
| +by porting the Font Software to a new environment. |
| + |
| +"Author" refers to any designer, engineer, programmer, technical writer |
| +or other person who contributed to the Font Software. |
| + |
| + |
| +PERMISSION & CONDITIONS |
| + |
| +Permission is hereby granted, free of charge, to any person obtaining a |
| +copy of the Font Software, to use, study, copy, merge, embed, modify, |
| +redistribute, and sell modified and unmodified copies of the Font |
| +Software, subject to the following conditions: |
| + |
| +1) Neither the Font Software nor any of its individual components,in |
| + Original or Modified Versions, may be sold by itself. |
| + |
| +2) Original or Modified Versions of the Font Software may be bundled, |
| + redistributed and/or sold with any software, provided that each copy |
| + contains the above copyright notice and this license. These can be |
| + included either as stand-alone text files, human-readable headers or |
| + in the appropriate machine-readable metadata fields within text or |
| + binary files as long as those fields can be easily viewed by the user. |
| + |
| +3) No Modified Version of the Font Software may use the Reserved Font |
| + Name(s) unless explicit written permission is granted by the |
| + corresponding Copyright Holder. This restriction only applies to the |
| + primary font name as presented to the users. |
| + |
| +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font |
| + Software shall not be used to promote, endorse or advertise any |
| + Modified Version, except to acknowledge the contribution(s) of the |
| + Copyright Holder(s) and the Author(s) or with their explicit written |
| + permission. |
| + |
| +5) The Font Software, modified or unmodified, in part or in whole, must |
| + be distributed entirely under this license, and must not be distributed |
| + under any other license. The requirement for fonts to remain under |
| + this license does not apply to any document created using the Font |
| + Software. |
| + |
| + |
| + |
| +TERMINATION |
| +This license becomes null and void if any of the above conditions are not met. |
| + |
| + |
| + |
| +DISCLAIMER |
| +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF |
| +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT |
| +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE |
| +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, |
| +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL |
| +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER |
| +DEALINGS IN THE FONT SOFTWARE. |
| + |
diff --git a/typeface/testdata/LiberationSans-Regular.ttf b/typeface/testdata/LiberationSans-Regular.ttf| new file mode 100644 |
| index 0000000..f524339 |
| Binary files /dev/null and b/typeface/testdata/LiberationSans-Regular.ttf differ |
diff --git a/typeface/typeface.go b/typeface/typeface.go| new file mode 100644 |
| index 0000000..2b82dde |
| --- /dev/null |
| +++ b/typeface/typeface.go |
| @@ -0,0 +1,531 @@ |
| +// 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'") |
| +} |
diff --git a/typeface/typeface_test.go b/typeface/typeface_test.go| new file mode 100644 |
| index 0000000..6597deb |
| --- /dev/null |
| +++ b/typeface/typeface_test.go |
| @@ -0,0 +1,628 @@ |
| +package typeface |
| + |
| +import ( |
| + "bytes" |
| + "compress/zlib" |
| + "crypto/sha256" |
| + "encoding/binary" |
| + "encoding/hex" |
| + "errors" |
| + "net/http/httptest" |
| + "os" |
| + "sort" |
| + "testing" |
| + |
| + "github.com/andybalholm/brotli" |
| +) |
| + |
| +// The test font is Liberation Sans Regular (SIL OFL 1.1; the licence is |
| +// beside it in testdata). Every other file these tests read is built from |
| +// it here: WOFF and WOFF2 copies, and synthetic sfnts with one table |
| +// swapped or patched. |
| + |
| +type table struct { |
| + tag string |
| + data []byte |
| +} |
| + |
| +func liberation(t *testing.T) []byte { |
| + t.Helper() |
| + b, err := os.ReadFile("testdata/LiberationSans-Regular.ttf") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +// tablesOf reads an sfnt's version and tables, in directory order. |
| +func tablesOf(t *testing.T, sfnt []byte) (uint32, []table) { |
| + t.Helper() |
| + n := int(binary.BigEndian.Uint16(sfnt[4:])) |
| + var ts []table |
| + for i := 0; i < n; i++ { |
| + rec := sfnt[12+16*i:] |
| + off := binary.BigEndian.Uint32(rec[8:]) |
| + length := binary.BigEndian.Uint32(rec[12:]) |
| + ts = append(ts, table{string(rec[:4]), bytes.Clone(sfnt[off : off+length])}) |
| + } |
| + return binary.BigEndian.Uint32(sfnt), ts |
| +} |
| + |
| +// buildSFNT writes an sfnt with the tables sorted by tag, each padded to |
| +// four bytes. Checksums are left zero: Inspect does not read them. |
| +func buildSFNT(version uint32, ts []table) []byte { |
| + ts = append([]table(nil), ts...) |
| + sort.Slice(ts, func(i, j int) bool { return ts[i].tag < ts[j].tag }) |
| + var b []byte |
| + b = binary.BigEndian.AppendUint32(b, version) |
| + b = binary.BigEndian.AppendUint16(b, uint16(len(ts))) |
| + b = append(b, 0, 0, 0, 0, 0, 0) // searchRange and friends: unread |
| + off := 12 + 16*len(ts) |
| + for _, tb := range ts { |
| + b = append(b, tb.tag...) |
| + b = binary.BigEndian.AppendUint32(b, 0) |
| + b = binary.BigEndian.AppendUint32(b, uint32(off)) |
| + b = binary.BigEndian.AppendUint32(b, uint32(len(tb.data))) |
| + off += (len(tb.data) + 3) &^ 3 |
| + } |
| + for _, tb := range ts { |
| + b = append(b, tb.data...) |
| + for len(b)%4 != 0 { |
| + b = append(b, 0) |
| + } |
| + } |
| + return b |
| +} |
| + |
| +func withTable(ts []table, tag string, data []byte) []table { |
| + out := withoutTable(ts, tag) |
| + return append(out, table{tag, data}) |
| +} |
| + |
| +func withoutTable(ts []table, tags ...string) []table { |
| + var out []table |
| + for _, tb := range ts { |
| + drop := false |
| + for _, tag := range tags { |
| + drop = drop || tb.tag == tag |
| + } |
| + if !drop { |
| + out = append(out, tb) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func tableData(ts []table, tag string) []byte { |
| + for _, tb := range ts { |
| + if tb.tag == tag { |
| + return tb.data |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// patched is Liberation with its OS/2 fsType and fsSelection set. |
| +func patched(t *testing.T, fsType, fsSelection uint16) []byte { |
| + t.Helper() |
| + v, ts := tablesOf(t, liberation(t)) |
| + os2 := bytes.Clone(tableData(ts, "OS/2")) |
| + binary.BigEndian.PutUint16(os2[8:], fsType) |
| + binary.BigEndian.PutUint16(os2[62:], fsSelection) |
| + return buildSFNT(v, withTable(ts, "OS/2", os2)) |
| +} |
| + |
| +// cff is Liberation's other tables in an OTTO with a CFF table of as |
| +// many glyphs where its glyf and loca were (outlines_test.go). |
| +func cff(t *testing.T) []byte { |
| + t.Helper() |
| + return otto(t, "CFF ", cffTable) |
| +} |
| + |
| +type axis struct { |
| + tag string |
| + min, def, max float64 |
| +} |
| + |
| +func fvar(axes ...axis) []byte { |
| + var b []byte |
| + b = binary.BigEndian.AppendUint16(b, 1) // majorVersion |
| + b = binary.BigEndian.AppendUint16(b, 0) // minorVersion |
| + b = binary.BigEndian.AppendUint16(b, 16) // axesArrayOffset |
| + b = binary.BigEndian.AppendUint16(b, 2) // reserved |
| + b = binary.BigEndian.AppendUint16(b, uint16(len(axes))) |
| + b = binary.BigEndian.AppendUint16(b, 20) // axisSize |
| + b = binary.BigEndian.AppendUint16(b, 0) // instanceCount |
| + b = binary.BigEndian.AppendUint16(b, uint16(4+4*len(axes))) |
| + for _, a := range axes { |
| + b = append(b, a.tag...) |
| + for _, v := range []float64{a.min, a.def, a.max} { |
| + b = binary.BigEndian.AppendUint32(b, uint32(int32(v*65536))) |
| + } |
| + b = binary.BigEndian.AppendUint16(b, 0) // flags |
| + b = binary.BigEndian.AppendUint16(b, 256) // axisNameID |
| + } |
| + return b |
| +} |
| + |
| +func variable(t *testing.T, axes ...axis) []byte { |
| + t.Helper() |
| + v, ts := tablesOf(t, liberation(t)) |
| + return buildSFNT(v, withTable(ts, "fvar", fvar(axes...))) |
| +} |
| + |
| +type nameRec struct { |
| + platform, encoding, language, id uint16 |
| + value string |
| +} |
| + |
| +// nameTable builds a format 0 name table: platform 1 strings in Mac |
| +// Roman (ASCII here, plus é as 0x8E), everything else UTF-16BE. |
| +func nameTable(recs ...nameRec) []byte { |
| + var storage []byte |
| + var b []byte |
| + b = binary.BigEndian.AppendUint16(b, 0) |
| + b = binary.BigEndian.AppendUint16(b, uint16(len(recs))) |
| + b = binary.BigEndian.AppendUint16(b, uint16(6+12*len(recs))) |
| + for _, r := range recs { |
| + var s []byte |
| + if r.platform == 1 { |
| + for _, c := range r.value { |
| + if c == 'é' { |
| + s = append(s, 0x8E) |
| + } else { |
| + s = append(s, byte(c)) |
| + } |
| + } |
| + } else { |
| + for _, c := range r.value { |
| + s = binary.BigEndian.AppendUint16(s, uint16(c)) |
| + } |
| + } |
| + for _, v := range []uint16{r.platform, r.encoding, r.language, r.id, uint16(len(s)), uint16(len(storage))} { |
| + b = binary.BigEndian.AppendUint16(b, v) |
| + } |
| + storage = append(storage, s...) |
| + } |
| + return append(b, storage...) |
| +} |
| + |
| +func named(t *testing.T, recs ...nameRec) []byte { |
| + t.Helper() |
| + v, ts := tablesOf(t, liberation(t)) |
| + return buildSFNT(v, withTable(ts, "name", nameTable(recs...))) |
| +} |
| + |
| +// buildWOFF wraps an sfnt in WOFF 1.0, each table zlib-compressed (or |
| +// stored when that is no smaller, as the format requires). |
| +func buildWOFF(t *testing.T, sfnt []byte) []byte { |
| + t.Helper() |
| + flavor, ts := tablesOf(t, sfnt) |
| + sort.Slice(ts, func(i, j int) bool { return ts[i].tag < ts[j].tag }) |
| + type entry struct { |
| + tag string |
| + comp []byte |
| + origLength int |
| + offset int |
| + storedLength int |
| + } |
| + var es []entry |
| + off := 44 + 20*len(ts) |
| + for _, tb := range ts { |
| + var z bytes.Buffer |
| + w := zlib.NewWriter(&z) |
| + w.Write(tb.data) |
| + w.Close() |
| + comp := z.Bytes() |
| + if len(comp) >= len(tb.data) { |
| + comp = tb.data |
| + } |
| + es = append(es, entry{tb.tag, comp, len(tb.data), off, len(comp)}) |
| + off += (len(comp) + 3) &^ 3 |
| + } |
| + var b []byte |
| + b = append(b, "wOFF"...) |
| + b = binary.BigEndian.AppendUint32(b, flavor) |
| + b = binary.BigEndian.AppendUint32(b, uint32(off)) // length |
| + b = binary.BigEndian.AppendUint16(b, uint16(len(ts))) |
| + b = binary.BigEndian.AppendUint16(b, 0) |
| + b = binary.BigEndian.AppendUint32(b, uint32(len(sfnt))) |
| + b = append(b, make([]byte, 4+20)...) // version, metadata, private |
| + for _, e := range es { |
| + b = append(b, e.tag...) |
| + b = binary.BigEndian.AppendUint32(b, uint32(e.offset)) |
| + b = binary.BigEndian.AppendUint32(b, uint32(e.storedLength)) |
| + b = binary.BigEndian.AppendUint32(b, uint32(e.origLength)) |
| + b = binary.BigEndian.AppendUint32(b, 0) |
| + } |
| + for _, e := range es { |
| + b = append(b, e.comp...) |
| + for len(b)%4 != 0 { |
| + b = append(b, 0) |
| + } |
| + } |
| + return b |
| +} |
| + |
| +var testWOFF2Tags = []string{"cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS", "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc", "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop", "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill"} |
| + |
| +func encodeBase128(n uint32) []byte { |
| + var out []byte |
| + for { |
| + out = append([]byte{byte(n & 0x7F)}, out...) |
| + n >>= 7 |
| + if n == 0 { |
| + break |
| + } |
| + } |
| + for i := 0; i < len(out)-1; i++ { |
| + out[i] |= 0x80 |
| + } |
| + return out |
| +} |
| + |
| +// woff2Entry is a WOFF2 directory entry as written: lengths may lie, |
| +// which is the point of some refusals. |
| +type woff2Entry struct { |
| + tag string |
| + version byte // transform version, the flags' top two bits |
| + origLength uint32 |
| + transform uint32 // written only when the entry is transformed |
| +} |
| + |
| +func woff2Transformed(e woff2Entry) bool { |
| + switch e.tag { |
| + case "glyf", "loca": |
| + return e.version != 3 |
| + default: |
| + return e.version != 0 |
| + } |
| +} |
| + |
| +func assembleWOFF2(flavor uint32, es []woff2Entry, compressed []byte) []byte { |
| + var dir []byte |
| + for _, e := range es { |
| + idx := 63 |
| + for i, tag := range testWOFF2Tags { |
| + if tag == e.tag { |
| + idx = i |
| + } |
| + } |
| + dir = append(dir, e.version<<6|byte(idx)) |
| + if idx == 63 { |
| + dir = append(dir, e.tag...) |
| + } |
| + dir = append(dir, encodeBase128(e.origLength)...) |
| + if woff2Transformed(e) { |
| + dir = append(dir, encodeBase128(e.transform)...) |
| + } |
| + } |
| + total := 48 + len(dir) + len(compressed) |
| + padded := (total + 3) &^ 3 |
| + var b []byte |
| + b = append(b, "wOF2"...) |
| + b = binary.BigEndian.AppendUint32(b, flavor) |
| + b = binary.BigEndian.AppendUint32(b, uint32(padded)) |
| + b = binary.BigEndian.AppendUint16(b, uint16(len(es))) |
| + b = binary.BigEndian.AppendUint16(b, 0) |
| + b = binary.BigEndian.AppendUint32(b, 0) // totalSfntSize: unread |
| + b = binary.BigEndian.AppendUint32(b, uint32(len(compressed))) |
| + b = append(b, make([]byte, 4+20)...) // version, metadata, private |
| + b = append(b, dir...) |
| + b = append(b, compressed...) |
| + return append(b, make([]byte, padded-total)...) |
| +} |
| + |
| +func brotliOf(data []byte) []byte { |
| + var z bytes.Buffer |
| + w := brotli.NewWriterLevel(&z, 5) |
| + w.Write(data) |
| + w.Close() |
| + return z.Bytes() |
| +} |
| + |
| +// woff2Parts is an sfnt's tables as WOFF2 entries, glyf and loca with |
| +// the null transform, and their concatenation (the uncompressed stream). |
| +func woff2Parts(t *testing.T, sfnt []byte) (uint32, []woff2Entry, []byte) { |
| + t.Helper() |
| + flavor, ts := tablesOf(t, sfnt) |
| + var es []woff2Entry |
| + var stream []byte |
| + for _, tb := range ts { |
| + e := woff2Entry{tag: tb.tag, origLength: uint32(len(tb.data))} |
| + if tb.tag == "glyf" || tb.tag == "loca" { |
| + e.version = 3 |
| + } |
| + es = append(es, e) |
| + stream = append(stream, tb.data...) |
| + } |
| + return flavor, es, stream |
| +} |
| + |
| +func buildWOFF2(t *testing.T, sfnt []byte) []byte { |
| + t.Helper() |
| + flavor, es, stream := woff2Parts(t, sfnt) |
| + return assembleWOFF2(flavor, es, brotliOf(stream)) |
| +} |
| + |
| +func mustInspect(t *testing.T, data []byte) Face { |
| + t.Helper() |
| + f, err := Inspect(data) |
| + if err != nil { |
| + t.Fatalf("Inspect: %v", err) |
| + } |
| + return f |
| +} |
| + |
| +func TestInspectReadsTheNamesAndStyle(t *testing.T) { |
| + data := liberation(t) |
| + f := mustInspect(t, data) |
| + sum := sha256.Sum256(data) |
| + want := Face{ |
| + Ref: hex.EncodeToString(sum[:]), |
| + Format: "ttf", |
| + Outline: "truetype", |
| + Family: "Liberation Sans", |
| + Style: "Regular", |
| + Weight: 400, |
| + WeightMin: 400, |
| + WeightMax: 400, |
| + } |
| + if f != want { |
| + t.Fatalf("Inspect(Liberation Sans)\n got %+v\nwant %+v", f, want) |
| + } |
| + if f.ContentType() != "font/ttf" { |
| + t.Errorf("ContentType = %q", f.ContentType()) |
| + } |
| + |
| + t.Run("italic from fsSelection", func(t *testing.T) { |
| + if f := mustInspect(t, patched(t, 0, 0x0001)); !f.Italic { |
| + t.Errorf("fsSelection bit 0 set, Italic = false") |
| + } |
| + }) |
| + t.Run("italic from macStyle", func(t *testing.T) { |
| + v, ts := tablesOf(t, liberation(t)) |
| + head := bytes.Clone(tableData(ts, "head")) |
| + binary.BigEndian.PutUint16(head[44:], 0x0002) |
| + if f := mustInspect(t, buildSFNT(v, withTable(ts, "head", head))); !f.Italic { |
| + t.Errorf("macStyle bit 1 set, Italic = false") |
| + } |
| + }) |
| + t.Run("typographic names win, Windows before Mac", func(t *testing.T) { |
| + f := mustInspect(t, named(t, |
| + nameRec{1, 0, 0, 1, "Mac Family"}, |
| + nameRec{1, 0, 0, 2, "Mac Style"}, |
| + nameRec{1, 0, 0, 16, "Mac Typo"}, |
| + nameRec{3, 1, 0x0409, 1, "Win Family"}, |
| + nameRec{3, 1, 0x0409, 2, "Bold"}, |
| + nameRec{3, 1, 0x0409, 16, "Café Sans"}, |
| + nameRec{3, 1, 0x0409, 17, "Semibold"}, |
| + )) |
| + if f.Family != "Café Sans" || f.Style != "Semibold" { |
| + t.Errorf("Family, Style = %q, %q; want Café Sans, Semibold", f.Family, f.Style) |
| + } |
| + }) |
| + t.Run("legacy names, Mac Roman when there is nothing else", func(t *testing.T) { |
| + f := mustInspect(t, named(t, |
| + nameRec{1, 0, 0, 1, "Café Mac"}, |
| + nameRec{1, 0, 0, 2, "Italic"}, |
| + )) |
| + if f.Family != "Café Mac" || f.Style != "Italic" { |
| + t.Errorf("Family, Style = %q, %q; want Café Mac, Italic", f.Family, f.Style) |
| + } |
| + }) |
| +} |
| + |
| +func TestInspectReadsWOFFAndWOFF2(t *testing.T) { |
| + ttf := mustInspect(t, liberation(t)) |
| + for _, c := range []struct { |
| + format Format |
| + data []byte |
| + ctype string |
| + }{ |
| + {"woff", buildWOFF(t, liberation(t)), "font/woff"}, |
| + {"woff2", buildWOFF2(t, liberation(t)), "font/woff2"}, |
| + } { |
| + t.Run(string(c.format), func(t *testing.T) { |
| + f := mustInspect(t, c.data) |
| + sum := sha256.Sum256(c.data) |
| + want := ttf |
| + want.Ref = hex.EncodeToString(sum[:]) |
| + want.Format = c.format |
| + if f != want { |
| + t.Fatalf("\n got %+v\nwant %+v", f, want) |
| + } |
| + if f.ContentType() != c.ctype { |
| + t.Errorf("ContentType = %q, want %q", f.ContentType(), c.ctype) |
| + } |
| + }) |
| + } |
| + t.Run("woff2 of a cff", func(t *testing.T) { |
| + f := mustInspect(t, buildWOFF2(t, cff(t))) |
| + if f.Format != "woff2" || f.Outline != "cff" { |
| + t.Errorf("Format, Outline = %q, %q", f.Format, f.Outline) |
| + } |
| + }) |
| +} |
| + |
| +func TestInspectReadsCFFAndVariable(t *testing.T) { |
| + f := mustInspect(t, cff(t)) |
| + if f.Format != "otf" || f.Outline != "cff" || f.Family != "Liberation Sans" || f.ContentType() != "font/otf" { |
| + t.Errorf("CFF: %+v (content type %q)", f, f.ContentType()) |
| + } |
| + |
| + v := mustInspect(t, variable(t, axis{"wdth", 75, 100, 100}, axis{"wght", 100, 400, 900})) |
| + if !v.Variable || v.Weight != 400 || v.WeightMin != 100 || v.WeightMax != 900 { |
| + t.Errorf("variable: Variable %v, Weight %d, range %d..%d; want true, 400, 100..900", |
| + v.Variable, v.Weight, v.WeightMin, v.WeightMax) |
| + } |
| + |
| + w := mustInspect(t, buildWOFF2(t, variable(t, axis{"wght", 100, 400, 900}))) |
| + if !w.Variable || w.WeightMin != 100 || w.WeightMax != 900 { |
| + t.Errorf("variable woff2: %+v", w) |
| + } |
| + |
| + s := mustInspect(t, variable(t, axis{"wdth", 75, 100, 100})) |
| + if !s.Variable || s.WeightMin != 400 || s.WeightMax != 400 { |
| + t.Errorf("fvar with no wght axis: %+v; want variable, weight range 400..400", s) |
| + } |
| +} |
| + |
| +func TestPicturesOnlyForStaticTrueTypeThatMayEmbed(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + data []byte |
| + want bool |
| + }{ |
| + {"ttf, installable", liberation(t), true}, |
| + {"preview and print", patched(t, 0x0004, 0), true}, |
| + {"editable", patched(t, 0x0008, 0), true}, |
| + {"editable, no subsetting", patched(t, 0x0108, 0), false}, |
| + {"installable, no subsetting", patched(t, 0x0100, 0), false}, |
| + {"restricted licence", patched(t, 0x0002, 0), false}, |
| + {"restricted with preview and print", patched(t, 0x0006, 0), false}, |
| + {"bitmap embedding only", patched(t, 0x0200, 0), false}, |
| + {"cff", cff(t), false}, |
| + {"variable", variable(t, axis{"wght", 100, 400, 900}), false}, |
| + {"variable in width only", variable(t, axis{"wdth", 75, 100, 100}), false}, |
| + {"woff", buildWOFF(t, liberation(t)), false}, |
| + {"woff2", buildWOFF2(t, liberation(t)), false}, |
| + } { |
| + f := mustInspect(t, c.data) |
| + if got := f.Pictures(); got != c.want { |
| + t.Errorf("%s: Pictures() = %v, want %v (%+v)", c.name, got, c.want, f) |
| + } |
| + } |
| + if f := mustInspect(t, patched(t, 0x0002, 0)); f.FSType != 0x0002 { |
| + t.Errorf("FSType = %#x, want 0x2", f.FSType) |
| + } |
| +} |
| + |
| +func TestHeaders(t *testing.T) { |
| + for format, ctype := range map[Format]string{"ttf": "font/ttf", "otf": "font/otf", "woff": "font/woff", "woff2": "font/woff2"} { |
| + w := httptest.NewRecorder() |
| + Headers(w, format) |
| + h := w.Header() |
| + for k, v := range map[string]string{ |
| + "Content-Type": ctype, |
| + "X-Content-Type-Options": "nosniff", |
| + "Cache-Control": "private, max-age=31536000, immutable", |
| + "Content-Security-Policy": "default-src 'none'", |
| + } { |
| + if h.Get(k) != v { |
| + t.Errorf("Headers(%s): %s = %q, want %q", format, k, h.Get(k), v) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestInspectRefuses(t *testing.T) { |
| + ttf := liberation(t) |
| + |
| + truncatedDir := ttf[:12+16*3] |
| + |
| + pastEnd := bytes.Clone(ttf) |
| + binary.BigEndian.PutUint32(pastEnd[12+16*4+12:], uint32(len(ttf))) // the fifth table's length |
| + |
| + tooBig := make([]byte, MaxBytes+1) |
| + copy(tooBig, ttf) |
| + |
| + flavor, es, stream := woff2Parts(t, ttf) |
| + good := brotliOf(stream) |
| + badStream := bytes.Clone(good) |
| + for i := 8; i < len(badStream) && i < 64; i++ { |
| + badStream[i] ^= 0xA5 |
| + } |
| + shortStream := assembleWOFF2(flavor, es, good[:len(good)/2]) |
| + longer := append([]woff2Entry(nil), es...) |
| + longer[0].origLength += 4096 // claims more than the stream holds |
| + extra := append([]woff2Entry(nil), es...) |
| + extra[0].origLength -= 4 // the stream holds more than the tables claim |
| + bomb := append([]woff2Entry(nil), es...) |
| + bomb[0].origLength = 4*MaxBytes + 1 |
| + transformedName := append([]woff2Entry(nil), es...) |
| + for i := range transformedName { |
| + if transformedName[i].tag == "name" { |
| + transformedName[i].version = 1 |
| + transformedName[i].transform = transformedName[i].origLength |
| + } |
| + } |
| + |
| + woff := buildWOFF(t, ttf) |
| + badZlib := bytes.Clone(woff) |
| + { |
| + // Corrupt the name table's compressed bytes. |
| + n := int(binary.BigEndian.Uint16(woff[12:])) |
| + for i := 0; i < n; i++ { |
| + rec := woff[44+20*i:] |
| + if string(rec[:4]) == "name" { |
| + off := binary.BigEndian.Uint32(rec[4:]) |
| + for j := off + 2; j < off+40; j++ { |
| + badZlib[j] ^= 0xA5 |
| + } |
| + } |
| + } |
| + } |
| + |
| + badGlyf := bytes.Clone(woff) |
| + { |
| + // Corrupt the glyf table's compressed bytes: a table Inspect |
| + // does not otherwise read. |
| + n := int(binary.BigEndian.Uint16(woff[12:])) |
| + for i := 0; i < n; i++ { |
| + rec := woff[44+20*i:] |
| + if string(rec[:4]) == "glyf" { |
| + off := binary.BigEndian.Uint32(rec[4:]) |
| + for j := off + 2; j < off+40; j++ { |
| + badGlyf[j] ^= 0xA5 |
| + } |
| + } |
| + } |
| + } |
| + |
| + v, ts := tablesOf(t, ttf) |
| + shortFvar := fvar(axis{"wght", 100, 400, 900}) |
| + binary.BigEndian.PutUint16(shortFvar[8:], 40) // 40 axes, room for one |
| + |
| + pngHeader := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00") |
| + |
| + for _, c := range []struct { |
| + name string |
| + data []byte |
| + want error |
| + }{ |
| + {"empty", nil, ErrNotAFont}, |
| + {"a PNG", pngHeader, ErrNotAFont}, |
| + {"a font collection", append([]byte("ttcf"), ttf[4:]...), ErrNotAFont}, |
| + {"a truncated table directory", truncatedDir, ErrMalformed}, |
| + {"a table past the end", pastEnd, ErrMalformed}, |
| + {"no tables", append(bytes.Clone(ttf[:4]), make([]byte, 8)...), ErrMalformed}, |
| + {"over MaxBytes", tooBig, ErrTooBig}, |
| + {"no OS/2", buildSFNT(v, withoutTable(ts, "OS/2")), ErrMalformed}, |
| + {"no name", buildSFNT(v, withoutTable(ts, "name")), ErrMalformed}, |
| + {"no family name", named(t, nameRec{3, 1, 0x409, 2, "Regular"}), ErrMalformed}, |
| + {"no outlines", buildSFNT(v, withoutTable(ts, "glyf", "loca")), ErrMalformed}, |
| + {"a TrueType without glyf", buildSFNT(v, withoutTable(ts, "glyf")), ErrMalformed}, |
| + {"a TrueType without loca", buildSFNT(v, withoutTable(ts, "loca")), ErrMalformed}, |
| + {"an OTTO without CFF", buildSFNT(0x4F54544F, withoutTable(ts, "glyf", "loca")), ErrMalformed}, |
| + {"an OTTO with glyf but no CFF", buildSFNT(0x4F54544F, ts), ErrMalformed}, |
| + {"an fvar shorter than its axes", buildSFNT(v, withTable(ts, "fvar", shortFvar)), ErrMalformed}, |
| + {"a truncated WOFF", woff[:len(woff)/2], ErrMalformed}, |
| + {"a WOFF whose zlib is bad", badZlib, ErrMalformed}, |
| + {"a WOFF whose glyf stream is corrupt", badGlyf, ErrMalformed}, |
| + {"a WOFF2 whose brotli stream is bad", assembleWOFF2(flavor, es, badStream), ErrMalformed}, |
| + {"a WOFF2 whose brotli stream is cut short", shortStream, ErrMalformed}, |
| + {"a WOFF2 table past the stream", assembleWOFF2(flavor, longer, good), ErrMalformed}, |
| + {"a WOFF2 stream longer than its tables", assembleWOFF2(flavor, extra, good), ErrMalformed}, |
| + {"a WOFF2 that unpacks too big", assembleWOFF2(flavor, bomb, good), ErrTooBig}, |
| + {"a WOFF2 with a transformed name table", assembleWOFF2(flavor, transformedName, good), ErrMalformed}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + f, err := Inspect(c.data) |
| + if !errors.Is(err, c.want) { |
| + t.Fatalf("Inspect = %+v, %v; want %v", f, err, c.want) |
| + } |
| + t.Log(err) |
| + }) |
| + } |
| +} |
diff --git a/typeface/woff.go b/typeface/woff.go| new file mode 100644 |
| index 0000000..d141bce |
| --- /dev/null |
| +++ b/typeface/woff.go |
| @@ -0,0 +1,264 @@ |
| +package typeface |
| + |
| +import ( |
| + "bytes" |
| + "compress/zlib" |
| + "encoding/binary" |
| + "fmt" |
| + "io" |
| + |
| + "github.com/andybalholm/brotli" |
| +) |
| + |
| +// WOFF and WOFF2 unwrapping, as far as Inspect needs it: the table |
| +// directory, and the bytes of the tables it reads. Neither rebuilds the |
| +// sfnt. |
| + |
| +// readWOFF reads a WOFF 1.0 file (zlib per table). Every table must lie |
| +// inside the file and inflate to exactly the length the directory gives |
| +// it (or be stored, when its packed and unpacked lengths are equal); only |
| +// the tables Inspect reads are kept. |
| +func readWOFF(data []byte) (fontTables, error) { |
| + const headerLen, entryLen = 44, 20 |
| + if len(data) < headerLen { |
| + return fontTables{}, malformed("WOFF header cut short") |
| + } |
| + flavor := binary.BigEndian.Uint32(data[4:]) |
| + if err := checkFlavor(flavor); err != nil { |
| + return fontTables{}, err |
| + } |
| + if int64(binary.BigEndian.Uint32(data[8:])) != int64(len(data)) { |
| + return fontTables{}, malformed("WOFF length is not the file's") |
| + } |
| + n := int(binary.BigEndian.Uint16(data[12:])) |
| + if n == 0 { |
| + return fontTables{}, malformed("no tables") |
| + } |
| + if headerLen+entryLen*n > len(data) { |
| + return fontTables{}, malformed("WOFF table directory cut short: %d tables", n) |
| + } |
| + ft := fontTables{version: flavor, has: map[string]bool{}, data: map[string][]byte{}} |
| + spans := make([]span, 0, n) |
| + for i := 0; i < n; i++ { |
| + e := data[headerLen+entryLen*i:] |
| + spans = append(spans, span{string(e[:4]), uint64(binary.BigEndian.Uint32(e[4:])), uint64(binary.BigEndian.Uint32(e[8:]))}) |
| + } |
| + for _, s := range spans { |
| + if s.off+s.length > uint64(len(data)) { |
| + return fontTables{}, malformed("table %q runs past the end of the file", s.tag) |
| + } |
| + } |
| + if err := disjoint(spans, uint64(headerLen+entryLen*n), uint64(len(data))); err != nil { |
| + return fontTables{}, err |
| + } |
| + var unpacked uint64 |
| + for i := 0; i < n; i++ { |
| + e := data[headerLen+entryLen*i:] |
| + tag := string(e[:4]) |
| + off := uint64(binary.BigEndian.Uint32(e[4:])) |
| + compLen := uint64(binary.BigEndian.Uint32(e[8:])) |
| + origLen := uint64(binary.BigEndian.Uint32(e[12:])) |
| + if off+compLen > uint64(len(data)) { |
| + return fontTables{}, malformed("table %q runs past the end of the file", tag) |
| + } |
| + if compLen > origLen { |
| + return fontTables{}, malformed("table %q is bigger packed than unpacked", tag) |
| + } |
| + if unpacked += origLen; unpacked > maxUnpacked { |
| + return fontTables{}, fmt.Errorf("%w: unpacks to over %d bytes", ErrTooBig, maxUnpacked) |
| + } |
| + if ft.has[tag] { |
| + return fontTables{}, malformed("table %q appears twice", tag) |
| + } |
| + ft.has[tag] = true |
| + packed := data[off : off+compLen] |
| + if compLen == origLen { |
| + if wanted(tag) { |
| + ft.data[tag] = packed // stored, not compressed |
| + } |
| + continue |
| + } |
| + b, err := inflate(packed, int(origLen), wanted(tag)) |
| + if err != nil { |
| + return fontTables{}, malformed("table %q: %v", tag, err) |
| + } |
| + if wanted(tag) { |
| + ft.data[tag] = b |
| + } |
| + } |
| + return ft, nil |
| +} |
| + |
| +// inflate unpacks a zlib stream that must hold exactly n bytes, returning |
| +// them if keep is set and otherwise only checking them. |
| +func inflate(packed []byte, n int, keep bool) ([]byte, error) { |
| + r, err := zlib.NewReader(bytes.NewReader(packed)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer r.Close() |
| + if keep { |
| + return readExactly(r, n) |
| + } |
| + got, err := io.Copy(io.Discard, io.LimitReader(r, int64(n)+1)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if got != int64(n) { |
| + return nil, fmt.Errorf("unpacks to %d bytes, not %d", got, n) |
| + } |
| + return nil, nil |
| +} |
| + |
| +// readExactly reads n bytes from r and checks that r then ends cleanly. |
| +// It reads no more than n+1 bytes whatever r holds. |
| +func readExactly(r io.Reader, n int) ([]byte, error) { |
| + b, err := io.ReadAll(io.LimitReader(r, int64(n)+1)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(b) > n { |
| + return nil, fmt.Errorf("unpacks to more than the %d bytes its tables hold", n) |
| + } |
| + if len(b) < n { |
| + return nil, fmt.Errorf("unpacks to %d bytes, not %d", len(b), n) |
| + } |
| + return b, nil |
| +} |
| + |
| +// woff2Tags is WOFF2's known-tag table: a directory entry's flags name a |
| +// tag by its index here, or 63 for a tag written out in full. |
| +var woff2Tags = [63]string{ |
| + "cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", |
| + "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", "VORG", "EBDT", |
| + "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", |
| + "vmtx", "BASE", "GDEF", "GPOS", "GSUB", "EBSC", "JSTF", "MATH", |
| + "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", |
| + "bdat", "bloc", "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", |
| + "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop", |
| + "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill", |
| +} |
| + |
| +// readWOFF2 reads a WOFF2 file: the table directory, then the one brotli |
| +// stream holding every table end to end. The stream must unpack to |
| +// exactly the tables' total length, and that total may not pass |
| +// maxUnpacked. Only glyf, loca and hmtx may be transformed; their |
| +// transformed bytes are not rebuilt, so the outline checks skip them. Any |
| +// other table Inspect reads that says it is transformed is refused, |
| +// since its bytes are not the table. |
| +func readWOFF2(data []byte) (fontTables, error) { |
| + const headerLen = 48 |
| + if len(data) < headerLen { |
| + return fontTables{}, malformed("WOFF2 header cut short") |
| + } |
| + flavor := binary.BigEndian.Uint32(data[4:]) |
| + if err := checkFlavor(flavor); err != nil { |
| + return fontTables{}, err |
| + } |
| + if int64(binary.BigEndian.Uint32(data[8:])) != int64(len(data)) { |
| + return fontTables{}, malformed("WOFF2 length is not the file's") |
| + } |
| + n := int(binary.BigEndian.Uint16(data[12:])) |
| + if n == 0 { |
| + return fontTables{}, malformed("no tables") |
| + } |
| + compressedLen := uint64(binary.BigEndian.Uint32(data[20:])) |
| + |
| + type entry struct { |
| + tag string |
| + off, size uint64 // in the unpacked stream |
| + } |
| + entries := make([]entry, 0, n) |
| + has, transforms := map[string]bool{}, map[string]bool{} |
| + p := data[headerLen:] |
| + var total uint64 |
| + for i := 0; i < n; i++ { |
| + if len(p) < 1 { |
| + return fontTables{}, malformed("WOFF2 table directory cut short") |
| + } |
| + flags := p[0] |
| + p = p[1:] |
| + var tag string |
| + if idx := flags & 0x3F; idx == 63 { |
| + if len(p) < 4 { |
| + return fontTables{}, malformed("WOFF2 table directory cut short") |
| + } |
| + tag, p = string(p[:4]), p[4:] |
| + } else { |
| + tag = woff2Tags[idx] |
| + } |
| + origLen, rest, err := base128(p) |
| + if err != nil { |
| + return fontTables{}, err |
| + } |
| + p = rest |
| + size := uint64(origLen) |
| + version := flags >> 6 |
| + transformed := version != 0 |
| + if tag == "glyf" || tag == "loca" { |
| + transformed = version != 3 |
| + } |
| + if transformed { |
| + transformLen, rest, err := base128(p) |
| + if err != nil { |
| + return fontTables{}, err |
| + } |
| + p, size = rest, uint64(transformLen) |
| + switch { |
| + case tag == "glyf" || tag == "loca" || tag == "hmtx": |
| + transforms[tag] = true // not rebuilt, so not checked |
| + case wanted(tag): |
| + return fontTables{}, malformed("table %q is transformed", tag) |
| + } |
| + } |
| + if uint64(origLen) > maxUnpacked { |
| + return fontTables{}, fmt.Errorf("%w: table %q unpacks to %d bytes", ErrTooBig, tag, origLen) |
| + } |
| + if has[tag] { |
| + return fontTables{}, malformed("table %q appears twice", tag) |
| + } |
| + has[tag] = true |
| + entries = append(entries, entry{tag, total, size}) |
| + if total += size; total > maxUnpacked { |
| + return fontTables{}, fmt.Errorf("%w: unpacks to over %d bytes", ErrTooBig, maxUnpacked) |
| + } |
| + } |
| + start := uint64(len(data) - len(p)) |
| + if start+compressedLen > uint64(len(data)) { |
| + return fontTables{}, malformed("WOFF2 stream runs past the end of the file") |
| + } |
| + stream, err := readExactly(brotli.NewReader(bytes.NewReader(data[start:start+compressedLen])), int(total)) |
| + if err != nil { |
| + return fontTables{}, malformed("WOFF2 stream: %v", err) |
| + } |
| + ft := fontTables{version: flavor, has: has, data: map[string][]byte{}, transformed: transforms} |
| + for _, e := range entries { |
| + if wanted(e.tag) && !transforms[e.tag] { |
| + ft.data[e.tag] = stream[e.off : e.off+e.size] |
| + } |
| + } |
| + return ft, nil |
| +} |
| + |
| +// base128 reads WOFF2's UIntBase128: at most five bytes, no leading zero |
| +// byte, and a value that fits 32 bits. |
| +func base128(p []byte) (uint32, []byte, error) { |
| + var v uint32 |
| + for i := 0; i < 5; i++ { |
| + if i >= len(p) { |
| + return 0, nil, malformed("WOFF2 table directory cut short") |
| + } |
| + b := p[i] |
| + if i == 0 && b == 0x80 { |
| + return 0, nil, malformed("UIntBase128 with a leading zero") |
| + } |
| + if v&0xFE000000 != 0 { |
| + return 0, nil, malformed("UIntBase128 past 32 bits") |
| + } |
| + v = v<<7 | uint32(b&0x7F) |
| + if b&0x80 == 0 { |
| + return v, p[i+1:], nil |
| + } |
| + } |
| + return 0, nil, malformed("UIntBase128 longer than five bytes") |
| +} |