summaryrefslogtreecommitdiffstats
path: root/src/HTTP/TransferEncodingParser.cpp
blob: a14900e9ce1d250fce4824916522c045d8bcfaa9 (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

// TransferEncodingParser.cpp

// Implements the cTransferEncodingParser class and its descendants representing the parsers for the various transfer encodings (chunked etc.)

#include "Globals.h"
#include "TransferEncodingParser.h"
#include "EnvelopeParser.h"





////////////////////////////////////////////////////////////////////////////////
// cChunkedTEParser:

class cChunkedTEParser:
	public cTransferEncodingParser,
	public cEnvelopeParser::cCallbacks
{
	typedef cTransferEncodingParser Super;

public:
	cChunkedTEParser(Super::cCallbacks & a_Callbacks):
		Super(a_Callbacks),
		m_State(psChunkLength),
		m_ChunkDataLengthLeft(0),
		m_TrailerParser(*this)
	{
	}


protected:
	enum eState
	{
		psChunkLength,         ///< Parsing the chunk length hex number
		psChunkLengthTrailer,  ///< Any trailer (chunk extension) specified after the chunk length
		psChunkLengthLF,       ///< The LF character after the CR character terminating the chunk length
		psChunkData,           ///< Relaying chunk data
		psChunkDataCR,         ///< Skipping the extra CR character after chunk data
		psChunkDataLF,         ///< Skipping the extra LF character after chunk data
		psTrailer,             ///< Received an empty chunk, parsing the trailer (through the envelope parser)
		psFinished,            ///< The parser has finished parsing, either successfully or with an error
	};

	/** The current state of the parser (parsing chunk length / chunk data). */
	eState m_State;

	/** Number of bytes that still belong to the chunk currently being parsed.
	When in psChunkLength, the value is the currently parsed length digits. */
	size_t m_ChunkDataLengthLeft;

	/** The parser used for the last (empty) chunk's trailer data */
	cEnvelopeParser m_TrailerParser;


	/** Calls the OnError callback and sets parser state to finished. */
	void Error(const AString & a_ErrorMsg)
	{
		m_State = psFinished;
		m_Callbacks.OnError(a_ErrorMsg);
	}


	/** Parses the incoming data, the current state is psChunkLength.
	Stops parsing when either the chunk length has been read, or there is no more data in the input.
	Returns the number of bytes consumed from the input, or AString::npos on error (calls the Error handler). */
	size_t ParseChunkLength(const char * a_Data, size_t a_Size)
	{
		// Expected input: <hexnumber>[;<trailer>]<CR><LF>
		// Only the hexnumber is parsed into m_ChunkDataLengthLeft, the rest is postponed into psChunkLengthTrailer or psChunkLengthLF
		for (size_t i = 0; i < a_Size; i++)
		{
			switch (a_Data[i])
			{
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
				{
					m_ChunkDataLengthLeft = m_ChunkDataLengthLeft * 16 + static_cast<decltype(m_ChunkDataLengthLeft)>(a_Data[i] - '0');
					break;
				}
				case 'a':
				case 'b':
				case 'c':
				case 'd':
				case 'e':
				case 'f':
				{
					m_ChunkDataLengthLeft = m_ChunkDataLengthLeft * 16 + static_cast<decltype(m_ChunkDataLengthLeft)>(a_Data[i] - 'a' + 10);
					break;
				}
				case 'A':
				case 'B':
				case 'C':
				case 'D':
				case 'E':
				case 'F':
				{
					m_ChunkDataLengthLeft = m_ChunkDataLengthLeft * 16 + static_cast<decltype(m_ChunkDataLengthLeft)>(a_Data[i] - 'A' + 10);
					break;
				}
				case '\r':
				{
					m_State = psChunkLengthLF;
					return i + 1;
				}
				case ';':
				{
					m_State = psChunkLengthTrailer;
					return i + 1;
				}
				default:
				{
					Error(Printf("Invalid character in chunk length line: 0x%x", a_Data[i]));
					return AString::npos;
				}
			}  // switch (a_Data[i])
		}  // for i - a_Data[]
		return a_Size;
	}


	/** Parses the incoming data, the current state is psChunkLengthTrailer.
	Stops parsing when either the chunk length trailer has been read, or there is no more data in the input.
	Returns the number of bytes consumed from the input, or AString::npos on error (calls the Error handler). */
	size_t ParseChunkLengthTrailer(const char * a_Data, size_t a_Size)
	{
		// Expected input: <trailer><CR><LF>
		// The LF itself is not parsed, it is instead postponed into psChunkLengthLF
		for (size_t i = 0; i < a_Size; i++)
		{
			switch (a_Data[i])
			{
				case '\r':
				{
					m_State = psChunkLengthLF;
					return i;
				}
				default:
				{
					if (a_Data[i] < 32)
					{
						// Only printable characters are allowed in the trailer
						Error(Printf("Invalid character in chunk length line: 0x%x", a_Data[i]));
						return AString::npos;
					}
				}
			}  // switch (a_Data[i])
		}  // for i - a_Data[]
		return a_Size;
	}


	/** Parses the incoming data, the current state is psChunkLengthLF.
	Only the LF character is expected, if found, moves to psChunkData, otherwise issues an error.
	If the chunk length that just finished reading is equal to 0, signals the end of stream (via psTrailer).
	Returns the number of bytes consumed from the input, or AString::npos on error (calls the Error handler). */
	size_t ParseChunkLengthLF(const char * a_Data, size_t a_Size)
	{
		// Expected input: <LF>
		if (a_Size == 0)
		{
			return 0;
		}
		if (a_Data[0] == '\n')
		{
			if (m_ChunkDataLengthLeft == 0)
			{
				m_State = psTrailer;
			}
			else
			{
				m_State = psChunkData;
			}
			return 1;
		}
		Error(Printf("Invalid character past chunk length's CR: 0x%x", a_Data[0]));
		return AString::npos;
	}


	/** Consumes as much chunk data from the input as possible.
	Returns the number of bytes consumed from the input, or AString::npos on error (calls the Error() handler). */
	size_t ParseChunkData(const char * a_Data, size_t a_Size)
	{
		ASSERT(m_ChunkDataLengthLeft > 0);
		auto bytes = std::min(a_Size, m_ChunkDataLengthLeft);
		m_ChunkDataLengthLeft -= bytes;
		m_Callbacks.OnBodyData(a_Data, bytes);
		if (m_ChunkDataLengthLeft == 0)
		{
			m_State = psChunkDataCR;
		}
		return bytes;
	}


	/** Parses the incoming data, the current state is psChunkDataCR.
	Only the CR character is expected, if found, moves to psChunkDataLF, otherwise issues an error.
	Returns the number of bytes consumed from the input, or AString::npos on error (calls the Error handler). */
	size_t ParseChunkDataCR(const char * a_Data, size_t a_Size)
	{
		// Expected input: <CR>
		if (a_Size == 0)
		{
			return 0;
		}
		if (a_Data[0] == '\r')
		{
			m_State = psChunkDataLF;
			return 1;
		}
		Error(Printf("Invalid character past chunk data: 0x%x", a_Data[0]));
		return AString::npos;
	}




	/** Parses the incoming data, the current state is psChunkDataCR.
	Only the CR character is expected, if found, moves to psChunkDataLF, otherwise issues an error.
	Returns the number of bytes consumed from the input, or AString::npos on error (calls the Error handler). */
	size_t ParseChunkDataLF(const char * a_Data, size_t a_Size)
	{
		// Expected input: <LF>
		if (a_Size == 0)
		{
			return 0;
		}
		if (a_Data[0] == '\n')
		{
			m_State = psChunkLength;
			return 1;
		}
		Error(Printf("Invalid character past chunk data's CR: 0x%x", a_Data[0]));
		return AString::npos;
	}


	/** Parses the incoming data, the current state is psChunkDataCR.
	The trailer is normally a set of "Header: Value" lines, terminated by an empty line. Use the m_TrailerParser for that.
	Returns the number of bytes consumed from the input, or AString::npos on error (calls the Error handler). */
	size_t ParseTrailer(const char * a_Data, size_t a_Size)
	{
		auto res = m_TrailerParser.Parse(a_Data, a_Size);
		if (res == AString::npos)
		{
			Error("Error while parsing the trailer");
		}
		if ((res < a_Size) || !m_TrailerParser.IsInHeaders())
		{
			m_Callbacks.OnBodyFinished();
			m_State = psFinished;
		}
		return res;
	}


	// cTransferEncodingParser overrides:
	virtual size_t Parse(const char * a_Data, size_t a_Size) override
	{
		while ((a_Size > 0) && (m_State != psFinished))
		{
			size_t consumed = 0;
			switch (m_State)
			{
				case psChunkLength:        consumed = ParseChunkLength       (a_Data, a_Size); break;
				case psChunkLengthTrailer: consumed = ParseChunkLengthTrailer(a_Data, a_Size); break;
				case psChunkLengthLF:      consumed = ParseChunkLengthLF     (a_Data, a_Size); break;
				case psChunkData:          consumed = ParseChunkData         (a_Data, a_Size); break;
				case psChunkDataCR:        consumed = ParseChunkDataCR       (a_Data, a_Size); break;
				case psChunkDataLF:        consumed = ParseChunkDataLF       (a_Data, a_Size); break;
				case psTrailer:            consumed = ParseTrailer           (a_Data, a_Size); break;
				case psFinished:           consumed = 0;                                       break;  // Not supposed to happen, but Clang complains without it
			}
			if (consumed == AString::npos)
			{
				return AString::npos;
			}
			a_Data += consumed;
			a_Size -= consumed;
		}
		return a_Size;
	}

	virtual void Finish(void) override
	{
		if (m_State != psFinished)
		{
			Error(Printf("ChunkedTransferEncoding: Finish signal received before the data stream ended (state: %d)", m_State));
		}
		m_State = psFinished;
	}


	// cEnvelopeParser::cCallbacks overrides:
	virtual void OnHeaderLine(const AString & a_Key, const AString & a_Value) override
	{
		// Ignored
	}
};





////////////////////////////////////////////////////////////////////////////////
// cIdentityTEParser:

class cIdentityTEParser:
	public cTransferEncodingParser
{
	typedef cTransferEncodingParser Super;

public:
	cIdentityTEParser(cCallbacks & a_Callbacks, size_t a_ContentLength):
		Super(a_Callbacks),
		m_BytesLeft(a_ContentLength)
	{
	}


protected:
	/** How many bytes of content are left before the message ends. */
	size_t m_BytesLeft;

	// cTransferEncodingParser overrides:
	virtual size_t Parse(const char * a_Data, size_t a_Size) override
	{
		auto size = std::min(a_Size, m_BytesLeft);
		if (size > 0)
		{
			m_Callbacks.OnBodyData(a_Data, size);
		}
		m_BytesLeft -= size;
		if (m_BytesLeft == 0)
		{
			m_Callbacks.OnBodyFinished();
		}
		return a_Size - size;
	}

	virtual void Finish(void) override
	{
		if (m_BytesLeft > 0)
		{
			m_Callbacks.OnError("IdentityTransferEncoding: body was truncated");
		}
		else
		{
			// BodyFinished has already been called, just bail out
		}
	}
};





////////////////////////////////////////////////////////////////////////////////
// cTransferEncodingParser:

cTransferEncodingParserPtr cTransferEncodingParser::Create(
	cCallbacks & a_Callbacks,
	const AString & a_TransferEncoding,
	size_t a_ContentLength
)
{
	if (a_TransferEncoding == "chunked")
	{
		return std::make_shared<cChunkedTEParser>(a_Callbacks);
	}
	if (a_TransferEncoding == "identity")
	{
		return std::make_shared<cIdentityTEParser>(a_Callbacks, a_ContentLength);
	}
	if (a_TransferEncoding.empty())
	{
		return std::make_shared<cIdentityTEParser>(a_Callbacks, a_ContentLength);
	}
	return nullptr;
}