-
Notifications
You must be signed in to change notification settings - Fork 357
Expand file tree
/
Copy pathInternetMessageFormatHeaderParser.cs
More file actions
361 lines (313 loc) · 13.9 KB
/
InternetMessageFormatHeaderParser.cs
File metadata and controls
361 lines (313 loc) · 13.9 KB
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;
namespace System.Net.Http.Formatting.Parsers
{
/// <summary>
/// Buffer-oriented RFC 5322 style Internet Message Format parser which can be used to pass header
/// fields used in HTTP and MIME message entities.
/// </summary>
internal class InternetMessageFormatHeaderParser
{
internal const int MinHeaderSize = 2;
private int _totalBytesConsumed;
private int _maxHeaderSize;
private HeaderFieldState _headerState;
private HttpHeaders _headers;
private CurrentHeaderFieldStore _currentHeader;
private readonly bool _ignoreHeaderValidation;
/// <summary>
/// Initializes a new instance of the <see cref="InternetMessageFormatHeaderParser"/> class.
/// </summary>
/// <param name="headers">Concrete <see cref="HttpHeaders"/> instance where header fields are added as they are parsed.</param>
/// <param name="maxHeaderSize">Maximum length of complete header containing all the individual header fields.</param>
public InternetMessageFormatHeaderParser(HttpHeaders headers, int maxHeaderSize)
: this(headers, maxHeaderSize, ignoreHeaderValidation: false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InternetMessageFormatHeaderParser"/> class.
/// </summary>
/// <param name="headers">
/// Concrete <see cref="HttpHeaders"/> instance where header fields are added as they are parsed.
/// </param>
/// <param name="maxHeaderSize">
/// Maximum length of complete header containing all the individual header fields.
/// </param>
/// <param name="ignoreHeaderValidation">
/// Will validate content and names of headers if set to <c>false</c>.
/// </param>
public InternetMessageFormatHeaderParser(HttpHeaders headers, int maxHeaderSize, bool ignoreHeaderValidation)
{
// The minimum length which would be an empty header terminated by CRLF
if (maxHeaderSize < InternetMessageFormatHeaderParser.MinHeaderSize)
{
throw Error.ArgumentMustBeGreaterThanOrEqualTo("maxHeaderSize", maxHeaderSize, MinHeaderSize);
}
if (headers == null)
{
throw Error.ArgumentNull("headers");
}
_headers = headers;
_maxHeaderSize = maxHeaderSize;
_ignoreHeaderValidation = ignoreHeaderValidation;
_currentHeader = new CurrentHeaderFieldStore();
}
private enum HeaderFieldState
{
Name = 0,
Value,
AfterCarriageReturn,
FoldingLine
}
/// <summary>
/// Parse a buffer of RFC 5322 style header fields and add them to the <see cref="HttpHeaders"/> collection.
/// Bytes are parsed in a consuming manner from the beginning of the buffer meaning that the same bytes can not be
/// present in the buffer.
/// </summary>
/// <param name="buffer">Request buffer from where request is read</param>
/// <param name="bytesReady">Size of request buffer</param>
/// <param name="bytesConsumed">Offset into request buffer</param>
/// <returns>State of the parser. Call this method with new data until it reaches a final state.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is translated to parse state.")]
public ParserState ParseBuffer(
byte[] buffer,
int bytesReady,
ref int bytesConsumed)
{
if (buffer == null)
{
throw Error.ArgumentNull("buffer");
}
ParserState parseStatus = ParserState.NeedMoreData;
if (bytesConsumed >= bytesReady)
{
// We already can tell we need more data
return parseStatus;
}
try
{
parseStatus = InternetMessageFormatHeaderParser.ParseHeaderFields(
buffer,
bytesReady,
ref bytesConsumed,
ref _headerState,
_maxHeaderSize,
ref _totalBytesConsumed,
_currentHeader,
_headers,
_ignoreHeaderValidation);
}
catch (Exception)
{
parseStatus = ParserState.Invalid;
}
return parseStatus;
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "This is a parser which cannot be split up for performance reasons.")]
private static ParserState ParseHeaderFields(
byte[] buffer,
int bytesReady,
ref int bytesConsumed,
ref HeaderFieldState requestHeaderState,
int maximumHeaderLength,
ref int totalBytesConsumed,
CurrentHeaderFieldStore currentField,
HttpHeaders headers,
bool ignoreHeaderValidation)
{
Contract.Assert((bytesReady - bytesConsumed) >= 0, "ParseHeaderFields()|(inputBufferLength - bytesParsed) < 0");
Contract.Assert(maximumHeaderLength <= 0 || totalBytesConsumed <= maximumHeaderLength, "ParseHeaderFields()|Headers already read exceeds limit.");
// Remember where we started.
int initialBytesParsed = bytesConsumed;
int segmentStart;
// Set up parsing status with what will happen if we exceed the buffer.
ParserState parseStatus = ParserState.DataTooBig;
int effectiveMax = maximumHeaderLength <= 0 ? Int32.MaxValue : maximumHeaderLength - totalBytesConsumed + initialBytesParsed;
if (bytesReady < effectiveMax)
{
parseStatus = ParserState.NeedMoreData;
effectiveMax = bytesReady;
}
Contract.Assert(bytesConsumed < effectiveMax, "We have already consumed more than the max header length.");
switch (requestHeaderState)
{
case HeaderFieldState.Name:
segmentStart = bytesConsumed;
while (buffer[bytesConsumed] != ':')
{
if (buffer[bytesConsumed] == '\r')
{
if (!currentField.IsEmpty())
{
parseStatus = ParserState.Invalid;
goto quit;
}
else
{
// Move past the '\r'
requestHeaderState = HeaderFieldState.AfterCarriageReturn;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case HeaderFieldState.AfterCarriageReturn;
}
}
if (++bytesConsumed == effectiveMax)
{
string headerFieldName = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);
currentField.Name.Append(headerFieldName);
goto quit;
}
}
if (bytesConsumed > segmentStart)
{
string headerFieldName = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);
currentField.Name.Append(headerFieldName);
}
// Move past the ':'
requestHeaderState = HeaderFieldState.Value;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case HeaderFieldState.Value;
case HeaderFieldState.Value:
segmentStart = bytesConsumed;
while (buffer[bytesConsumed] != '\r')
{
if (++bytesConsumed == effectiveMax)
{
string headerFieldValue = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);
currentField.Value.Append(headerFieldValue);
goto quit;
}
}
if (bytesConsumed > segmentStart)
{
string headerFieldValue = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);
currentField.Value.Append(headerFieldValue);
}
// Move past the CR
requestHeaderState = HeaderFieldState.AfterCarriageReturn;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case HeaderFieldState.AfterCarriageReturn;
case HeaderFieldState.AfterCarriageReturn:
if (buffer[bytesConsumed] != '\n')
{
parseStatus = ParserState.Invalid;
goto quit;
}
if (currentField.IsEmpty())
{
parseStatus = ParserState.Done;
bytesConsumed++;
goto quit;
}
requestHeaderState = HeaderFieldState.FoldingLine;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case HeaderFieldState.FoldingLine;
case HeaderFieldState.FoldingLine:
if (buffer[bytesConsumed] != ' ' && buffer[bytesConsumed] != '\t')
{
currentField.CopyTo(headers, ignoreHeaderValidation);
requestHeaderState = HeaderFieldState.Name;
if (bytesConsumed == effectiveMax)
{
goto quit;
}
goto case HeaderFieldState.Name;
}
// Unfold line by inserting SP instead
currentField.Value.Append(' ');
// Continue parsing header field value
requestHeaderState = HeaderFieldState.Value;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case HeaderFieldState.Value;
}
quit:
totalBytesConsumed += bytesConsumed - initialBytesParsed;
return parseStatus;
}
/// <summary>
/// Maintains information about the current header field being parsed.
/// </summary>
private class CurrentHeaderFieldStore
{
private const int DefaultFieldNameAllocation = 128;
private const int DefaultFieldValueAllocation = 2 * 1024;
private static readonly char[] _linearWhiteSpace = new char[] { ' ', '\t' };
private readonly StringBuilder _name = new StringBuilder(CurrentHeaderFieldStore.DefaultFieldNameAllocation);
private readonly StringBuilder _value = new StringBuilder(CurrentHeaderFieldStore.DefaultFieldValueAllocation);
/// <summary>
/// Gets the header field name.
/// </summary>
public StringBuilder Name
{
get { return _name; }
}
/// <summary>
/// Gets the header field value.
/// </summary>
public StringBuilder Value
{
get { return _value; }
}
/// <summary>
/// Copies current header field to the provided <see cref="HttpHeaders"/> instance.
/// </summary>
/// <param name="headers">The headers.</param>
/// <param name="ignoreHeaderValidation">Set to false to validate headers</param>
public void CopyTo(HttpHeaders headers, bool ignoreHeaderValidation)
{
var name = _name.ToString();
var value = _value.ToString().Trim(CurrentHeaderFieldStore._linearWhiteSpace);
if (string.Equals("expires", name, StringComparison.OrdinalIgnoreCase))
{
ignoreHeaderValidation = true;
}
if (ignoreHeaderValidation)
{
headers.TryAddWithoutValidation(name, value);
}
else
{
headers.Add(name, value);
}
Clear();
}
/// <summary>
/// Determines whether this instance is empty.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </returns>
public bool IsEmpty()
{
return _name.Length == 0 && _value.Length == 0;
}
/// <summary>
/// Clears this instance.
/// </summary>
private void Clear()
{
_name.Clear();
_value.Clear();
}
}
}
}