-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathHTTPRequest.pas
More file actions
1317 lines (1192 loc) · 37.6 KB
/
HTTPRequest.pas
File metadata and controls
1317 lines (1192 loc) · 37.6 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
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
{
HTTPRequest - Simple HTTP Server Component
Author: Gecko71
Copyright: 2025
LICENSE:
========
This code is provided for non-commercial use only. The code is provided "as is"
without warranty of any kind, either expressed or implied, including but not
limited to the implied warranties of merchantability and fitness for a particular
purpose.
You are free to:
- Use this code for personal, educational, or non-commercial purposes
- Modify, adapt, or build upon this code as needed
- Share the code with others under the same license terms
You may not:
- Use this code for commercial purposes without explicit permission
- Remove this license notice from any copies or derivatives
THE AUTHOR(S) SHALL NOT BE LIABLE FOR ANY DAMAGES ARISING FROM THE USE
OF THIS SOFTWARE.
By using this code, you acknowledge that you have read and understood
this license and agree to its terms.
}
unit HTTPRequest;
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections,
System.NetEncoding, Logger;
type
EHTTPParseError = class(Exception);
EHTTPHeaderError = class(EHTTPParseError);
THTTPHeader = record
Name: string;
Value: string;
end;
THTTPMultipartFile = class
private
FName: string;
FFilename: string;
FContentType: string;
FData: TBytes;
FStream: TStream;
FOwnsStream: Boolean;
FIsStreaming: Boolean;
public
constructor Create(const AName, AFilename, AContentType: string; const AData: TBytes); overload;
constructor CreateFromStream(const AName, AFilename, AContentType: string; AStream: TStream; AOwnsStream: Boolean = True); overload;
destructor Destroy; override;
property Name: string read FName;
property Filename: string read FFilename;
property ContentType: string read FContentType;
property Data: TBytes read FData;
property Stream: TStream read FStream;
property IsStreaming: Boolean read FIsStreaming;
end;
THTTPRequestParser = class
private
FRawData: TBytes;
FMethod: string;
FPath: string;
FProtocol: string;
FHeaders: TList<THTTPHeader>;
FParams: TDictionary<string, string>;
FFiles: TObjectList<THTTPMultipartFile>;
FBody: TBytes;
FContentType: string;
FBoundary: string;
FIsMultipart: Boolean;
FIsFormUrlEncoded: Boolean;
FIsValid: Boolean;
FPathParams: TDictionary<string, string>;
FBasePath: string;
FStreamingThreshold: Integer;
FHttpLogger: THttpLogger;
procedure ParsePathParams;
procedure ParseRequest;
procedure ParseHeaders(const HeaderSection: string);
procedure ParseUrlEncodedParams(const ParamsStr: string);
procedure ParseMultipartData;
function FindBoundaryPositions(const Data: TBytes; const Boundary: TBytes): TArray<Integer>;
function ExtractContentDisposition(const Headers: string; out Name, Filename: string): Boolean;
function ExtractContentType(const Headers: string): string;
function IsLargeFile(const ContentLength: Integer): Boolean;
function GetBodyValue: string;
procedure DecodeChunkedEncoding(const ChunkedData: TBytes);
procedure WriteLog(log: string);
function FindRequestLineEnd(const Data: TBytes): Integer;
function ParseRequestLine(const Data: TBytes; RequestLineEnd: Integer;
out MethodBytes, PathBytes, ProtocolBytes: TBytes): Boolean;
procedure FindHeadersEnd(const Data: TBytes; RequestLineEnd: Integer;
out HeaderEndPos, BodyStartPos: Integer);
procedure ParseHeadersSection(const Data: TBytes; HeaderEndPos: Integer);
function ParseContentLength(const ContentLengthStr: string): Integer;
procedure ProcessRequestBody(const Data: TBytes; BodyStartPos, ContentLength: Integer;
ChunkedEncoding: Boolean);
procedure ProcessRequestContent(const ContentType: string);
function CompareBoundary(const Data: TBytes; Offset: Integer; const Boundary: TBytes): Boolean;
function FastIndexOf(const Data, Pattern: TBytes; StartPos, DataLength: Integer): Integer;
public
constructor Create(const RequestData: TBytes; AHttpLogger:THttpLogger;
AStreamingThreshold: Integer = 1024 * 1024);
destructor Destroy; override;
function MatchPathPattern(const Pattern, Path: string; out Params: TDictionary<string, string>): Boolean;
function GetPathParam(const Name: string): string;
function GetHeader(const Name: string): string;
function GetParam(const Name: string): string;
function GetFile(const Name: string): THTTPMultipartFile;
property BasePath: string read FBasePath;
property Method: string read FMethod;
property Path: string read FPath;
property Protocol: string read FProtocol;
property Body: TBytes read FBody;
property BodyValue: String read GetBodyValue;
property ContentType: string read FContentType;
property IsMultipart: Boolean read FIsMultipart;
property IsFormUrlEncoded: Boolean read FIsFormUrlEncoded;
property IsValid: Boolean read FIsValid;
property StreamingThreshold: Integer read FStreamingThreshold write FStreamingThreshold;
property Params: TDictionary<string, string> read FParams;
property HttpLogger: THttpLogger read FHttpLogger write FHttpLogger;
end;
implementation
uses System.Math, GHTTPConstants, HttpServerUtils;
{ THTTPMultipartFile }
constructor THTTPMultipartFile.Create(const AName, AFilename, AContentType: string; const AData: TBytes);
begin
inherited Create;
FName := AName;
FFilename := AFilename;
FContentType := AContentType;
FData := AData;
FIsStreaming := False;
FStream := nil;
end;
constructor THTTPMultipartFile.CreateFromStream(const AName, AFilename, AContentType: string; AStream: TStream; AOwnsStream: Boolean = True);
begin
inherited Create;
FName := AName;
FFilename := AFilename;
FContentType := AContentType;
FStream := AStream;
FOwnsStream := AOwnsStream;
FIsStreaming := True;
end;
destructor THTTPMultipartFile.Destroy;
begin
SetLength(FData, 0);
if FIsStreaming and FOwnsStream and Assigned(FStream) then
FStream.Free;
inherited;
end;
{ THTTPRequestParser }
constructor THTTPRequestParser.Create(const RequestData: TBytes; AHttpLogger:THttpLogger;
AStreamingThreshold: Integer = 1024 * 1024);
begin
inherited Create;
FHttpLogger := AHttpLogger;
FRawData := RequestData;
FHeaders := TList<THTTPHeader>.Create;
FParams := TDictionary<string, string>.Create;
FFiles := TObjectList<THTTPMultipartFile>.Create(True);
FPathParams := TDictionary<string, string>.Create;
FIsValid := False;
FIsMultipart := False;
FIsFormUrlEncoded := False;
FStreamingThreshold := AStreamingThreshold;
ParseRequest;
end;
destructor THTTPRequestParser.Destroy;
begin
FHeaders.Free;
FParams.Free;
FFiles.Free;
if Assigned(FPathParams) then
FPathParams.Free;
SetLength(FRawData, 0);
SetLength(FBody, 0);
inherited;
end;
function THTTPRequestParser.IsLargeFile(const ContentLength: Integer): Boolean;
begin
Result := ContentLength > FStreamingThreshold;
end;
procedure THTTPRequestParser.ParsePathParams;
begin
FBasePath := FPath;
end;
function THTTPRequestParser.MatchPathPattern(const Pattern, Path: string; out Params: TDictionary<string, string>): Boolean;
var
PatternParts, PathParts: TArray<string>;
i: Integer;
ParamName: string;
begin
Result := False;
Params := TDictionary<string, string>.Create;
PatternParts := Pattern.Split(['/']);
PathParts := Path.Split(['/']);
if Length(PatternParts) <> Length(PathParts) then
begin
Params.Free;
Exit;
end;
for i := 0 to Length(PatternParts) - 1 do
begin
if (Length(PatternParts[i]) > 2) and (PatternParts[i][1] = '{') and
(PatternParts[i][Length(PatternParts[i])] = '}') then
begin
ParamName := Copy(PatternParts[i], 2, Length(PatternParts[i]) - 2);
Params.Add(ParamName, PathParts[i]);
end
else if PatternParts[i] <> PathParts[i] then
begin
Params.Free;
Exit;
end;
end;
Result := True;
if Assigned(FPathParams) then
begin
for ParamName in Params.Keys do
begin
FPathParams.Add(ParamName, Params[ParamName]);
end;
end;
FBasePath := Pattern;
end;
function THTTPRequestParser.GetBodyValue: string;
var
ContentTypeLC: string;
EncodingToUse: TEncoding;
begin
Result := EMPTY_STRING;
if Length(FBody) = 0 then
Exit;
ContentTypeLC := LowerCase(FContentType);
EncodingToUse := TEncoding.UTF8;
if Pos(MIME_TYPE_JSON, ContentTypeLC) > 0 then
begin
try
Result := EncodingToUse.GetString(FBody);
Result := Trim(Result);
if (Result <> EMPTY_STRING) then
begin
if (Result[1] = JSON_OPEN_BRACE) and (Result[Length(Result)] <> JSON_CLOSE_BRACE) then
begin
var OpenBraces := 0;
var CloseBraces := 0;
var InString := False;
var EscapeNext := False;
for var I := 1 to Length(Result) do
begin
var C := Result[I];
if C = JSON_QUOTE then
begin
if not EscapeNext then
InString := not InString;
end;
if C = JSON_ESCAPE then
EscapeNext := not EscapeNext
else
EscapeNext := False;
if not InString then
begin
if C = JSON_OPEN_BRACE then Inc(OpenBraces);
if C = JSON_CLOSE_BRACE then Inc(CloseBraces);
end;
end;
if OpenBraces > CloseBraces then
begin
Result := JSON_ERROR_MISSING_BRACES;
end;
end
else if (Result[1] = JSON_OPEN_BRACKET) and (Result[Length(Result)] <> JSON_CLOSE_BRACKET) then
begin
var OpenBrackets := 0;
var CloseBrackets := 0;
var InString := False;
var EscapeNext := False;
for var I := 1 to Length(Result) do
begin
var C := Result[I];
if C = JSON_QUOTE then
begin
if not EscapeNext then
InString := not InString;
end;
if C = JSON_ESCAPE then
EscapeNext := not EscapeNext
else
EscapeNext := False;
if not InString then
begin
if C = JSON_OPEN_BRACKET then Inc(OpenBrackets);
if C = JSON_CLOSE_BRACKET then Inc(CloseBrackets);
end;
end;
if OpenBrackets > CloseBrackets then
begin
Result := JSON_ERROR_MISSING_BRACKETS;
end;
end;
end;
except
on E: Exception do
begin
Result := Format(JSON_ERROR_PARSE_FORMAT, [E.Message]);
end;
end;
end
else if Pos(CONTENT_TYPE_TEXT_PREFIX, ContentTypeLC) > 0 then
begin
try
Result := EncodingToUse.GetString(FBody);
except
on E: Exception do
begin
try
Result := TEncoding.Default.GetString(FBody);
except
Result := EMPTY_STRING;
end;
end;
end;
end
else
begin
try
Result := EncodingToUse.GetString(FBody);
except
Result := EMPTY_STRING;
end;
end;
end;
function THTTPRequestParser.GetPathParam(const Name: string): string;
begin
Result := '';
if Assigned(FPathParams) and FPathParams.TryGetValue(Name, Result) then
else
Result := '';
end;
procedure THTTPRequestParser.ParseRequest;
var
requestLineEnd, headerEndPos, bodyStartPos: Integer;
contentLengthStr: string;
contentLength, actualBodyLength: Integer;
transferEncoding: string;
chunkedEncoding: Boolean;
queryPos: Integer;
queryStr, rawPath: string;
methodBytes, pathBytes, protocolBytes: TBytes;
errorMessage: string;
begin
try
requestLineEnd := FindRequestLineEnd(FRawData);
if requestLineEnd < 0 then
begin
FIsValid := False;
Exit;
end;
if not ParseRequestLine(FRawData, requestLineEnd, methodBytes, pathBytes, protocolBytes) then
begin
FIsValid := False;
Exit;
end;
FMethod := TEncoding.UTF8.GetString(methodBytes);
rawPath := TEncoding.UTF8.GetString(pathBytes);
FProtocol := TEncoding.UTF8.GetString(protocolBytes);
if not (FProtocol.StartsWith(HTTP_VERSION_1_0) or
FProtocol.StartsWith(HTTP_VERSION_1_1) or
FProtocol.StartsWith(HTTP_VERSION_2_0) or
FProtocol.StartsWith(HTTP_VERSION_3_0)) then
FProtocol := HTTP_VERSION_1_1;
FindHeadersEnd(FRawData, requestLineEnd, headerEndPos, bodyStartPos);
if headerEndPos < 0 then
begin
FIsValid := False;
Exit;
end;
ParseHeadersSection(FRawData, headerEndPos);
FContentType := GetHeader(HTTP_HEADER_CONTENT_TYPE);
contentLengthStr := GetHeader(HTTP_HEADER_CONTENT_LENGTH);
transferEncoding := GetHeader(HTTP_HEADER_CONNECTION);
chunkedEncoding := SameText(Trim(transferEncoding), HTTP_TRANSFER_ENCODING_CHUNKED);
contentLength := ParseContentLength(contentLengthStr);
ProcessRequestBody(FRawData, bodyStartPos, contentLength, chunkedEncoding);
ProcessRequestContent(FContentType);
queryPos := Pos(QUERY_SEPARATOR, rawPath);
if queryPos > 0 then
begin
queryStr := Copy(rawPath, queryPos + 1, Length(rawPath));
FPath := TNetEncoding.URL.Decode(Copy(rawPath, 1, queryPos - 1));
ParseUrlEncodedParams(queryStr);
end
else
begin
FPath := TNetEncoding.URL.Decode(rawPath);
end;
if not Assigned(FPathParams) then
FPathParams := TDictionary<string, string>.Create;
ParsePathParams;
FIsValid := True;
except
on E: Exception do
begin
errorMessage := Format(ERROR_PARSE_REQUEST_FORMAT, [E.Message]);
FIsValid := False;
end;
end;
end;
function THTTPRequestParser.FindRequestLineEnd(const Data: TBytes): Integer;
var
i, scanLimit: Integer;
CR, LF: Byte;
begin
CR := 13;
LF := 10;
Result := -1;
scanLimit := Min(1024, Length(Data) - 2);
for i := 0 to scanLimit do
begin
if (Data[i] = CR) and (i + 1 < Length(Data)) and (Data[i + 1] = LF) then
begin
Result := i;
Exit;
end
else if (Data[i] = LF) then
begin
Result := i;
Exit;
end;
end;
for i := scanLimit + 1 to Length(Data) - 2 do
begin
if (Data[i] = CR) and (Data[i + 1] = LF) then
begin
Result := i;
Exit;
end
else if (Data[i] = LF) then
begin
Result := i;
Exit;
end;
end;
end;
function THTTPRequestParser.ParseRequestLine(const Data: TBytes; RequestLineEnd: Integer;
out MethodBytes, PathBytes, ProtocolBytes: TBytes): Boolean;
var
i, partCount, partStart: Integer;
SPACE: Byte;
parts: TArray<TBytes>;
begin
SPACE := 32;
SetLength(parts, 3);
partCount := 0;
partStart := 0;
for i := 0 to RequestLineEnd - 1 do
begin
if Data[i] = SPACE then
begin
if partCount < 3 then
begin
SetLength(parts[partCount], i - partStart);
if (i - partStart) > 0 then
Move(Data[partStart], parts[partCount][0], i - partStart);
Inc(partCount);
partStart := i + 1;
end;
end;
end;
if (partCount < 3) and (partStart < RequestLineEnd) then
begin
SetLength(parts[partCount], RequestLineEnd - partStart);
if (RequestLineEnd - partStart) > 0 then
Move(Data[partStart], parts[partCount][0], RequestLineEnd - partStart);
Inc(partCount);
end;
Result := (partCount = 3);
if Result then
begin
MethodBytes := parts[0];
PathBytes := parts[1];
ProtocolBytes := parts[2];
end;
end;
procedure THTTPRequestParser.FindHeadersEnd(const Data: TBytes; RequestLineEnd: Integer;
out HeaderEndPos, BodyStartPos: Integer);
var
i, j, skipSize: Integer;
CR, LF: Byte;
begin
CR := 13;
LF := 10;
HeaderEndPos := -1;
BodyStartPos := -1;
i := RequestLineEnd;
if (Data[RequestLineEnd] = CR) and (RequestLineEnd + 1 < Length(Data)) and (Data[RequestLineEnd + 1] = LF) then
i := RequestLineEnd + 2
else if (Data[RequestLineEnd] = LF) then
i := RequestLineEnd + 1;
while i < Length(Data) - 1 do
begin
if (Data[i] = CR) then
begin
if (i + 1 < Length(Data)) and (Data[i + 1] = LF) then
begin
if (i + 3 < Length(Data)) and (Data[i + 2] = CR) and (Data[i + 3] = LF) then
begin
HeaderEndPos := i;
BodyStartPos := i + 4;
Exit;
end;
i := i + 2;
end
else
begin
Inc(i);
end;
end
else if (Data[i] = LF) then
begin
if (i + 1 < Length(Data)) and (Data[i + 1] = LF) then
begin
HeaderEndPos := i;
BodyStartPos := i + 2;
Exit;
end;
Inc(i);
end
else
begin
skipSize := 1;
for j := 1 to Min(16, Length(Data) - i - 1) do
begin
if (Data[i + j] = CR) or (Data[i + j] = LF) then
begin
skipSize := j;
Break;
end;
end;
i := i + skipSize;
end;
end;
end;
procedure THTTPRequestParser.ParseHeadersSection(const Data: TBytes; HeaderEndPos: Integer);
var
headersBytes: TBytes;
headersStr: string;
begin
headersBytes := Copy(Data, 0, HeaderEndPos);
headersStr := TEncoding.UTF8.GetString(headersBytes);
ParseHeaders(headersStr);
end;
function THTTPRequestParser.ParseContentLength(const ContentLengthStr: string): Integer;
begin
Result := 0;
if ContentLengthStr <> EMPTY_STRING then
begin
try
Result := StrToInt(Trim(ContentLengthStr));
if Result < 0 then
Result := 0;
except
Result := 0;
end;
end;
end;
procedure THTTPRequestParser.ProcessRequestBody(const Data: TBytes; BodyStartPos, ContentLength: Integer;
ChunkedEncoding: Boolean);
var
actualBodyLength: Integer;
begin
if BodyStartPos < Length(Data) then
begin
actualBodyLength := Length(Data) - BodyStartPos;
if ChunkedEncoding then
begin
try
DecodeChunkedEncoding(Copy(Data, BodyStartPos, actualBodyLength));
except
on E: Exception do
begin
SetLength(FBody, actualBodyLength);
if actualBodyLength > 0 then
Move(Data[BodyStartPos], FBody[0], actualBodyLength);
end;
end;
end
else
begin
if (ContentLength > 0) and (ContentLength <= actualBodyLength) then
begin
SetLength(FBody, ContentLength);
if ContentLength > 0 then
Move(Data[BodyStartPos], FBody[0], ContentLength);
end
else
begin
SetLength(FBody, actualBodyLength);
if actualBodyLength > 0 then
Move(Data[BodyStartPos], FBody[0], actualBodyLength);
end;
end;
end
else
begin
SetLength(FBody, 0);
end;
end;
procedure THTTPRequestParser.ProcessRequestContent(const ContentType: string);
var
boundaryPos: Integer;
bodyStr: string;
begin
if Pos(MIME_TYPE_JSON, LowerCase(ContentType)) > 0 then
begin
end
else if Pos(CONTENT_TYPE_MULTIPART_FORM_DATA, LowerCase(ContentType)) > 0 then
begin
boundaryPos := Pos(HEADER_BOUNDARY_PREFIX, LowerCase(ContentType));
if boundaryPos > 0 then
begin
FBoundary := Copy(ContentType, boundaryPos + Length(HEADER_BOUNDARY_PREFIX), Length(ContentType));
if (Length(FBoundary) >= 2) and (FBoundary[1] = '"') and (FBoundary[Length(FBoundary)] = '"') then
FBoundary := Copy(FBoundary, 2, Length(FBoundary) - 2);
FIsMultipart := True;
ParseMultipartData;
end;
end
else if Pos(CONTENT_TYPE_FORM_URLENCODED, LowerCase(ContentType)) > 0 then
begin
FIsFormUrlEncoded := True;
if Length(FBody) > 0 then
begin
bodyStr := TEncoding.UTF8.GetString(FBody);
ParseUrlEncodedParams(bodyStr);
end;
end;
end;
procedure THTTPRequestParser.DecodeChunkedEncoding(const ChunkedData: TBytes);
var
i, ChunkSize, TotalSize: Integer;
HexSize: string;
ResultStream: TMemoryStream;
IsInChunkSize: Boolean;
IsInChunkData: Boolean;
CR, LF: Byte;
begin
ChunkSize := 0;
CR := Byte(13);
LF := Byte(10);
ResultStream := TMemoryStream.Create;
try
i := 0;
IsInChunkSize := True;
IsInChunkData := False;
HexSize := '';
while i < Length(ChunkedData) do
begin
if IsInChunkSize then
begin
if ((ChunkedData[i] = CR) and (i + 1 < Length(ChunkedData)) and (ChunkedData[i+1] = LF)) then
begin
Inc(i, 2);
if HexSize = '' then
Break;
try
ChunkSize := StrToInt('$' + HexSize);
except
ChunkSize := 0;
end;
if ChunkSize = 0 then
Break;
IsInChunkSize := False;
IsInChunkData := True;
HexSize := '';
end
else
begin
var C: Char := Char(ChunkedData[i]);
if CharInSet(C, ['0'..'9', 'a'..'f', 'A'..'F']) then
HexSize := HexSize + C;
Inc(i);
end;
end
else if IsInChunkData then
begin
if ChunkSize > 0 then
begin
if i + ChunkSize <= Length(ChunkedData) then
begin
ResultStream.Write(ChunkedData[i], ChunkSize);
Inc(i, ChunkSize);
if (i + 1 < Length(ChunkedData)) and (ChunkedData[i] = CR) and (ChunkedData[i+1] = LF) then
Inc(i, 2);
IsInChunkData := False;
IsInChunkSize := True;
end
else
begin
var AvailableSize := Length(ChunkedData) - i;
ResultStream.Write(ChunkedData[i], AvailableSize);
Inc(i, AvailableSize);
end;
end
else
begin
IsInChunkData := False;
IsInChunkSize := True;
end;
end;
end;
TotalSize := ResultStream.Size;
if TotalSize > 0 then
begin
SetLength(FBody, TotalSize);
ResultStream.Position := 0;
ResultStream.Read(FBody[0], TotalSize);
end
else
begin
SetLength(FBody, 0);
end;
finally
ResultStream.Free;
end;
end;
procedure THTTPRequestParser.ParseHeaders(const HeaderSection: string);
var
HeaderLines: TArray<string>;
i, j: Integer;
Line, CurrentHeaderName, CurrentHeaderValue: string;
SeparatorPos: Integer;
Header: THTTPHeader;
TempHeader: THTTPHeader;
ExistingHeader: Boolean;
MultilineHeaderAllowed: Boolean;
HeaderEnded: Boolean;
begin
if Length(HeaderSection) = 0 then
raise EHTTPHeaderError.Create(EMPTY_HEADER_SECTION);
HeaderLines := HeaderSection.Split([#13#10]);
if Length(HeaderLines) < 1 then
raise EHTTPHeaderError.Create(INVALID_HEADER_FORMAT_NO_LINES);
CurrentHeaderName := '';
CurrentHeaderValue := '';
MultilineHeaderAllowed := False;
HeaderEnded := False;
for i := 1 to High(HeaderLines) do
begin
Line := HeaderLines[i];
if Line = '' then
begin
HeaderEnded := True;
Break;
end;
if (Length(Line) > 0) and ((Line[1] = ' ') or (Line[1] = #9)) then
begin
if MultilineHeaderAllowed and (CurrentHeaderName <> '') then
CurrentHeaderValue := CurrentHeaderValue + SPACE_SEPARATOR + TrimLeft(Line)
else
raise EHTTPHeaderError.CreateFmt(INVALID_FOLDED_HEADER_LINE, [Line]);
Continue;
end;
if CurrentHeaderName <> '' then
begin
ExistingHeader := False;
for j := 0 to FHeaders.Count - 1 do
begin
if SameText(FHeaders[j].Name, CurrentHeaderName) then
begin
TempHeader := FHeaders[j];
if SameText(CurrentHeaderName, SET_COOKIE_HEADER) then
begin
TempHeader.Value := TempHeader.Value + SEMICOLON_SEPARATOR + CurrentHeaderValue;
FHeaders[j] := TempHeader;
ExistingHeader := True;
Break;
end
else if SameText(CurrentHeaderName, CACHE_CONTROL_HEADER) or
SameText(CurrentHeaderName, ACCEPT_HEADER) or
SameText(CurrentHeaderName, ACCEPT_ENCODING_HEADER) or
SameText(CurrentHeaderName, ACCEPT_LANGUAGE_HEADER) then
begin
TempHeader.Value := TempHeader.Value + COMMA_SEPARATOR + CurrentHeaderValue;
FHeaders[j] := TempHeader;
ExistingHeader := True;
Break;
end;
end;
end;
if not ExistingHeader then
begin
Header.Name := CurrentHeaderName;
Header.Value := CurrentHeaderValue;
FHeaders.Add(Header);
end;
CurrentHeaderName := '';
CurrentHeaderValue := '';
MultilineHeaderAllowed := False;
end;
SeparatorPos := Pos(':', Line);
if SeparatorPos <= 0 then
raise EHTTPHeaderError.CreateFmt(INVALID_HEADER_FORMAT_MISSING_COLON, [Line]);
if SeparatorPos = 1 then
raise EHTTPHeaderError.CreateFmt(INVALID_HEADER_FORMAT_EMPTY_NAME, [Line]);
CurrentHeaderName := Trim(Copy(Line, 1, SeparatorPos - 1));
CurrentHeaderValue := Trim(Copy(Line, SeparatorPos + 1, Length(Line)));
if CurrentHeaderName = '' then
raise EHTTPHeaderError.Create(EMPTY_HEADER_NAME_AFTER_TRIMMING);
for j := 1 to Length(CurrentHeaderName) do
begin
if not (
((CurrentHeaderName[j] >= 'a') and (CurrentHeaderName[j] <= 'z')) or
((CurrentHeaderName[j] >= 'A') and (CurrentHeaderName[j] <= 'Z')) or
((CurrentHeaderName[j] >= '0') and (CurrentHeaderName[j] <= '9')) or
(CurrentHeaderName[j] = '-') or (CurrentHeaderName[j] = '_')
) then
begin
raise EHTTPHeaderError.CreateFmt(
INVALID_CHARACTER_IN_HEADER_NAME,
[CurrentHeaderName, j, CurrentHeaderName[j]]);
end;
end;
MultilineHeaderAllowed := True;
end;
if CurrentHeaderName <> '' then
begin
ExistingHeader := False;
for j := 0 to FHeaders.Count - 1 do
begin
if SameText(FHeaders[j].Name, CurrentHeaderName) then
begin
TempHeader := FHeaders[j];
if SameText(CurrentHeaderName, SET_COOKIE_HEADER) then
begin
TempHeader.Value := TempHeader.Value + SEMICOLON_SEPARATOR + CurrentHeaderValue;
FHeaders[j] := TempHeader;
ExistingHeader := True;
Break;
end
else if SameText(CurrentHeaderName, CACHE_CONTROL_HEADER) or
SameText(CurrentHeaderName, ACCEPT_HEADER) or
SameText(CurrentHeaderName, ACCEPT_ENCODING_HEADER) or
SameText(CurrentHeaderName, ACCEPT_LANGUAGE_HEADER) then
begin
TempHeader.Value := TempHeader.Value + COMMA_SEPARATOR + CurrentHeaderValue;
FHeaders[j] := TempHeader;
ExistingHeader := True;
Break;
end;
end;
end;
if not ExistingHeader then
begin
Header.Name := CurrentHeaderName;
Header.Value := CurrentHeaderValue;
FHeaders.Add(Header);
end;
end;
if not HeaderEnded and (Length(HeaderLines) > 1) then
WriteLog(WARNING_HEADER);
end;
procedure THTTPRequestParser.WriteLog(log: string);
begin
try
if Assigned(FHttpLogger) then
HttpLogger.Log(log);
except
end;
end;
procedure THTTPRequestParser.ParseUrlEncodedParams(const ParamsStr: string);
var
ParamPairs: TArray<string>;
i: Integer;
Pair: string;
SeparatorPos: Integer;
ParamName, ParamValue: string;
begin
ParamPairs := ParamsStr.Split(['&']);
for i := 0 to Length(ParamPairs) - 1 do
begin
Pair := ParamPairs[i];
SeparatorPos := Pos('=', Pair);
if SeparatorPos > 0 then
begin
ParamName := Copy(Pair, 1, SeparatorPos - 1);
ParamValue := Copy(Pair, SeparatorPos + 1, Length(Pair));
try
ParamName := TNetEncoding.URL.Decode(ParamName);
except
end;
try
ParamValue := TNetEncoding.URL.Decode(ParamValue);
except
end;
FParams.AddOrSetValue(ParamName, ParamValue);
end
else if Pair <> '' then
begin
try
ParamName := TNetEncoding.URL.Decode(Pair);
except
ParamName := Pair;
end;
FParams.AddOrSetValue(ParamName, '');
end;
end;