Coverage Report

Created: 2026-06-16 06:39

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