This repository has been archived by the owner on Nov 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathEvilWorks.Web.HTTP.pas
2025 lines (1771 loc) · 55.3 KB
/
EvilWorks.Web.HTTP.pas
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
//
// EvilLibrary by Vedran Vuk 2010-2012
//
// Name: EvilWorks.Web.HTTP
// Description: HTTP Client.
// File last change date: October 21st. 2012
// File version: Dev 0.0.0
// Licence: Free.
//
{ TODO: Implement request octet-stream type sending. }
{ TODO: Implement gzip/deflate for posting/requests. }
unit EvilWorks.Web.HTTP;
interface
uses
Winapi.Windows,
System.Classes,
System.SysUtils,
EvilWorks.Api.Winsock2,
EvilWorks.Api.ZLib,
EvilWorks.System.SysUtils,
EvilWorks.System.StrUtils,
EvilWorks.System.DateUtils,
EvilWorks.Web.Utils,
EvilWorks.Web.AsyncSockets,
EvilWorks.Web.Base64,
EvilWorks.Web.URI,
EvilWorks.Crypto.HMAC_SHA1;
const
{ HTTP header fields }
CAccept = 'Accept';
CAcceptCharset = 'Accept-Charset';
CAcceptEncoding = 'Accept-Encoding';
CAcceptLanguage = 'Accept-Language';
CAuthorization = 'Authorization';
CConnection = 'Connection';
CContentEncoding = 'Content-Encoding';
CContentLength = 'Content-Length';
CContentType = 'Content-Type';
CHost = 'Host';
CTransferEncoding = 'Transfer-Encoding';
CUserAgent = 'User-Agent';
{ OAuth parameters }
COAuthConsumerKey = 'oauth_consumer_key';
COAuthNonce = 'oauth_nonce';
COAuthSignature = 'oauth_signature';
COAuthSignatureMethod = 'oauth_signature_method';
COAuthTimestamp = 'oauth_timestamp';
COAuthToken = 'oauth_token';
COAuthVersion = 'oauth_version';
{ OAuth signature methods }
CHMACSHA1 = 'HMAC-SHA1';
{ OAuth versions}
C1Point0 = '1.0';
{ Authorization values }
CBasic = 'basic';
COAuth = 'OAuth';
{ Transfer-Encoding values }
CChunked = 'chunked';
{ Connection values }
CClose = 'close';
CKeepALive = 'keep-alive';
{ Content-Encoding values }
CDeflate = 'deflate';
CGZip = 'gzip';
{ Content-Type values }
CContentTypeForm = 'application/x-www-form-urlencoded';
CContentTypeOctetStream = 'application/octet-stream';
CContentTypeJSON = 'application/json';
{ THTTPMethods }
THTTPMethods: array [0 .. 8] of string = (
'HEAD', 'GET', 'POST', 'OPTIONS', 'TRACE', 'PUT', 'DELETE', 'CONNECT', 'UPDATE'
);
{ THTTPVersions }
THTTPVersions: array [0 .. 1] of string = (
'HTTP/1.0', 'HTTP/1.1'
);
type
{ Forward declarations. }
THTTPAuthorization = class;
THTTPContentDecoder = class;
TCustomHTTPClient = class;
{ THTTPMethod }
THTTPMethod = (hmHead, hmGet, hmPost, hmOptions, hmTrace, hmPut, hmDelete, hmConnect);
{ THTTPVersion }
THTTPVersion = (hv10, hv11);
{ THTTPClientOption }
THTTPClientOption = (
hcoAllowResponseWithoutMessage, // Allow responses without an HTTP message (Some REST APIs).
hcoExpectResponseWithoutMessage, // For streaming REST APIs. Does not parse response, only returns data.
hcoReceiveExtraData, // Receive data that exceeds Content-Length.
hcoCombineChunks, // Combine chunked transfer. For small responses like JSON. Extremely slow and memory hungry with big responses and should be avoided.
hcoEnableCompression // Enable gzip and/or deflate compression.
);
THTTPClientOptions = set of THTTPClientOption;
{ THTTPRequestLine }
{ First line in an HTTP request message, e.g. "GET /path/to/file.json HTTP/1.1" }
THTTPRequestLine = class(TPersistent)
private
FVersion: string;
FPath : string;
FMethod : string;
FValid : boolean;
FURI : string;
public
procedure Assign(aSource: TPersistent); override;
public
procedure Parse(const aText: string);
function AsString: string;
function AsStringCRLF: string;
procedure Clear;
public
property URI: string read FURI write FURI;
property Method : string read FMethod write FMethod;
property Path : string read FPath write FPath;
property Version: string read FVersion write FVersion;
property Valid: boolean read FValid write FValid;
end;
{ THTTPStatusLine }
{ First line in an HTTP response message, e.g. "HTTP/1.1 200 OK" }
THTTPStatusLine = class(TPersistent)
private
FVersion: string;
FCode : string;
FComment: string;
FValid : boolean;
public
procedure Assign(aSource: TPersistent); override;
public
procedure Parse(const aText: string);
function AsString: string;
function AsStringCRLF: string;
procedure Clear;
public
property Version: string read FVersion write FVersion;
property Code : string read FCode write FCode;
property Comment: string read FComment write FComment;
property Valid: boolean read FValid write FValid;
end;
{ THTTPHeaderLine }
{ A "Key: Value" header in an HTTP message. e.g. "Accept: */*" }
THTTPHeaderLine = class(TPersistent)
private
FKey : string;
FVal : string;
FValid: boolean;
public
procedure Assign(aSource: TPersistent); override;
public
procedure Parse(const aText: string);
function AsString: string;
function AsStringCRLF: string;
procedure Clear;
public
property Key: string read FKey write FKey;
property Val: string read FVal write FVal;
property Valid: boolean read FValid write FValid;
end;
{ THTTPMessage }
{ An HTTP message containing a request|response header and a list of HTTP headers. }
THTTPMessage = class(TPersistent)
public type
THTTPMessageType = (htUndefined, htRequest, htResponse);
private
FItems : array of THTTPHeaderLine;
FCount : integer;
FMessageType : THTTPMessageType;
FRequestHeader : THTTPRequestLine;
FResponseHeader : THTTPStatusLine;
FPostData : TStream;
FPostDataIsLocal: boolean;
function Find(const aKey: string): integer;
function GetItem(const aIndex: integer): THTTPHeaderLine;
procedure SetItem(const aIndex: integer; const aValue: THTTPHeaderLine);
procedure SetRequestHeader(const aValue: THTTPRequestLine);
procedure SetResponseHeader(const aValue: THTTPStatusLine);
function GetValidRequest: boolean;
function GetValidresponse: boolean;
public
constructor Create;
destructor Destroy; override;
procedure Assign(aSource: TPersistent); override;
public
procedure Parse(const aText: string);
function AsString: string;
procedure Add(const aKey, aVal: string); overload;
procedure Add(const aText: string); overload;
procedure DelKey(const aKey: string);
procedure DelVal(const aKey: string);
procedure Clear;
function Val(const aKey: string): string;
property Items[const aIndex: integer]: THTTPHeaderLine read GetItem write SetItem; default;
property Count: integer read FCount;
property MessageType: THTTPMessageType read FMessageType write FMessageType;
property RequestHeader: THTTPRequestLine read FRequestHeader write SetRequestHeader;
property ResponseHeader: THTTPStatusLine read FResponseHeader write SetResponseHeader;
property ValidRequest: boolean read GetValidRequest;
property ValidResponse: boolean read GetValidResponse;
property PostData: TStream read FPostData write FPostData;
property PostDataIsLocal: boolean read FPostDataIsLocal write FPostDataIsLocal;
end;
{ THTTPAuth }
{ Base Authorization type-specific class. }
THTTPAuth = class(TPersistent)
private
FAuthorization: THTTPAuthorization;
protected
procedure AuthorizeRequest(var aRequest: THTTPMessage); virtual; abstract;
public
constructor Create(aOwner: THTTPAuthorization); virtual;
end;
{ THTTPAuthBasic }
{ Implements "Authorization: basic <signature>" header. }
THTTPAuthBasic = class(THTTPAuth)
private
FPassword: string;
FUsername: string;
protected
procedure AuthorizeRequest(var aRequest: THTTPMessage); override;
public
procedure Assign(aSource: TPersistent); override;
published
property Username: string read FUsername write FUsername;
property Password: string read FPassword write FPassword;
end;
{ THTTPAuthOAuth1Mode }
{ Type of OAuth1.0 signing performed on an HTTP request. }
THTTPAuthOAuth1Mode = (
hao3Step, // If you have 2 public and secret oauth tokens after performing 3step auth on behalf of a user.
hao4Keys // If you have all 4 tokens; public + secret for both consumer and user. (Usually devs only).
);
{ THTTPAuthOAuth1 }
{ Implements "Authorization: OAuth <oauth_params>" (v1.0a) Authorization header. }
{ 3-step authentication process is not directly implemented in THTTPClient/THTTPOAuth1. }
{ You will have to do the authentication flow manually to obtain oauth_token and oauth_token_secret. }
{ This is because of the browser involvement and redirection required in this process. }
THTTPAuthOAuth1 = class(THTTPAuth)
private
FMode : THTTPAuthOAuth1Mode;
FOAuthTokenSecret : string;
FOAuthToken : string;
FConsumerKeySecret: string;
FAccessTokenPublic: string;
FAccessTokenSecret: string;
FConsumerKeyPublic: string;
protected
procedure AuthorizeRequest(var aRequest: THTTPMessage); override;
public
constructor Create(aOwner: THTTPAuthorization); override;
procedure Assign(aSource: TPersistent); override;
published
property AccessTokenPublic: string read FAccessTokenPublic write FAccessTokenPublic;
property AccessTokenSecret: string read FAccessTokenSecret write FAccessTokenSecret;
property ConsumerKeyPublic: string read FConsumerKeyPublic write FConsumerKeyPublic;
property ConsumerKeySecret: string read FConsumerKeySecret write FConsumerKeySecret;
property Mode: THTTPAuthOAuth1Mode read FMode write FMode default hao3Step;
property OAuthToken : string read FOAuthToken write FOAuthToken;
property OAuthTokenSecret: string read FOAuthTokenSecret write FOAuthTokenSecret;
end;
{ THTTPAuthorizationType }
THTTPAuthorizationType = (hatBasic, hatOAuth1);
{ THTTPAuthorization }
{ Handles HTTP Authorization header. }
THTTPAuthorization = class(TPersistent)
private
FHTTPClient : TCustomHTTPClient;
FAuthorizationType: THTTPAuthorizationType;
FAuth : THTTPAuth;
FEnabled : boolean;
procedure SetAuthorizationType(const aValue: THTTPAuthorizationType);
procedure SetAuth(const Value: THTTPAuth);
protected
procedure AuthorizeRequest(var aRequest: THTTPMessage);
public
constructor Create(aOwner: TCustomHTTPClient);
destructor Destroy; override;
procedure Assign(aSource: TPersistent); override;
published
property AuthorizationType: THTTPAuthorizationType read FAuthorizationType write SetAuthorizationType;
property Auth : THTTPAuth read FAuth write SetAuth;
property Enabled : boolean read FEnabled write FEnabled default False;
end;
{ TContentDecoder events. }
TOnContentDecoderError = procedure(aSender: THTTPContentDecoder; const aError: string) of object;
TOnContentDecoderDecoded = procedure(aSender: THTTPContentDecoder; const aSize: integer) of object;
{ TContentDecoder }
{ Decodes raw deflate, ZLib and GZip files/response body. Acts much like TSSLFilter. }
{ Give data with Decode(), wait for OnDecoded, read with ReadDecoded(). }
THTTPContentDecoder = class
private
FHTTPClient: TCustomHTTPClient;
FStream : TZStreamRec;
FBuffer : TBuffer;
FReadBuf : pbyte;
FReadBufSize: integer;
FOnDecoded: TOnContentDecoderDecoded;
FOnError : TOnContentDecoderError;
protected
procedure EventError(const aError: string);
procedure EventDecoded(const aSize: integer);
public
constructor Create(aClient: TCustomHTTPClient);
destructor Destroy; override;
procedure Decode(const aData: pByte; const aSize: integer);
function ReadDecoded(const aData: pByte; const aSize: integer): integer;
property OnError: TOnContentDecoderError read FOnError write FOnError;
property OnDecoded: TOnContentDecoderDecoded read FOnDecoded write FOnDecoded;
end;
{ TCustomHTTPClient events. }
TOnHeadersAvailable = procedure(aSender: TCustomHTTPClient; const aHeaders: THTTPMessage) of object;
TOnDataAvailable = procedure(aSender: TCustomHTTPClient; aResponse: TStream) of object;
{ TCustomHTTPClient }
TCustomHTTPClient = class(TCustomAsyncTCPClient)
private
// Property variables
FOptions : THTTPClientOptions;
FUserAgent : string;
FAcceptCharset : string;
FAcceptLanguage: string;
FAccept : string;
FAuthorization : THTTPAuthorization;
// Request variables
// These are initialized before each request, connected or not
// and are initialized using ResetSession();
FRequestHeaders: THTTPMessage; // Request message
// Response variables
// These are initialized before each request, connected or not
// and are initialized using ResetSession();
FResponseMessage : THTTPMessage; // Response HTTP message.
FResponseStream : TStream; // Stream provided by application in request methods.
FResponseBuffer : TBuffer; // Receive buffer.
FResponseMessageParsed : boolean; // Flag for EventDataAvailable
FResponseSize : integer; // Content-Length, as int.
FResponseChunked : boolean; // Is response body chunked?
FResponseChunkBytes : integer; // Bytes in the next chunk.
FResponseContentDecoder: THTTPContentDecoder; // Name says it. Created on demand after response read.
FResponseSkipContent : boolean; // If HEAD is issued, ignores Content-Length.
// Events
FOnRequestHeaders : TOnHeadersAvailable;
FOnResponseHeaders: TOnHeadersAvailable;
FOnDataAvailable : TOnDataAvailable;
FConnection : string;
// Session functions.
procedure ResetSession;
// Event handlers
procedure EventDecoderError(aSender: THTTPContentDecoder; const aError: string);
procedure EventDecoderDataDecoded(aSender: THTTPContentDecoder; const aSize: integer);
// Getters/setters.
procedure SetOptions(const Value: THTTPClientOptions);
procedure SetRequestHeaders(const aValue: THTTPMessage);
procedure SetUserAgent(const Value: string);
procedure SetAuthorization(const Value: THTTPAuthorization);
protected
procedure ConstructRequest(const aMethod: THTTPMethod; const aURI, aContentType: string; aPostData: TStream);
// Overriden events.
procedure EventConnect; override;
procedure EventDataAvailable(const aSize: integer); override;
// Introduced events.
procedure EventRequestHeaders(aHeaders: THTTPMessage); virtual;
procedure EventResponseHeaders(aHeaders: THTTPMessage); virtual;
procedure EventBodyAvailable(aData: TStream); virtual;
// Introduced properties for lowering in descendants.
property Accept: string read FAccept write FAccept;
property AcceptCharset: string read FAcceptCharset write FAcceptCharset;
property AcceptLanguage: string read FAcceptLanguage write FAcceptLanguage;
property Authorization: THTTPAuthorization read FAuthorization write SetAuthorization;
property Connection: string read FConnection write FConnection;
property Options: THTTPClientOptions read FOptions write SetOptions;
property RequestHeaders: THTTPMessage read FRequestHeaders write SetRequestHeaders;
property UserAgent: string read FUserAgent write SetUserAgent;
// Introduced events
property OnDataAvailable: TOnDataAvailable read FOnDataAvailable write FOnDataAvailable;
property OnRequestHeaders: TOnHeadersAvailable read FOnRequestHeaders write FOnRequestHeaders;
property OnResponseHeaders: TOnHeadersAvailable read FOnResponseHeaders write FOnResponseHeaders;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(aSource: TPersistent); override;
procedure Connect; override;
procedure Disconnect; override;
// Request methods.
function GET(const aURI: string; aResponse: TStream): boolean;
function POSTForm(const aURI, aFormData: string; aResponse: TStream): boolean;
function POSTOctetStream(const aURI: string; aPostData, aResponse: TStream): boolean; overload;
end;
{ THTTPClient }
THTTPClient = class(TCustomHTTPClient)
published
// From TCustomAsyncTCPClient
property AddressFamily;
property Authorization;
property BindHost;
property BindPort;
property Connection;
property ConnectTimeout;
property ProxyChain;
property RemoteHost;
property RemotePort;
property SocketState;
property SSL;
property OnConnected;
property OnConnecting;
property OnConnectTimeout;
property OnDisconnected;
property OnError;
property OnLog;
property OnProxyChainConnected;
property OnProxyConnecting;
property OnProxyConnected;
property OnResolved;
property OnResolving;
// Introduced
property Accept;
property AcceptCharset;
property AcceptLanguage;
property Options default [hcoEnableCompression];
property RequestHeaders;
property UserAgent;
property OnRequestHeaders;
property OnResponseHeaders;
property OnDataAvailable;
end;
function HTTPMethodToString(const aMethod: THTTPMethod): string;
implementation
{ THTTPMethod to text. }
function HTTPMethodToString(const aMethod: THTTPMethod): string;
begin
case aMethod of
hmHead:
Result := 'HEAD';
hmGet:
Result := 'GET';
hmPost:
Result := 'POST';
hmOptions:
Result := 'OPTIONS';
hmTrace:
Result := 'TRACE';
hmPut:
Result := 'PUT';
hmDelete:
Result := 'DELETE';
hmConnect:
Result := 'CONNECT';
end;
end;
{ ================ }
{ THTTPRequestLine }
{ ================ }
{ Assign. }
procedure THTTPRequestLine.Assign(aSource: TPersistent);
begin
if (aSource is THTTPRequestLine) then
begin
Method := THTTPRequestLine(aSource).Method;
Path := THTTPRequestLine(aSource).Path;
Version := THTTPRequestLine(aSource).Version;
end;
end;
{ Clears the values. }
procedure THTTPRequestLine.Clear;
begin
FURI := '';
FMethod := '';
FPath := '';
FVersion := '';
FValid := False;
end;
{ Parses an HTTP request line to property values. }
procedure THTTPRequestLine.Parse(const aText: string);
var
tokens: TArray<string>;
i : integer;
begin
// Split by space, count must be 3 for a valid request line.
tokens := TextSplit(TextRemoveLineFeeds(aText));
if (Length(tokens) > 3) or (Length(tokens) < 2) then
Exit;
// Check for known method at index 0.
for i := 0 to high(THTTPMethods) do
begin
if (TextEquals(tokens[0], THTTPMethods[i])) then
begin
FMethod := tokens[0];
Break;
end;
end;
// If no recognized methods found, abort.
if (FMethod = '') then
Exit;
FPath := tokens[1];
FVersion := tokens[2];
FValid := True;
// Double check for valid version if exists.
if (FVersion <> '') then
begin
for i := 0 to high(THTTPVersions) do
if (TextEquals(FVersion, THTTPVersions[i])) then
Exit;
end
else
Exit;
FMethod := '';
FPath := '';
FVersion := '';
FValid := False;
end;
{ Returns property values formated as an HTTP request line. }
function THTTPRequestLine.AsString: string;
begin
if (Method = '') or (Path = '') or (Version = '') then
Exit('');
Result := UpperCase(Method) + ' ' + Path + ' ' + UpperCase(Version);
end;
{ Same as AsString + CR LF. }
function THTTPRequestLine.AsStringCRLF: string;
begin
Result := AsString;
if (Result = '') then
Exit;
Result := Result + #13#10;
end;
{ =============== }
{ THTTPStatusLine }
{ =============== }
{ Assign. }
procedure THTTPStatusLine.Assign(aSource: TPersistent);
begin
if (aSource is THTTPStatusLine) then
begin
Version := THTTPStatusLine(aSource).Version;
Code := THTTPStatusLine(aSource).Code;
Comment := THTTPStatusLine(aSource).Comment;
end;
end;
{ Clears the values. }
procedure THTTPStatusLine.Clear;
begin
FVersion := '';
FCode := '';
FComment := '';
Fvalid := False;
end;
{ Parses an HTTP status line to property values. }
procedure THTTPStatusLine.Parse(const aText: string);
var
s: string;
begin
s := aText;
FVersion := TextExtractLeft(s, ' ', True);
FCode := TextExtractLeft(s, ' ', True);
FComment := TextRemoveLineFeeds(s);
// Check that code can be converted to integer.
// If not, this is not a status line.
if (TextToInt(FCode, - 1) = - 1) then
begin
FVersion := '';
FCode := '';
FComment := '';
end
else
FValid := True;
end;
{ Returns property values formated as an HTTP status line. }
function THTTPStatusLine.AsString: string;
begin
if (Version = '') or (Code = '') then
Exit('');
Result := Version + ' ' + Code;
if (Comment <> '') then
Result := Result + ' ' + Comment;
Result := Result;
end;
{ Same as AsString + CR LF. }
function THTTPStatusLine.AsStringCRLF: string;
begin
Result := AsString;
if (Result = '') then
Exit;
Result := Result + #13#10;
end;
{ =============== }
{ THTTPHeaderLine }
{ =============== }
{ Assign. }
procedure THTTPHeaderLine.Assign(aSource: TPersistent);
begin
if (aSource is THTTPHeaderLine) then
begin
Key := THTTPHeaderLine(aSource).Key;
Val := THTTPHeaderLine(aSource).Val;
end;
end;
{ Clears THTTPHeaderLine. }
procedure THTTPHeaderLine.Clear;
begin
FKey := CEmpty;
FVal := CEmpty;
FValid := False;
end;
{ Parses an HTTP header line. }
procedure THTTPHeaderLine.Parse(const aText: string);
begin
FKey := Trim(TextFetchLeft(aText, ':', True));
FVal := Trim(TextFetchRight(aText, ':', True));
FValid := (FKey <> '');
end;
{ Returns the header in form of "Key: Val;" }
function THTTPHeaderLine.AsString: string;
begin
if (Key = CEmpty) then
Exit(CEmpty);
Result := Key + CColon + CSpace + Val;
end;
{ Get + CRLF }
function THTTPHeaderLine.AsStringCRLF: string;
begin
Result := AsString;
if (Result = CEmpty) then
Exit;
Result := Result + CCrLf;
end;
{ ============ }
{ THTTPMessage }
{ ============ }
{ Constructor. }
constructor THTTPMessage.Create;
begin
FMessageType := htUndefined;
FRequestHeader := THTTPRequestLine.Create;
FResponseHeader := THTTPStatusLine.Create;
FCount := 0;
end;
{ Destructor. }
destructor THTTPMessage.Destroy;
begin
Clear;
FResponseHeader.Free;
FRequestHeader.Free;
inherited;
end;
{ Clears/initializes the THTTPHeaders. }
procedure THTTPMessage.Assign(aSource: TPersistent);
var
i: integer;
begin
if (aSource is THTTPMessage) then
begin
Clear;
for i := 0 to THTTPMessage(aSource).Count - 1 do
Add(THTTPMessage(aSource)[i].Key, THTTPMessage(aSource)[i].Val);
RequestHeader.Assign(THTTPMessage(aSource).RequestHeader);
ResponseHeader.Assign(THTTPMessage(aSource).ResponseHeader);
end;
end;
{ Gets the index of item whose Key matches aKey. -1 if not found. }
function THTTPMessage.Find(const aKey: string): integer;
var
i: integer;
begin
for i := 0 to Count - 1 do
if (TextEquals(FItems[i].Key, aKey)) then
Exit(i);
Result := - 1;
end;
{ Adds aKey:aVal to list of HTTP headers. }
{ If an aKey already exists, its' value is replaced with aVal. }
procedure THTTPMessage.Add(const aKey, aVal: string);
var
i: integer;
begin
i := Find(aKey);
if (i < 0) then
begin
Inc(FCount);
SetLength(FItems, FCount);
FItems[FCount - 1] := THTTPHeaderLine.Create;
FItems[FCount - 1].FKey := aKey;
FItems[FCount - 1].FVal := aVal;
Exit;
end;
FItems[i].Val := aVal;
end;
{ Parses aText as an HTTP message header line. }
procedure THTTPMessage.Add(const aText: string);
var
s, k, v: string;
begin
s := aText;
k := Trim(TextExtractLeft(s, ':', True));
if (k = '') then
Exit;
v := Trim(s);
Add(k, v);
end;
{ Get Val of aKey. }
function THTTPMessage.Val(const aKey: string): string;
var
i: integer;
begin
for i := 0 to Count - 1 do
if (TextSame(Items[i].Key, aKey)) then
Exit(Items[i].Val);
Result := CEmpty;
end;
{ Parse aText as a possible complete HTTP message or as just one line. }
{ aText needs to be valid by being CRLF terminated. }
{ Partial data will possibly break the parse procedure. }
procedure THTTPMessage.Parse(const aText: string);
var
tokens: TArray<string>;
token : string;
begin
tokens := TextSplit(aText, CCrLf);
for token in tokens do
begin
if (token = CEmpty) then
Continue;
if (TextBegins(token, 'HTTP')) then
FResponseHeader.Parse(token)
else if (TextInArray(token, THTTPMethods, False)) then
FRequestHeader.Parse(token)
else
Add(token);
end;
end;
{ Deletes an item whose Key matches aKey. }
procedure THTTPMessage.DelKey(const aKey: string);
var
i: integer;
begin
i := Find(aKey);
if (i < 0) then
Exit;
FItems[i].Free;
Dec(FCount);
if (i < FCount) then
Move(FItems[i + 1], FItems[i], (FCount - i) * SizeOf(THTTPHeaderLine));
SetLength(FItems, FCount);
end;
{ Deletes Val of item whose Key equals aVal. }
procedure THTTPMessage.DelVal(const aKey: string);
var
i: integer;
begin
i := Find(aKey);
if (i < 0) then
Exit;
FItems[FCount - 1].FVal := CEmpty;
end;
{ Clears the THTTPHeader. }
procedure THTTPMessage.Clear;
var
i: integer;
begin
for i := 0 to Count - 1 do
Items[i].Free;
SetLength(FItems, 0);
FCount := 0;
FRequestHeader.Clear;
FResponseHeader.Clear;
FMessageType := htUndefined;
if (FPostDataIsLocal) then
FPostData.Free;
FPostData := nil;
FPostDataIsLocal := False;
end;
{ All headers in one string. }
function THTTPMessage.AsString: string;
var
i: integer;
begin
Result := '';
case FMessageType of
htUndefined:
Result := '';
htRequest:
Result := FRequestHeader.AsStringCRLF;
htResponse:
Result := FResponseHeader.AsStringCRLF;
end;
for i := 0 to Count - 1 do
Result := Result + Items[i].AsStringCRLF;
Result := Result + #13#10;
if (FPostData <> nil) then
if (FPostData is TStringStream) then
Result := Result + TStringStream(FPostData).DataString;
end;
{ Items getter. }
function THTTPMessage.GetItem(const aIndex: integer): THTTPHeaderLine;
begin
if (aIndex < 0) or (aIndex >= FCount) then
Exit(nil);
Result := FItems[aIndex];
end;
{ ValidRequest getter. }
function THTTPMessage.GetValidRequest: boolean;
begin
Result := FRequestHeader.Valid;
end;
{ ValidResponse getter. }
function THTTPMessage.GetValidResponse: boolean;
begin
Result := FResponseHeader.Valid;
end;
{ Items setter. }
procedure THTTPMessage.SetItem(const aIndex: integer; const aValue: THTTPHeaderLine);
begin
if (aIndex < 0) or (aIndex >= FCount) then
Exit;
FItems[aIndex].Assign(aValue);
end;
{ RequestHeader setter. }
procedure THTTPMessage.SetRequestHeader(const aValue: THTTPRequestLine);
begin
FRequestHeader.Assign(aValue);
end;
{ ResponseHeader setter. }
procedure THTTPMessage.SetResponseHeader(const aValue: THTTPStatusLine);
begin
FResponseHeader.Assign(aValue);
end;
{ ========= }
{ THTTPAuth }
{ ========= }
{ Constructor. }
constructor THTTPAuth.Create(aOwner: THTTPAuthorization);
begin
FAuthorization := aOwner;
end;
{ ============== }
{ THTTPAuthBasic }
{ ============== }
{ Assign }
procedure THTTPAuthBasic.Assign(aSource: TPersistent);
begin
inherited;
if (aSource is THTTPAuthBasic) then
begin
Username := THTTPAuthBasic(aSource).Username;
Password := THTTPAuthBasic(aSource).Password;
end;
end;
{ Sign/Authorize the request message. }
procedure THTTPAuthBasic.AuthorizeRequest(var aRequest: THTTPMessage);
begin
aRequest.Add(CAuthorization, CBasic + ' ' + Base64Encode(Username + ':' + Password));
end;
{ =============== }
{ THTTPAuthOAuth1 }
{ =============== }
{ Constructor. }
constructor THTTPAuthOAuth1.Create(aOwner: THTTPAuthorization);
begin
inherited;
FMode := hao3Step;
end;
{ Assign }
procedure THTTPAuthOAuth1.Assign(aSource: TPersistent);
begin
inherited;
if (aSource is THTTPAuthOAuth1) then
begin
Mode := THTTPAuthOAuth1(aSource).Mode;
OAuthToken := THTTPAuthOAuth1(aSource).OAuthToken;
OAuthTokenSecret := THTTPAuthOAuth1(aSource).OAuthTokenSecret;