/
validator.py
2743 lines (2524 loc) · 85.5 KB
/
validator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
"""
A module for validating the the file structure of WOFF Files.
*validateFont* is the only public function.
This can also be used as a command line tool for validating WOFF files.
"""
# import
from __future__ import division, print_function
import os
import re
import time
import sys
import struct
import zlib
import optparse
import codecs
from io import BytesIO
from xml.etree import ElementTree
from xml.parsers.expat import ExpatError
try:
basestring
except NameError:
basestring = str
# ----------------------
# Support: Metadata Spec
# ----------------------
"""
The Extended Metadata specifications are defined as a set of
nested Python objects. This allows for a very simple XML
validation procedure. The common element structure is as follows:
{
# ----------
# Attributes
# ----------
# In all cases, the dictionary has the attribute name at the top
# with the possible value(s) as the value. If an attribute has
# more than one representation (for exmaple xml:lang and lang)
# the two are specified as a space separated string for example
# "xml:lang lang".
# Required
"requiredAttributes" : {
# empty or one or more of the following
"name" : "default as string, list of options or None"
},
# Recommended
"recommendedAttributes" : {
# empty or one or more of the following
"name" : "default as string, list of options or None"
},
# Optional
"optionalAttributes" : {
# empty or one or more of the following
"name" : "default as string, list of options or None"
},
# -------
# Content
# -------
"contentLevel" : "not allowed", "recommended" or "required",
# --------------
# Child Elements
# --------------
# In all cases, the dictionary has the element name at the top
# with a dictionary as the value. The value dictionary defines
# the number of times the shild-element may occur along with
# the specification for the child-element.
# Required
"requiredChildElements" : {
# empty or one or more of the following
"name" : {
"minimumOccurrences" : int or None,
"maximumOccurrences" : int or None,
"spec" : {}
}
},
# Recommended
"recommendedChildElements" : {
# empty or one or more of the following
"name" : {
# minimumOccurrences is implicitly 0
"maximumOccurrences" : int or None,
"spec" : {}
}
},
# Optional
"optionalChildElements" : {
# empty or one or more of the following
"name" : {
# minimumOccurrences is implicitly 0
"maximumOccurrences" : int or None,
"spec" : {}
}
}
}
The recommendedAttributes and recommendedChildElements are optional
but they are separated from the optionalAttributes and optionalChildElements
to allow for more detailed reporting.
"""
# Metadata 1.0
# ------------
# Common Options
dirOptions_1_0 = ["ltr", "rtl"]
# Fourth-Level Elements
divSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {
"dir" : dirOptions_1_0,
"class" : None
},
"content" : "recommended",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {
"div" : {
"maximumOccurrences" : None,
"spec" : "recursive divSpec_1_0" # special override for recursion.
},
"span" : {
"maximumOccurrences" : None,
"spec" : "recursive spanSpec_1_0" # special override for recursion.
}
}
}
spanSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {
"dir" : dirOptions_1_0,
"class" : None
},
"content" : "recommended",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {
"div" : {
"maximumOccurrences" : None,
"spec" : "recursive divSpec_1_0" # special override for recursion.
},
"span" : {
"maximumOccurrences" : None,
"spec" : "recursive spanSpec_1_0" # special override for recursion.
}
}
}
# Third-Level Elements
creditSpec_1_0 = {
"requiredAttributes" : {
"name" : None
},
"recommendedAttributes" : {},
"optionalAttributes" : {
"url" : None,
"role" : None,
"dir" : dirOptions_1_0,
"class" : None
},
"content" : "not allowed",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
textSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {
"url" : None,
"role" : None,
"dir" : dirOptions_1_0,
"class" : None,
"xml:lang lang" : None
},
"content" : "recommended",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {
"div" : {
"maximumOccurrences" : None,
"spec" : divSpec_1_0
},
"span" : {
"maximumOccurrences" : None,
"spec" : spanSpec_1_0
}
}
}
extensionNameSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {
"dir" : dirOptions_1_0,
"class" : None,
"xml:lang lang" : None
},
"content" : "recommended",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
extensionValueSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {
"dir" : dirOptions_1_0,
"class" : None,
"xml:lang lang" : None
},
"content" : "recommended",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
extensionItemSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {
"id" : None
},
"content" : "not allowed",
"requiredChildElements" : {
"name" : {
"minimumOccurrences" : 1,
"maximumOccurrences" : None,
"spec" : extensionNameSpec_1_0
},
"value" : {
"minimumOccurrences" : 1,
"maximumOccurrences" : None,
"spec" : extensionValueSpec_1_0
}
},
"recommendedChildElements" : {
},
"optionalChildElements" : {}
}
# Second Level Elements
uniqueidSpec_1_0 = {
"requiredAttributes" : {
"id" : None
},
"recommendedAttributes" : {},
"optionalAttributes" : {},
"content" : "not allowed",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
vendorSpec_1_0 = {
"requiredAttributes" : {
"name" : None
},
"recommendedAttributes" : {},
"optionalAttributes" : {
"url" : None,
"dir" : dirOptions_1_0,
"class" : None
},
"content" : "not allowed",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
creditsSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {},
"content" : "not allowed",
"requiredChildElements" : {
"credit" : {
"minimumOccurrences" : 1,
"maximumOccurrences" : None,
"spec" : creditSpec_1_0
}
},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
descriptionSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {
"url" : None,
},
"content" : "not allowed",
"requiredChildElements" : {
"text" : {
"minimumOccurrences" : 1,
"maximumOccurrences" : None,
"spec" : textSpec_1_0
}
},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
licenseSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {
"url" : None,
"id" : None
},
"content" : "not allowed",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {
"text" : {
"maximumOccurrences" : None,
"spec" : textSpec_1_0
}
}
}
copyrightSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {},
"content" : "not allowed",
"requiredChildElements" : {
"text" : {
"minimumOccurrences" : 1,
"maximumOccurrences" : None,
"spec" : textSpec_1_0
}
},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
trademarkSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {},
"content" : "not allowed",
"requiredChildElements" : {
"text" : {
"minimumOccurrences" : 1,
"maximumOccurrences" : None,
"spec" : textSpec_1_0
}
},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
licenseeSpec_1_0 = {
"requiredAttributes" : {
"name" : None,
},
"recommendedAttributes" : {},
"optionalAttributes" : {
"dir" : dirOptions_1_0,
"class" : None
},
"content" : "not allowed",
"requiredChildElements" : {},
"recommendedChildElements" : {},
"optionalChildElements" : {}
}
extensionSpec_1_0 = {
"requiredAttributes" : {},
"recommendedAttributes" : {},
"optionalAttributes" : {
"id" : None
},
"content" : "not allowed",
"requiredChildElements" : {
"item" : {
"minimumOccurrences" : 1,
"maximumOccurrences" : None,
"spec" : extensionItemSpec_1_0
}
},
"recommendedChildElements" : {},
"optionalChildElements" : {
"name" : {
"maximumOccurrences" : None,
"spec" : extensionNameSpec_1_0
}
}
}
# First Level Elements
metadataSpec_1_0 = {
"requiredAttributes" : {
"version" : "1.0"
},
"recommendedAttributes" : {},
"optionalAttributes" : {},
"content" : "not allowed",
"requiredChildElements" : {},
"recommendedChildElements" : {
"uniqueid" : {
"maximumOccurrences" : 1,
"spec" : uniqueidSpec_1_0
}
},
"optionalChildElements" : {
"vendor" : {
"maximumOccurrences" : 1,
"spec" : vendorSpec_1_0
},
"credits" : {
"maximumOccurrences" : 1,
"spec" : creditsSpec_1_0
},
"description" : {
"maximumOccurrences" : 1,
"spec" : descriptionSpec_1_0
},
"license" : {
"maximumOccurrences" : 1,
"spec" : licenseSpec_1_0
},
"copyright" : {
"maximumOccurrences" : 1,
"spec" : copyrightSpec_1_0
},
"trademark" : {
"maximumOccurrences" : 1,
"spec" : trademarkSpec_1_0
},
"licensee" : {
"maximumOccurrences" : 1,
"spec" : licenseeSpec_1_0
},
"extension" : {
"maximumOccurrences" : None,
"spec" : extensionSpec_1_0
}
}
}
# ----------------------
# Support: struct Helper
# ----------------------
# This was inspired by Just van Rossum's sstruct module.
# http://fonttools.svn.sourceforge.net/svnroot/fonttools/trunk/Lib/sstruct.py
def structPack(format, obj):
keys, formatString = _structGetFormat(format)
values = []
for key in keys:
values.append(obj[key])
data = struct.pack(formatString, *values)
return data
def structUnpack(format, data):
keys, formatString = _structGetFormat(format)
size = struct.calcsize(formatString)
values = struct.unpack(formatString, data[:size])
unpacked = {}
for index, key in enumerate(keys):
value = values[index]
unpacked[key] = value
return unpacked, data[size:]
def structCalcSize(format):
keys, formatString = _structGetFormat(format)
return struct.calcsize(formatString)
_structFormatCache = {}
def _structGetFormat(format):
if format not in _structFormatCache:
keys = []
formatString = [">"] # always big endian
for line in format.strip().splitlines():
line = line.split("#", 1)[0].strip()
if not line:
continue
key, formatCharacter = line.split(":")
key = key.strip()
formatCharacter = formatCharacter.strip()
keys.append(key)
formatString.append(formatCharacter)
_structFormatCache[format] = (keys, "".join(formatString))
return _structFormatCache[format]
# -------------
# Tests: Header
# -------------
def testHeader(data, reporter):
"""
Test the WOFF header.
"""
functions = [
_testHeaderSignature,
_testHeaderFlavor,
_testHeaderLength,
_testHeaderReserved,
_testHeaderTotalSFNTSize,
_testHeaderNumTables
]
nonStoppingError = False
for function in functions:
stoppingError, nsError = function(data, reporter)
if nsError:
nonStoppingError = True
if stoppingError:
return True, nonStoppingError
return False, nonStoppingError
headerFormat = """
signature: 4s
flavor: 4s
length: L
numTables: H
reserved: H
totalSfntSize: L
majorVersion: H
minorVersion: H
metaOffset: L
metaLength: L
metaOrigLength: L
privOffset: L
privLength: L
"""
headerSize = structCalcSize(headerFormat)
def _testHeaderStructure(data, reporter):
"""
Tests:
- Header must be the proper structure.
"""
try:
structUnpack(headerFormat, data)
reporter.logPass(message="The header structure is correct.")
except:
reporter.logError(message="The header is not properly structured.")
return True, False
return False, False
def _testHeaderSignature(data, reporter):
"""
Tests:
- The signature must be "wOFF".
"""
header = unpackHeader(data)
signature = header["signature"].decode()
if signature != "wOFF":
reporter.logError(message="Invalid signature: %s." % signature)
return True, False
else:
reporter.logPass(message="The signature is correct.")
return False, False
def _testHeaderFlavor(data, reporter):
"""
Tests:
- The flavor should be OTTO, 0x00010000 or true. Warn if another value is found.
- If the flavor is OTTO, the CFF table must be present.
- If the flavor is not OTTO, the CFF must not be present.
- If the directory cannot be unpacked, the flavor can not be validated. Issue a warning.
"""
header = unpackHeader(data)
flavor = header["flavor"].decode()
if flavor not in ("OTTO", "\000\001\000\000", "true"):
reporter.logWarning(message="Unknown flavor: %s." % flavor)
else:
try:
tags = [table["tag"] for table in unpackDirectory(data)]
if "CFF " in tags and flavor != "OTTO":
reporter.logError(message="A \"CFF\" table is defined in the font and the flavor is not set to \"OTTO\".")
return False, True
elif "CFF " not in tags and flavor == "OTTO":
reporter.logError(message="The flavor is set to \"OTTO\" but no \"CFF\" table is defined.")
return False, True
else:
reporter.logPass(message="The flavor is a correct value.")
except:
reporter.logWarning(message="Could not validate the flavor.")
return False, False
def _testHeaderLength(data, reporter):
"""
Tests:
- The length of the data must match the defined length.
- The length of the data must be long enough for header and directory for defined number of tables.
- The length of the data must be long enough to contain the table lengths defined in the directory,
the metaLength and the privLength.
"""
header = unpackHeader(data)
length = header["length"]
numTables = header["numTables"]
minLength = headerSize + (directorySize * numTables)
if length != len(data):
reporter.logError(message="Defined length (%d) does not match actual length of the data (%d)." % (length, len(data)))
return False, True
if length < minLength:
reporter.logError(message="Invalid length defined (%d) for number of tables defined." % length)
return False, True
directory = unpackDirectory(data)
for entry in directory:
compLength = entry["compLength"]
if compLength % 4:
compLength += 4 - (compLength % 4)
minLength += compLength
metaLength = privLength = 0
if header["metaOffset"]:
metaLength = header["metaLength"]
if header["privOffset"]:
privLength = header["privLength"]
if privLength and metaLength % 4:
metaLength += 4 - (metaLength % 4)
minLength += metaLength + privLength
if length < minLength:
reporter.logError(message="Defined length (%d) does not match the required length of the data (%d)." % (length, minLength))
return False, True
reporter.logPass(message="The length defined in the header is correct.")
return False, False
def _testHeaderReserved(data, reporter):
"""
Tests:
- The reserved bit must be set to 0.
"""
header = unpackHeader(data)
reserved = header["reserved"]
if reserved != 0:
reporter.logError(message="Invalid value in reserved field (%d)." % reserved)
return False, True
else:
reporter.logPass(message="The value in the reserved field is correct.")
return False, False
def _testHeaderTotalSFNTSize(data, reporter):
"""
Tests:
- The size of the unpacked SFNT data must be a multiple of 4.
- The origLength values in the directory, with proper padding, must sum
to the totalSfntSize in the header.
"""
header = unpackHeader(data)
directory = unpackDirectory(data)
totalSfntSize = header["totalSfntSize"]
isValid = True
if totalSfntSize % 4:
reporter.logError(message="The total sfnt size (%d) is not a multiple of four." % totalSfntSize)
isValid = False
else:
numTables = header["numTables"]
requiredSize = sfntHeaderSize + (numTables * sfntDirectoryEntrySize)
for table in directory:
origLength = table["origLength"]
if origLength % 4:
origLength += 4 - (origLength % 4)
requiredSize += origLength
if totalSfntSize != requiredSize:
reporter.logError(message="The total sfnt size (%d) does not match the required sfnt size (%d)." % (totalSfntSize, requiredSize))
isValid = False
if isValid:
reporter.logPass(message="The total sfnt size is valid.")
return False, not isValid
def _testHeaderNumTables(data, reporter):
"""
Tests:
- The number of tables must be at least 1.
- The directory entries for the specified number of tables must be properly formatted.
"""
header = unpackHeader(data)
numTables = header["numTables"]
if numTables < 1:
reporter.logError(message="Invalid number of tables defined in header structure (%d)." % numTables)
return False, True
data = data[headerSize:]
for index in range(numTables):
try:
d, data = structUnpack(directoryFormat, data)
except:
reporter.logError(message="The defined number of tables in the header (%d) does not match the actual number of tables (%d)." % (numTables, index))
return False, True
reporter.logPass(message="The number of tables defined in the header is valid.")
return False, False
# -------------
# Tests: Tables
# -------------
def testDataBlocks(data, reporter):
"""
Test the WOFF data blocks.
"""
functions = [
_testBlocksOffsetLengthZero,
_testBlocksPositioning
]
nonStoppingError = False
for function in functions:
stoppingError, nsError = function(data, reporter)
if nsError:
nonStoppingError = True
if stoppingError:
return True, nonStoppingError
return False, nonStoppingError
def _testBlocksOffsetLengthZero(data, reporter):
"""
- The metadata must have the offset and length set to zero consistently.
- The private data must have the offset and length set to zero consistently.
"""
header = unpackHeader(data)
haveError = False
# metadata
metaOffset = header["metaOffset"]
metaLength = header["metaLength"]
if metaOffset == 0 or metaLength == 0:
if metaOffset == 0 and metaLength == 0:
reporter.logPass(message="The length and offset are appropriately set for empty metadata.")
else:
reporter.logError(message="The metadata offset (%d) and metadata length (%d) are not properly set. If one is 0, they both must be 0." % (metaOffset, metaLength))
haveError = True
# private data
privOffset = header["privOffset"]
privLength = header["privLength"]
if privOffset == 0 or privLength == 0:
if privOffset == 0 and privLength == 0:
reporter.logPass(message="The length and offset are appropriately set for empty private data.")
else:
reporter.logError(message="The private data offset (%d) and private data length (%d) are not properly set. If one is 0, they both must be 0." % (privOffset, privLength))
haveError = True
return False, haveError
def _testBlocksPositioning(data, reporter):
"""
Tests:
- The table data must start immediately after the directory.
- The table data must end at the beginning of the metadata, the beginning of the private data or the end of the file.
- The metadata must start immediately after the table data.
- the metadata must end at the beginning of he private data (padded as needed) or the end of the file.
- The private data must start immediately after the table data or metadata.
- The private data must end at the edge of the file.
"""
header = unpackHeader(data)
haveError = False
# table data start
directory = unpackDirectory(data)
if not directory:
return False, False
expectedTableDataStart = headerSize + (directorySize * header["numTables"])
offsets = [entry["offset"] for entry in directory]
tableDataStart = min(offsets)
if expectedTableDataStart != tableDataStart:
reporter.logError(message="The table data does not start (%d) in the required position (%d)." % (tableDataStart, expectedTableDataStart))
haveError = True
else:
reporter.logPass(message="The table data begins in the required position.")
# table data end
if header["metaOffset"]:
definedTableDataEnd = header["metaOffset"]
elif header["privOffset"]:
definedTableDataEnd = header["privOffset"]
else:
definedTableDataEnd = header["length"]
directory = unpackDirectory(data)
ends = [table["offset"] + table["compLength"] + calcPaddingLength(table["compLength"]) for table in directory]
expectedTableDataEnd = max(ends)
if expectedTableDataEnd != definedTableDataEnd:
reporter.logError(message="The table data end (%d) is not in the required position (%d)." % (definedTableDataEnd, expectedTableDataEnd))
haveError = True
else:
reporter.logPass(message="The table data ends in the required position.")
# metadata
if header["metaOffset"]:
# start
expectedMetaStart = expectedTableDataEnd
definedMetaStart = header["metaOffset"]
if expectedMetaStart != definedMetaStart:
reporter.logError(message="The metadata does not start (%d) in the required position (%d)." % (definedMetaStart, expectedMetaStart))
haveError = True
else:
reporter.logPass(message="The metadata begins in the required position.")
# end
if header["privOffset"]:
definedMetaEnd = header["privOffset"]
needMetaPadding = True
else:
definedMetaEnd = header["length"]
needMetaPadding = False
expectedMetaEnd = header["metaOffset"] + header["metaLength"]
if needMetaPadding:
expectedMetaEnd += calcPaddingLength(header["metaLength"])
if expectedMetaEnd != definedMetaEnd:
reporter.logError(message="The metadata end (%d) is not in the required position (%d)." % (definedMetaEnd, expectedMetaEnd))
haveError = True
else:
reporter.logPass(message="The metadata ends in the required position.")
# private data
if header["privOffset"]:
# start
if header["metaOffset"]:
expectedPrivateStart = expectedMetaEnd
else:
expectedPrivateStart = expectedTableDataEnd
definedPrivateStart = header["privOffset"]
if expectedPrivateStart != definedPrivateStart:
reporter.logError(message="The private data does not start (%d) in the required position (%d)." % (definedPrivateStart, expectedPrivateStart))
haveError = True
else:
reporter.logPass(message="The private data begins in the required position.")
# end
expectedPrivateEnd = header["length"]
definedPrivateEnd = header["privOffset"] + header["privLength"]
if expectedPrivateEnd != definedPrivateEnd:
reporter.logError(message="The private data end (%d) is not in the required position (%d)." % (definedPrivateEnd, expectedPrivateEnd))
haveError = True
else:
reporter.logPass(message="The private data ends in the required position.")
return False, haveError
# ----------------------
# Tests: Table Directory
# ----------------------
def testTableDirectory(data, reporter):
"""
Test the WOFF table directory.
"""
functions = [
_testTableDirectoryStructure,
_testTableDirectory4ByteOffsets,
_testTableDirectoryPadding,
_testTableDirectoryPositions,
_testTableDirectoryCompressedLength,
_testTableDirectoryDecompressedLength,
_testTableDirectoryChecksums,
_testTableDirectoryTableOrder
]
nonStoppingError = False
for function in functions:
stoppingError, nsError = function(data, reporter)
if nsError:
nonStoppingError = True
if stoppingError:
return True, nonStoppingError
return False, nonStoppingError
directoryFormat = """
tag: 4s
offset: L
compLength: L
origLength: L
origChecksum: L
"""
directorySize = structCalcSize(directoryFormat)
def _testTableDirectoryStructure(data, reporter):
"""
Tests:
- The entries in the table directory can be unpacked.
"""
header = unpackHeader(data)
numTables = header["numTables"]
data = data[headerSize:]
try:
for index in range(numTables):
table, data = structUnpack(directoryFormat, data)
reporter.logPass(message="The table directory structure is correct.")
except:
reporter.logError(message="The table directory is not properly structured.")
return True, False
return False, False
def _testTableDirectory4ByteOffsets(data, reporter):
"""
Tests:
- The font tables must each begin on a 4-byte boundary.
"""
directory = unpackDirectory(data)
haveError = False
for table in directory:
tag = table["tag"].decode()
offset = table["offset"]
if offset % 4:
reporter.logError(message="The \"%s\" table does not begin on a 4-byte boundary (%d)." % (tag, offset))
haveError = True
else:
reporter.logPass(message="The \"%s\" table begins on a 4-byte boundary." % tag)
return False, haveError
def _testTableDirectoryPadding(data, reporter):
"""
Tests:
- All tables, including the final table, must be padded to a
four byte boundary using null bytes as needed.
"""
header = unpackHeader(data)
directory = unpackDirectory(data)
haveError = False
# test final table
if header["metaOffset"] != 0:
sfntEnd = header["metaOffset"]
elif header["privOffset"] != 0:
sfntEnd = header["privOffset"]
else:
sfntEnd = header["length"]
if sfntEnd % 4:
reporter.logError(message="The sfnt data does not end with proper padding.")
haveError = True
else:
reporter.logPass(message="The sfnt data ends with proper padding.")
# test the bytes used for padding
for table in directory:
tag = table["tag"].decode()
offset = table["offset"]
length = table["compLength"]
paddingLength = calcPaddingLength(length)
if paddingLength:
paddingOffset = offset + length
padding = data[paddingOffset:paddingOffset+paddingLength]
expectedPadding = ("\0" * paddingLength).encode()
if padding != expectedPadding:
reporter.logError(message="The \"%s\" table is not padded with null bytes." % tag)
haveError = True
else:
reporter.logPass(message="The \"%s\" table is padded with null bytes." % tag)
return False, haveError
def _testTableDirectoryPositions(data, reporter):
"""
Tests:
- The table offsets must not be before the end of the header/directory.
- The table offset + length must not be greater than the edge of the available space.
- The table offsets must not be after the edge of the available space.
- Table blocks must not overlap.
- There must be no gaps between the tables.
"""
directory = unpackDirectory(data)
tablesWithProblems = set()
haveError = False
# test for overlapping tables
locations = []
for table in directory:
offset = table["offset"]
length = table["compLength"]
length = length + calcPaddingLength(length)
locations.append((offset, offset + length, table["tag"]))
for start, end, tag in locations:
for otherStart, otherEnd, otherTag in locations:
if tag == otherTag:
continue
if start >= otherStart and start < otherEnd:
reporter.logError(message="The \"%s\" table overlaps the \"%s\" table." % (tag, otherTag))
tablesWithProblems.add(tag)
tablesWithProblems.add(otherTag)
haveError = True
# test for invalid offset, length and combo
header = unpackHeader(data)
if header["metaOffset"] != 0:
tableDataEnd = header["metaOffset"]
elif header["privOffset"] != 0:
tableDataEnd = header["privOffset"]
else:
tableDataEnd = header["length"]
numTables = header["numTables"]
minOffset = headerSize + (directorySize * numTables)
for table in directory:
tag = table["tag"]
offset = table["offset"]