summaryrefslogtreecommitdiffstats
path: root/source/HTTPServer/HTTPMessage.cpp
blob: b2e21c712028920501801cac29774f6a5df75c75 (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

// HTTPMessage.cpp

// Declares the cHTTPMessage class representing the common ancestor for HTTP request and response classes

#include "Globals.h"
#include "HTTPMessage.h"





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cHTTPMessage:

cHTTPMessage::cHTTPMessage(eKind a_Kind) :
	m_Kind(a_Kind)
{
}





void cHTTPMessage::AddHeader(const AString & a_Key, const AString & a_Value)
{
	cNameValueMap::iterator itr = m_Headers.find(a_Key);
	if (itr == m_Headers.end())
	{
		m_Headers[a_Key] = a_Value;
	}
	else
	{
		// The header-field key is specified multiple times, combine into comma-separated list (RFC 2616 @ 4.2)
		itr->second.append(", ");
		itr->second.append(a_Value);
	}
	
	// Special processing for well-known headers:
	if (a_Key == "Content-Type")
	{
		m_ContentType = m_Headers["Content-Type"];
	}
	else if (a_Key == "Content-Length")
	{
		m_ContentLength = atoi(m_Headers["Content-Length"].c_str());
	}
}





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cHTTPRequest:

cHTTPRequest::cHTTPRequest(void) :
	super(mkRequest)
{
}





bool cHTTPRequest::ParseHeaders(const char * a_IncomingData, size_t a_IdxEnd)
{
	// The first line contains the method and the URL:
	size_t Next = ParseRequestLine(a_IncomingData, a_IdxEnd);
	if (Next == AString::npos)
	{
		return false;
	}
	
	// The following lines contain headers:
	AString Key;
	const char * Data = a_IncomingData + Next;
	size_t End = a_IdxEnd - Next;
	while (End > 0)
	{
		Next = ParseHeaderField(Data, End, Key);
		if (Next == AString::npos)
		{
			return false;
		}
		ASSERT(End >= Next);
		Data += Next;
		End -= Next;
	}
	
	if (!HasReceivedContentLength())
	{
		SetContentLength(0);
	}
	return true;
}




size_t cHTTPRequest::ParseRequestLine(const char * a_Data, size_t a_IdxEnd)
{	
	// Ignore the initial CRLFs (HTTP spec's "should")
	size_t LineStart = 0;
	while (
		(LineStart < a_IdxEnd) &&
		(
			(a_Data[LineStart] == '\r') ||
			(a_Data[LineStart] == '\n')
		)
	)
	{
		LineStart++;
	}
	if (LineStart >= a_IdxEnd)
	{
		return AString::npos;
	}
	
	size_t Last = LineStart;
	int NumSpaces = 0;
	for (size_t i = LineStart; i < a_IdxEnd; i++)
	{
		switch (a_Data[i])
		{
			case ' ':
			{
				switch (NumSpaces)
				{
					case 0:
					{
						m_Method.assign(a_Data, Last, i - Last);
						break;
					}
					case 1:
					{
						m_URL.assign(a_Data, Last, i - Last);
						break;
					}
					default:
					{
						// Too many spaces in the request
						return AString::npos;
					}
				}
				Last = i + 1;
				NumSpaces += 1;
				break;
			}
			case '\n':
			{
				if ((i == 0) || (a_Data[i - 1] != '\r') || (NumSpaces != 2) || (i < Last + 7))
				{
					// LF too early, without a CR, without two preceeding spaces or too soon after the second space
					return AString::npos;
				}
				// Check that there's HTTP/version at the end
				if (strncmp(a_Data + Last, "HTTP/1.", 7) != 0)
				{
					return AString::npos;
				}
				return i + 1;
			}
		}  // switch (a_Data[i])
	}  // for i - a_Data[]
	return AString::npos;
}





size_t cHTTPRequest::ParseHeaderField(const char * a_Data, size_t a_IdxEnd, AString & a_Key)
{
	if (*a_Data <= ' ')
	{
		size_t res = ParseHeaderFieldContinuation(a_Data + 1, a_IdxEnd - 1, a_Key);
		return (res == AString::npos) ? res : (res + 1);
	}
	size_t ValueIdx = 0;
	AString Key;
	for (size_t i = 0; i < a_IdxEnd; i++)
	{
		switch (a_Data[i])
		{
			case '\n':
			{
				if ((ValueIdx == 0) || (i < ValueIdx - 2) || (i == 0) || (a_Data[i - 1] != '\r'))
				{
					// Invalid header field - no colon or no CR before LF
					return AString::npos;
				}
				AString Value(a_Data, ValueIdx + 1, i - ValueIdx - 2);
				AddHeader(Key, Value);
				a_Key = Key;
				return i + 1;
			}
			case ':':
			{
				if (ValueIdx == 0)
				{
					Key.assign(a_Data, 0, i);
					ValueIdx = i;
				}
				break;
			}
			case ' ':
			case '\t':
			{
				if (ValueIdx == i - 1)
				{
					// Value has started in this char, but it is whitespace, so move the start one char further
					ValueIdx = i;
				}
			}
		}  // switch (char)
	}  // for i - m_IncomingHeaderData[]
	// No header found, return the end-of-data index:
	return a_IdxEnd;
}





size_t cHTTPRequest::ParseHeaderFieldContinuation(const char * a_Data, size_t a_IdxEnd, AString & a_Key)
{
	size_t Start = 0;
	for (size_t i = 0; i < a_IdxEnd; i++)
	{
		if ((a_Data[i] > ' ') && (Start == 0))
		{
			Start = i;
		}
		else if (a_Data[i] == '\n')
		{
			if ((i == 0) || (a_Data[i - 1] != '\r'))
			{
				// There wasn't a CR before this LF
				return AString::npos;
			}
			AString Value(a_Data, 0, i - Start - 1);
			AddHeader(a_Key, Value);
			return i + 1;
		}
	}
	// LF not found, how? We found it at the header end (CRLFCRLF)
	ASSERT(!"LF not found, wtf?");
	return AString::npos;
}





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cHTTPResponse:

cHTTPResponse::cHTTPResponse(void) :
	super(mkResponse)
{
}





void cHTTPResponse::AppendToData(AString & a_DataStream) const
{
	a_DataStream.append("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Type: ");
	a_DataStream.append(m_ContentType);
	a_DataStream.append("\r\n");
	for (cNameValueMap::const_iterator itr = m_Headers.begin(), end = m_Headers.end(); itr != end; ++itr)
	{
		if ((itr->first == "Content-Type") || (itr->first == "Content-Length"))
		{
			continue;
		}
		a_DataStream.append(itr->first);
		a_DataStream.append(": ");
		a_DataStream.append(itr->second);
		a_DataStream.append("\r\n");
	}  // for itr - m_Headers[]
	a_DataStream.append("\r\n");
}