Coverage Report

Created: 2026-04-12 06:59

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