Coverage Report

Created: 2025-11-09 06:17

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