Coverage Report

Created: 2026-01-25 06:25

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