Coverage Report

Created: 2025-11-24 06:48

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