-
Notifications
You must be signed in to change notification settings - Fork 311
Expand file tree
/
Copy pathCoreTokenScanner.cs
More file actions
399 lines (336 loc) · 14.7 KB
/
CoreTokenScanner.cs
File metadata and controls
399 lines (336 loc) · 14.7 KB
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
namespace UglyToad.PdfPig.Tokenization.Scanner
{
using System;
using System.Collections.Generic;
using Core;
using Tokens;
/// <summary>
/// The default <see cref="ITokenScanner"/> for reading PostScript/PDF style data.
/// </summary>
public class CoreTokenScanner : ISeekableTokenScanner
{
private static readonly CommentTokenizer CommentTokenizer = new CommentTokenizer();
private static readonly HexTokenizer HexTokenizer = new HexTokenizer();
private static readonly NameTokenizer NameTokenizer = new NameTokenizer();
private static readonly PlainTokenizer PlainTokenizer = new PlainTokenizer();
private static readonly NumericTokenizer NumericTokenizer = new NumericTokenizer();
private readonly StringTokenizer stringTokenizer;
private readonly ArrayTokenizer arrayTokenizer;
private readonly DictionaryTokenizer dictionaryTokenizer;
private readonly ScannerScope scope;
private readonly IReadOnlyDictionary<NameToken, IReadOnlyList<NameToken>> namedDictionaryRequiredKeys;
private readonly IInputBytes inputBytes;
private readonly bool usePdfDocEncoding;
private readonly List<(byte firstByte, ITokenizer tokenizer)> customTokenizers = new List<(byte, ITokenizer)>();
private readonly bool useLenientParsing;
/// <summary>
/// The offset in the input data at which the <see cref="CurrentToken"/> starts.
/// </summary>
public long CurrentTokenStart { get; private set; }
/// <inheritdoc />
public IToken CurrentToken { get; private set; }
/// <inheritdoc />
public long CurrentPosition => inputBytes.CurrentOffset;
/// <inheritdoc />
public long Length => inputBytes.Length;
private bool hasBytePreRead;
private bool isInInlineImage;
/// <summary>
/// '%' only identifies comments outside of PDF streams and strings, inside these we should ignore it.
/// </summary>
/// <remarks>
/// PDFBox skips all of a line following a comment character inside streams, see:
/// https://github.com/apache/pdfbox/blob/0e1c42dace1c3a2631d5309f662de5628b80fda6/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/BaseParser.java#L1319
/// </remarks>
private readonly bool isStream;
/// <summary>
/// Create a new <see cref="CoreTokenScanner"/> from the input.
/// </summary>
public CoreTokenScanner(
IInputBytes inputBytes,
bool usePdfDocEncoding,
ScannerScope scope = ScannerScope.None,
IReadOnlyDictionary<NameToken, IReadOnlyList<NameToken>> namedDictionaryRequiredKeys = null,
bool useLenientParsing = false,
bool isStream = false)
{
this.inputBytes = inputBytes ?? throw new ArgumentNullException(nameof(inputBytes));
this.usePdfDocEncoding = usePdfDocEncoding;
this.stringTokenizer = new StringTokenizer(usePdfDocEncoding);
this.arrayTokenizer = new ArrayTokenizer(usePdfDocEncoding);
this.dictionaryTokenizer = new DictionaryTokenizer(usePdfDocEncoding, useLenientParsing: useLenientParsing);
this.scope = scope;
this.namedDictionaryRequiredKeys = namedDictionaryRequiredKeys;
this.useLenientParsing = useLenientParsing;
this.isStream = isStream;
}
/// <inheritdoc />
public bool TryReadToken<T>(out T token) where T : class, IToken
{
token = default(T);
if (!MoveNext())
{
return false;
}
if (CurrentToken is T canCast)
{
token = canCast;
return true;
}
return false;
}
/// <inheritdoc />
public void Seek(long position)
{
inputBytes.Seek(position);
}
/// <inheritdoc />
public bool MoveNext()
{
var endAngleBracesRead = 0;
bool isSkippingLine = false;
bool isSkippingSymbol = false;
while ((hasBytePreRead && !inputBytes.IsAtEnd()) || inputBytes.MoveNext())
{
hasBytePreRead = false;
var currentByte = inputBytes.CurrentByte;
var c = (char) currentByte;
if (isSkippingLine)
{
if (ReadHelper.IsEndOfLine(c))
{
isSkippingLine = false;
continue;
}
continue;
}
ITokenizer tokenizer = null;
foreach (var customTokenizer in customTokenizers)
{
if (currentByte == customTokenizer.firstByte)
{
tokenizer = customTokenizer.tokenizer;
break;
}
}
if (tokenizer == null)
{
if (ReadHelper.IsWhitespace(currentByte) || char.IsControl(c))
{
isSkippingSymbol = false;
continue;
}
if (currentByte == (byte)'%' && isStream)
{
isSkippingLine = true;
continue;
}
// If we failed to read the symbol for whatever reason we pass over it.
if (isSkippingSymbol && c != '>')
{
continue;
}
switch (c)
{
case '(':
tokenizer = stringTokenizer;
break;
case '<':
var following = inputBytes.Peek();
if (following == '<')
{
isSkippingSymbol = true;
tokenizer = dictionaryTokenizer;
if (namedDictionaryRequiredKeys != null
&& CurrentToken is NameToken name
&& namedDictionaryRequiredKeys.TryGetValue(name, out var requiredKeys))
{
tokenizer = new DictionaryTokenizer(usePdfDocEncoding, requiredKeys, useLenientParsing);
}
}
else
{
tokenizer = HexTokenizer;
}
break;
case '>' when scope == ScannerScope.Dictionary:
endAngleBracesRead++;
if (endAngleBracesRead == 2)
{
return false;
}
break;
case '[':
tokenizer = arrayTokenizer;
break;
case ']' when scope == ScannerScope.Array:
return false;
case '/':
tokenizer = NameTokenizer;
break;
case '%':
tokenizer = CommentTokenizer;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '+':
case '.':
tokenizer = NumericTokenizer;
break;
default:
tokenizer = PlainTokenizer;
break;
}
}
CurrentTokenStart = inputBytes.CurrentOffset - 1;
if (tokenizer == null || !tokenizer.TryTokenize(currentByte, inputBytes, out var token))
{
isSkippingSymbol = true;
hasBytePreRead = false;
continue;
}
if (token is OperatorToken op)
{
if (op.Data == "BI")
{
isInInlineImage = true;
}
else if (isInInlineImage && op.Data == "ID")
{
// Special case handling for inline images.
var imageData = ReadInlineImageData();
isInInlineImage = false;
CurrentToken = new InlineImageDataToken(new Memory<byte>([..imageData]));
hasBytePreRead = false;
return true;
}
}
CurrentToken = token;
/*
* Some tokenizers need to read the symbol of the next token to know if they have ended
* so we don't want to move on to the next byte, we would lose a byte, e.g.: /NameOne/NameTwo or /Name(string)
*/
hasBytePreRead = tokenizer.ReadsNextByte;
return true;
}
return false;
}
/// <inheritdoc />
public void RegisterCustomTokenizer(byte firstByte, ITokenizer tokenizer)
{
if (tokenizer == null)
{
throw new ArgumentNullException(nameof(tokenizer));
}
customTokenizers.Add((firstByte, tokenizer));
}
/// <inheritdoc />
public void DeregisterCustomTokenizer(ITokenizer tokenizer)
{
customTokenizers.RemoveAll(x => ReferenceEquals(x.tokenizer, tokenizer));
}
/// <summary>
/// Handles the situation where "EI" was encountered in the inline image data but was
/// not the end of the image.
/// </summary>
/// <param name="lastEndImageOffset">The offset of the "E" of the "EI" marker which was incorrectly read.</param>
/// <returns>The set of bytes from the incorrect "EI" to the correct "EI" including the incorrect "EI".</returns>
public IReadOnlyList<byte> RecoverFromIncorrectEndImage(long lastEndImageOffset)
{
var data = new List<byte>();
inputBytes.Seek(lastEndImageOffset);
if (!inputBytes.MoveNext() || inputBytes.CurrentByte != 'E')
{
var message = $"Failed to recover the image data stream for an inline image at offset {lastEndImageOffset}. " +
$"Expected to read byte 'E' instead got {inputBytes.CurrentByte}.";
throw new PdfDocumentFormatException(message);
}
data.Add(inputBytes.CurrentByte);
if (!inputBytes.MoveNext() || inputBytes.CurrentByte != 'I')
{
var message = $"Failed to recover the image data stream for an inline image at offset {lastEndImageOffset}. " +
$"Expected to read second byte 'I' following 'E' instead got {inputBytes.CurrentByte}.";
throw new PdfDocumentFormatException(message);
}
data.Add(inputBytes.CurrentByte);
data.AddRange(ReadUntilEndImage(lastEndImageOffset));
// Skip beyond the 'I' in the "EI" token we just read so the scanner is in a valid position.
inputBytes.MoveNext();
return data;
}
private List<byte> ReadInlineImageData()
{
// The ID operator should be followed by a single white-space character, and the next character is interpreted
// as the first byte of image data.
if (!ReadHelper.IsWhitespace(inputBytes.CurrentByte))
{
throw new PdfDocumentFormatException($"No whitespace character following the image data (ID) operator. Position: {inputBytes.CurrentOffset}.");
}
var startsAt = inputBytes.CurrentOffset - 2;
return ReadUntilEndImage(startsAt);
}
private List<byte> ReadUntilEndImage(long startsAt)
{
const byte lastPlainText = 127;
const byte space = 32;
var imageData = new List<byte>();
byte prevByte = 0;
while (inputBytes.MoveNext())
{
if (inputBytes.CurrentByte == 'I' && prevByte == 'E')
{
// Check for EI appearing in binary data.
var buffer = new byte[6];
var currentOffset = inputBytes.CurrentOffset;
var read = inputBytes.Read(buffer);
var isEnd = true;
if (read == buffer.Length)
{
var containsWhitespace = false;
for (var i = 0; i < buffer.Length; i++)
{
var b = buffer[i];
if (ReadHelper.IsWhitespace(b))
{
containsWhitespace = true;
continue;
}
if (b > lastPlainText)
{
isEnd = false;
break;
}
if (b < space && b != '\r' && b != '\n' && b != '\t')
{
isEnd = false;
break;
}
}
if (!containsWhitespace)
{
isEnd = false;
}
}
inputBytes.Seek(currentOffset);
if (isEnd)
{
imageData.RemoveAt(imageData.Count - 1);
return imageData;
}
}
imageData.Add(inputBytes.CurrentByte);
prevByte = inputBytes.CurrentByte;
}
throw new PdfDocumentFormatException($"No end of inline image data (EI) was found for image data at position {startsAt}.");
}
}
}