forked from aspnet/KestrelHttpServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKnownHeaders.cs
636 lines (606 loc) · 25 KB
/
KnownHeaders.cs
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace CodeGenerator
{
// This project can output the Class library as a NuGet Package.
// To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
public class KnownHeaders
{
static string Each<T>(IEnumerable<T> values, Func<T, string> formatter)
{
return values.Any() ? values.Select(formatter).Aggregate((a, b) => a + b) : "";
}
static string If(bool condition, Func<string> formatter)
{
return condition ? formatter() : "";
}
static string AppendSwitch(IEnumerable<IGrouping<int, KnownHeader>> values, string className) =>
$@"var pUL = (ulong*)pUB;
var pUI = (uint*)pUB;
var pUS = (ushort*)pUB;
var stringValue = new StringValues(value);
switch (keyLength)
{{{Each(values, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if ({header.EqualIgnoreCaseBytes()})
{{{(header.Identifier == "ContentLength" ? $@"
if (_contentLength.HasValue)
{{
ThrowMultipleContentLengthsException();
}}
else
{{
_contentLength = ParseContentLength(value);
}}
return;" : $@"
if ({header.TestBit()})
{{
_headers._{header.Identifier} = AppendValue(_headers._{header.Identifier}, value);
}}
else
{{
{header.SetBit()};
_headers._{header.Identifier} = stringValue;{(header.EnhancedSetter == false ? "" : $@"
_headers._raw{header.Identifier} = null;")}
}}
return;")}
}}
")}}}
break;
")}}}";
class KnownHeader
{
public string Name { get; set; }
public int Index { get; set; }
public string Identifier => Name.Replace("-", "");
public byte[] Bytes => Encoding.ASCII.GetBytes($"\r\n{Name}: ");
public int BytesOffset { get; set; }
public int BytesCount { get; set; }
public bool EnhancedSetter { get; set; }
public bool PrimaryHeader { get; set; }
public string TestBit() => $"(_bits & {1L << Index}L) != 0";
public string TestTempBit() => $"(tempBits & {1L << Index}L) != 0";
public string TestNotTempBit() => $"(tempBits & ~{1L << Index}L) == 0";
public string TestNotBit() => $"(_bits & {1L << Index}L) == 0";
public string SetBit() => $"_bits |= {1L << Index}L";
public string ClearBit() => $"_bits &= ~{1L << Index}L";
public string EqualIgnoreCaseBytes()
{
var result = "";
var delim = "";
var index = 0;
while (index != Name.Length)
{
if (Name.Length - index >= 8)
{
result += delim + Term(Name, index, 8, "pUL", "uL");
index += 8;
}
else if (Name.Length - index >= 4)
{
result += delim + Term(Name, index, 4, "pUI", "u");
index += 4;
}
else if (Name.Length - index >= 2)
{
result += delim + Term(Name, index, 2, "pUS", "u");
index += 2;
}
else
{
result += delim + Term(Name, index, 1, "pUB", "u");
index += 1;
}
delim = " && ";
}
return $"({result})";
}
protected string Term(string name, int offset, int count, string array, string suffix)
{
ulong mask = 0;
ulong comp = 0;
for (var scan = 0; scan < count; scan++)
{
var ch = (byte)name[offset + count - scan - 1];
var isAlpha = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
comp = (comp << 8) + (ch & (isAlpha ? 0xdfu : 0xffu));
mask = (mask << 8) + (isAlpha ? 0xdfu : 0xffu);
}
return $"(({array}[{offset / count}] & {mask}{suffix}) == {comp}{suffix})";
}
}
public static string GeneratedFile()
{
var requestPrimaryHeaders = new[]
{
"Accept",
"Connection",
"Host",
"User-Agent"
};
var responsePrimaryHeaders = new[]
{
"Connection",
"Date",
"Content-Type",
"Server",
};
var commonHeaders = new[]
{
"Cache-Control",
"Connection",
"Date",
"Keep-Alive",
"Pragma",
"Trailer",
"Transfer-Encoding",
"Upgrade",
"Via",
"Warning",
"Allow",
"Content-Type",
"Content-Encoding",
"Content-Language",
"Content-Location",
"Content-MD5",
"Content-Range",
"Expires",
"Last-Modified"
};
// http://www.w3.org/TR/cors/#syntax
var corsRequestHeaders = new[]
{
"Origin",
"Access-Control-Request-Method",
"Access-Control-Request-Headers",
};
var requestHeaders = commonHeaders.Concat(new[]
{
"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Cookie",
"Expect",
"From",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
"Max-Forwards",
"Proxy-Authorization",
"Referer",
"Range",
"TE",
"Translate",
"User-Agent",
})
.Concat(corsRequestHeaders)
.Select((header, index) => new KnownHeader
{
Name = header,
Index = index,
PrimaryHeader = requestPrimaryHeaders.Contains(header)
})
.Concat(new[] { new KnownHeader
{
Name = "Content-Length",
Index = -1,
PrimaryHeader = requestPrimaryHeaders.Contains("Content-Length")
}})
.ToArray();
Debug.Assert(requestHeaders.Length <= 64);
Debug.Assert(requestHeaders.Max(x => x.Index) <= 62);
var enhancedHeaders = new[]
{
"Connection",
"Server",
"Date",
"Transfer-Encoding"
};
// http://www.w3.org/TR/cors/#syntax
var corsResponseHeaders = new[]
{
"Access-Control-Allow-Credentials",
"Access-Control-Allow-Headers",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Origin",
"Access-Control-Expose-Headers",
"Access-Control-Max-Age",
};
var responseHeaders = commonHeaders.Concat(new[]
{
"Accept-Ranges",
"Age",
"ETag",
"Location",
"Proxy-Authenticate",
"Retry-After",
"Server",
"Set-Cookie",
"Vary",
"WWW-Authenticate",
})
.Concat(corsResponseHeaders)
.Select((header, index) => new KnownHeader
{
Name = header,
Index = index,
EnhancedSetter = enhancedHeaders.Contains(header),
PrimaryHeader = responsePrimaryHeaders.Contains(header)
})
.Concat(new[] { new KnownHeader
{
Name = "Content-Length",
Index = -1,
EnhancedSetter = enhancedHeaders.Contains("Content-Length"),
PrimaryHeader = responsePrimaryHeaders.Contains("Content-Length")
}})
.ToArray();
// 63 for reponseHeaders as it steals one bit for Content-Length in CopyTo(ref MemoryPoolIterator output)
Debug.Assert(responseHeaders.Length <= 63);
Debug.Assert(responseHeaders.Max(x => x.Index) <= 62);
var loops = new[]
{
new
{
Headers = requestHeaders,
HeadersByLength = requestHeaders.GroupBy(x => x.Name.Length),
ClassName = "FrameRequestHeaders",
Bytes = default(byte[])
},
new
{
Headers = responseHeaders,
HeadersByLength = responseHeaders.GroupBy(x => x.Name.Length),
ClassName = "FrameResponseHeaders",
Bytes = responseHeaders.SelectMany(header => header.Bytes).ToArray()
}
};
foreach (var loop in loops.Where(l => l.Bytes != null))
{
var offset = 0;
foreach (var header in loop.Headers)
{
header.BytesOffset = offset;
header.BytesCount += header.Bytes.Length;
offset += header.BytesCount;
}
}
return $@"// 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;
using System.Collections.Generic;
using System.IO.Pipelines;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Infrastructure;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Server.Kestrel.Internal.Http
{{
{Each(loops, loop => $@"
public partial class {loop.ClassName}
{{{(loop.Bytes != null ?
$@"
private static byte[] _headerBytes = new byte[]
{{
{Each(loop.Bytes, b => $"{b},")}
}};"
: "")}
private long _bits = 0;
private HeaderReferences _headers;
{Each(loop.Headers, header => $@"
public StringValues Header{header.Identifier}
{{{(header.Identifier == "ContentLength" ? $@"
get
{{
StringValues value;
if (_contentLength.HasValue)
{{
value = new StringValues(HeaderUtilities.FormatNonNegativeInt64(_contentLength.Value));
}}
return value;
}}
set
{{
_contentLength = ParseContentLength(value);
}}" : $@"
get
{{
StringValues value;
if ({header.TestBit()})
{{
value = _headers._{header.Identifier};
}}
return value;
}}
set
{{
{header.SetBit()};
_headers._{header.Identifier} = value; {(header.EnhancedSetter == false ? "" : $@"
_headers._raw{header.Identifier} = null;")}
}}")}
}}")}
{Each(loop.Headers.Where(header => header.EnhancedSetter), header => $@"
public void SetRaw{header.Identifier}(StringValues value, byte[] raw)
{{
{header.SetBit()};
_headers._{header.Identifier} = value;
_headers._raw{header.Identifier} = raw;
}}")}
protected override int GetCountFast()
{{
return (_contentLength.HasValue ? 1 : 0 ) + BitCount(_bits) + (MaybeUnknown?.Count ?? 0);
}}
protected override bool TryGetValueFast(string key, out StringValues value)
{{
switch (key.Length)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if (""{header.Name}"".Equals(key, StringComparison.OrdinalIgnoreCase))
{{{(header.Identifier == "ContentLength" ? @"
if (_contentLength.HasValue)
{
value = HeaderUtilities.FormatNonNegativeInt64(_contentLength.Value);
return true;
}
return false;" : $@"
if ({header.TestBit()})
{{
value = _headers._{header.Identifier};
return true;
}}
return false;")}
}}")}
}}
break;")}
}}
return MaybeUnknown?.TryGetValue(key, out value) ?? false;
}}
protected override void SetValueFast(string key, StringValues value)
{{{(loop.ClassName == "FrameResponseHeaders" ? @"
ValidateHeaderCharacters(value);" : "")}
switch (key.Length)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if (""{header.Name}"".Equals(key, StringComparison.OrdinalIgnoreCase))
{{{(header.Identifier == "ContentLength" ? $@"
_contentLength = ParseContentLength(value.ToString());" : $@"
{header.SetBit()};
_headers._{header.Identifier} = value;{(header.EnhancedSetter == false ? "" : $@"
_headers._raw{header.Identifier} = null;")}")}
return;
}}")}
}}
break;")}
}}
SetValueUnknown(key, value);
}}
protected override bool AddValueFast(string key, StringValues value)
{{{(loop.ClassName == "FrameResponseHeaders" ? @"
ValidateHeaderCharacters(value);" : "")}
switch (key.Length)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if (""{header.Name}"".Equals(key, StringComparison.OrdinalIgnoreCase))
{{{(header.Identifier == "ContentLength" ? $@"
if (!_contentLength.HasValue)
{{
_contentLength = ParseContentLength(value);
return true;
}}
return false;" : $@"
if ({header.TestNotBit()})
{{
{header.SetBit()};
_headers._{header.Identifier} = value;{(header.EnhancedSetter == false ? "" : $@"
_headers._raw{header.Identifier} = null;")}
return true;
}}
return false;")}
}}")}
}}
break;")}
}}
{(loop.ClassName == "FrameResponseHeaders" ? @"
ValidateHeaderCharacters(key);" : "")}
Unknown.Add(key, value);
// Return true, above will throw and exit for false
return true;
}}
protected override bool RemoveFast(string key)
{{
switch (key.Length)
{{{Each(loop.HeadersByLength, byLength => $@"
case {byLength.Key}:
{{{Each(byLength, header => $@"
if (""{header.Name}"".Equals(key, StringComparison.OrdinalIgnoreCase))
{{{(header.Identifier == "ContentLength" ? @"
if (_contentLength.HasValue)
{
_contentLength = null;
return true;
}
return false;" : $@"
if ({header.TestBit()})
{{
{header.ClearBit()};
_headers._{header.Identifier} = default(StringValues);{(header.EnhancedSetter == false ? "" : $@"
_headers._raw{header.Identifier} = null;")}
return true;
}}
return false;")}
}}")}
}}
break;")}
}}
return MaybeUnknown?.Remove(key) ?? false;
}}
protected override void ClearFast()
{{
MaybeUnknown?.Clear();
_contentLength = null;
var tempBits = _bits;
_bits = 0;
if(FrameHeaders.BitCount(tempBits) > 12)
{{
_headers = default(HeaderReferences);
return;
}}
{Each(loop.Headers.Where(header => header.Identifier != "ContentLength").OrderBy(h => !h.PrimaryHeader), header => $@"
if ({header.TestTempBit()})
{{
_headers._{header.Identifier} = default(StringValues);
if({header.TestNotTempBit()})
{{
return;
}}
tempBits &= ~{1L << header.Index}L;
}}
")}
}}
protected override bool CopyToFast(KeyValuePair<string, StringValues>[] array, int arrayIndex)
{{
if (arrayIndex < 0)
{{
return false;
}}
{Each(loop.Headers.Where(header => header.Identifier != "ContentLength"), header => $@"
if ({header.TestBit()})
{{
if (arrayIndex == array.Length)
{{
return false;
}}
array[arrayIndex] = new KeyValuePair<string, StringValues>(""{header.Name}"", _headers._{header.Identifier});
++arrayIndex;
}}")}
if (_contentLength.HasValue)
{{
if (arrayIndex == array.Length)
{{
return false;
}}
array[arrayIndex] = new KeyValuePair<string, StringValues>(""Content-Length"", HeaderUtilities.FormatNonNegativeInt64(_contentLength.Value));
++arrayIndex;
}}
((ICollection<KeyValuePair<string, StringValues>>)MaybeUnknown)?.CopyTo(array, arrayIndex);
return true;
}}
{(loop.ClassName == "FrameResponseHeaders" ? $@"
protected void CopyToFast(ref WritableBuffer output)
{{
var tempBits = _bits | (_contentLength.HasValue ? {1L << 63}L : 0);
{Each(loop.Headers.Where(header => header.Identifier != "ContentLength").OrderBy(h => !h.PrimaryHeader), header => $@"
if ({header.TestTempBit()})
{{ {(header.EnhancedSetter == false ? "" : $@"
if (_headers._raw{header.Identifier} != null)
{{
output.WriteFast(_headers._raw{header.Identifier});
}}
else ")}
{{
var valueCount = _headers._{header.Identifier}.Count;
for (var i = 0; i < valueCount; i++)
{{
var value = _headers._{header.Identifier}[i];
if (value != null)
{{
output.WriteFast(_headerBytes, {header.BytesOffset}, {header.BytesCount});
output.WriteAsciiNoValidation(value);
}}
}}
}}
if({header.TestNotTempBit()})
{{
return;
}}
tempBits &= ~{1L << header.Index}L;
}}{(header.Identifier == "Server" ? $@"
if ((tempBits & {1L << 63}L) != 0)
{{
output.WriteFast(_headerBytes, {loop.Headers.First(x => x.Identifier == "ContentLength").BytesOffset}, {loop.Headers.First(x => x.Identifier == "ContentLength").BytesCount});
output.WriteNumeric((ulong)ContentLength.Value);
if((tempBits & ~{1L << 63}L) == 0)
{{
return;
}}
tempBits &= ~{1L << 63}L;
}}" : "")}")}
}}" : "")}
{(loop.ClassName == "FrameRequestHeaders" ? $@"
public unsafe void Append(byte* pKeyBytes, int keyLength, string value)
{{
var pUB = pKeyBytes;
{AppendSwitch(loop.Headers.Where(h => h.PrimaryHeader).GroupBy(x => x.Name.Length), loop.ClassName)}
AppendNonPrimaryHeaders(pKeyBytes, keyLength, value);
}}
private unsafe void AppendNonPrimaryHeaders(byte* pKeyBytes, int keyLength, string value)
{{
var pUB = pKeyBytes;
{AppendSwitch(loop.Headers.Where(h => !h.PrimaryHeader).GroupBy(x => x.Name.Length), loop.ClassName)}
AppendUnknownHeaders(pKeyBytes, keyLength, value);
}}" : "")}
private struct HeaderReferences
{{{Each(loop.Headers.Where(header => header.Identifier != "ContentLength"), header => @"
public StringValues _" + header.Identifier + ";")}
{Each(loop.Headers.Where(header => header.EnhancedSetter), header => @"
public byte[] _raw" + header.Identifier + ";")}
}}
public partial struct Enumerator
{{
public bool MoveNext()
{{
switch (_state)
{{
{Each(loop.Headers.Where(header => header.Identifier != "ContentLength"), header => $@"
case {header.Index}:
goto state{header.Index};
")}
case {loop.Headers.Count()}:
goto state{loop.Headers.Count()};
default:
goto state_default;
}}
{Each(loop.Headers.Where(header => header.Identifier != "ContentLength"), header => $@"
state{header.Index}:
if ({header.TestBit()})
{{
_current = new KeyValuePair<string, StringValues>(""{header.Name}"", _collection._headers._{header.Identifier});
_state = {header.Index + 1};
return true;
}}
")}
state{loop.Headers.Count()}:
if (_collection._contentLength.HasValue)
{{
_current = new KeyValuePair<string, StringValues>(""Content-Length"", HeaderUtilities.FormatNonNegativeInt64(_collection._contentLength.Value));
_state = {loop.Headers.Count() + 1};
return true;
}}
state_default:
if (!_hasUnknown || !_unknownEnumerator.MoveNext())
{{
_current = default(KeyValuePair<string, StringValues>);
return false;
}}
_current = _unknownEnumerator.Current;
return true;
}}
}}
}}
")}}}";
}
}
}