Coverage Report

Created: 2025-07-12 06:26

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