Coverage Report

Created: 2026-06-09 07:00

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
348M
{
26
348M
    return (
27
348M
        ch == ' ' || ch == '\n' || ch == '/' || ch == '(' || ch == ')' || ch == '{' || ch == '}' ||
28
341M
        ch == '<' || ch == '>' || ch == '[' || ch == ']' || ch == '%' || ch == '\t' || ch == '\r' ||
29
340M
        ch == '\v' || ch == '\f' || ch == 0);
30
348M
}
31
32
namespace
33
{
34
    class QPDFWordTokenFinder: public InputSource::Finder
35
    {
36
      public:
37
        QPDFWordTokenFinder(InputSource& is, std::string const& str) :
38
13.3k
            is(is),
39
13.3k
            str(str)
40
13.3k
        {
41
13.3k
        }
42
13.3k
        ~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
89.2k
{
54
    // Find a word token matching the given string, preceded by a delimiter, and followed by a
55
    // delimiter or EOF.
56
89.2k
    Tokenizer tokenizer;
57
89.2k
    tokenizer.nextToken(is, "finder", str.size() + 2);
58
89.2k
    qpdf_offset_t pos = is.tell();
59
89.2k
    if (tokenizer.getType() != tt::tt_word || tokenizer.getValue() != str) {
60
76.6k
        QTC::TC("qpdf", "QPDFTokenizer finder found wrong word");
61
76.6k
        return false;
62
76.6k
    }
63
12.6k
    qpdf_offset_t token_start = is.getLastOffset();
64
12.6k
    char next;
65
12.6k
    bool next_okay = false;
66
12.6k
    if (is.read(&next, 1) == 0) {
67
12
        QTC::TC("qpdf", "QPDFTokenizer inline image at EOF");
68
12
        next_okay = true;
69
12.6k
    } else {
70
12.6k
        next_okay = is_delimiter(next);
71
12.6k
    }
72
12.6k
    is.seek(pos, SEEK_SET);
73
12.6k
    if (!next_okay) {
74
0
        return false;
75
0
    }
76
12.6k
    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
12.6k
    return true;
81
12.6k
}
82
83
void
84
Tokenizer::reset()
85
41.7M
{
86
41.7M
    state = st_before_token;
87
41.7M
    type = tt::tt_bad;
88
41.7M
    val.clear();
89
41.7M
    raw_val.clear();
90
41.7M
    error_message = "";
91
41.7M
    before_token = true;
92
41.7M
    in_token = false;
93
41.7M
    char_to_unread = '\0';
94
41.7M
    inline_image_bytes = 0;
95
41.7M
    string_depth = 0;
96
41.7M
    bad = false;
97
41.7M
}
98
99
QPDFTokenizer::Token::Token(token_type_e type, std::string const& value) :
100
1.23k
    type(type),
101
1.23k
    value(value),
102
1.23k
    raw_value(value)
103
1.23k
{
104
1.23k
    if (type == tt_string) {
105
0
        raw_value = QPDFObjectHandle::newString(value).unparse();
106
1.23k
    } else if (type == tt_name) {
107
0
        raw_value = QPDFObjectHandle::newName(value).unparse();
108
0
    }
109
1.23k
}
110
111
QPDFTokenizer::QPDFTokenizer() :
112
13.4k
    m(std::make_unique<qpdf::Tokenizer>())
113
13.4k
{
114
13.4k
}
115
116
13.4k
QPDFTokenizer::~QPDFTokenizer() = default;
117
118
Tokenizer::Tokenizer()
119
153k
{
120
153k
    reset();
121
153k
}
122
123
void
124
QPDFTokenizer::allowEOF()
125
13.4k
{
126
13.4k
    m->allowEOF();
127
13.4k
}
128
129
void
130
Tokenizer::allowEOF()
131
52.0k
{
132
52.0k
    allow_eof = true;
133
52.0k
}
134
135
void
136
QPDFTokenizer::includeIgnorable()
137
13.4k
{
138
13.4k
    m->includeIgnorable();
139
13.4k
}
140
141
void
142
Tokenizer::includeIgnorable()
143
13.4k
{
144
13.4k
    include_ignorable = true;
145
13.4k
}
146
147
bool
148
Tokenizer::isSpace(char ch)
149
66.6M
{
150
66.6M
    return (ch == '\0' || util::is_space(ch));
151
66.6M
}
152
153
bool
154
Tokenizer::isDelimiter(char ch)
155
348M
{
156
348M
    return is_delimiter(ch);
157
348M
}
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.5k
{
168
21.5k
    handleCharacter(ch);
169
170
21.5k
    if (in_token) {
171
0
        raw_val += ch;
172
0
    }
173
21.5k
}
174
175
void
176
Tokenizer::handleCharacter(char ch)
177
587M
{
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
587M
    switch (state) {
182
0
    case st_top:
183
0
        inTop(ch);
184
0
        return;
185
186
810k
    case st_in_space:
187
810k
        inSpace(ch);
188
810k
        return;
189
190
5.65M
    case st_in_comment:
191
5.65M
        inComment(ch);
192
5.65M
        return;
193
194
566k
    case st_lt:
195
566k
        inLt(ch);
196
566k
        return;
197
198
285k
    case st_gt:
199
285k
        inGt(ch);
200
285k
        return;
201
202
136M
    case st_in_string:
203
136M
        inString(ch);
204
136M
        return;
205
206
88.1M
    case st_name:
207
88.1M
        inName(ch);
208
88.1M
        return;
209
210
6.88M
    case st_number:
211
6.88M
        inNumber(ch);
212
6.88M
        return;
213
214
875k
    case st_real:
215
875k
        inReal(ch);
216
875k
        return;
217
218
249k
    case st_string_after_cr:
219
249k
        inStringAfterCR(ch);
220
249k
        return;
221
222
168k
    case st_string_escape:
223
168k
        inStringEscape(ch);
224
168k
        return;
225
226
82.8k
    case st_char_code:
227
82.8k
        inCharCode(ch);
228
82.8k
        return;
229
230
255M
    case st_literal:
231
255M
        inLiteral(ch);
232
255M
        return;
233
234
11.4M
    case st_inline_image:
235
11.4M
        inInlineImage(ch);
236
11.4M
        return;
237
238
6.29M
    case st_in_hexstring:
239
6.29M
        inHexstring(ch);
240
6.29M
        return;
241
242
6.27M
    case st_in_hexstring_2nd:
243
6.27M
        inHexstring2nd(ch);
244
6.27M
        return;
245
246
1.92M
    case st_name_hex1:
247
1.92M
        inNameHex1(ch);
248
1.92M
        return;
249
250
26.6k
    case st_name_hex2:
251
26.6k
        inNameHex2(ch);
252
26.6k
        return;
253
254
129k
    case st_sign:
255
129k
        inSign(ch);
256
129k
        return;
257
258
26.4k
    case st_decimal:
259
26.4k
        inDecimal(ch);
260
26.4k
        return;
261
262
65.8M
    case (st_before_token):
263
65.8M
        inBeforeToken(ch);
264
65.8M
        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
587M
    }
273
587M
}
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
65.8M
{
285
    // Note: we specifically do not use ctype here.  It is locale-dependent.
286
65.8M
    if (isSpace(ch)) {
287
30.2M
        before_token = !include_ignorable;
288
30.2M
        in_token = include_ignorable;
289
30.2M
        if (include_ignorable) {
290
381k
            state = st_in_space;
291
381k
        }
292
35.5M
    } else if (ch == '%') {
293
34.3k
        before_token = !include_ignorable;
294
34.3k
        in_token = include_ignorable;
295
34.3k
        state = st_in_comment;
296
35.5M
    } else {
297
35.5M
        before_token = false;
298
35.5M
        in_token = true;
299
35.5M
        inTop(ch);
300
35.5M
    }
301
65.8M
}
302
303
void
304
Tokenizer::inTop(char ch)
305
35.5M
{
306
35.5M
    switch (ch) {
307
164k
    case '(':
308
164k
        string_depth = 1;
309
164k
        state = st_in_string;
310
164k
        return;
311
312
568k
    case '<':
313
568k
        state = st_lt;
314
568k
        return;
315
316
286k
    case '>':
317
286k
        state = st_gt;
318
286k
        return;
319
320
108k
    case (')'):
321
108k
        type = tt::tt_bad;
322
108k
        QTC::TC("qpdf", "QPDFTokenizer bad )");
323
108k
        error_message = "unexpected )";
324
108k
        state = st_token_ready;
325
108k
        return;
326
327
225k
    case '[':
328
225k
        type = tt::tt_array_open;
329
225k
        state = st_token_ready;
330
225k
        return;
331
332
168k
    case ']':
333
168k
        type = tt::tt_array_close;
334
168k
        state = st_token_ready;
335
168k
        return;
336
337
1.58M
    case '{':
338
1.58M
        type = tt::tt_brace_open;
339
1.58M
        state = st_token_ready;
340
1.58M
        return;
341
342
5.24k
    case '}':
343
5.24k
        type = tt::tt_brace_close;
344
5.24k
        state = st_token_ready;
345
5.24k
        return;
346
347
2.48M
    case '/':
348
2.48M
        state = st_name;
349
2.48M
        val += ch;
350
2.48M
        return;
351
352
1.26M
    case '0':
353
2.12M
    case '1':
354
2.41M
    case '2':
355
2.58M
    case '3':
356
2.83M
    case '4':
357
3.05M
    case '5':
358
3.22M
    case '6':
359
3.34M
    case '7':
360
3.57M
    case '8':
361
3.62M
    case '9':
362
3.62M
        state = st_number;
363
3.62M
        return;
364
365
4.55k
    case '+':
366
134k
    case '-':
367
134k
        state = st_sign;
368
134k
        return;
369
370
31.1k
    case '.':
371
31.1k
        state = st_decimal;
372
31.1k
        return;
373
374
26.1M
    default:
375
26.1M
        state = st_literal;
376
26.1M
        return;
377
35.5M
    }
378
35.5M
}
379
380
void
381
Tokenizer::inSpace(char ch)
382
810k
{
383
    // We only enter this state if include_ignorable is true.
384
810k
    if (!isSpace(ch)) {
385
376k
        type = tt::tt_space;
386
376k
        in_token = false;
387
376k
        char_to_unread = ch;
388
376k
        state = st_token_ready;
389
376k
    }
390
810k
}
391
392
void
393
Tokenizer::inComment(char ch)
394
5.65M
{
395
5.65M
    if ((ch == '\r') || (ch == '\n')) {
396
33.4k
        if (include_ignorable) {
397
1.30k
            type = tt::tt_comment;
398
1.30k
            in_token = false;
399
1.30k
            char_to_unread = ch;
400
1.30k
            state = st_token_ready;
401
32.1k
        } else {
402
32.1k
            state = st_before_token;
403
32.1k
        }
404
33.4k
    }
405
5.65M
}
406
407
void
408
Tokenizer::inString(char ch)
409
136M
{
410
136M
    switch (ch) {
411
168k
    case '\\':
412
168k
        state = st_string_escape;
413
168k
        return;
414
415
142k
    case '(':
416
142k
        val += ch;
417
142k
        ++string_depth;
418
142k
        return;
419
420
244k
    case ')':
421
244k
        if (--string_depth == 0) {
422
153k
            type = tt::tt_string;
423
153k
            state = st_token_ready;
424
153k
            return;
425
153k
        }
426
427
90.7k
        val += ch;
428
90.7k
        return;
429
430
249k
    case '\r':
431
        // CR by itself is converted to LF
432
249k
        val += '\n';
433
249k
        state = st_string_after_cr;
434
249k
        return;
435
436
606k
    case '\n':
437
606k
        val += ch;
438
606k
        return;
439
440
135M
    default:
441
135M
        val += ch;
442
135M
        return;
443
136M
    }
444
136M
}
445
446
void
447
Tokenizer::inName(char ch)
448
90.0M
{
449
90.0M
    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
2.40M
        type = bad ? tt::tt_bad : tt::tt_name;
457
2.40M
        in_token = false;
458
2.40M
        char_to_unread = ch;
459
2.40M
        state = st_token_ready;
460
87.6M
    } else if (ch == '#') {
461
1.92M
        char_code = 0;
462
1.92M
        state = st_name_hex1;
463
85.7M
    } else {
464
85.7M
        val += ch;
465
85.7M
    }
466
90.0M
}
467
468
void
469
Tokenizer::inNameHex1(char ch)
470
1.92M
{
471
1.92M
    hex_char = ch;
472
473
1.92M
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
474
26.6k
        char_code = int(hval) << 4;
475
26.6k
        state = st_name_hex2;
476
1.90M
    } else {
477
1.90M
        QTC::TC("qpdf", "QPDFTokenizer bad name 1");
478
1.90M
        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
1.90M
        val += '\0';
481
1.90M
        state = st_name;
482
1.90M
        inName(ch);
483
1.90M
    }
484
1.92M
}
485
486
void
487
Tokenizer::inNameHex2(char ch)
488
26.6k
{
489
26.6k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
490
10.2k
        char_code |= int(hval);
491
16.3k
    } else {
492
16.3k
        QTC::TC("qpdf", "QPDFTokenizer bad name 2");
493
16.3k
        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
16.3k
        val += '\0';
496
16.3k
        val += hex_char;
497
16.3k
        state = st_name;
498
16.3k
        inName(ch);
499
16.3k
        return;
500
16.3k
    }
501
10.2k
    if (char_code == 0) {
502
6.83k
        QTC::TC("qpdf", "QPDFTokenizer null in name");
503
6.83k
        error_message = "null character not allowed in name token";
504
6.83k
        val += "#00";
505
6.83k
        state = st_name;
506
6.83k
        bad = true;
507
6.83k
    } else {
508
3.44k
        val += char(char_code);
509
3.44k
        state = st_name;
510
3.44k
    }
511
10.2k
}
512
513
void
514
Tokenizer::inSign(char ch)
515
129k
{
516
129k
    if (util::is_digit(ch)) {
517
122k
        state = st_number;
518
122k
    } else if (ch == '.') {
519
592
        state = st_decimal;
520
6.74k
    } else {
521
6.74k
        state = st_literal;
522
6.74k
        inLiteral(ch);
523
6.74k
    }
524
129k
}
525
526
void
527
Tokenizer::inDecimal(char ch)
528
26.4k
{
529
26.4k
    if (util::is_digit(ch)) {
530
19.6k
        state = st_real;
531
19.6k
    } else {
532
6.82k
        state = st_literal;
533
6.82k
        inLiteral(ch);
534
6.82k
    }
535
26.4k
}
536
537
void
538
Tokenizer::inNumber(char ch)
539
6.88M
{
540
6.88M
    if (util::is_digit(ch)) {
541
3.54M
    } else if (ch == '.') {
542
257k
        state = st_real;
543
3.28M
    } else if (isDelimiter(ch)) {
544
3.20M
        type = tt::tt_integer;
545
3.20M
        state = st_token_ready;
546
3.20M
        in_token = false;
547
3.20M
        char_to_unread = ch;
548
3.20M
    } else {
549
82.6k
        state = st_literal;
550
82.6k
    }
551
6.88M
}
552
553
void
554
Tokenizer::inReal(char ch)
555
875k
{
556
875k
    if (util::is_digit(ch)) {
557
597k
    } else if (isDelimiter(ch)) {
558
267k
        type = tt::tt_real;
559
267k
        state = st_token_ready;
560
267k
        in_token = false;
561
267k
        char_to_unread = ch;
562
267k
    } else {
563
10.2k
        state = st_literal;
564
10.2k
    }
565
875k
}
566
void
567
Tokenizer::inStringEscape(char ch)
568
168k
{
569
168k
    state = st_in_string;
570
168k
    switch (ch) {
571
15.5k
    case '0':
572
16.4k
    case '1':
573
29.1k
    case '2':
574
43.0k
    case '3':
575
43.7k
    case '4':
576
44.2k
    case '5':
577
44.6k
    case '6':
578
45.2k
    case '7':
579
45.2k
        state = st_char_code;
580
45.2k
        char_code = 0;
581
45.2k
        digit_count = 0;
582
45.2k
        inCharCode(ch);
583
45.2k
        return;
584
585
7.61k
    case 'n':
586
7.61k
        val += '\n';
587
7.61k
        return;
588
589
2.23k
    case 'r':
590
2.23k
        val += '\r';
591
2.23k
        return;
592
593
32.9k
    case 't':
594
32.9k
        val += '\t';
595
32.9k
        return;
596
597
1.16k
    case 'b':
598
1.16k
        val += '\b';
599
1.16k
        return;
600
601
23.7k
    case 'f':
602
23.7k
        val += '\f';
603
23.7k
        return;
604
605
574
    case '\n':
606
574
        return;
607
608
293
    case '\r':
609
293
        state = st_string_after_cr;
610
293
        return;
611
612
54.4k
    default:
613
        // PDF spec says backslash is ignored before anything else
614
54.4k
        val += ch;
615
54.4k
        return;
616
168k
    }
617
168k
}
618
619
void
620
Tokenizer::inStringAfterCR(char ch)
621
249k
{
622
249k
    state = st_in_string;
623
249k
    if (ch != '\n') {
624
142k
        inString(ch);
625
142k
    }
626
249k
}
627
628
void
629
Tokenizer::inLt(char ch)
630
566k
{
631
566k
    if (ch == '<') {
632
360k
        type = tt::tt_dict_open;
633
360k
        state = st_token_ready;
634
360k
        return;
635
360k
    }
636
637
205k
    state = st_in_hexstring;
638
205k
    inHexstring(ch);
639
205k
}
640
641
void
642
Tokenizer::inGt(char ch)
643
285k
{
644
285k
    if (ch == '>') {
645
262k
        type = tt::tt_dict_close;
646
262k
        state = st_token_ready;
647
262k
    } else {
648
22.3k
        type = tt::tt_bad;
649
22.3k
        QTC::TC("qpdf", "QPDFTokenizer bad >");
650
22.3k
        error_message = "unexpected >";
651
22.3k
        in_token = false;
652
22.3k
        char_to_unread = ch;
653
22.3k
        state = st_token_ready;
654
22.3k
    }
655
285k
}
656
657
void
658
Tokenizer::inLiteral(char ch)
659
255M
{
660
255M
    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
14.3M
        in_token = false;
667
14.3M
        char_to_unread = ch;
668
14.3M
        state = st_token_ready;
669
14.3M
        type = (raw_val == "true") || (raw_val == "false")
670
14.3M
            ? tt::tt_bool
671
14.3M
            : (raw_val == "null" ? tt::tt_null : tt::tt_word);
672
14.3M
    }
673
255M
}
674
675
void
676
Tokenizer::inHexstring(char ch)
677
6.49M
{
678
6.49M
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
679
6.27M
        char_code = int(hval) << 4;
680
6.27M
        state = st_in_hexstring_2nd;
681
682
6.27M
    } else if (ch == '>') {
683
169k
        type = tt::tt_string;
684
169k
        state = st_token_ready;
685
686
169k
    } else if (isSpace(ch)) {
687
        // ignore
688
689
33.3k
    } else {
690
19.9k
        type = tt::tt_bad;
691
19.9k
        QTC::TC("qpdf", "QPDFTokenizer bad hexstring character");
692
19.9k
        error_message = std::string("invalid character (") + ch + ") in hexstring";
693
19.9k
        state = st_token_ready;
694
19.9k
    }
695
6.49M
}
696
697
void
698
Tokenizer::inHexstring2nd(char ch)
699
6.27M
{
700
6.27M
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
701
6.25M
        val += char(char_code) | hval;
702
6.25M
        state = st_in_hexstring;
703
704
6.25M
    } else if (ch == '>') {
705
        // PDF spec says odd hexstrings have implicit trailing 0.
706
6.20k
        val += char(char_code);
707
6.20k
        type = tt::tt_string;
708
6.20k
        state = st_token_ready;
709
710
15.6k
    } else if (isSpace(ch)) {
711
        // ignore
712
713
9.53k
    } else {
714
6.13k
        type = tt::tt_bad;
715
6.13k
        QTC::TC("qpdf", "QPDFTokenizer bad hexstring 2nd character");
716
6.13k
        error_message = std::string("invalid character (") + ch + ") in hexstring";
717
6.13k
        state = st_token_ready;
718
6.13k
    }
719
6.27M
}
720
721
void
722
Tokenizer::inCharCode(char ch)
723
128k
{
724
128k
    bool handled = false;
725
128k
    if (('0' <= ch) && (ch <= '7')) {
726
119k
        char_code = 8 * char_code + (int(ch) - int('0'));
727
119k
        if (++(digit_count) < 3) {
728
83.5k
            return;
729
83.5k
        }
730
36.0k
        handled = true;
731
36.0k
    }
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
44.4k
    val += char(char_code % 256);
735
44.4k
    state = st_in_string;
736
44.4k
    if (!handled) {
737
8.47k
        inString(ch);
738
8.47k
    }
739
44.4k
}
740
741
void
742
Tokenizer::inInlineImage(char ch)
743
11.4M
{
744
11.4M
    if ((raw_val.length() + 1) == inline_image_bytes) {
745
2.47k
        QTC::TC("qpdf", "QPDFTokenizer found EI by byte count");
746
2.47k
        type = tt::tt_inline_image;
747
2.47k
        inline_image_bytes = 0;
748
2.47k
        state = st_token_ready;
749
2.47k
    }
750
11.4M
}
751
752
void
753
QPDFTokenizer::presentEOF()
754
0
{
755
0
    m->presentEOF();
756
0
}
757
758
void
759
Tokenizer::presentEOF()
760
63.9k
{
761
63.9k
    switch (state) {
762
1.79k
    case st_name:
763
1.96k
    case st_name_hex1:
764
2.13k
    case st_name_hex2:
765
8.57k
    case st_number:
766
8.81k
    case st_real:
767
8.95k
    case st_sign:
768
9.05k
    case st_decimal:
769
21.5k
    case st_literal:
770
21.5k
        QTC::TC("qpdf", "QPDFTokenizer EOF reading appendable token");
771
        // Push any delimiter to the state machine to finish off the final token.
772
21.5k
        presentCharacter('\f');
773
21.5k
        in_token = true;
774
21.5k
        break;
775
776
0
    case st_top:
777
33.2k
    case st_before_token:
778
33.2k
        type = tt::tt_eof;
779
33.2k
        break;
780
781
4.65k
    case st_in_space:
782
4.65k
        type = include_ignorable ? tt::tt_space : tt::tt_eof;
783
4.65k
        break;
784
785
856
    case st_in_comment:
786
856
        type = include_ignorable ? tt::tt_comment : tt::tt_bad;
787
856
        break;
788
789
0
    case st_token_ready:
790
0
        break;
791
792
3.60k
    default:
793
3.60k
        QTC::TC("qpdf", "QPDFTokenizer EOF reading token");
794
3.60k
        type = tt::tt_bad;
795
3.60k
        error_message = "EOF while reading token";
796
63.9k
    }
797
63.9k
    state = st_token_ready;
798
63.9k
}
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
1.23k
{
809
1.23k
    m->expectInlineImage(input);
810
1.23k
}
811
812
void
813
Tokenizer::expectInlineImage(InputSource& input)
814
2.66k
{
815
2.66k
    if (state == st_token_ready) {
816
1.43k
        reset();
817
1.43k
    } 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
2.66k
    findEI(input);
822
2.66k
    before_token = false;
823
2.66k
    in_token = true;
824
2.66k
    state = st_inline_image;
825
2.66k
}
826
827
void
828
Tokenizer::findEI(InputSource& input)
829
2.66k
{
830
2.66k
    qpdf_offset_t last_offset = input.getLastOffset();
831
2.66k
    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
2.66k
    bool okay = false;
841
2.66k
    bool first_try = true;
842
15.2k
    while (!okay) {
843
13.3k
        QPDFWordTokenFinder f(input, "EI");
844
13.3k
        if (!input.findFirst("EI", input.tell(), 0, f)) {
845
677
            break;
846
677
        }
847
12.6k
        inline_image_bytes = QIntC::to_size(input.tell() - pos - 2);
848
849
12.6k
        Tokenizer check;
850
12.6k
        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
42.4k
        for (int i = 0; i < 10; ++i) {
857
40.5k
            check.nextToken(input, "checker");
858
40.5k
            auto typ = check.getType();
859
40.5k
            if (typ == tt::tt_eof) {
860
0
                okay = true;
861
40.5k
            } else if (typ == tt::tt_bad) {
862
5.01k
                found_bad = true;
863
35.4k
            } 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
18.1k
                bool found_alpha = false;
870
18.1k
                bool found_non_printable = false;
871
18.1k
                bool found_other = false;
872
102k
                for (char ch: check.getValue()) {
873
102k
                    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
58.8k
                        found_alpha = true;
877
58.8k
                    } 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
2.80k
                        found_non_printable = true;
880
2.80k
                        break;
881
40.7k
                    } else {
882
40.7k
                        found_other = true;
883
40.7k
                    }
884
102k
                }
885
18.1k
                if (found_non_printable || (found_alpha && found_other)) {
886
5.63k
                    found_bad = true;
887
5.63k
                }
888
18.1k
            }
889
40.5k
            if (okay || found_bad) {
890
10.6k
                break;
891
10.6k
            }
892
40.5k
        }
893
12.6k
        if (!found_bad) {
894
1.98k
            okay = true;
895
1.98k
        }
896
12.6k
        if (!okay) {
897
10.6k
            first_try = false;
898
10.6k
        }
899
12.6k
    }
900
2.66k
    if (okay && (!first_try)) {
901
150
        QTC::TC("qpdf", "QPDFTokenizer found EI after more than one try");
902
150
    }
903
904
2.66k
    input.seek(pos, SEEK_SET);
905
2.66k
    input.setLastOffset(last_offset);
906
2.66k
}
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
5.59M
{
917
5.59M
    bool ready = (state == st_token_ready);
918
5.59M
    unread_char = !in_token && !before_token;
919
5.59M
    ch = char_to_unread;
920
5.59M
    if (ready) {
921
5.59M
        token = (!(type == tt::tt_name || type == tt::tt_string))
922
5.59M
            ? Token(type, raw_val, raw_val, error_message)
923
5.59M
            : Token(type, val, raw_val, error_message);
924
925
5.59M
        reset();
926
5.59M
    }
927
5.59M
    return ready;
928
5.59M
}
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
2.60M
{
946
2.60M
    return m->readToken(input, context, allow_bad, max_len);
947
2.60M
}
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
5.59M
{
959
5.59M
    nextToken(input, context, max_len);
960
961
5.59M
    Token token;
962
5.59M
    bool unread_char;
963
5.59M
    char char_to_unread;
964
5.59M
    getToken(token, unread_char, char_to_unread);
965
966
5.59M
    if (token.getType() == tt::tt_bad) {
967
317k
        if (allow_bad) {
968
317k
            QTC::TC("qpdf", "QPDFTokenizer allowing bad token");
969
317k
        } 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
317k
    }
978
5.59M
    return token;
979
5.59M
}
980
981
bool
982
Tokenizer::nextToken(InputSource& input, std::string const& context, size_t max_len)
983
35.9M
{
984
35.9M
    if (state != st_inline_image) {
985
35.9M
        reset();
986
35.9M
    }
987
35.9M
    qpdf_offset_t offset = input.fastTell();
988
989
623M
    while (state != st_token_ready) {
990
587M
        char ch;
991
587M
        if (!input.fastRead(ch)) {
992
63.9k
            presentEOF();
993
994
63.9k
            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
103
                type = tt::tt_bad;
998
103
                error_message = "unexpected EOF";
999
103
                offset = input.getLastOffset();
1000
103
            }
1001
587M
        } else {
1002
587M
            handleCharacter(ch);
1003
587M
            if (before_token) {
1004
32.0M
                ++offset;
1005
32.0M
            }
1006
587M
            if (in_token) {
1007
534M
                raw_val += ch;
1008
534M
            }
1009
587M
            if (max_len && (raw_val.length() >= max_len) && (state != st_token_ready)) {
1010
                // terminate this token now
1011
12.1M
                QTC::TC("qpdf", "QPDFTokenizer block long token");
1012
12.1M
                type = tt::tt_bad;
1013
12.1M
                state = st_token_ready;
1014
12.1M
                error_message = "exceeded allowable length while reading token";
1015
12.1M
            }
1016
587M
        }
1017
587M
    }
1018
1019
35.9M
    input.fastUnread(!in_token && !before_token);
1020
1021
35.9M
    if (type != tt::tt_eof) {
1022
35.9M
        input.setLastOffset(offset);
1023
35.9M
    }
1024
1025
35.9M
    return error_message.empty();
1026
35.9M
}