forked from grijjy/GrijjyFoundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrijjy.Http.pas
1930 lines (1733 loc) · 52.7 KB
/
Grijjy.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
unit Grijjy.Http;
{ Windows and Linux Cross-platform HTTP, HTTPS and HTTP/2 protocol
support class using scalable client sockets }
interface
{$I Grijjy.inc}
//{$DEFINE LOGGING}
{$DEFINE HTTP2}
uses
System.Classes,
System.SysUtils,
System.StrUtils,
System.SyncObjs,
System.DateUtils,
System.Messaging,
System.Net.URLClient,
System.Net.Socket,
System.Generics.Collections,
{$IFDEF MSWINDOWS}
Grijjy.SocketPool.Win,
Windows,
{$ENDIF}
{$IFDEF LINUX}
Grijjy.SocketPool.Linux,
Posix.Pthread,
{$ENDIF}
{$IFDEF HTTP2}
Nghttp2,
{$ENDIF}
Grijjy.BinaryCoding;
const
{ Socket buffer size }
BUFFER_SIZE = 32768;
{ Timeout for operations }
TIMEOUT_CONNECT = 20000;
TIMEOUT_RECV = 5000;
{ Strings }
S_CONTENT_LENGTH = 'content-length';
S_CONTENT_TYPE = 'content-type';
S_TRANSFER_ENCODING = 'transfer-encoding';
S_CHUNKED = 'chunked';
S_CHARSET = 'charset';
{ End of line }
CRLF = #13#10;
{ Ports }
DEFAULT_HTTP_PORT = 80;
DEFAULT_HTTPS_PORT = 443;
{ Cleanup }
INTERVAL_CLEANUP = 5000;
type
{ Http events }
TOnRedirect = procedure(Sender: TObject; var ALocation: String; const AFollow: Boolean) of object;
TOnPassword = procedure(Sender: TObject; var AAgain: Boolean) of object;
TOnRecv = procedure(Sender: TObject; const ABuffer: Pointer; const ASize: Integer; var ACreateResponse: Boolean) of object;
TOnSent = procedure(Sender: TObject; const ABuffer: Pointer; const ASize: Integer) of object;
{ ISO-8859-1 ASCII compatible string }
{$IFDEF MSWINDOWS}
ISO8859String = type AnsiString(28591);
{$ELSE}
ISO8859String = type RawByteString;
{$ENDIF}
type
{ Thread safe buffer }
TThreadSafeBuffer = class(TObject)
private
FLock: TCriticalSection;
FBuffer: TBytes;
FSize: Integer;
public
constructor Create(const ACapacity: Integer = BUFFER_SIZE);
destructor Destroy; override;
protected
function GetSize: Integer;
public
{ Write buffer }
procedure Write(const ABuffer: Pointer; const ASize: Integer);
{ Read entire buffer }
function Read(out ABytes: TBytes): Boolean; overload;
{ Read count number of bytes from the buffer }
function Read(out ABytes: TBytes; const ACount: Integer): Boolean; overload;
{ Read up to length number of bytes from the buffer, for nghttp2 }
function Read(const ABuffer: Pointer; var ALength: NativeInt): Boolean; overload;
{ Read all bytes up to and including substring match }
function ReadTo(const ASubStr: RawByteString; out ABytes: TBytes): Boolean;
{ Clear the buffer }
procedure Clear;
{$IFDEF LOGGING}
{ Outputs the buffer to log }
procedure Log(const AText: String);
{$ENDIF}
public
{ Current actual size of the buffer }
property Size: Integer read GetSize;
end;
type
{ Client activity state }
TgoHttpClientState = (None, Error, Sending, Receiving, Finished);
{ Http header }
TgoHttpHeader = record
Name: String;
Value: String;
{$IFDEF HTTP2}
NameAsISO8859: ISO8859String; { nghttp2 requires a pointer to a memory object we maintain }
ValueAsISO8859: ISO8859String;
{$ENDIF}
end;
{ Http headers class }
TgoHttpHeaders = class(TObject)
private
FHeaders: TArray<TgoHttpHeader>;
public
constructor Create;
destructor Destroy; override;
public
{ Add or set a header and value to a list of headers }
procedure AddOrSet(const AName, AValue: String); overload;
procedure AddOrSet(const AHeader: String); overload;
{ Get the value associated with the header }
function Value(const AName: String): String;
{ Returns the index of the associated header }
function IndexOf(const AName: String): Integer;
{ Reads headers as http compatible header string }
function AsString: String;
{ Reads headers as ngHttp2 compatible header array }
{$IFDEF HTTP2}
procedure AsNgHttp2Array(var AHeaders: TArray<nghttp2_nv>);
{$ENDIF}
public
property Headers: TArray<TgoHttpHeader> read FHeaders write FHeaders;
end;
{ Http client }
TgoHttpClient = class(TObject)
private
{$IFDEF HTTP2}
FHttp2: Boolean;
{$ENDIF}
FBlocking: Boolean;
FConnection: TgoSocketConnection;
FConnectionLock: TCriticalSection;
FState: TgoHttpClientState;
FConnectTimeout: Integer;
FRecvTimeout: Integer;
{ SSL }
FCertificate: TBytes;
FPrivateKey: TBytes;
{ Recv }
FRecvBuffer: TThreadSafeBuffer;
FRecvBuffer2: TThreadSafeBuffer;
FLastRecv: TDateTime;
FRecvAbort: Boolean;
FRecv: TEvent;
{ Send }
FSendBuffer: TThreadSafeBuffer;
FLastSent: TDateTime;
{ Http request }
FURL: String;
FMethod: String;
FURI: TURI;
FLastURI: TURI;
FContentLength: Int64;
FTransferEncoding: String;
FHttpVersion: String;
FFollowRedirects: Boolean;
FSentCookies: TStrings;
FCookies: TStrings;
FAuthorization: String;
FUserName: String;
FPassword: String;
FContentType: String;
FConnected: TEvent;
FInternalHeaders: TgoHttpHeaders;
FRequestStatusLine: String;
FRequestHeaders: TgoHttpHeaders;
FRequestBody: String;
FRequestData: TBytes;
FUserAgent: String;
FRange: String;
{ Http response }
FResponseHeader: Boolean;
FResponseHeaders: TgoHttpHeaders;
FResponseStatusCode: Integer;
FResponseContentType: String;
FResponseContentCharset: String;
FResponse: TBytes;
FResponseBytes: Integer;
FChunkSize: Integer;
{ ngHttp2 }
{$IFDEF HTTP2}
FStreamId2: Integer;
FResponseHeader2: Boolean;
FResponseContent2: Boolean;
FCallbacks_http2: pnghttp2_session_callbacks;
FSession_http2: pnghttp2_session;
{$ENDIF}
private
{ ngHttp2 callbacks }
{$IFDEF HTTP2}
function nghttp2_data_source_read_callback(session: pnghttp2_session;
stream_id: int32; buf: puint8; len: size_t; data_flags: puint32;
source: pnghttp2_data_source; user_data: Pointer): ssize_t; cdecl;
function nghttp2_on_data_chunk_recv_callback(session: pnghttp2_session;
flags: uint8; stream_id: int32; const data: puint8; len: size_t;
user_data: Pointer): Integer; cdecl;
function nghttp2_on_frame_recv_callback(session: pnghttp2_session;
const frame: pnghttp2_frame; user_data: Pointer): Integer; cdecl;
function nghttp2_on_header_callback(session: pnghttp2_session;
const frame: pnghttp2_frame; const name: puint8; namelen: size_t;
const value: puint8; valuelen: size_t; flags: uint8;
user_data: Pointer): Integer; cdecl;
function nghttp2_on_stream_close_callback(session: pnghttp2_session;
stream_id: int32; error_code: uint32; user_data: Pointer): Integer; cdecl;
function nghttp2_Send: Boolean;
function nghttp2_Recv: Boolean;
{$ENDIF}
protected
FOnPassword: TOnPassword;
FOnRedirect: TOnRedirect;
FOnSent: TOnSent;
FOnRecv: TOnRecv;
procedure SetCookies(const AValue: TStrings);
function GetIdleTime: Integer;
private
function GetCookies: TStrings;
private
procedure Reset;
procedure CreateRequest;
function SendRequest: Boolean;
function ResponseHeader: Boolean;
function ResponseContent: Boolean;
function WaitForRecv: Boolean;
function DoResponse(var AAgain: Boolean): TBytes;
function DoRequest(const AMethod, AURL: String;
out AResponse: TBytes; const AConnectTimeout, ARecvTimeout: Integer): Boolean;
protected
{ Socket routines }
procedure OnSocketConnected;
procedure OnSocketDisconnected;
procedure OnSocketSent(const ABuffer: Pointer; const ASize: Integer);
procedure OnSocketRecv(const ABuffer: Pointer; const ASize: Integer);
protected
procedure DoRecv(const ABuffer: Pointer; const ASize: Integer);
public
constructor Create(const AHttp2: Boolean = False; const ABlocking: Boolean = True);
destructor Destroy; override;
public
{ Get method }
function Get(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Get(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Get(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Head method }
function Head(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean;
{ Post method }
function Post(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Post(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Post(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Put method }
function Put(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Put(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Put(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Delete method }
function Delete(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Delete(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Delete(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Options method }
function Options(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Options(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Options(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Close connection }
procedure Close;
{ Convert bytes to string }
function BytesToString(const ABytes: TBytes; const ACharset: String): String;
public
{ State }
property State: TgoHttpClientState read FState;
{ Idle time in milliseconds }
property IdleTime: Integer read GetIdleTime;
{ Cookies sent to the server and received from the server }
property Cookies: TStrings read GetCookies write SetCookies;
{ Optional body for a request.
You can either use RequestBody or RequestData. If both are specified then
only RequestBody is used. }
property RequestBody: String read FRequestBody write FRequestBody;
{ Optional binary body data for a request.
You can either use RequestBody or RequestData. If both are specified then
only RequestBody is used. }
property RequestData: TBytes read FRequestData write FRequestData;
{ Request headers }
property RequestHeaders: TgoHttpHeaders read FRequestHeaders;
{ Response headers from the server }
property ResponseHeaders: TgoHttpHeaders read FResponseHeaders;
{ Response status code }
property ResponseStatusCode: Integer read FResponseStatusCode;
{ Response content type }
property ResponseContentType: String read FResponseContentType;
{ Response charset }
property ResponseContentCharset: String read FResponseContentCharset;
{ Response content length }
property ContentLength: Int64 read FContentLength;
{ Allow 301 and other redirects }
property FollowRedirects: Boolean read FFollowRedirects write FFollowRedirects;
{ Called when a redirect is requested }
property OnRedirect: TOnRedirect read FOnRedirect write FOnRedirect;
{ Called when a password is needed }
property OnPassword: TOnPassword read FOnPassword write FOnPassword;
{ Called when a buffer is received from the socket }
property OnRecv: TOnRecv read FOnRecv write FOnRecv;
{ Called when the data has been sent by the socket }
property OnSent: TOnSent read FOnSent write FOnSent;
{ Username and password for Basic Authentication }
property UserName: String read FUserName write FUserName;
property Password: String read FPassword write FPassword;
{ Content type }
property ContentType: String read FContentType write FContentType;
{ User agent }
property UserAgent: String read FUserAgent write FUserAgent;
{ Range }
property Range: String read FRange write FRange;
{ Authorization }
property Authorization: String read FAuthorization write FAuthorization;
{ Certificate in PEM format }
property Certificate: TBytes read FCertificate write FCertificate;
{ Private key in PEM format }
property PrivateKey: TBytes read FPrivateKey write FPrivateKey;
end;
{ Http response message }
TgoHttpResponseMessage = class(TMessage)
private
FHttpClient: TgoHttpClient;
FResponseHeaders: TgoHttpHeaders;
FResponseStatusCode: Integer;
FResponseContentType: String;
FResponseContentCharset: String;
FResponse: TBytes;
public
constructor Create(
const AHttpClient: TgoHttpClient;
const AResponseHeaders: TgoHttpHeaders;
const AResponseStatusCode: Integer;
const AResponseContentType: String;
const AResponseContentCharset: String;
const AResponse: TBytes);
public
property HttpClient: TgoHttpClient read FHttpClient;
property ResponseHeaders: TgoHttpHeaders read FResponseHeaders;
property ResponseStatusCode: Integer read FResponseStatusCode;
property ResponseContentType: String read FResponseContentType;
property ResponseContentCharset: String read FResponseContentCharset;
property Response: TBytes read FResponse;
end;
{ Http client manager }
TgoHttpClientManager = class(TThread)
private
FHttpClients: TList<TgoHttpClient>;
FLock: TCriticalSection;
procedure FreeClients(const AForce: Boolean = False);
protected
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
public
{ Queues the http client for release }
procedure Release(const AHttpClient: TgoHttpClient);
end;
var
HttpClientManager: TgoHttpClientManager;
implementation
uses
Grijjy.SysUtils;
var
_HttpClientSocketManager: TgoClientSocketManager;
{ ngHttp2 callback cdecl }
{$IFDEF HTTP2}
function data_source_read_callback(session: pnghttp2_session;
stream_id: int32; buf: puint8; len: size_t; data_flags: puint32;
source: pnghttp2_data_source; user_data: Pointer): ssize_t; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_data_source_read_callback(session, stream_id, buf, len, data_flags, source, user_data);
end;
function on_header_callback(session: pnghttp2_session; const frame: pnghttp2_frame;
const name: puint8; namelen: size_t; const value: puint8; valuelen: size_t;
flags: uint8; user_data: Pointer): Integer; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_on_header_callback(session, frame, name, namelen, value, valuelen, flags, user_data);
end;
function on_frame_recv_callback(session: pnghttp2_session;
const frame: pnghttp2_frame; user_data: Pointer): Integer; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_on_frame_recv_callback(session, frame, user_data);
end;
function on_data_chunk_recv_callback(session: pnghttp2_session;
flags: uint8; stream_id: int32; const data: puint8; len: size_t;
user_data: Pointer): Integer; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_on_data_chunk_recv_callback(session, flags, stream_id, data, len, user_data);
end;
function on_stream_close_callback(session: pnghttp2_session;
stream_id: int32; error_code: uint32; user_data: Pointer): Integer; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_on_stream_close_callback(session, stream_id, error_code, user_data);
end;
{$ENDIF}
{ TThreadSafeBuffer }
constructor TThreadSafeBuffer.Create(const ACapacity: Integer);
begin
SetLength(FBuffer, ACapacity);
FSize := 0;
FLock := TCriticalSection.Create;
end;
destructor TThreadSafeBuffer.Destroy;
begin
FLock.Free;
inherited;
end;
function TThreadSafeBuffer.GetSize: Integer;
begin
FLock.Enter;
try
Result := FSize;
finally
FLock.Leave;
end;
end;
procedure TThreadSafeBuffer.Write(const ABuffer: Pointer; const ASize: Integer);
begin
FLock.Enter;
try
{ expand buffer }
if FSize + ASize >= Length(FBuffer) then
SetLength(FBuffer, (FSize + ASize) * 2);
{ append bytes }
Move(ABuffer^, FBuffer[FSize], ASize);
FSize := FSize + ASize;
finally
FLock.Leave;
end;
end;
function TThreadSafeBuffer.Read(out ABytes: TBytes): Boolean;
begin
FLock.Enter;
try
if FSize > 0 then
begin
{ read bytes into new buffer }
SetLength(ABytes, FSize);
Move(FBuffer[0], ABytes[0], FSize);
{ clear buffer }
FSize := 0;
Result := True;
end
else
Result := False;
finally
FLock.Leave;
end;
end;
function TThreadSafeBuffer.Read(out ABytes: TBytes; const ACount: Integer): Boolean;
var
Size: Integer;
begin
FLock.Enter;
try
if FSize > 0 then
begin
{ read bytes into new buffer }
if FSize >= ACount then
Size := ACount
else
Size := FSize;
SetLength(ABytes, Size);
Move(FBuffer[0], ABytes[0], Size);
{ delete buffer }
if FSize > Size then
begin
Move(FBuffer[Size], FBuffer[0], FSize - Size);
FSize := FSize - Size;
end
else
FSize := 0;
Result := True;
end
else
Result := False;
finally
FLock.Leave;
end;
end;
function TThreadSafeBuffer.Read(const ABuffer: Pointer;
var ALength: NativeInt): Boolean;
begin
FLock.Enter;
try
if FSize > 0 then
begin
{ read bytes into existing buffer }
if FSize < ALength then
ALength := FSize;
Move(FBuffer[0], ABuffer^, ALength);
{ delete buffer }
if FSize > ALength then
begin
Move(FBuffer[ALength], FBuffer[0], FSize - ALength);
FSize := FSize - ALength;
end
else
FSize := 0;
Result := True;
end
else
Result := False;
finally
FLock.Leave;
end;
end;
function TThreadSafeBuffer.ReadTo(const ASubStr: RawByteString; out ABytes: TBytes): Boolean;
var
Size, Index: Integer;
begin
Result := False;
Size := Length(ASubStr);
FLock.Enter;
try
if FSize > Size then
for Index := 0 to FSize - Size do
if CompareMem(@FBuffer[Index], @ASubStr[1], Size) then
begin
{ read bytes into new buffer }
SetLength(ABytes, Index + Size);
Move(FBuffer[0], ABytes[0], Index + Size);
{ delete buffer }
if FSize > (Index + Size) then
begin
Move(FBuffer[Index + Size], FBuffer[0], FSize - (Index + Size));
FSize := FSize - (Index + Size);
end
else
FSize := 0;
Result := True;
Break;
end;
finally
FLock.Leave;
end;
end;
procedure TThreadSafeBuffer.Clear;
begin
FLock.Enter;
try
FSize := 0;
finally
FLock.Leave;
end;
end;
{$IFDEF LOGGING}
procedure TThreadSafeBuffer.Log(const AText: String);
begin
//grLog(Format('RecvBuffer %s (Size=%d)', [AText, FSize]), @FBuffer[0], FSize);
end;
{$ENDIF}
{ THttpHeaders }
constructor TgoHttpHeaders.Create;
begin
end;
destructor TgoHttpHeaders.Destroy;
begin
FHeaders := nil;
inherited;
end;
procedure TgoHttpHeaders.AddOrSet(const AName, AValue: String);
var
Index: Integer;
Header: TgoHttpHeader;
begin
Index := IndexOf(AName);
if Index = -1 then
begin
Header.Name := AName;
Header.Value := AValue;
{$IFDEF HTTP2}
Header.NameAsISO8859 := ISO8859String(AName);
Header.ValueAsISO8859 := ISO8859String(AValue);
{$ENDIF}
FHeaders := FHeaders + [Header];
end
else
begin
FHeaders[Index].Name := AName;
FHeaders[Index].Value := AValue;
{$IFDEF HTTP2}
FHeaders[Index].NameAsISO8859 := ISO8859String(AName);
FHeaders[Index].ValueAsISO8859 := ISO8859String(AValue);
{$ENDIF}
end;
end;
procedure TgoHttpHeaders.AddOrSet(const AHeader: String);
var
Index: Integer;
Name: String;
Value: String;
begin
Index := AHeader.IndexOf(':');
if Index > -1 then
begin
Name := AHeader.Substring(0, Index);
Value := AHeader.Substring(Index + 1);
AddOrSet(Name, Value);
end;
end;
function TgoHttpHeaders.Value(const AName: String): String;
var
Header: TgoHttpHeader;
begin
Result := '';
for Header in FHeaders do
if Header.Name.ToLower = AName.ToLower then
begin
Result := String(Header.Value).TrimLeft;
Break;
end;
end;
function TgoHttpHeaders.IndexOf(const AName: String): Integer;
var
Index: Integer;
begin
Result := -1;
for Index := 0 to Length(FHeaders) - 1 do
if FHeaders[Index].Name.ToLower = AName.ToLower then
begin
Result := Index;
Break;
end;
end;
function TgoHttpHeaders.AsString: String;
var
Header: TgoHttpHeader;
begin
for Header in FHeaders do
Result := Result + Header.Name + ': ' + Header.Value + CRLF;
end;
{$IFDEF HTTP2}
procedure TgoHttpHeaders.AsNgHttp2Array(var AHeaders: TArray<nghttp2_nv>);
var
Header: TgoHttpHeader;
NgHttp2Header: nghttp2_nv;
begin
for Header in FHeaders do
begin
NgHttp2Header.name := MarshaledAString(Header.NameAsISO8859);
NgHttp2Header.value := MarshaledAString(Header.ValueAsISO8859);
NgHttp2Header.namelen := Length(Header.Name);
NgHttp2Header.valuelen := Length(Header.Value);
NgHttp2Header.flags := NGHTTP2_NV_FLAG_NONE;
AHeaders := AHeaders + [NgHttp2Header];
end;
end;
{$ENDIF}
{ TgoHttpResponseMessage }
constructor TgoHttpResponseMessage.Create(const AHttpClient: TgoHttpClient;
const AResponseHeaders: TgoHttpHeaders;
const AResponseStatusCode: Integer;
const AResponseContentType, AResponseContentCharset: String;
const AResponse: TBytes);
begin
inherited Create;
FHttpClient := AHttpClient;
FResponseHeaders := AResponseHeaders;
FResponseStatusCode := AResponseStatusCode;
FResponseContentType := AResponseContentType;
FResponseContentCharset := AResponseContentCharset;
FResponse := AResponse;
end;
{ TgoHttpClientManager }
constructor TgoHttpClientManager.Create;
begin
inherited Create;
FHttpClients := TList<TgoHttpClient>.Create;
FLock := TCriticalSection.Create;
end;
destructor TgoHttpClientManager.Destroy;
begin
FreeClients(True);
FLock.Free;
FHttpClients.Free;
inherited;
end;
procedure TgoHttpClientManager.FreeClients(const AForce: Boolean);
var
HttpClient: TgoHttpClient;
HttpClients: TArray<TgoHttpClient>;
ClientsToFree: TArray<TgoHttpClient>;
begin
FLock.Enter;
try
HttpClients := FHttpClients.ToArray;
for HttpClient in HttpClients do
begin
if (AForce) or
(HttpClient.IdleTime > HttpClient.FRecvTimeout) then
if (HttpClient.State = TgoHttpClientState.Sending) or
(HttpClient.State = TgoHttpClientState.Receiving) then
HttpClient.Close;
if (AForce) or
(HttpClient.IdleTime > HttpClient.FRecvTimeout) or
(HttpClient.State = TgoHttpClientState.Finished) or
(HttpClient.State = TgoHttpClientState.Error) or
(HttpClient.State = TgoHttpClientState.None) then
begin
ClientsToFree := ClientsToFree + [HttpClient];
FHttpClients.Remove(HttpClient);
end;
end;
finally
FLock.Leave;
end;
for HttpClient in ClientsToFree do
HttpClient.Free;
end;
procedure TgoHttpClientManager.Execute;
var
LastCleanup: TDateTime;
begin
LastCleanup := Now;
while not Terminated do
begin
if MillisecondsBetween(Now, LastCleanup) > INTERVAL_CLEANUP then
begin
FreeClients;
LastCleanup := Now;
end
else
Sleep(5); { waiting for interval }
end;
end;
procedure TgoHttpClientManager.Release(const AHttpClient: TgoHttpClient);
begin
FLock.Enter;
try
FHttpClients.Add(AHttpClient);
finally
FLock.Leave;
end;
end;
{ TgoHttpClient }
constructor TgoHttpClient.Create(const AHttp2: Boolean = False; const ABlocking: Boolean = True);
{$IFDEF HTTP2}
var
Settings: nghttp2_settings_entry;
Error: Integer;
{$ENDIF}
begin
inherited Create;
{ initialize nghttp2 library }
{$IFDEF HTTP2}
if nghttp2_session_callbacks_new(FCallbacks_http2) = 0 then
begin
nghttp2_session_callbacks_set_on_header_callback(FCallbacks_http2, on_header_callback);
nghttp2_session_callbacks_set_on_frame_recv_callback(FCallbacks_http2, on_frame_recv_callback);
nghttp2_session_callbacks_set_on_data_chunk_recv_callback(FCallbacks_http2, on_data_chunk_recv_callback);
nghttp2_session_callbacks_set_on_stream_close_callback(FCallbacks_http2, on_stream_close_callback);
if (nghttp2_session_client_new(FSession_http2, FCallbacks_http2, Self) = 0) then
begin
Settings.settings_id := NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
Settings.value := 100;
Error := nghttp2_submit_settings(FSession_http2, NGHTTP2_FLAG_NONE, @Settings, 1);
if (Error <> 0) then
raise Exception.Create('Unable to submit ngHttp2 settings');
end
else
raise Exception.Create('Unable to setup ngHttp2 session.');
end
else
raise Exception.Create('Unable to setup ngHttp2 callbacks.');
FHttp2 := AHttp2;
{$ENDIF}
FState := TgoHttpClientState.None;
FBlocking := ABlocking;
FHttpVersion := '1.1';
FAuthorization := '';
FContentType := '';
FUserAgent := '';
FRange := '';
FConnection := nil;
FConnectionLock := TCriticalSection.Create;
FConnected := TEvent.Create(nil, False, False, '');
FFollowRedirects := True;
FSendBuffer := TThreadSafeBuffer.Create;
FRecvBuffer := TThreadSafeBuffer.Create;
FRecvBuffer2 := TThreadSafeBuffer.Create;
FRecv := TEvent.Create(nil, False, False, '');
FRequestHeaders := TgoHttpHeaders.Create;
FInternalHeaders := TgoHttpHeaders.Create;
FResponseHeaders := TgoHttpHeaders.Create;
end;
destructor TgoHttpClient.Destroy;
var
Connection: TgoSocketConnection;
begin
{$IFDEF HTTP2}
nghttp2_session_callbacks_del(FCallbacks_http2);
nghttp2_session_terminate_session(FSession_http2, NGHTTP2_NO_ERROR);
{$ENDIF}
FConnectionLock.Enter;
try
Connection := FConnection;
FConnection := nil;
finally
FConnectionLock.Leave;
end;
if Connection <> nil then
_HttpClientSocketManager.Release(Connection);
FreeAndNil(FRequestHeaders);
FreeAndNil(FInternalHeaders);
FreeAndNil(FResponseHeaders);
FreeAndNil(FCookies);
FreeAndNil(FSentCookies);
FConnected.Free;
FConnectionLock.Free;
FSendBuffer.Free;
FRecvBuffer2.Free;
FRecvBuffer.Free;
FRecv.Free;
inherited Destroy;
end;
{$IFDEF HTTP2}
function TgoHttpClient.nghttp2_data_source_read_callback(session: pnghttp2_session;
stream_id: int32; buf: puint8; len: size_t; data_flags: puint32;
source: pnghttp2_data_source; user_data: Pointer): ssize_t;
begin
// Note: if you want request specific data you can use the API nghttp2_session_get_stream_user_data(session, stream_id);
if NativeUInt(FSendBuffer.Size) <= len then
begin
Result := FSendBuffer.Size;