Coverage Report

Created: 2025-07-18 07:03

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