aboutsummaryrefslogtreecommitdiffstats
path: root/libqpdf/QPDFTokenizer.cc
blob: 4d9b375a2d72e48f6cd42643017e3e776234fe78 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#include <qpdf/QPDFTokenizer.hh>

// DO NOT USE ctype -- it is locale dependent for some things, and
// it's not worth the risk of including it in case it may accidentally
// be used.

#include <qpdf/PCRE.hh>
#include <qpdf/QTC.hh>

#include <stdexcept>
#include <string.h>

// See note above about ctype.
static bool is_hex_digit(char ch)
{
    return (strchr("0123456789abcdefABCDEF", ch) != 0);
}

DLL_EXPORT
QPDFTokenizer::QPDFTokenizer() :
    pound_special_in_name(true)
{
    reset();
}

DLL_EXPORT
void
QPDFTokenizer::allowPoundAnywhereInName()
{
    QTC::TC("qpdf", "QPDFTokenizer allow pound anywhere in name");
    this->pound_special_in_name = false;
}

void
QPDFTokenizer::reset()
{
    state = st_top;
    type = tt_bad;
    val = "";
    raw_val = "";
    error_message = "";
    unread_char = false;
    char_to_unread = '\0';
    string_depth = 0;
    string_ignoring_newline = false;
    last_char_was_bs = false;
}

DLL_EXPORT
void
QPDFTokenizer::presentCharacter(char ch)
{
    static PCRE num_re("^[\\+\\-]?(?:\\.\\d+|\\d+(?:\\.\\d+)?)$");

    if (state == st_token_ready)
    {
	throw std::logic_error(
	    "INTERNAL ERROR: QPDF tokenizer presented character "
	    "while token is waiting");
    }

    char orig_ch = ch;

    // State machine is implemented such that some characters may be
    // handled more than once.  This happens whenever you have to use
    // the character that caused a state change in the new state.

    bool handled = true;
    if (state == st_top)
    {
	// Note: we specifically do not use ctype here.  It is
	// locale-dependent.
	if (strchr(" \t\n\v\f\r", ch))
	{
	    // ignore
	}
	else if (ch == '%')
	{
	    // Discard comments
	    state = st_in_comment;
	}
	else if (ch == '(')
	{
	    string_depth = 1;
	    string_ignoring_newline = false;
	    memset(bs_num_register, '\0', sizeof(bs_num_register));
	    last_char_was_bs = false;
	    state = st_in_string;
	}
	else if (ch == '<')
	{
	    state = st_lt;
	}
	else if (ch == '>')
	{
	    state = st_gt;
	}
	else
	{
	    val += ch;
	    if (ch == ')')
	    {
		type = tt_bad;
		QTC::TC("qpdf", "QPDF_Tokenizer bad )");
		error_message = "unexpected )";
		state = st_token_ready;
	    }
	    else if (ch == '[')
	    {
		type = tt_array_open;
		state = st_token_ready;
	    }
	    else if (ch == ']')
	    {
		type = tt_array_close;
		state = st_token_ready;
	    }
	    else if (ch == '{')
	    {
		type = tt_brace_open;
		state = st_token_ready;
	    }
	    else if (ch == '}')
	    {
		type = tt_brace_close;
		state = st_token_ready;
	    }
	    else
	    {
		state = st_literal;
	    }
	}
    }
    else if (state == st_in_comment)
    {
	if ((ch == '\r') || (ch == '\n'))
	{
	    state = st_top;
	}
    }
    else if (state == st_lt)
    {
	if (ch == '<')
	{
	    val = "<<";
	    type = tt_dict_open;
	    state = st_token_ready;
	}
	else
	{
	    handled = false;
	    state = st_in_hexstring;
	}
    }
    else if (state == st_gt)
    {
	if (ch == '>')
	{
	    val = ">>";
	    type = tt_dict_close;
	    state = st_token_ready;
	}
	else
	{
	    val = ">";
	    type = tt_bad;
	    QTC::TC("qpdf", "QPDF_Tokenizer bad >");
	    error_message = "unexpected >";
	    unread_char = true;
	    char_to_unread = ch;
	    state = st_token_ready;
	}
    }
    else if (state == st_in_string)
    {
	if (string_ignoring_newline && (! ((ch == '\r') || (ch == '\n'))))
	{
	    string_ignoring_newline = false;
	}

	unsigned int bs_num_count = strlen(bs_num_register);
	bool ch_is_octal = ((ch >= '0') && (ch <= '7'));
	if ((bs_num_count == 3) || ((bs_num_count > 0) && (! ch_is_octal)))
	{
	    // We've accumulated \ddd.  PDF Spec says to ignore
	    // high-order overflow.
	    val += (char) strtol(bs_num_register, 0, 8);
	    memset(bs_num_register, '\0', sizeof(bs_num_register));
	    bs_num_count = 0;
	}

	if (string_ignoring_newline && ((ch == '\r') || (ch == '\n')))
	{
	    // ignore
	}
	else if (ch_is_octal && (last_char_was_bs || (bs_num_count > 0)))
	{
	    bs_num_register[bs_num_count++] = ch;
	}
	else if (last_char_was_bs)
	{
	    switch (ch)
	    {
	      case 'n':
		val += '\n';
		break;

	      case 'r':
		val += '\r';
		break;

	      case 't':
		val += '\t';
		break;

	      case 'b':
		val += '\b';
		break;

	      case 'f':
		val += '\f';
		break;

	      case '\r':
	      case '\n':
		string_ignoring_newline = true;
		break;

	      default:
		// PDF spec says backslash is ignored before anything else
		val += ch;
		break;
	    }
	}
	else if (ch == '\\')
	{
	    // last_char_was_bs is set/cleared below as appropriate
	    if (bs_num_count)
	    {
		throw std::logic_error(
		    "INTERNAL ERROR: QPDFTokenizer: bs_num_count != 0 "
		    "when ch == '\\'");
	    }
	}
	else if (ch == '(')
	{
	    val += ch;
	    ++string_depth;
	}
	else if ((ch == ')') && (--string_depth == 0))
	{
	    type = tt_string;
	    state = st_token_ready;
	}
	else
	{
	    val += ch;
	}

	last_char_was_bs = ((! last_char_was_bs) && (ch == '\\'));
    }
    else if (state == st_literal)
    {
	if (strchr(" \t\n\v\f\r()<>[]{}/%", ch) != 0)
	{
	    // A C-locale whitespace character or delimiter terminates
	    // token.  It is important to unread the whitespace
	    // character even though it is ignored since it may be the
	    // newline after a stream keyword.  Removing it here could
	    // make the stream-reading code break on some files,
	    // though not on any files in the test suite as of this
	    // writing.

	    type = tt_word;
	    unread_char = true;
	    char_to_unread = ch;
	    state = st_token_ready;
	}
	else
	{
	    val += ch;
	}
    }
    else
    {
	handled = false;
    }


    if (handled)
    {
	// okay
    }
    else if (state == st_in_hexstring)
    {
	if (ch == '>')
	{
	    type = tt_string;
	    state = st_token_ready;
	    if (val.length() % 2)
	    {
		// PDF spec says odd hexstrings have implicit
		// trailing 0.
		val += '0';
	    }
	    char num[3];
	    num[2] = '\0';
	    std::string nval;
	    for (unsigned int i = 0; i < val.length(); i += 2)
	    {
		num[0] = val[i];
		num[1] = val[i+1];
		char nch = (char)(strtol(num, 0, 16));
		nval += nch;
	    }
	    val = nval;
	}
	else if (is_hex_digit(ch))
	{
	    val += ch;
	}
	else if (strchr(" \t\n\v\f\r", ch))
	{
	    // ignore
	}
	else
	{
	    type = tt_bad;
	    QTC::TC("qpdf", "QPDF_Tokenizer bad (");
	    error_message = std::string("invalid character (") +
		ch + ") in hexstring";
	    state = st_token_ready;
	}
    }
    else
    {
	throw std::logic_error(
	    "INTERNAL ERROR: invalid state while reading token");
    }

    if ((state == st_token_ready) && (type == tt_word))
    {
	if ((val.length() > 0) && (val[0] == '/'))
	{
	    type = tt_name;
	    // Deal with # in name token.  Note: '/' by itself is a
	    // valid name, so don't strip leading /.  That way we
	    // don't have to deal with the empty string as a name.
	    std::string nval = "/";
	    char const* valstr = val.c_str() + 1;
	    for (char const* p = valstr; *p; ++p)
	    {
		if ((*p == '#') && this->pound_special_in_name)
		{
		    if (p[1] && p[2] &&
			is_hex_digit(p[1]) && is_hex_digit(p[2]))
		    {
			char num[3];
			num[0] = p[1];
			num[1] = p[2];
			num[2] = '\0';
			char ch = (char)(strtol(num, 0, 16));
			if (ch == '\0')
			{
			    type = tt_bad;
			    QTC::TC("qpdf", "QPDF_Tokenizer null in name");
			    error_message =
				"null character not allowed in name token";
			    nval += "#00";
			}
			else
			{
			    nval += ch;
			}
			p += 2;
		    }
		    else
		    {
			QTC::TC("qpdf", "QPDF_Tokenizer bad name");
			type = tt_bad;
			error_message = "invalid name token";
			nval += *p;
		    }
		}
		else
		{
		    nval += *p;
		}
	    }
	    val = nval;
	}
	else if (num_re.match(val.c_str()))
	{
	    if (val.find('.') != std::string::npos)
	    {
		type = tt_real;
	    }
	    else
	    {
		type = tt_integer;
	    }
	}
	else if ((val == "true") || (val == "false"))
	{
	    type = tt_bool;
	}
	else if (val == "null")
	{
	    type = tt_null;
	}
	else
	{
	    // I don't really know what it is, so leave it as tt_word.
	    // Lots of cases ($, #, etc.) other than actual words fall
	    // into this category, but that's okay at least for now.
	    type = tt_word;
	}
    }

    if (! (betweenTokens() || ((state == st_token_ready) && unread_char)))
    {
	this->raw_val += orig_ch;
    }
}

DLL_EXPORT
void
QPDFTokenizer::presentEOF()
{
    switch (state)
    {
      case st_token_ready:
      case st_top:
	// okay
	break;

      case st_in_comment:
	state = st_top;
	break;

      default:
	type = tt_bad;
	error_message = "EOF while reading token";
	state = st_token_ready;
    }
}

DLL_EXPORT
bool
QPDFTokenizer::getToken(Token& token, bool& unread_char, char& ch)
{
    bool ready = (this->state == st_token_ready);
    unread_char = this->unread_char;
    ch = this->char_to_unread;
    if (ready)
    {
	token = Token(type, val, raw_val, error_message);
	reset();
    }
    return ready;
}

DLL_EXPORT
bool
QPDFTokenizer::betweenTokens()
{
    return ((state == st_top) || (state == st_in_comment));
}