sfnt.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package fonts
  2. /*
  3. sfnt.go
  4. Reads the table directory of an OpenType / TrueType font (an "sfnt") and
  5. writes one back. Fonts reach this package from users, so every offset is
  6. checked against the data before it is used: nothing here trusts a length
  7. field, and nothing panics on a short or hostile file.
  8. */
  9. import (
  10. "encoding/binary"
  11. "errors"
  12. "fmt"
  13. "math"
  14. "sort"
  15. )
  16. const (
  17. flavorTrueType = 0x00010000
  18. flavorTrue = 0x74727565 // 'true', old Apple TrueType
  19. flavorCFF = 0x4F54544F // 'OTTO', CFF outlines
  20. tagCollection = 0x74746366 // 'ttcf'
  21. sigWOFF = 0x774F4646 // 'wOFF'
  22. sigWOFF2 = 0x774F4632 // 'wOF2'
  23. maxTables = 256
  24. // headMagic is the magicNumber field of every valid head table
  25. headMagic = 0x5F0F3CF5
  26. )
  27. var (
  28. errTruncated = errors.New("the font data is truncated or an offset points outside it")
  29. errCollection = errors.New("font collections (.ttc) are not supported, upload the single fonts instead")
  30. errNotFont = errors.New("this is not a TrueType, OpenType, WOFF or WOFF2 font")
  31. errNoOutline = errors.New("the font has no glyph outlines (glyf, CFF or CFF2 table)")
  32. errMissingName = errors.New("the font does not name its family")
  33. )
  34. // Font is a parsed sfnt: its flavor and its tables by tag.
  35. type Font struct {
  36. Flavor uint32
  37. Tables map[string][]byte
  38. // Transformed lists tables a WOFF2 file stores transformed: the font has
  39. // them, but their bytes are not available here.
  40. Transformed map[string]bool
  41. }
  42. // Table returns the bytes of a table, nil when the font has no such table
  43. func (f *Font) Table(tag string) []byte {
  44. return f.Tables[tag]
  45. }
  46. // Has reports whether the font has a table, transformed or not
  47. func (f *Font) Has(tag string) bool {
  48. _, ok := f.Tables[tag]
  49. return ok || f.Transformed[tag]
  50. }
  51. // IsCFF reports whether the outlines are PostScript (CFF / CFF2) ones
  52. func (f *Font) IsCFF() bool {
  53. return f.Flavor == flavorCFF || f.Has("CFF ") || f.Has("CFF2")
  54. }
  55. /* ── Bounds checked readers ── */
  56. func u16(b []byte, off int) (uint16, error) {
  57. if off < 0 || off > len(b)-2 {
  58. return 0, errTruncated
  59. }
  60. return binary.BigEndian.Uint16(b[off:]), nil
  61. }
  62. func u32(b []byte, off int) (uint32, error) {
  63. if off < 0 || off > len(b)-4 {
  64. return 0, errTruncated
  65. }
  66. return binary.BigEndian.Uint32(b[off:]), nil
  67. }
  68. // sub returns b[off:off+n] when the whole range lies inside b
  69. func sub(b []byte, off int64, n int64) ([]byte, error) {
  70. if off < 0 || n < 0 || off > int64(len(b)) || n > int64(len(b))-off {
  71. return nil, errTruncated
  72. }
  73. return b[off : off+n], nil
  74. }
  75. // tagString turns a 4 byte tag into its string, refusing unprintable bytes
  76. func tagString(b []byte) (string, error) {
  77. if len(b) < 4 {
  78. return "", errTruncated
  79. }
  80. for _, c := range b[:4] {
  81. if c < 0x20 || c > 0x7E {
  82. return "", fmt.Errorf("invalid table tag %q", b[:4])
  83. }
  84. }
  85. return string(b[:4]), nil
  86. }
  87. // sniff returns the signature of a font file: an sfnt flavor or a WOFF one
  88. func sniff(data []byte) (uint32, error) {
  89. sig, err := u32(data, 0)
  90. if err != nil {
  91. return 0, errNotFont
  92. }
  93. switch sig {
  94. case flavorTrueType, flavorTrue, flavorCFF, sigWOFF, sigWOFF2:
  95. return sig, nil
  96. case tagCollection:
  97. return 0, errCollection
  98. }
  99. return 0, errNotFont
  100. }
  101. // ParseSFNT reads the table directory of an uncompressed font. The returned
  102. // tables share data with the given slice.
  103. func ParseSFNT(data []byte) (*Font, error) {
  104. flavor, err := sniff(data)
  105. if err != nil {
  106. return nil, err
  107. }
  108. if flavor == sigWOFF || flavor == sigWOFF2 {
  109. return nil, errors.New("expected an uncompressed font, got WOFF")
  110. }
  111. numTables, err := u16(data, 4)
  112. if err != nil {
  113. return nil, err
  114. }
  115. if numTables == 0 || numTables > maxTables {
  116. return nil, fmt.Errorf("the font lists %d tables", numTables)
  117. }
  118. if 12+16*int(numTables) > len(data) {
  119. return nil, errTruncated
  120. }
  121. font := &Font{Flavor: flavor, Tables: map[string][]byte{}}
  122. for i := 0; i < int(numTables); i++ {
  123. rec := data[12+16*i : 12+16*i+16]
  124. tag, err := tagString(rec)
  125. if err != nil {
  126. return nil, err
  127. }
  128. if _, dup := font.Tables[tag]; dup {
  129. return nil, fmt.Errorf("the font has two %q tables", tag)
  130. }
  131. offset := binary.BigEndian.Uint32(rec[8:])
  132. length := binary.BigEndian.Uint32(rec[12:])
  133. table, err := sub(data, int64(offset), int64(length))
  134. if err != nil {
  135. return nil, fmt.Errorf("table %q: %w", tag, err)
  136. }
  137. font.Tables[tag] = table
  138. }
  139. return font, nil
  140. }
  141. // Decode reads any supported font file (TTF, OTF, WOFF, WOFF2). It returns
  142. // the parsed font and the container it came in: "sfnt", "woff" or "woff2".
  143. func Decode(data []byte) (*Font, string, error) {
  144. sig, err := sniff(data)
  145. if err != nil {
  146. return nil, "", err
  147. }
  148. switch sig {
  149. case sigWOFF:
  150. font, err := decodeWOFF(data)
  151. return font, "woff", err
  152. case sigWOFF2:
  153. font, err := decodeWOFF2(data)
  154. return font, "woff2", err
  155. }
  156. font, err := ParseSFNT(data)
  157. return font, "sfnt", err
  158. }
  159. /* ── Writing ── */
  160. func checksum(b []byte) uint32 {
  161. var sum uint32
  162. for i := 0; i < len(b); i += 4 {
  163. var word [4]byte
  164. copy(word[:], b[i:])
  165. sum += binary.BigEndian.Uint32(word[:])
  166. }
  167. return sum
  168. }
  169. func pad4(n int) int {
  170. return (n + 3) &^ 3
  171. }
  172. // sortedTags returns the table tags in the order an sfnt stores them
  173. func sortedTags(tables map[string][]byte) []string {
  174. tags := make([]string, 0, len(tables))
  175. for tag := range tables {
  176. tags = append(tags, tag)
  177. }
  178. sort.Strings(tags)
  179. return tags
  180. }
  181. // sfntSize is the size of the sfnt AssembleSFNT builds from these tables
  182. func sfntSize(tables map[string][]byte) int {
  183. size := 12 + 16*len(tables)
  184. for _, t := range tables {
  185. size += pad4(len(t))
  186. }
  187. return size
  188. }
  189. // AssembleSFNT writes a font file from its tables and fills in the checksums,
  190. // including the head table's checkSumAdjustment. The tables map is updated
  191. // with the head table carrying that adjustment.
  192. func AssembleSFNT(flavor uint32, tables map[string][]byte) ([]byte, error) {
  193. if len(tables) == 0 || len(tables) > maxTables {
  194. return nil, fmt.Errorf("cannot write a font with %d tables", len(tables))
  195. }
  196. if head, ok := tables["head"]; ok {
  197. if len(head) < 54 {
  198. return nil, errors.New("the head table is too short")
  199. }
  200. head = append([]byte(nil), head...)
  201. binary.BigEndian.PutUint32(head[8:], 0)
  202. tables["head"] = head
  203. }
  204. tags := sortedTags(tables)
  205. n := len(tags)
  206. out := make([]byte, 12+16*n, sfntSize(tables))
  207. binary.BigEndian.PutUint32(out[0:], flavor)
  208. binary.BigEndian.PutUint16(out[4:], uint16(n))
  209. entrySelector := uint16(math.Floor(math.Log2(float64(n))))
  210. searchRange := uint16(16 << entrySelector)
  211. binary.BigEndian.PutUint16(out[6:], searchRange)
  212. binary.BigEndian.PutUint16(out[8:], entrySelector)
  213. binary.BigEndian.PutUint16(out[10:], uint16(16*n)-searchRange)
  214. headOffset := -1
  215. for i, tag := range tags {
  216. t := tables[tag]
  217. rec := out[12+16*i:]
  218. copy(rec, tag)
  219. binary.BigEndian.PutUint32(rec[4:], checksum(t))
  220. binary.BigEndian.PutUint32(rec[8:], uint32(len(out)))
  221. binary.BigEndian.PutUint32(rec[12:], uint32(len(t)))
  222. if tag == "head" {
  223. headOffset = len(out)
  224. }
  225. out = append(out, t...)
  226. out = append(out, make([]byte, pad4(len(t))-len(t))...)
  227. }
  228. if headOffset >= 0 {
  229. binary.BigEndian.PutUint32(out[headOffset+8:], 0xB1B0AFBA-checksum(out))
  230. tables["head"] = out[headOffset : headOffset+len(tables["head"])]
  231. }
  232. return out, nil
  233. }