Coverage Report

Created: 2025-11-11 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFTokenizer.cc
Line
Count
Source
1
#include <qpdf/QPDFTokenizer_private.hh>
2
3
// DO NOT USE ctype -- it is locale dependent for some things, and it's not worth the risk of
4
// including it in case it may accidentally be used.
5
6
#include <qpdf/InputSource_private.hh>
7
#include <qpdf/QIntC.hh>
8
#include <qpdf/QPDFExc.hh>
9
#include <qpdf/QPDFObjectHandle.hh>
10
#include <qpdf/QTC.hh>
11
#include <qpdf/QUtil.hh>
12
#include <qpdf/Util.hh>
13
14
#include <cstdlib>
15
#include <cstring>
16
#include <stdexcept>
17
18
using namespace qpdf;
19
20
using Token = QPDFTokenizer::Token;
21
using tt = QPDFTokenizer::token_type_e;
22
23
static inline bool
24
is_delimiter(char ch)
25
140M
{
26
140M
    return (
27
140M
        ch == ' ' || ch == '\n' || ch == '/' || ch == '(' || ch == ')' || ch == '{' || ch == '}' ||
28
130M
        ch == '<' || ch == '>' || ch == '[' || ch == ']' || ch == '%' || ch == '\t' || ch == '\r' ||
29
129M
        ch == '\v' || ch == '\f' || ch == 0);
30
140M
}
31
32
namespace
33
{
34
    class QPDFWordTokenFinder: public InputSource::Finder
35
    {
36
      public:
37
        QPDFWordTokenFinder(InputSource& is, std::string const& str) :
38
23.9k
            is(is),
39
23.9k
            str(str)
40
23.9k
        {
41
23.9k
        }
42
23.9k
        ~QPDFWordTokenFinder() override = default;
43
        bool check() override;
44
45
      private:
46
        InputSource& is;
47
        std::string str;
48
    };
49
} // namespace
50
51
bool
52
QPDFWordTokenFinder::check()
53
45.9k
{
54
    // Find a word token matching the given string, preceded by a delimiter, and followed by a
55
    // delimiter or EOF.
56
45.9k
    Tokenizer tokenizer;
57
45.9k
    tokenizer.nextToken(is, "finder", str.size() + 2);
58
45.9k
    qpdf_offset_t pos = is.tell();
59
45.9k
    if (tokenizer.getType() != tt::tt_word || tokenizer.getValue() != str) {
60
22.6k
        QTC::TC("qpdf", "QPDFTokenizer finder found wrong word");
61
22.6k
        return false;
62
22.6k
    }
63
23.3k
    qpdf_offset_t token_start = is.getLastOffset();
64
23.3k
    char next;
65
23.3k
    bool next_okay = false;
66
23.3k
    if (is.read(&next, 1) == 0) {
67
7
        QTC::TC("qpdf", "QPDFTokenizer inline image at EOF");
68
7
        next_okay = true;
69
23.2k
    } else {
70
23.2k
        next_okay = is_delimiter(next);
71
23.2k
    }
72
23.3k
    is.seek(pos, SEEK_SET);
73
23.3k
    if (!next_okay) {
74
0
        return false;
75
0
    }
76
23.3k
    if (token_start == 0) {
77
        // Can't actually happen...we never start the search at the beginning of the input.
78
0
        return false;
79
0
    }
80
23.3k
    return true;
81
23.3k
}
82
83
void
84
Tokenizer::reset()
85
19.5M
{
86
19.5M
    state = st_before_token;
87
19.5M
    type = tt::tt_bad;
88
19.5M
    val.clear();
89
19.5M
    raw_val.clear();
90
19.5M
    error_message = "";
91
19.5M
    before_token = true;
92
19.5M
    in_token = false;
93
19.5M
    char_to_unread = '\0';
94
19.5M
    inline_image_bytes = 0;
95
19.5M
    string_depth = 0;
96
19.5M
    bad = false;
97
19.5M
}
98
99
QPDFTokenizer::Token::Token(token_type_e type, std::string const& value) :
100
248
    type(type),
101
248
    value(value),
102
248
    raw_value(value)
103
248
{
104
248
    if (type == tt_string) {
105
0
        raw_value = QPDFObjectHandle::newString(value).unparse();
106
248
    } else if (type == tt_name) {
107
0
        raw_value = QPDFObjectHandle::newName(value).unparse();
108
0
    }
109
248
}
110
111
QPDFTokenizer::QPDFTokenizer() :
112
5.56k
    m(std::make_unique<qpdf::Tokenizer>())
113
5.56k
{
114
5.56k
}
115
116
5.56k
QPDFTokenizer::~QPDFTokenizer() = default;
117
118
Tokenizer::Tokenizer()
119
115k
{
120
115k
    reset();
121
115k
}
122
123
void
124
QPDFTokenizer::allowEOF()
125
5.56k
{
126
5.56k
    m->allowEOF();
127
5.56k
}
128
129
void
130
Tokenizer::allowEOF()
131
46.0k
{
132
46.0k
    allow_eof = true;
133
46.0k
}
134
135
void
136
QPDFTokenizer::includeIgnorable()
137
5.56k
{
138
5.56k
    m->includeIgnorable();
139
5.56k
}
140
141
void
142
Tokenizer::includeIgnorable()
143
5.56k
{
144
5.56k
    include_ignorable = true;
145
5.56k
}
146
147
bool
148
Tokenizer::isSpace(char ch)
149
28.2M
{
150
28.2M
    return (ch == '\0' || util::is_space(ch));
151
28.2M
}
152
153
bool
154
Tokenizer::isDelimiter(char ch)
155
140M
{
156
140M
    return is_delimiter(ch);
157
140M
}
158
159
void
160
QPDFTokenizer::presentCharacter(char ch)
161
0
{
162
0
    m->presentCharacter(ch);
163
0
}
164
165
void
166
Tokenizer::presentCharacter(char ch)
167
21.2k
{
168
21.2k
    handleCharacter(ch);
169
170
21.2k
    if (in_token) {
171
0
        raw_val += ch;
172
0
    }
173
21.2k
}
174
175
void
176
Tokenizer::handleCharacter(char ch)
177
295M
{
178
    // In some cases, functions called below may call a second handler. This happens whenever you
179
    // have to use a character from the next token to detect the end of the current token.
180
181
295M
    switch (state) {
182
0
    case st_top:
183
0
        inTop(ch);
184
0
        return;
185
186
486k
    case st_in_space:
187
486k
        inSpace(ch);
188
486k
        return;
189
190
4.29M
    case st_in_comment:
191
4.29M
        inComment(ch);
192
4.29M
        return;
193
194
601k
    case st_lt:
195
601k
        inLt(ch);
196
601k
        return;
197
198
374k
    case st_gt:
199
374k
        inGt(ch);
200
374k
        return;
201
202
104M
    case st_in_string:
203
104M
        inString(ch);
204
104M
        return;
205
206
77.4M
    case st_name:
207
77.4M
        inName(ch);
208
77.4M
        return;
209
210
7.78M
    case st_number:
211
7.78M
        inNumber(ch);
212
7.78M
        return;
213
214
1.29M
    case st_real:
215
1.29M
        inReal(ch);
216
1.29M
        return;
217
218
287k
    case st_string_after_cr:
219
287k
        inStringAfterCR(ch);
220
287k
        return;
221
222
209k
    case st_string_escape:
223
209k
        inStringEscape(ch);
224
209k
        return;
225
226
26.9k
    case st_char_code:
227
26.9k
        inCharCode(ch);
228
26.9k
        return;
229
230
58.5M
    case st_literal:
231
58.5M
        inLiteral(ch);
232
58.5M
        return;
233
234
9.80M
    case st_inline_image:
235
9.80M
        inInlineImage(ch);
236
9.80M
        return;
237
238
593k
    case st_in_hexstring:
239
593k
        inHexstring(ch);
240
593k
        return;
241
242
600k
    case st_in_hexstring_2nd:
243
600k
        inHexstring2nd(ch);
244
600k
        return;
245
246
57.2k
    case st_name_hex1:
247
57.2k
        inNameHex1(ch);
248
57.2k
        return;
249
250
38.6k
    case st_name_hex2:
251
38.6k
        inNameHex2(ch);
252
38.6k
        return;
253
254
130k
    case st_sign:
255
130k
        inSign(ch);
256
130k
        return;
257
258
19.7k
    case st_decimal:
259
19.7k
        inDecimal(ch);
260
19.7k
        return;
261
262
27.6M
    case (st_before_token):
263
27.6M
        inBeforeToken(ch);
264
27.6M
        return;
265
266
0
    case (st_token_ready):
267
0
        inTokenReady(ch);
268
0
        return;
269
270
0
    default:
271
0
        throw std::logic_error("INTERNAL ERROR: invalid state while reading token");
272
295M
    }
273
295M
}
274
275
void
276
Tokenizer::inTokenReady(char ch)
277
0
{
278
0
    throw std::logic_error(
279
0
        "INTERNAL ERROR: QPDF tokenizer presented character while token is waiting");
280
0
}
281
282
void
283
Tokenizer::inBeforeToken(char ch)
284
27.6M
{
285
    // Note: we specifically do not use ctype here.  It is locale-dependent.
286
27.6M
    if (isSpace(ch)) {
287
13.3M
        before_token = !include_ignorable;
288
13.3M
        in_token = include_ignorable;
289
13.3M
        if (include_ignorable) {
290
179k
            state = st_in_space;
291
179k
        }
292
14.2M
    } else if (ch == '%') {
293
35.9k
        before_token = !include_ignorable;
294
35.9k
        in_token = include_ignorable;
295
35.9k
        state = st_in_comment;
296
14.2M
    } else {
297
14.2M
        before_token = false;
298
14.2M
        in_token = true;
299
14.2M
        inTop(ch);
300
14.2M
    }
301
27.6M
}
302
303
void
304
Tokenizer::inTop(char ch)
305
14.2M
{
306
14.2M
    switch (ch) {
307
225k
    case '(':
308
225k
        string_depth = 1;
309
225k
        state = st_in_string;
310
225k
        return;
311
312
614k
    case '<':
313
614k
        state = st_lt;
314
614k
        return;
315
316
378k
    case '>':
317
378k
        state = st_gt;
318
378k
        return;
319
320
27.1k
    case (')'):
321
27.1k
        type = tt::tt_bad;
322
27.1k
        QTC::TC("qpdf", "QPDFTokenizer bad )");
323
27.1k
        error_message = "unexpected )";
324
27.1k
        state = st_token_ready;
325
27.1k
        return;
326
327
338k
    case '[':
328
338k
        type = tt::tt_array_open;
329
338k
        state = st_token_ready;
330
338k
        return;
331
332
216k
    case ']':
333
216k
        type = tt::tt_array_close;
334
216k
        state = st_token_ready;
335
216k
        return;
336
337
9.54k
    case '{':
338
9.54k
        type = tt::tt_brace_open;
339
9.54k
        state = st_token_ready;
340
9.54k
        return;
341
342
7.01k
    case '}':
343
7.01k
        type = tt::tt_brace_close;
344
7.01k
        state = st_token_ready;
345
7.01k
        return;
346
347
3.68M
    case '/':
348
3.68M
        state = st_name;
349
3.68M
        val += ch;
350
3.68M
        return;
351
352
1.86M
    case '0':
353
2.58M
    case '1':
354
2.95M
    case '2':
355
3.20M
    case '3':
356
3.47M
    case '4':
357
3.74M
    case '5':
358
3.98M
    case '6':
359
4.19M
    case '7':
360
4.34M
    case '8':
361
4.41M
    case '9':
362
4.41M
        state = st_number;
363
4.41M
        return;
364
365
10.2k
    case '+':
366
141k
    case '-':
367
141k
        state = st_sign;
368
141k
        return;
369
370
17.3k
    case '.':
371
17.3k
        state = st_decimal;
372
17.3k
        return;
373
374
4.18M
    default:
375
4.18M
        state = st_literal;
376
4.18M
        return;
377
14.2M
    }
378
14.2M
}
379
380
void
381
Tokenizer::inSpace(char ch)
382
486k
{
383
    // We only enter this state if include_ignorable is true.
384
486k
    if (!isSpace(ch)) {
385
179k
        type = tt::tt_space;
386
179k
        in_token = false;
387
179k
        char_to_unread = ch;
388
179k
        state = st_token_ready;
389
179k
    }
390
486k
}
391
392
void
393
Tokenizer::inComment(char ch)
394
4.29M
{
395
4.29M
    if ((ch == '\r') || (ch == '\n')) {
396
35.0k
        if (include_ignorable) {
397
2.04k
            type = tt::tt_comment;
398
2.04k
            in_token = false;
399
2.04k
            char_to_unread = ch;
400
2.04k
            state = st_token_ready;
401
32.9k
        } else {
402
32.9k
            state = st_before_token;
403
32.9k
        }
404
35.0k
    }
405
4.29M
}
406
407
void
408
Tokenizer::inString(char ch)
409
104M
{
410
104M
    switch (ch) {
411
209k
    case '\\':
412
209k
        state = st_string_escape;
413
209k
        return;
414
415
257k
    case '(':
416
257k
        val += ch;
417
257k
        ++string_depth;
418
257k
        return;
419
420
352k
    case ')':
421
352k
        if (--string_depth == 0) {
422
215k
            type = tt::tt_string;
423
215k
            state = st_token_ready;
424
215k
            return;
425
215k
        }
426
427
136k
        val += ch;
428
136k
        return;
429
430
286k
    case '\r':
431
        // CR by itself is converted to LF
432
286k
        val += '\n';
433
286k
        state = st_string_after_cr;
434
286k
        return;
435
436
904k
    case '\n':
437
904k
        val += ch;
438
904k
        return;
439
440
102M
    default:
441
102M
        val += ch;
442
102M
        return;
443
104M
    }
444
104M
}
445
446
void
447
Tokenizer::inName(char ch)
448
77.5M
{
449
77.5M
    if (isDelimiter(ch)) {
450
        // A C-locale whitespace character or delimiter terminates token.  It is important to unread
451
        // the whitespace character even though it is ignored since it may be the newline after a
452
        // stream keyword.  Removing it here could make the stream-reading code break on some files,
453
        // though not on any files in the test suite as of this
454
        // writing.
455
456
3.60M
        type = bad ? tt::tt_bad : tt::tt_name;
457
3.60M
        in_token = false;
458
3.60M
        char_to_unread = ch;
459
3.60M
        state = st_token_ready;
460
73.9M
    } else if (ch == '#') {
461
57.2k
        char_code = 0;
462
57.2k
        state = st_name_hex1;
463
73.8M
    } else {
464
73.8M
        val += ch;
465
73.8M
    }
466
77.5M
}
467
468
void
469
Tokenizer::inNameHex1(char ch)
470
57.2k
{
471
57.2k
    hex_char = ch;
472
473
57.2k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
474
38.6k
        char_code = int(hval) << 4;
475
38.6k
        state = st_name_hex2;
476
38.6k
    } else {
477
18.6k
        QTC::TC("qpdf", "QPDFTokenizer bad name 1");
478
18.6k
        error_message = "name with stray # will not work with PDF >= 1.2";
479
        // Use null to encode a bad # -- this is reversed in QPDF_Name::normalizeName.
480
18.6k
        val += '\0';
481
18.6k
        state = st_name;
482
18.6k
        inName(ch);
483
18.6k
    }
484
57.2k
}
485
486
void
487
Tokenizer::inNameHex2(char ch)
488
38.6k
{
489
38.6k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
490
27.0k
        char_code |= int(hval);
491
27.0k
    } else {
492
11.5k
        QTC::TC("qpdf", "QPDFTokenizer bad name 2");
493
11.5k
        error_message = "name with stray # will not work with PDF >= 1.2";
494
        // Use null to encode a bad # -- this is reversed in QPDF_Name::normalizeName.
495
11.5k
        val += '\0';
496
11.5k
        val += hex_char;
497
11.5k
        state = st_name;
498
11.5k
        inName(ch);
499
11.5k
        return;
500
11.5k
    }
501
27.0k
    if (char_code == 0) {
502
3.98k
        QTC::TC("qpdf", "QPDFTokenizer null in name");
503
3.98k
        error_message = "null character not allowed in name token";
504
3.98k
        val += "#00";
505
3.98k
        state = st_name;
506
3.98k
        bad = true;
507
23.0k
    } else {
508
23.0k
        val += char(char_code);
509
23.0k
        state = st_name;
510
23.0k
    }
511
27.0k
}
512
513
void
514
Tokenizer::inSign(char ch)
515
130k
{
516
130k
    if (util::is_digit(ch)) {
517
118k
        state = st_number;
518
118k
    } else if (ch == '.') {
519
3.35k
        state = st_decimal;
520
8.42k
    } else {
521
8.42k
        state = st_literal;
522
8.42k
        inLiteral(ch);
523
8.42k
    }
524
130k
}
525
526
void
527
Tokenizer::inDecimal(char ch)
528
19.7k
{
529
19.7k
    if (util::is_digit(ch)) {
530
12.6k
        state = st_real;
531
12.6k
    } else {
532
7.09k
        state = st_literal;
533
7.09k
        inLiteral(ch);
534
7.09k
    }
535
19.7k
}
536
537
void
538
Tokenizer::inNumber(char ch)
539
7.78M
{
540
7.78M
    if (util::is_digit(ch)) {
541
4.14M
    } else if (ch == '.') {
542
350k
        state = st_real;
543
3.79M
    } else if (isDelimiter(ch)) {
544
3.66M
        type = tt::tt_integer;
545
3.66M
        state = st_token_ready;
546
3.66M
        in_token = false;
547
3.66M
        char_to_unread = ch;
548
3.66M
    } else {
549
131k
        state = st_literal;
550
131k
    }
551
7.78M
}
552
553
void
554
Tokenizer::inReal(char ch)
555
1.29M
{
556
1.29M
    if (util::is_digit(ch)) {
557
929k
    } else if (isDelimiter(ch)) {
558
346k
        type = tt::tt_real;
559
346k
        state = st_token_ready;
560
346k
        in_token = false;
561
346k
        char_to_unread = ch;
562
346k
    } else {
563
14.3k
        state = st_literal;
564
14.3k
    }
565
1.29M
}
566
void
567
Tokenizer::inStringEscape(char ch)
568
209k
{
569
209k
    state = st_in_string;
570
209k
    switch (ch) {
571
9.18k
    case '0':
572
9.68k
    case '1':
573
10.4k
    case '2':
574
10.9k
    case '3':
575
11.4k
    case '4':
576
12.0k
    case '5':
577
16.0k
    case '6':
578
17.1k
    case '7':
579
17.1k
        state = st_char_code;
580
17.1k
        char_code = 0;
581
17.1k
        digit_count = 0;
582
17.1k
        inCharCode(ch);
583
17.1k
        return;
584
585
2.87k
    case 'n':
586
2.87k
        val += '\n';
587
2.87k
        return;
588
589
11.3k
    case 'r':
590
11.3k
        val += '\r';
591
11.3k
        return;
592
593
65.4k
    case 't':
594
65.4k
        val += '\t';
595
65.4k
        return;
596
597
577
    case 'b':
598
577
        val += '\b';
599
577
        return;
600
601
60.9k
    case 'f':
602
60.9k
        val += '\f';
603
60.9k
        return;
604
605
4.30k
    case '\n':
606
4.30k
        return;
607
608
365
    case '\r':
609
365
        state = st_string_after_cr;
610
365
        return;
611
612
46.8k
    default:
613
        // PDF spec says backslash is ignored before anything else
614
46.8k
        val += ch;
615
46.8k
        return;
616
209k
    }
617
209k
}
618
619
void
620
Tokenizer::inStringAfterCR(char ch)
621
287k
{
622
287k
    state = st_in_string;
623
287k
    if (ch != '\n') {
624
91.8k
        inString(ch);
625
91.8k
    }
626
287k
}
627
628
void
629
Tokenizer::inLt(char ch)
630
601k
{
631
601k
    if (ch == '<') {
632
402k
        type = tt::tt_dict_open;
633
402k
        state = st_token_ready;
634
402k
        return;
635
402k
    }
636
637
198k
    state = st_in_hexstring;
638
198k
    inHexstring(ch);
639
198k
}
640
641
void
642
Tokenizer::inGt(char ch)
643
374k
{
644
374k
    if (ch == '>') {
645
333k
        type = tt::tt_dict_close;
646
333k
        state = st_token_ready;
647
333k
    } else {
648
41.1k
        type = tt::tt_bad;
649
41.1k
        QTC::TC("qpdf", "QPDFTokenizer bad >");
650
41.1k
        error_message = "unexpected >";
651
41.1k
        in_token = false;
652
41.1k
        char_to_unread = ch;
653
41.1k
        state = st_token_ready;
654
41.1k
    }
655
374k
}
656
657
void
658
Tokenizer::inLiteral(char ch)
659
58.6M
{
660
58.6M
    if (isDelimiter(ch)) {
661
        // A C-locale whitespace character or delimiter terminates token.  It is important to unread
662
        // the whitespace character even though it is ignored since it may be the newline after a
663
        // stream keyword.  Removing it here could make the stream-reading code break on some files,
664
        // though not on any files in the test suite as of this writing.
665
666
3.46M
        in_token = false;
667
3.46M
        char_to_unread = ch;
668
3.46M
        state = st_token_ready;
669
3.46M
        type = (raw_val == "true") || (raw_val == "false")
670
3.46M
            ? tt::tt_bool
671
3.46M
            : (raw_val == "null" ? tt::tt_null : tt::tt_word);
672
3.46M
    }
673
58.6M
}
674
675
void
676
Tokenizer::inHexstring(char ch)
677
791k
{
678
791k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
679
570k
        char_code = int(hval) << 4;
680
570k
        state = st_in_hexstring_2nd;
681
682
570k
    } else if (ch == '>') {
683
132k
        type = tt::tt_string;
684
132k
        state = st_token_ready;
685
686
132k
    } else if (isSpace(ch)) {
687
        // ignore
688
689
50.0k
    } else {
690
39.3k
        type = tt::tt_bad;
691
39.3k
        QTC::TC("qpdf", "QPDFTokenizer bad hexstring character");
692
39.3k
        error_message = std::string("invalid character (") + ch + ") in hexstring";
693
39.3k
        state = st_token_ready;
694
39.3k
    }
695
791k
}
696
697
void
698
Tokenizer::inHexstring2nd(char ch)
699
600k
{
700
600k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
701
544k
        val += char(char_code) | hval;
702
544k
        state = st_in_hexstring;
703
704
544k
    } else if (ch == '>') {
705
        // PDF spec says odd hexstrings have implicit trailing 0.
706
10.4k
        val += char(char_code);
707
10.4k
        type = tt::tt_string;
708
10.4k
        state = st_token_ready;
709
710
45.6k
    } else if (isSpace(ch)) {
711
        // ignore
712
713
36.4k
    } else {
714
9.12k
        type = tt::tt_bad;
715
9.12k
        QTC::TC("qpdf", "QPDFTokenizer bad hexstring 2nd character");
716
9.12k
        error_message = std::string("invalid character (") + ch + ") in hexstring";
717
9.12k
        state = st_token_ready;
718
9.12k
    }
719
600k
}
720
721
void
722
Tokenizer::inCharCode(char ch)
723
44.1k
{
724
44.1k
    bool handled = false;
725
44.1k
    if (('0' <= ch) && (ch <= '7')) {
726
36.3k
        char_code = 8 * char_code + (int(ch) - int('0'));
727
36.3k
        if (++(digit_count) < 3) {
728
27.1k
            return;
729
27.1k
        }
730
9.17k
        handled = true;
731
9.17k
    }
732
    // We've accumulated \ddd or we have \d or \dd followed by other than an octal digit. The PDF
733
    // Spec says to ignore high-order overflow.
734
16.9k
    val += char(char_code % 256);
735
16.9k
    state = st_in_string;
736
16.9k
    if (!handled) {
737
7.82k
        inString(ch);
738
7.82k
    }
739
16.9k
}
740
741
void
742
Tokenizer::inInlineImage(char ch)
743
9.80M
{
744
9.80M
    if ((raw_val.length() + 1) == inline_image_bytes) {
745
1.63k
        QTC::TC("qpdf", "QPDFTokenizer found EI by byte count");
746
1.63k
        type = tt::tt_inline_image;
747
1.63k
        inline_image_bytes = 0;
748
1.63k
        state = st_token_ready;
749
1.63k
    }
750
9.80M
}
751
752
void
753
QPDFTokenizer::presentEOF()
754
0
{
755
0
    m->presentEOF();
756
0
}
757
758
void
759
Tokenizer::presentEOF()
760
55.4k
{
761
55.4k
    switch (state) {
762
2.55k
    case st_name:
763
2.71k
    case st_name_hex1:
764
2.78k
    case st_name_hex2:
765
8.51k
    case st_number:
766
8.74k
    case st_real:
767
8.87k
    case st_sign:
768
8.94k
    case st_decimal:
769
21.2k
    case st_literal:
770
21.2k
        QTC::TC("qpdf", "QPDFTokenizer EOF reading appendable token");
771
        // Push any delimiter to the state machine to finish off the final token.
772
21.2k
        presentCharacter('\f');
773
21.2k
        in_token = true;
774
21.2k
        break;
775
776
0
    case st_top:
777
29.2k
    case st_before_token:
778
29.2k
        type = tt::tt_eof;
779
29.2k
        break;
780
781
94
    case st_in_space:
782
94
        type = include_ignorable ? tt::tt_space : tt::tt_eof;
783
94
        break;
784
785
878
    case st_in_comment:
786
878
        type = include_ignorable ? tt::tt_comment : tt::tt_bad;
787
878
        break;
788
789
0
    case st_token_ready:
790
0
        break;
791
792
3.93k
    default:
793
3.93k
        QTC::TC("qpdf", "QPDFTokenizer EOF reading token");
794
3.93k
        type = tt::tt_bad;
795
3.93k
        error_message = "EOF while reading token";
796
55.4k
    }
797
55.4k
    state = st_token_ready;
798
55.4k
}
799
800
void
801
QPDFTokenizer::expectInlineImage(std::shared_ptr<InputSource> input)
802
0
{
803
0
    m->expectInlineImage(*input);
804
0
}
805
806
void
807
QPDFTokenizer::expectInlineImage(InputSource& input)
808
248
{
809
248
    m->expectInlineImage(input);
810
248
}
811
812
void
813
Tokenizer::expectInlineImage(InputSource& input)
814
1.69k
{
815
1.69k
    if (state == st_token_ready) {
816
1.44k
        reset();
817
1.44k
    } else if (state != st_before_token) {
818
0
        throw std::logic_error(
819
0
            "QPDFTokenizer::expectInlineImage called when tokenizer is in improper state");
820
0
    }
821
1.69k
    findEI(input);
822
1.69k
    before_token = false;
823
1.69k
    in_token = true;
824
1.69k
    state = st_inline_image;
825
1.69k
}
826
827
void
828
Tokenizer::findEI(InputSource& input)
829
1.69k
{
830
1.69k
    qpdf_offset_t last_offset = input.getLastOffset();
831
1.69k
    qpdf_offset_t pos = input.tell();
832
833
    // Use QPDFWordTokenFinder to find EI surrounded by delimiters. Then read the next several
834
    // tokens or up to EOF. If we find any suspicious-looking or tokens, this is probably still part
835
    // of the image data, so keep looking for EI. Stop at the first EI that passes. If we get to the
836
    // end without finding one, return the last EI we found. Store the number of bytes expected in
837
    // the inline image including the EI and use that to break out of inline image, falling back to
838
    // the old method if needed.
839
840
1.69k
    bool okay = false;
841
1.69k
    bool first_try = true;
842
24.9k
    while (!okay) {
843
23.9k
        QPDFWordTokenFinder f(input, "EI");
844
23.9k
        if (!input.findFirst("EI", input.tell(), 0, f)) {
845
613
            break;
846
613
        }
847
23.3k
        inline_image_bytes = QIntC::to_size(input.tell() - pos - 2);
848
849
23.3k
        Tokenizer check;
850
23.3k
        bool found_bad = false;
851
        // Look at the next 10 tokens or up to EOF. The next inline image's image data would look
852
        // like bad tokens, but there will always be at least 10 tokens between one inline image's
853
        // EI and the next valid one's ID since width, height, bits per pixel, and color space are
854
        // all required as well as a BI and ID. If we get 10 good tokens in a row or hit EOF, we can
855
        // be pretty sure we've found the actual EI.
856
50.8k
        for (int i = 0; i < 10; ++i) {
857
49.7k
            check.nextToken(input, "checker");
858
49.7k
            auto typ = check.getType();
859
49.7k
            if (typ == tt::tt_eof) {
860
0
                okay = true;
861
49.7k
            } else if (typ == tt::tt_bad) {
862
2.80k
                found_bad = true;
863
46.9k
            } else if (typ == tt::tt_word) {
864
                // The qpdf tokenizer lumps alphabetic and otherwise uncategorized characters into
865
                // "words". We recognize strings of alphabetic characters as potential valid
866
                // operators for purposes of telling whether we're in valid content or not. It's not
867
                // perfect, but it should work more reliably than what we used to do, which was
868
                // already good enough for the vast majority of files.
869
33.6k
                bool found_alpha = false;
870
33.6k
                bool found_non_printable = false;
871
33.6k
                bool found_other = false;
872
118k
                for (char ch: check.getValue()) {
873
118k
                    if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '*')) {
874
                        // Treat '*' as alpha since there are valid PDF operators that contain *
875
                        // along with alphabetic characters.
876
65.1k
                        found_alpha = true;
877
65.1k
                    } else if (static_cast<signed char>(ch) < 32 && !isSpace(ch)) {
878
                        // Compare ch as a signed char so characters outside of 7-bit will be < 0.
879
4.39k
                        found_non_printable = true;
880
4.39k
                        break;
881
49.1k
                    } else {
882
49.1k
                        found_other = true;
883
49.1k
                    }
884
118k
                }
885
33.6k
                if (found_non_printable || (found_alpha && found_other)) {
886
19.4k
                    found_bad = true;
887
19.4k
                }
888
33.6k
            }
889
49.7k
            if (okay || found_bad) {
890
22.2k
                break;
891
22.2k
            }
892
49.7k
        }
893
23.3k
        if (!found_bad) {
894
1.08k
            okay = true;
895
1.08k
        }
896
23.3k
        if (!okay) {
897
22.2k
            first_try = false;
898
22.2k
        }
899
23.3k
    }
900
1.69k
    if (okay && (!first_try)) {
901
251
        QTC::TC("qpdf", "QPDFTokenizer found EI after more than one try");
902
251
    }
903
904
1.69k
    input.seek(pos, SEEK_SET);
905
1.69k
    input.setLastOffset(last_offset);
906
1.69k
}
907
908
bool
909
QPDFTokenizer::getToken(Token& token, bool& unread_char, char& ch)
910
0
{
911
0
    return m->getToken(token, unread_char, ch);
912
0
}
913
914
bool
915
Tokenizer::getToken(Token& token, bool& unread_char, char& ch)
916
4.96M
{
917
4.96M
    bool ready = (state == st_token_ready);
918
4.96M
    unread_char = !in_token && !before_token;
919
4.96M
    ch = char_to_unread;
920
4.96M
    if (ready) {
921
4.96M
        token = (!(type == tt::tt_name || type == tt::tt_string))
922
4.96M
            ? Token(type, raw_val, raw_val, error_message)
923
4.96M
            : Token(type, val, raw_val, error_message);
924
925
4.96M
        reset();
926
4.96M
    }
927
4.96M
    return ready;
928
4.96M
}
929
930
bool
931
QPDFTokenizer::betweenTokens()
932
0
{
933
0
    return m->betweenTokens();
934
0
}
935
936
bool
937
Tokenizer::betweenTokens()
938
0
{
939
0
    return before_token;
940
0
}
941
942
QPDFTokenizer::Token
943
QPDFTokenizer::readToken(
944
    InputSource& input, std::string const& context, bool allow_bad, size_t max_len)
945
1.34M
{
946
1.34M
    return m->readToken(input, context, allow_bad, max_len);
947
1.34M
}
948
949
QPDFTokenizer::Token
950
QPDFTokenizer::readToken(
951
    std::shared_ptr<InputSource> input, std::string const& context, bool allow_bad, size_t max_len)
952
0
{
953
0
    return m->readToken(*input, context, allow_bad, max_len);
954
0
}
955
956
QPDFTokenizer::Token
957
Tokenizer::readToken(InputSource& input, std::string const& context, bool allow_bad, size_t max_len)
958
4.96M
{
959
4.96M
    nextToken(input, context, max_len);
960
961
4.96M
    Token token;
962
4.96M
    bool unread_char;
963
4.96M
    char char_to_unread;
964
4.96M
    getToken(token, unread_char, char_to_unread);
965
966
4.96M
    if (token.getType() == tt::tt_bad) {
967
241k
        if (allow_bad) {
968
241k
            QTC::TC("qpdf", "QPDFTokenizer allowing bad token");
969
241k
        } else {
970
0
            throw QPDFExc(
971
0
                qpdf_e_damaged_pdf,
972
0
                input.getName(),
973
0
                context.empty() ? "offset " + std::to_string(input.getLastOffset()) : context,
974
0
                input.getLastOffset(),
975
0
                token.getErrorMessage());
976
0
        }
977
241k
    }
978
4.96M
    return token;
979
4.96M
}
980
981
bool
982
Tokenizer::nextToken(InputSource& input, std::string const& context, size_t max_len)
983
14.4M
{
984
14.4M
    if (state != st_inline_image) {
985
14.4M
        reset();
986
14.4M
    }
987
14.4M
    qpdf_offset_t offset = input.fastTell();
988
989
309M
    while (state != st_token_ready) {
990
295M
        char ch;
991
295M
        if (!input.fastRead(ch)) {
992
55.4k
            presentEOF();
993
994
55.4k
            if ((type == tt::tt_eof) && (!allow_eof)) {
995
                // Nothing in the qpdf library calls readToken without allowEOF anymore, so this
996
                // case is not exercised.
997
75
                type = tt::tt_bad;
998
75
                error_message = "unexpected EOF";
999
75
                offset = input.getLastOffset();
1000
75
            }
1001
294M
        } else {
1002
294M
            handleCharacter(ch);
1003
294M
            if (before_token) {
1004
16.8M
                ++offset;
1005
16.8M
            }
1006
294M
            if (in_token) {
1007
266M
                raw_val += ch;
1008
266M
            }
1009
294M
            if (max_len && (raw_val.length() >= max_len) && (state != st_token_ready)) {
1010
                // terminate this token now
1011
1.40M
                QTC::TC("qpdf", "QPDFTokenizer block long token");
1012
1.40M
                type = tt::tt_bad;
1013
1.40M
                state = st_token_ready;
1014
1.40M
                error_message = "exceeded allowable length while reading token";
1015
1.40M
            }
1016
294M
        }
1017
295M
    }
1018
1019
14.4M
    input.fastUnread(!in_token && !before_token);
1020
1021
14.4M
    if (type != tt::tt_eof) {
1022
14.4M
        input.setLastOffset(offset);
1023
14.4M
    }
1024
1025
14.4M
    return error_message.empty();
1026
14.4M
}