-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathHttpRequest.cs
3345 lines (2773 loc) · 125 KB
/
HttpRequest.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <copyright file="HttpRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Request intrinsic
*
* Copyright (c) 1998 Microsoft Corporation
*/
namespace System.Web {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration.Assemblies;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Management;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Util;
// enumeration of dynamic server variables
internal enum DynamicServerVariable {
AUTH_TYPE = 1,
AUTH_USER = 2,
PATH_INFO = 3,
PATH_TRANSLATED = 4,
QUERY_STRING = 5,
SCRIPT_NAME = 6
};
internal enum HttpVerb {
Unparsed = 0, // must be 0 so that it's zero-init value is Unparsed
Unknown,
GET,
PUT,
HEAD,
POST,
DEBUG,
DELETE,
}
/// <devdoc>
/// <para>
/// Enables
/// type-safe browser to server communication. Used to gain access to HTTP request data
/// elements supplied by a client.
/// </para>
/// </devdoc>
public sealed class HttpRequest {
// worker request
[DoNotReset]
private HttpWorkerRequest _wr;
// context
[DoNotReset]
private HttpContext _context;
// properties
private String _httpMethod;
private HttpVerb _httpVerb;
private String _requestType;
private VirtualPath _path;
private String _rewrittenUrl;
private bool _computePathInfo;
private VirtualPath _filePath;
private VirtualPath _currentExecutionFilePath;
private VirtualPath _pathInfo;
private String _queryStringText;
private bool _queryStringOverriden;
private byte[] _queryStringBytes;
private String _pathTranslated;
private String _contentType;
private int _contentLength = -1;
private String _clientTarget;
private String[] _acceptTypes;
private String[] _userLanguages;
private HttpBrowserCapabilities _browsercaps;
private Uri _url;
private Uri _referrer;
private HttpInputStream _inputStream;
private HttpClientCertificate _clientCertificate;
private bool _tlsTokenBindingInfoResolved;
private ITlsTokenBindingInfo _tlsTokenBindingInfo;
private WindowsIdentity _logonUserIdentity;
[DoNotReset]
private RequestContext _requestContext;
private string _rawUrl;
private Stream _readEntityBodyStream;
private ReadEntityBodyMode _readEntityBodyMode;
// collections
private UnvalidatedRequestValues _unvalidatedRequestValues;
private HttpValueCollection _params;
private HttpValueCollection _queryString;
private HttpValueCollection _form;
private HttpHeaderCollection _headers;
private HttpServerVarsCollection _serverVariables;
private HttpCookieCollection _cookies;
[DoNotReset] // we can't reset this field when transitioning to WebSockets because it's our only remaining reference to the response cookies collection
private HttpCookieCollection _storedResponseCookies;
private HttpFileCollection _files;
// content (to be read once)
private HttpRawUploadedContent _rawContent;
private bool _needToInsertEntityBody;
private MultipartContentElement[] _multipartContentElements;
// encoding (for content and query string)
private Encoding _encoding;
// content filtering
private HttpInputStreamFilterSource _filterSource;
private Stream _installedFilter;
private bool _filterApplied;
// Input validation
#pragma warning disable 0649
private SimpleBitVector32 _flags;
#pragma warning restore 0649
// const masks into the BitVector32
private const int needToValidateQueryString = 0x0001;
private const int needToValidateForm = 0x0002;
private const int needToValidateCookies = 0x0004;
private const int needToValidateHeaders = 0x0008;
private const int needToValidateServerVariables = 0x0010;
private const int contentEncodingResolved = 0x0020;
private const int needToValidatePostedFiles = 0x0040;
private const int needToValidateRawUrl = 0x0080;
private const int needToValidatePath = 0x0100;
private const int needToValidatePathInfo = 0x0200;
private const int hasValidateInputBeenCalled = 0x8000;
private const int needToValidateCookielessHeader = 0x10000;
// True if granular request validation is enabled (validationmode >= 4.5); false if all collections validated eagerly.
private const int granularValidationEnabled = 0x40000000;
// True if request validation is suppressed (validationMode == 0.0); false if validation can be enabled via a call to ValidateInput().
private const int requestValidationSuppressed = unchecked((int)0x80000000);
// Browser caps one-time evaluator objects
internal static object s_browserLock = new object();
internal static bool s_browserCapsEvaled = false;
/*
* Internal constructor to create requests
* that have associated HttpWorkerRequest
*
* @param wr HttpWorkerRequest
*/
internal HttpRequest(HttpWorkerRequest wr, HttpContext context) {
_wr = wr;
_context = context;
}
/*
* Public constructor for request that come from arbitrary place
*
* @param filename physical file name
* @param queryString query string
*/
/// <devdoc>
/// <para>
/// Initializes an HttpRequest object.
/// </para>
/// </devdoc>
public HttpRequest(String filename, String url, String queryString) {
_wr = null;
_pathTranslated = filename;
_httpMethod = "GET";
_url = new Uri(url);
_path = VirtualPath.CreateAbsolute(_url.AbsolutePath);
_queryStringText = queryString;
_queryStringOverriden = true;
_queryString = new HttpValueCollection(_queryStringText, true, true, Encoding.Default);
PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_EXECUTING);
}
internal HttpRequest(VirtualPath virtualPath, String queryString) {
_wr = null;
_pathTranslated = virtualPath.MapPath();
_httpMethod = "GET";
_url = new Uri("http://localhost" + virtualPath.VirtualPathString);
_path = virtualPath;
_queryStringText = queryString;
_queryStringOverriden = true;
_queryString = new HttpValueCollection(_queryStringText, true, true, Encoding.Default);
PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_EXECUTING);
}
internal bool NeedToInsertEntityBody {
get { return _needToInsertEntityBody; }
set { _needToInsertEntityBody = value; }
}
internal void SetRawContent(HttpRawUploadedContent rawContent) {
Debug.Assert(rawContent != null);
if (rawContent.Length > 0) {
NeedToInsertEntityBody = true;
}
_rawContent = rawContent;
}
internal byte[] EntityBody { get { return NeedToInsertEntityBody ? _rawContent.GetAsByteArray() : null; } }
internal string ClientTarget {
get {
return (_clientTarget == null) ? String.Empty : _clientTarget;
}
set {
_clientTarget = value;
// force re-create of browser caps
_browsercaps = null;
}
}
internal HttpContext Context {
get { return _context; }
set { _context = value; }
}
public RequestContext RequestContext {
get {
// Create an empty request context if we don't have one set
if (_requestContext == null) {
HttpContext context = Context ?? HttpContext.Current;
_requestContext = new RequestContext(new HttpContextWrapper(context), new RouteData());
}
return _requestContext;
}
set {
_requestContext = value;
}
}
private bool HasTransitionedToWebSocketRequest {
get {
return (Context != null && Context.HasWebSocketRequestTransitionCompleted);
}
}
/*
* internal response object
*/
internal HttpResponse Response {
get {
if (_context == null)
return null;
return _context.Response;
}
}
/*
* Public property to determine if request is local
*/
public bool IsLocal {
get {
if (_wr != null) {
return _wr.IsLocal();
}
else {
return false;
}
}
}
/*
* Cleanup code
*/
internal void Dispose() {
if (_serverVariables != null)
_serverVariables.Dispose(); // disconnect from request
if (_rawContent != null)
_rawContent.Dispose(); // remove temp file with uploaded content
//
}
//
// Misc private methods to fill in collections from HttpWorkerRequest
// properties
//
internal static String[] ParseMultivalueHeader(String s) {
int l = (s != null) ? s.Length : 0;
if (l == 0)
return null;
// collect comma-separated values into list
ArrayList values = new ArrayList();
int i = 0;
while (i < l) {
// find next ,
int ci = s.IndexOf(',', i);
if (ci < 0)
ci = l;
// append corresponding server value
values.Add(s.Substring(i, ci-i));
// move to next
i = ci+1;
// skip leading space
if (i < l && s[i] == ' ')
i++;
}
// return list as array of strings
int n = values.Count;
if (n == 0)
return null;
String[] strings = new String[n];
values.CopyTo(0, strings, 0, n);
return strings;
}
//
// Query string collection support
//
private void FillInQueryStringCollection() {
// try from raw bytes when available (better for globalization)
byte[] rawQueryString = this.QueryStringBytes;
if (rawQueryString != null) {
if (rawQueryString.Length != 0)
_queryString.FillFromEncodedBytes(rawQueryString, QueryStringEncoding);
}
else if (!(String.IsNullOrEmpty(this.QueryStringText))) {
_queryString.FillFromString(this.QueryStringText, true, QueryStringEncoding);
}
}
//
// Form collection support
//
private void FillInFormCollection() {
if (_wr == null)
return;
if (!_wr.HasEntityBody())
return;
String contentType = this.ContentType;
if (contentType == null)
return;
if (_readEntityBodyMode == ReadEntityBodyMode.Bufferless) {
return;
}
if (StringUtil.StringStartsWithIgnoreCase(contentType, "application/x-www-form-urlencoded")) {
// regular urlencoded form
byte[] formBytes = null;
HttpRawUploadedContent content = GetEntireRawContent();
if (content != null)
formBytes = content.GetAsByteArray();
if (formBytes != null) {
try {
_form.FillFromEncodedBytes(formBytes, ContentEncoding);
}
catch (Exception e) {
// could be thrown because of malformed data
throw new HttpException(SR.GetString(SR.Invalid_urlencoded_form_data), e);
}
}
}
else if (StringUtil.StringStartsWithIgnoreCase(contentType, "multipart/form-data")) {
// multipart form
MultipartContentElement[] elements = GetMultipartContent();
if (elements != null) {
for (int i = 0; i < elements.Length; i++) {
if (elements[i].IsFormItem) {
_form.ThrowIfMaxHttpCollectionKeysExceeded();
_form.Add(elements[i].Name, elements[i].GetAsString(ContentEncoding));
}
}
}
}
}
//
// Headers collection support
//
private void FillInHeadersCollection() {
if (_wr == null)
return;
// known headers
for (int i = 0; i < HttpWorkerRequest.RequestHeaderMaximum; i++) {
String h = _wr.GetKnownRequestHeader(i);
if (!String.IsNullOrEmpty(h)) {
String name = HttpWorkerRequest.GetKnownRequestHeaderName(i);
_headers.SynchronizeHeader(name, h);
}
}
// unknown headers
String[][] hh = _wr.GetUnknownRequestHeaders();
if (hh != null) {
for (int i = 0; i < hh.Length; i++)
_headers.SynchronizeHeader(hh[i][0], hh[i][1]);
}
}
//
// Server variables collection support
//
private static String ServerVariableNameFromHeader(String header) {
return("HTTP_" + header.ToUpper(CultureInfo.InvariantCulture).Replace('-', '_'));
}
private String CombineAllHeaders(bool asRaw) {
if (_wr == null)
return String.Empty;
StringBuilder sb = new StringBuilder(256);
// known headers
for (int i = 0; i < HttpWorkerRequest.RequestHeaderMaximum; i++) {
String h = _wr.GetKnownRequestHeader(i);
if (!String.IsNullOrEmpty(h)) {
String name;
if (!asRaw)
name = HttpWorkerRequest.GetServerVariableNameFromKnownRequestHeaderIndex(i);
else
name = HttpWorkerRequest.GetKnownRequestHeaderName(i);
if (name != null) {
sb.Append(name);
sb.Append(asRaw ? ": " : ":"); // for ASP compat don't add space
sb.Append(h);
sb.Append("\r\n");
}
}
}
// unknown headers
String[][] hh = _wr.GetUnknownRequestHeaders();
if (hh != null) {
for (int i = 0; i < hh.Length; i++) {
String name = hh[i][0];
if (!asRaw)
name = ServerVariableNameFromHeader(name);
sb.Append(name);
sb.Append(asRaw ? ": " : ":"); // for ASP compat don't add space
sb.Append(hh[i][1]);
sb.Append("\r\n");
}
}
return sb.ToString();
}
// callback to calculate dynamic server variable
internal String CalcDynamicServerVariable(DynamicServerVariable var) {
String value = null;
switch (var) {
case DynamicServerVariable.AUTH_TYPE:
if (_context.User != null && _context.User.Identity.IsAuthenticated)
value = _context.User.Identity.AuthenticationType;
else
value = String.Empty;
break;
case DynamicServerVariable.AUTH_USER:
if (_context.User != null && _context.User.Identity.IsAuthenticated)
value = _context.User.Identity.Name;
else
value = String.Empty;
break;
case DynamicServerVariable.PATH_INFO:
value = this.Path;
break;
case DynamicServerVariable.PATH_TRANSLATED:
value = this.PhysicalPathInternal;
break;
case DynamicServerVariable.QUERY_STRING:
value = this.QueryStringText;
break;
case DynamicServerVariable.SCRIPT_NAME:
value = this.FilePath;
break;
}
return value;
}
private void AddServerVariableToCollection(String name, DynamicServerVariable var) {
// dynamic server var
_serverVariables.AddDynamic(name, var);
}
private void AddServerVariableToCollection(String name, String value) {
if (value == null)
value = String.Empty;
// static server var
_serverVariables.AddStatic(name, value);
}
private void AddServerVariableToCollection(String name) {
// static server var from worker request
_serverVariables.AddStatic(name, _wr.GetServerVariable(name));
}
internal void FillInServerVariablesCollection() {
if (_wr == null)
return;
// Add from hardcoded list
AddServerVariableToCollection("ALL_HTTP", CombineAllHeaders(false));
AddServerVariableToCollection("ALL_RAW", CombineAllHeaders(true));
AddServerVariableToCollection("APPL_MD_PATH");
AddServerVariableToCollection("APPL_PHYSICAL_PATH", _wr.GetAppPathTranslated());
AddServerVariableToCollection("AUTH_TYPE", DynamicServerVariable.AUTH_TYPE);
AddServerVariableToCollection("AUTH_USER", DynamicServerVariable.AUTH_USER);
AddServerVariableToCollection("AUTH_PASSWORD");
AddServerVariableToCollection("LOGON_USER");
AddServerVariableToCollection("REMOTE_USER", DynamicServerVariable.AUTH_USER);
AddServerVariableToCollection("CERT_COOKIE");
AddServerVariableToCollection("CERT_FLAGS");
AddServerVariableToCollection("CERT_ISSUER");
AddServerVariableToCollection("CERT_KEYSIZE");
AddServerVariableToCollection("CERT_SECRETKEYSIZE");
AddServerVariableToCollection("CERT_SERIALNUMBER");
AddServerVariableToCollection("CERT_SERVER_ISSUER");
AddServerVariableToCollection("CERT_SERVER_SUBJECT");
AddServerVariableToCollection("CERT_SUBJECT");
String clString = _wr.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength);
AddServerVariableToCollection("CONTENT_LENGTH", (clString != null) ? clString : "0");
AddServerVariableToCollection("CONTENT_TYPE", this.ContentType);
AddServerVariableToCollection("GATEWAY_INTERFACE");
AddServerVariableToCollection("HTTPS");
AddServerVariableToCollection("HTTPS_KEYSIZE");
AddServerVariableToCollection("HTTPS_SECRETKEYSIZE");
AddServerVariableToCollection("HTTPS_SERVER_ISSUER");
AddServerVariableToCollection("HTTPS_SERVER_SUBJECT");
AddServerVariableToCollection("INSTANCE_ID");
AddServerVariableToCollection("INSTANCE_META_PATH");
AddServerVariableToCollection("LOCAL_ADDR", _wr.GetLocalAddress());
AddServerVariableToCollection("PATH_INFO", DynamicServerVariable.PATH_INFO);
AddServerVariableToCollection("PATH_TRANSLATED", DynamicServerVariable.PATH_TRANSLATED);
AddServerVariableToCollection("QUERY_STRING", DynamicServerVariable.QUERY_STRING);
AddServerVariableToCollection("REMOTE_ADDR", this.UserHostAddress);
AddServerVariableToCollection("REMOTE_HOST", this.UserHostName);
AddServerVariableToCollection("REMOTE_PORT");
AddServerVariableToCollection("REQUEST_METHOD", this.HttpMethod);
AddServerVariableToCollection("SCRIPT_NAME", DynamicServerVariable.SCRIPT_NAME);
AddServerVariableToCollection("SERVER_NAME", _wr.GetServerName());
AddServerVariableToCollection("SERVER_PORT", _wr.GetLocalPortAsString());
AddServerVariableToCollection("SERVER_PORT_SECURE", _wr.IsSecure() ? "1" : "0");
AddServerVariableToCollection("SERVER_PROTOCOL", _wr.GetHttpVersion());
AddServerVariableToCollection("SERVER_SOFTWARE");
AddServerVariableToCollection("URL", DynamicServerVariable.SCRIPT_NAME);
// Add all headers in HTTP_XXX format
for (int i = 0; i < HttpWorkerRequest.RequestHeaderMaximum; i++) {
String h = _wr.GetKnownRequestHeader(i);
if (!String.IsNullOrEmpty(h))
AddServerVariableToCollection(HttpWorkerRequest.GetServerVariableNameFromKnownRequestHeaderIndex(i), h);
}
String[][] hh = _wr.GetUnknownRequestHeaders();
if (hh != null) {
for (int i = 0; i < hh.Length; i++)
AddServerVariableToCollection(ServerVariableNameFromHeader(hh[i][0]), hh[i][1]);
}
}
//
// Cookies collection support
//
internal static HttpCookie CreateCookieFromString(String s) {
HttpCookie c = new HttpCookie();
int l = (s != null) ? s.Length : 0;
int i = 0;
int ai, ei;
bool firstValue = true;
int numValues = 1;
// Format: cookiename[=key1=val2&key2=val2&...]
while (i < l) {
// find next &
ai = s.IndexOf('&', i);
if (ai < 0)
ai = l;
// first value might contain cookie name before =
if (firstValue) {
ei = s.IndexOf('=', i);
if (ei >= 0 && ei < ai) {
c.Name = s.Substring(i, ei-i);
i = ei+1;
}
else if (ai == l) {
// the whole cookie is just a name
c.Name = s;
break;
}
firstValue = false;
}
// find '='
ei = s.IndexOf('=', i);
if (ei < 0 && ai == l && numValues == 0) {
// simple cookie with simple value
c.Value = s.Substring(i, l-i);
}
else if (ei >= 0 && ei < ai) {
// key=value
c.Values.Add(s.Substring(i, ei-i), s.Substring(ei+1, ai-ei-1));
numValues++;
}
else {
// value without key
c.Values.Add(null, s.Substring(i, ai-i));
numValues++;
}
i = ai+1;
}
return c;
}
internal void FillInCookiesCollection(HttpCookieCollection cookieCollection, bool includeResponse) {
if (_wr == null)
return;
String s = _wr.GetKnownRequestHeader(HttpWorkerRequest.HeaderCookie);
// Parse the cookie server variable.
// Format: c1=k1=v1&k2=v2; c2=...
int l = (s != null) ? s.Length : 0;
int i = 0;
int j;
char ch;
HttpCookie lastCookie = null;
while (i < l) {
// find next ';' (don't look to ',' as per 91884)
j = i;
while (j < l) {
ch = s[j];
if (ch == ';')
break;
j++;
}
// create cookie form string
String cookieString = s.Substring(i, j-i).Trim();
i = j+1; // next cookie start
if (cookieString.Length == 0)
continue;
HttpCookie cookie = CreateCookieFromString(cookieString);
// some cookies starting with '$' are really attributes of the last cookie
if (lastCookie != null) {
String name = cookie.Name;
// add known attribute to the last cookie (if any)
if (name != null && name.Length > 0 && name[0] == '$') {
if (StringUtil.EqualsIgnoreCase(name, "$Path"))
lastCookie.Path = cookie.Value;
else if (StringUtil.EqualsIgnoreCase(name, "$Domain"))
lastCookie.Domain = cookie.Value;
continue;
}
}
// regular cookie
cookieCollection.AddCookie(cookie, true);
lastCookie = cookie;
// goto next cookie
}
// Append response cookies
if (includeResponse) {
// If we have a reference to the response cookies collection, use it directly
// rather than going through the Response object (which might not be available, e.g.
// if we have already transitioned to a WebSockets request).
HttpCookieCollection storedResponseCookies = _storedResponseCookies;
if (storedResponseCookies == null && !HasTransitionedToWebSocketRequest && Response != null) {
storedResponseCookies = Response.GetCookiesNoCreate();
}
if (storedResponseCookies != null && storedResponseCookies.Count > 0) {
if(AppSettings.AvoidDuplicatedSetCookie) {
cookieCollection.Append(storedResponseCookies);
}
else {
HttpCookie[] responseCookieArray = new HttpCookie[storedResponseCookies.Count];
storedResponseCookies.CopyTo(responseCookieArray, 0);
for (int iCookie = 0; iCookie < responseCookieArray.Length; iCookie++)
cookieCollection.AddCookie(responseCookieArray[iCookie], append: true);
}
}
// release any stored reference to the response cookie collection
_storedResponseCookies = null;
}
}
internal void StoreReferenceToResponseCookies(HttpCookieCollection responseCookies) {
_storedResponseCookies = responseCookies;
}
// Params collection support
private void FillInParamsCollection() {
_params.Add(this.QueryString);
_params.Add(this.Form);
_params.Add(this.Cookies);
_params.Add(this.ServerVariables);
}
//
// Files collection support
//
private void FillInFilesCollection() {
if (_wr == null)
return;
if (!StringUtil.StringStartsWithIgnoreCase(ContentType, "multipart/form-data"))
return;
MultipartContentElement[] elements = GetMultipartContent();
if (elements == null)
return;
for (int i = 0; i < elements.Length; i++) {
if (elements[i].IsFile) {
HttpPostedFile p = elements[i].GetAsPostedFile();
_files.AddFile(elements[i].Name, p);
}
}
}
//
// Reading posted content ...
//
/*
* Get attribute off header value
*/
private static String GetAttributeFromHeader(String headerValue, String attrName) {
if (headerValue == null)
return null;
int l = headerValue.Length;
int k = attrName.Length;
// find properly separated attribute name
int i = 1; // start searching from 1
while (i < l) {
i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, attrName, i, CompareOptions.IgnoreCase);
if (i < 0)
break;
if (i+k >= l)
break;
char chPrev = headerValue[i-1];
char chNext = headerValue[i+k];
if ((chPrev == ';' || chPrev == ',' || Char.IsWhiteSpace(chPrev)) && (chNext == '=' || Char.IsWhiteSpace(chNext)))
break;
i += k;
}
if (i < 0 || i >= l)
return null;
// skip to '=' and the following whitespaces
i += k;
while (i < l && Char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l || headerValue[i] != '=')
return null;
i++;
while (i < l && Char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l)
return null;
// parse the value
String attrValue = null;
int j;
if (i < l && headerValue[i] == '"') {
if (i == l-1)
return null;
j = headerValue.IndexOf('"', i+1);
if (j < 0 || j == i+1)
return null;
attrValue = headerValue.Substring(i+1, j-i-1).Trim();
}
else {
for (j = i; j < l; j++) {
if (headerValue[j] == ' ' || headerValue[j] == ',')
break;
if (!AppSettings.UseLegacyMultiValueHeaderHandling && headerValue[j] == ';')
break;
}
if (j == i)
return null;
attrValue = headerValue.Substring(i, j-i).Trim();
}
return attrValue;
}
/*
* In case content-type header contains encoding it should override the config
*/
private Encoding GetEncodingFromHeaders() {
if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) {
String postDataCharset = Headers["x-up-devcap-post-charset"];
if (!String.IsNullOrEmpty(postDataCharset)) {
try {
return Encoding.GetEncoding(postDataCharset);
}
catch {
// Exception may be thrown when charset is not valid.
// In this case, do nothing, and let the framework
// use the configured RequestEncoding setting.
}
}
}
if (!_wr.HasEntityBody())
return null;
String contentType = this.ContentType;
if (contentType == null)
return null;
String charSet = GetAttributeFromHeader(contentType, "charset");
if (charSet == null)
return null;
Encoding encoding = null;
try {
encoding = Encoding.GetEncoding(charSet);
}
catch {
// bad encoding string throws an exception that needs to be consumed
}
return encoding;
}
/*
* Read entire raw content as byte array
*/
private HttpRawUploadedContent GetEntireRawContent() {
if (_wr == null)
return null;
if (_rawContent != null) {
// if _rawContent was set by HttpBufferlessInputStream, then we will apply the filter here
if (_installedFilter != null && !_filterApplied) {
ApplyFilter(ref _rawContent, RuntimeConfig.GetConfig(_context).HttpRuntime.RequestLengthDiskThresholdBytes);
}
return _rawContent;
}
if (_readEntityBodyMode == ReadEntityBodyMode.None) {
_readEntityBodyMode = ReadEntityBodyMode.Classic;
}
else if (_readEntityBodyMode == ReadEntityBodyMode.Buffered) {
// _rawContent should have been set already
throw new InvalidOperationException(SR.GetString(SR.Invalid_operation_with_get_buffered_input_stream));
}
else if (_readEntityBodyMode == ReadEntityBodyMode.Bufferless) {
throw new HttpException(SR.GetString(SR.Incompatible_with_get_bufferless_input_stream));
}
// enforce the limit
HttpRuntimeSection cfg = RuntimeConfig.GetConfig(_context).HttpRuntime;
int limit = cfg.MaxRequestLengthBytes;
if (ContentLength > limit) {
if ( !(_wr is IIS7WorkerRequest) ) {
Response.CloseConnectionAfterError();
}
throw new HttpException(SR.GetString(SR.Max_request_length_exceeded),
null, WebEventCodes.RuntimeErrorPostTooLarge);
}
// threshold to go to file
int fileThreshold = cfg.RequestLengthDiskThresholdBytes;
// read the preloaded content
HttpRawUploadedContent rawContent = new HttpRawUploadedContent(fileThreshold, ContentLength);
byte[] preloadedContent = _wr.GetPreloadedEntityBody();
if (preloadedContent != null) {
_wr.UpdateRequestCounters(preloadedContent.Length);
rawContent.AddBytes(preloadedContent, 0, preloadedContent.Length);
}
// read the remaing content
if (!_wr.IsEntireEntityBodyIsPreloaded()) {
int remainingBytes = (ContentLength > 0) ? ContentLength - rawContent.Length : Int32.MaxValue;