forked from grijjy/GrijjyFoundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrijjy.SocketPool.Win.pas
1497 lines (1349 loc) · 44.5 KB
/
Grijjy.SocketPool.Win.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.SocketPool.Win;
{ IOCP based socket pool }
{$I Grijjy.inc}
{ Note: TgoSocketPoolBehavior = PoolAndReuse does not currently work with TLS/SSL connections }
{ Note: WSAENOBUFS(10055) error would indicate that you have exhausted
a resource in Windows there are several possibilities:
1. You may have exhausted the MaxUserPort, with a default of 5000. To verify this
run NETSTAT -AN > C:\NETSTAT.TXT and count the number of TIME_WAIT entries.
This happens when the TIME_WAIT holds onto the connection and there are no more
left to allocate. You can add more by creating the key for MaxUserPort under
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters.
You can also reduce the TIME_WAIT by reducing the TcpTimedWaitDelay under
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\TcpTimedWaitDelay
2. You may have exhausted the memory available to the page pool. This should not happen in
scale optimization because we perform a "zero byte read trick" to avoid buffer allocation.
However if you run out with speed optimization then you need to consider allocating
memory more efficiently. Perhaps use VirtualAlloc to allocate a large block
and manage the buffer manually in code, or reduce 4K buffers to 2K.
A good discussion of the issue is here, http://www.coastrd.com/windows-iocp
3. You may have exhausted the IoPageLockLimit, see
https://technet.microsoft.com/en-us/library/cc959494.aspx
}
interface
uses
Windows,
Messages,
Winsock2,
System.Classes,
System.SysUtils,
System.SyncObjs,
System.DateUtils,
System.IOUtils,
System.Generics.Collections,
Grijjy.Winsock2,
Grijjy.OpenSSL,
Grijjy.Collections,
Grijjy.MemoryPool;
const
DEFAULT_BLOCK_SIZE = 4096;
TIMEOUT_CLOSE = 5000;
TIMEOUT_STOP = 5000;
INTERVAL_CLEANUP = 10000;
INTERVAL_FREE = 5000;
type
TgoClientSocketManager = class;
TgoSocketConnection = class;
{ Internal operation }
TgoSocketOperation = (Connect, Disconnect, ReadZero, Read, Write);
{ Internal performance optimization }
TgoSocketOptimization = (Speed, Scale);
{ Internal socket pool behavior }
TgoSocketPoolBehavior = (CreateAndDestroy, PoolAndReuse);
{ Internal connection state }
TgoConnectionState = (Disconnected, Disconnecting, Connected);
{ Callback events }
TgoSocketNotifyEvent = procedure of object;
TgoSocketDataEvent = procedure(const ABuffer: Pointer; const ASize: Integer)
of object;
{ Iocp per transaction struct }
PPerIoData = ^TPerIoData;
TPerIoData = packed record
Overlapped: TWSAOverlapped;
WsaBuf: WsaBuf;
Socket: TSocket;
Operation: TgoSocketOperation;
end;
{ Socket connection instance }
TgoSocketConnection = class(TObject)
private
FOwner: TgoClientSocketManager;
FSocket: THandle;
FHostname: String;
FPort: Word;
FState: TgoConnectionState;
FOpenSSL: TgoOpenSSL;
FReleased: TDateTime;
FAttemptCloseSocket: Boolean;
{ Thread-safe variables for pending operations }
FLock: TCriticalSection;
FPending: array[TgoSocketOperation] of Integer;
FShutdown: Boolean;
[volatile] FClosed: Integer;
{ WSARecv buffer }
FReadBuffer: Pointer;
{ Log WSA and System related errors }
{$IFDEF GRIJJYLOGGING}
procedure HandleWSAError(const AError: String);
procedure HandleError(const AError: String);
{$ENDIF}
{ Pending operations }
function AddRef(const AOperation: TgoSocketOperation): Boolean; inline;
procedure ReleaseRef(const AOperation: TgoSocketOperation); inline;
function ReleaseRefCheckShutdown(const AOperation: TgoSocketOperation): Boolean; inline;
protected
FOnConnectedLock: TCriticalSection;
FOnConnected: TgoSocketNotifyEvent;
FOnDisconnectedLock: TCriticalSection;
FOnDisconnected: TgoSocketNotifyEvent;
FOnRecvLock: TCriticalSection;
FOnRecv: TgoSocketDataEvent;
FOnSentLock: TCriticalSection;
FOnSent: TgoSocketDataEvent;
private
{ OpenSSL related }
FSSL: Boolean;
FALPN: Boolean;
procedure SetCertificate(const Value: TBytes);
procedure SetPassword(const Value: String);
procedure SetPrivateKey(const Value: TBytes);
function GetCertificate: TBytes;
function GetPassword: String;
function GetPrivateKey: TBytes;
private
{ SSL callbacks }
procedure OnSSLConnected;
procedure OnSSLRead(const ABuffer: Pointer; const ASize: Integer);
procedure OnSSLWrite(const ABuffer: Pointer; const ASize: Integer);
{ Initialize the OpenSSL interface }
function GetOpenSSL: TgoOpenSSL;
private
{ Thread safe number of pending operations on a socket }
function GetPending: Integer; inline;
{ Thread safe closed boolean flag }
function GetClosed: Boolean;
procedure SetClosed(AValue: Boolean);
{ Thread safe shutdown boolean flag }
function GetShutdown: Boolean;
{ Resets the connection }
procedure Reset;
{ Post a zero byte read request which effectively tells IOCP to
notify when a read event is ready but does this without allocating a buffer
which allows more concurrent connections due to less memory page pooling }
function PostReadZero: Boolean;
{ Post a normal read request }
function PostRead(const ABuffer: Pointer): Boolean;
{ Post a normal write request }
function PostWrite(const ABuffer: Pointer; ASize: Integer): Boolean;
{ Connect the socket }
function PostConnect(const AHostname: String;
const APort: Word; const AUseNagle: Boolean = False): Boolean;
{ Disconnect the socket }
function PostDisconnect: Boolean;
private
{ Handle data that is read from the socket }
procedure Read(const ABuffer: Pointer; const ASize: Integer); inline;
{ Write data to the socket }
function Write(const ABuffer: Pointer; const ASize: Integer): Boolean; inline;
public
constructor Create(const AOwner: TgoClientSocketManager; const AHostname: String; const APort: Word);
destructor Destroy; override;
public
{ Connects the socket }
function Connect(const AUseNagle: Boolean = True): Boolean;
{ Disconnects the socket }
procedure Disconnect;
{ Sends the bytes to the socket }
function Send(const ABuffer: Pointer; const ASize: Integer): Boolean; overload;
function Send(const ABytes: TBytes): Boolean; overload;
{ Returns the pending operations as a string }
function PendingToString: String;
{ Stops all future callback events }
procedure StopCallbacks;
public
{ Socket handle }
property Socket: THandle read FSocket write FSocket;
{ Hostname }
property Hostname: String read FHostname write FHostname;
{ Port }
property Port: Word read FPort write FPort;
{ Current state of the socket connection }
property State: TgoConnectionState read FState write FState;
{ Number of pending operations on the socket }
property Pending: Integer read GetPending;
{ Socket is shutdown }
property Shutdown: Boolean read GetShutdown;
{ Connection is closed }
property Closed: Boolean read GetClosed write SetClosed;
{ OpenSSL interface }
property OpenSSL: TgoOpenSSL read GetOpenSSL;
public
{ Using SSL }
property SSL: Boolean read FSSL write FSSL;
{ Using ALPN }
property ALPN: Boolean read FALPN write FALPN;
{ Certificate in PEM format }
property Certificate: TBytes read GetCertificate write SetCertificate;
{ Private key in PEM format }
property PrivateKey: TBytes read GetPrivateKey write SetPrivateKey;
{ Password for private key }
property Password: String read GetPassword write SetPassword;
public
{ Fired when the socket is connected and ready to be written }
property OnConnected: TgoSocketNotifyEvent read FOnConnected write FOnConnected;
{ Fired when the socket is disconnected, either gracefully if the state
is Disconnecting or abrupt if the state is Connected }
property OnDisconnected: TgoSocketNotifyEvent read FOnDisconnected write FOnDisconnected;
{ Fired when the data has been received by the socket }
property OnRecv: TgoSocketDataEvent read FOnRecv write FOnRecv;
{ Fired when the data has been sent by the socket }
property OnSent: TgoSocketDataEvent read FOnSent write FOnSent;
end;
{ Socket pool worker thread }
TSocketPoolWorker = class(TThread)
private
FOwner: TgoClientSocketManager;
protected
procedure Execute; override;
public
constructor Create(const AOwner: TgoClientSocketManager);
destructor Destroy; override;
end;
{ Client socket manager }
TgoClientSocketManager = class(TThread)
private
FHandle: THandle;
FOptimization: TgoSocketOptimization;
FBehavior: TgoSocketPoolBehavior;
FWorkers: array of TSocketPoolWorker;
FWorkerHandles: array of THandle;
FShutdown: Boolean;
private
Connections: TgoSet<TgoSocketConnection>;
ConnectionsLock: TCriticalSection;
procedure FreeConnections;
protected
procedure Execute; override;
public
constructor Create(const AOptimization: TgoSocketOptimization = TgoSocketOptimization.Scale;
const ABehavior: TgoSocketPoolBehavior = TgoSocketPoolBehavior.CreateAndDestroy; const AWorkers: Integer = 0);
destructor Destroy; override;
public
{ Releases the connection back to the socket pool }
procedure Release(const AConnection: TgoSocketConnection);
{ Requests a connection from the socket pool }
function Request(const AHostname: String; const APort: Word): TgoSocketConnection;
public
{ Completion handle for IOCP }
property Handle: THandle read FHandle;
{ Optimization mode }
property Optimization: TgoSocketOptimization read FOptimization;
{ Shutdown }
property Shutdown: Boolean read FShutdown;
end;
implementation
{$IFDEF GRIJJYLOGGING}
uses
Grijjy.System.Logging;
{$ENDIF}
var
{$IFDEF GRIJJYLOGGING}
_Log: TgoLogging;
{$ENDIF}
_PerIoDataPool, _MemBufferPool: TgoMemoryPool;
function HasOverlappedIoCompleted(const PerIoData: PPerIoData): BOOL;
begin
Result := Integer(PerIoData.Overlapped.Internal) <> STATUS_PENDING;
end;
function OperationToString(const AOperation: TgoSocketOperation): String;
begin
case AOperation of
TgoSocketOperation.Connect:
Result := 'Connect';
TgoSocketOperation.Disconnect:
Result := 'Disconnect';
TgoSocketOperation.ReadZero:
Result := 'ReadZero';
TgoSocketOperation.Read:
Result := 'Read';
TgoSocketOperation.Write:
Result := 'Write';
end;
end;
{ WSA Helpers }
function WSAErrorOK(const AValue: Integer): Boolean;
begin
Result := (AValue = WSAEINTR) or (AValue = WSAECONNABORTED) or
(AValue = WSAECONNRESET) or (AValue = WSAESHUTDOWN);
end;
{ TgoSocketConnection }
constructor TgoSocketConnection.Create(const AOwner: TgoClientSocketManager; const AHostname: String; const APort: Word);
var
Operation: TgoSocketOperation;
begin
inherited Create;
FOwner := AOwner;
FHostname := AHostname;
FPort := APort;
FState := TgoConnectionState.Disconnected;
for Operation := Low(TgoSocketOperation) to High(TgoSocketOperation) do
FPending[Operation] := 0;
FShutdown := False;
FClosed := 0;
FAttemptCloseSocket := False;
FReleased := -1;
FLock := TCriticalSection.Create;
{ for speed optimization we allocate a single read buffer that we use
for serialized reads from the socket for the lifetime of the socket }
if FOwner.Optimization = TgoSocketOptimization.Speed then
FReadBuffer := _MemBufferPool.RequestMem('_TgoSocketConnection.ReadBuffer')
else
{ for scale optimization we allocate a read buffer on demand when a
pending read is waiting }
FReadBuffer := nil;
FOpenSSL := nil;
FSSL := False;
FALPN := False;
FOnConnectedLock := TCriticalSection.Create;
FOnDisconnectedLock := TCriticalSection.Create;
FOnRecvLock := TCriticalSection.Create;
FOnSentLock := TCriticalSection.Create;
end;
destructor TgoSocketConnection.Destroy;
begin
Disconnect;
if FReadBuffer <> nil then
_MemBufferPool.ReleaseMem(FReadBuffer, '_TgoSocketConnection.ReadBuffer');
if FOpenSSL <> nil then
FOpenSSL.Free;
FLock.Free;
FOnConnectedLock.Free;
FOnDisconnectedLock.Free;
FOnRecvLock.Free;
FOnSentLock.Free;
inherited Destroy;
end;
function IsFatalError(const ALastError: Integer): Boolean;
begin
{ 10053 (An established connection was aborted by the software) is common for aborted connections }
Result := ALastError <> 10053;
end;
{$IFDEF GRIJJYLOGGING}
procedure TgoSocketConnection.HandleWSAError(const AError: String);
var
LastError: Integer;
begin
LastError := WSAGetLastError;
if IsFatalError(LastError) then
_Log.Send(Format('Warning! WSA %s (Socket=%d, Connection=%d, ThreadId=%d, LastError=%d, SysErrorMessage=%s)',
[AError, FSocket, Cardinal(Self), GetCurrentThreadId, LastError, SysErrorMessage(LastError)]));
end;
procedure TgoSocketConnection.HandleError(const AError: String);
var
LastError: Integer;
begin
LastError := GetLastError;
_Log.Send(Format('Warning! %s (Socket=%d, Connection=%d, ThreadId=%d, LastError=%d, SysErrorMessage=%s)',
[AError, FSocket, Cardinal(Self), GetCurrentThreadId, LastError, SysErrorMessage(LastError)]));
end;
{$ENDIF}
function TgoSocketConnection.AddRef(const AOperation: TgoSocketOperation): Boolean;
begin
FLock.Enter;
try
if FShutdown then
Result := False
else
begin
if AOperation = TgoSocketOperation.Connect then
begin
Inc(FPending[AOperation]);
Result := True;
end
else
if AOperation = TgoSocketOperation.Disconnect then
begin
Inc(FPending[AOperation]);
Result := True;
FShutdown := True;
end
else
begin
if Pending = 0 then
Result := False
else
begin
Inc(FPending[AOperation]);
Result := True;
end;
end;
end;
finally
FLock.Leave;
end;
end;
procedure TgoSocketConnection.ReleaseRef(const AOperation: TgoSocketOperation);
begin
FLock.Enter;
try
Dec(FPending[AOperation]);
finally
FLock.Leave;
end;
end;
function TgoSocketConnection.ReleaseRefCheckShutdown(const AOperation: TgoSocketOperation): Boolean;
begin
FLock.Enter;
try
Dec(FPending[AOperation]);
Result := (FShutdown) and (Pending = 0);
finally
FLock.Leave;
end;
end;
procedure TgoSocketConnection.SetCertificate(const Value: TBytes);
begin
OpenSSL.Certificate := Value;
end;
procedure TgoSocketConnection.SetPassword(const Value: String);
begin
OpenSSL.Password := Value;
end;
procedure TgoSocketConnection.SetPrivateKey(const Value: TBytes);
begin
OpenSSL.PrivateKey := Value;
end;
function TgoSocketConnection.GetCertificate: TBytes;
begin
Result := OpenSSL.Certificate;
end;
function TgoSocketConnection.GetPassword: String;
begin
Result := OpenSSL.Password;
end;
function TgoSocketConnection.GetPrivateKey: TBytes;
begin
Result := OpenSSL.PrivateKey;
end;
procedure TgoSocketConnection.OnSSLConnected;
begin
FState := TgoConnectionState.Connected;
{ did ALPN negotation succeed? }
if FALPN and not OpenSSL.ALPN then
begin
{$IFDEF GRIJJYLOGGING}
HandleError('ALPN negotation failed for SSL.');
{$ENDIF}
Exit;
end;
FOnConnectedLock.Enter;
try
if Assigned(FOnConnected) then
FOnConnected;
finally
FOnConnectedLock.Leave;
end;
end;
procedure TgoSocketConnection.OnSSLRead(const ABuffer: Pointer; const ASize: Integer);
begin
FOnRecvLock.Enter;
try
if Assigned(FOnRecv) then
FOnRecv(ABuffer, ASize);
finally
FOnRecvLock.Leave;
end;
end;
procedure TgoSocketConnection.OnSSLWrite(const ABuffer: Pointer; const ASize: Integer);
begin
PostWrite(ABuffer, ASize);
end;
function TgoSocketConnection.GetOpenSSL: TgoOpenSSL;
begin
if FOpenSSL = nil then
begin
FOpenSSL := TgoOpenSSL.Create;
FOpenSSL.OnConnected := OnSSLConnected;
FOpenSSL.OnRead := OnSSLRead;
FOpenSSL.OnWrite := OnSSLWrite;
end;
Result := FOpenSSL;
end;
function TgoSocketConnection.GetPending: Integer;
var
Operation: TgoSocketOperation;
begin
Result := 0;
FLock.Enter;
try
for Operation := Low(TgoSocketOperation) to High(TgoSocketOperation) do
Result := Result + FPending[Operation];
finally
FLock.Leave;
end;
end;
procedure TgoSocketConnection.SetClosed(AValue: Boolean);
begin
TInterlocked.Increment(FClosed);
end;
function TgoSocketConnection.GetClosed: Boolean;
begin
Result := TInterlocked.CompareExchange(FClosed, 0, 0) <> 0;
end;
function TgoSocketConnection.GetShutdown: Boolean;
begin
FLock.Enter;
try
Result := FShutdown;
finally
FLock.Leave;
end;
end;
procedure TgoSocketConnection.StopCallbacks;
begin
FOnConnectedLock.Enter;
try
FOnConnected := nil;
finally
FOnConnectedLock.Leave;
end;
FOnDisconnectedLock.Enter;
try
FOnDisconnected := nil;
finally
FOnDisconnectedLock.Leave;
end;
FOnRecvLock.Enter;
try
FOnRecv := nil;
finally
FOnRecvLock.Leave;
end;
FOnSentLock.Enter;
try
FOnSent := nil;
finally
FOnSentLock.Leave;
end;
end;
function TgoSocketConnection.PostReadZero: Boolean;
var
Bytes, Flags: Cardinal;
PerIoData: PPerIoData;
begin
Result := False;
if not AddRef(TgoSocketOperation.ReadZero) then Exit;
//_Log('PostReadZero');
PerIoData := _PerIoDataPool.RequestMem('_TgoSocketConnection.PostReadZero.PerIoData');
PerIoData.Socket := FSocket;
PerIoData.Operation := TgoSocketOperation.ReadZero;
PerIoData.WsaBuf.Buf := nil;
PerIoData.WsaBuf.Len := 0;
Flags := 0;
Bytes := 0;
if (WSARecv(FSocket, @PerIoData.WsaBuf, 1, Bytes, Flags,
PWSAOverlapped(PerIoData), nil) = SOCKET_ERROR) and
(WSAGetLastError <> WSA_IO_PENDING) then
begin
{$IFDEF GRIJJYLOGGING}
HandleWSAError('PostReadZero.WSARecv');
{$ENDIF}
_PerIoDataPool.ReleaseMem(PerIoData, '_TgoSocketConnection.PostReadZero.PerIoData');
ReleaseRef(TgoSocketOperation.ReadZero);
end
else
Result := True;
end;
function TgoSocketConnection.PostRead(const ABuffer: Pointer): Boolean;
var
Bytes, Flags: Cardinal;
PerIoData: PPerIoData;
begin
Result := False;
if not AddRef(TgoSocketOperation.Read) then Exit;
//_Log('PostRead');
PerIoData := _PerIoDataPool.RequestMem('_TgoSocketConnection.PostRead.PerIoData');
PerIoData.Socket := FSocket;
PerIoData.Operation := TgoSocketOperation.Read;
PerIoData.WsaBuf.Buf := ABuffer;
PerIoData.WsaBuf.Len := DEFAULT_BLOCK_SIZE;
Flags := 0;
Bytes := 0;
if (WSARecv(FSocket, @PerIoData.WsaBuf, 1, Bytes, Flags,
PWSAOverlapped(PerIoData), nil) = SOCKET_ERROR) and
(WSAGetLastError <> WSA_IO_PENDING) then
begin
{$IFDEF GRIJJYLOGGING}
HandleWSAError('PostRead.WSARecv');
{$ENDIF}
_PerIoDataPool.ReleaseMem(PerIoData, '_TgoSocketConnection.PostRead.PerIoData');
ReleaseRef(TgoSocketOperation.Read);
end
else
Result := True;
end;
function TgoSocketConnection.PostWrite(const ABuffer: Pointer;
ASize: Integer): Boolean;
var
PerIoData: PPerIoData;
Bytes: DWORD;
WriteBuffer: Pointer;
begin
Result := False;
if not AddRef(TgoSocketOperation.Write) then Exit;
//_Log('PostWrite');
WriteBuffer := _MemBufferPool.RequestMem('_TgoSocketConnection.PostWrite.WriteBuffer');
Move(ABuffer^, WriteBuffer^, ASize);
PerIoData := _PerIoDataPool.RequestMem(('_TgoSocketConnection.PostWrite.PerIoData'));
PerIoData.Socket := FSocket;
PerIoData.Operation := TgoSocketOperation.Write;
PerIoData.WsaBuf.Buf := WriteBuffer;
PerIoData.WsaBuf.Len := ASize;
if (WSASend(FSocket, @PerIoData.WsaBuf, 1, Bytes, 0, PWSAOverlapped(PerIoData), nil) = SOCKET_ERROR) and
(WSAGetLastError <> WSA_IO_PENDING) then
begin
{$IFDEF GRIJJYLOGGING}
HandleWSAError('PostWrite.WSASend');
{$ENDIF}
_PerIoDataPool.ReleaseMem(PerIoData, '_TgoSocketConnection.PostWrite.PerIoData');
_MemBufferPool.ReleaseMem(WriteBuffer, '_TgoSocketConnection.PostWrite.WriteBuffer');
ReleaseRef(TgoSocketOperation.Write);
end
else
Result := True;
end;
function TgoSocketConnection.PostConnect(const AHostname: String;
const APort: Word; const AUseNagle: Boolean): Boolean;
var
Hints: TAddrInfoW;
AddrInfo: PAddrInfoW;
ConnectAddr: TSockAddrIn;
PerIoData: PPerIoData;
Port: String;
Size: Integer;
begin
Result := False;
FillChar(Hints, SizeOf(TAddrInfoW), 0);
Hints.ai_family := AF_INET;
Hints.ai_socktype := SOCK_STREAM;
Hints.ai_protocol := IPPROTO_TCP;
AddrInfo := nil;
{ get the addrinfo for hostname and port }
Port := IntToStr(APort);
if getaddrinfo(PWideChar(AHostname), PWideChar(Port), @Hints, @AddrInfo) <> 0
then
begin
{$IFDEF GRIJJYLOGGING}
HandleWSAError('PostConnect.getaddrinfo');
{$ENDIF}
Exit;
end;
try
{ create an overlapped socket }
FSocket := WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, nil, 0,
WSA_FLAG_OVERLAPPED);
if FSocket = INVALID_SOCKET then
begin
{$IFDEF GRIJJYLOGGING}
HandleWSAError('PostConnect.WSASocket');
{$ENDIF}
Exit;
end;
{ set SO_SNDBUF to zero for a zero-copy network stack as we maintain the buffers }
Size := 0;
if setsockopt(FSocket, SOL_SOCKET, SO_SNDBUF, @Size, SizeOf(Size)) = SOCKET_ERROR
then
begin
{$IFDEF GRIJJYLOGGING}
HandleError('PostConnect.setsockopt');
{$ENDIF}
Exit;
end;
{ set SO_RCVBUF to zero for a zero-copy network stack as we maintain the buffers }
Size := 0;
if setsockopt(FSocket, SOL_SOCKET, SO_RCVBUF, @Size, SizeOf(Size)) = SOCKET_ERROR
then
begin
{$IFDEF GRIJJYLOGGING}
HandleError('PostConnect.setsockopt');
{$ENDIF}
Exit;
end;
{ set TCP_NODELAY to reduce latency }
if not AUseNagle then
begin
Size := 0;
if setsockopt(FSocket, IPPROTO_TCP, TCP_NODELAY, @Size, SizeOf(Size)) = SOCKET_ERROR then
begin
{$IFDEF GRIJJYLOGGING}
HandleError('PostConnect.setsockopt');
{$ENDIF}
Exit;
end;
end;
{ bind the socket }
ConnectAddr.sin_family := AF_INET;
ConnectAddr.sin_addr.S_addr := INADDR_ANY;
ConnectAddr.sin_port := 0;
if bind(FSocket, @ConnectAddr, SizeOf(ConnectAddr)) = SOCKET_ERROR then
begin
{$IFDEF GRIJJYLOGGING}
HandleWSAError('PostConnect.bind');
{$ENDIF}
closesocket(FSocket);
Closed := True;
Exit;
end;
{ associate socket and connection object with completion port }
if CreateIoCompletionPort(FSocket, FOwner.Handle, ULONG_PTR(Self), 0) = 0
then
begin
{$IFDEF GRIJJYLOGGING}
HandleError('PostConnect.CreateIoCompletionPort');
{$ENDIF}
closesocket(FSocket);
Closed := True;
Exit;
end;
{ queue a connect command to the completion port }
//_Log('PostConnect');
if not AddRef(TgoSocketOperation.Connect) then Exit;
PerIoData := _PerIoDataPool.RequestMem('_TgoSocketConnection.PostConnect.PerIoData');
PerIoData.Socket := FSocket;
PerIoData.Operation := TgoSocketOperation.Connect;
if not ConnectEx(FSocket, AddrInfo.ai_addr, AddrInfo.ai_addrlen, nil, 0,
PCardinal(0)^, PWSAOverlapped(PerIoData)) and
(WSAGetLastError <> WSA_IO_PENDING) then
begin
{$IFDEF GRIJJYLOGGING}
HandleWSAError('PostConnect.ConnectEx');
{$ENDIF}
_PerIoDataPool.ReleaseMem(PerIoData, '_TgoSocketConnection.PostConnect.PerIoData');
ReleaseRef(TgoSocketOperation.Connect);
closesocket(FSocket);
Closed := True;
end
else
Result := True;
finally
freeaddrinfo(AddrInfo);
end;
end;
function TgoSocketConnection.PostDisconnect: Boolean;
var
PerIoData: PPerIoData;
begin
Result := False;
if not AddRef(TgoSocketOperation.Disconnect) then Exit;
if FSocket = 0 then Exit;
//_Log('PostDisconnect');
PerIoData := _PerIoDataPool.RequestMem('_TgoSocketConnection.PostDisconnect.PerIoData');
PerIoData.Socket := FSocket;
PerIoData.Operation := TgoSocketOperation.Disconnect;
if not DisconnectEx(FSocket, PWSAOverlapped(PerIoData), TF_REUSE_SOCKET, 0)
and (WSAGetLastError <> WSA_IO_PENDING) then
begin
{$IFDEF GRIJJYLOGGING}
HandleWSAError('PostDisconnect.DisconnectEx');
{$ENDIF}
_PerIoDataPool.ReleaseMem(PerIoData, '_TgoSocketConnection.PostDisconnect.PerIoData');
ReleaseRef(TgoSocketOperation.Disconnect);
end
else
Result := True;
end;
procedure TgoSocketConnection.Reset;
var
Operation: TgoSocketOperation;
begin
FLock.Enter;
try
for Operation := Low(TgoSocketOperation) to High(TgoSocketOperation) do
FPending[Operation] := 0;
FShutdown := False;
finally
FLock.Leave;
end;
FClosed := 0;
FAttemptCloseSocket := False;
FReleased := -1;
end;
function TgoSocketConnection.PendingToString: String;
begin
FLock.Enter;
try
Result := Format('(Connect=%d, Disconnect=%d, ReadZero=%d, Read=%d, Write=%d)', [
FPending[TgoSocketOperation.Connect],
FPending[TgoSocketOperation.Disconnect],
FPending[TgoSocketOperation.ReadZero],
FPending[TgoSocketOperation.Read],
FPending[TgoSocketOperation.Write]
]);
finally
FLock.Leave;
end;
end;
function TgoSocketConnection.Connect(const AUseNagle: Boolean): Boolean;
begin
Reset;
if PostConnect(FHostname, FPort, AUseNagle) then
Result := True
else
Result := False;
end;
procedure TgoSocketConnection.Disconnect;
begin
//_Log('Disconnect');
{ if not already shutdown, then post disconnect }
if not Shutdown then
begin
{ we set the state to disconnecting so we know when the OnDisconnected event
was triggered gracefully by a requested disconnect or abruptly by a socket error }
FState := TgoConnectionState.Disconnecting;
PostDisconnect;
end;
end;
function TgoSocketConnection.Send(const ABuffer: Pointer;
const ASize: Integer): Boolean;
var
Index: Integer;
BlockSize: Integer;
Bytes: PByte;
begin
Result := True;
Index := 0;
Bytes := ABuffer;
{ we chunk the buffer to match the memory pool block size to
avoid memory reallocations }
if ASize < DEFAULT_BLOCK_SIZE then
BlockSize := ASize
else
BlockSize := DEFAULT_BLOCK_SIZE;
while Index < ASize do
begin
if ASize - Index < BlockSize then
BlockSize := ASize - Index;
if Write(@Bytes[Index], BlockSize) then
Inc(Index, BlockSize)
else
begin
Result := False;
PostDisconnect;
Break; { write failed }
end;
end;
end;
function TgoSocketConnection.Send(const ABytes: TBytes): Boolean;
begin
Result := Send(@ABytes[0], Length(ABytes));
end;
procedure TgoSocketConnection.Read(const ABuffer: Pointer;
const ASize: Integer);
begin
if FSSL then
OpenSSL.Read(ABuffer, ASize)
else
begin
FOnRecvLock.Enter;
try
if Assigned(FOnRecv) then
FOnRecv(ABuffer, ASize);
finally
FOnRecvLock.Leave;
end;
end;
end;
function TgoSocketConnection.Write(const ABuffer: Pointer;
const ASize: Integer): Boolean;
begin
if FSSL then
Result := OpenSSL.Write(ABuffer, ASize)
else
Result := PostWrite(ABuffer, ASize);
end;
{ TSocketPoolWorker }
constructor TSocketPoolWorker.Create(const AOwner: TgoClientSocketManager);
begin
inherited Create;
FOwner := AOwner;
end;
destructor TSocketPoolWorker.Destroy;
begin
inherited;
end;
procedure TSocketPoolWorker.Execute;
var
ReturnValue: Boolean;
BytesTransferred: DWORD;
Connection: TgoSocketConnection;
PerIoData: PPerIoData;
ReadBuffer: Pointer;
Error: Integer;
begin
{$IFDEF DEBUG}
NameThreadForDebugging('TSocketPoolWorker');
{$ENDIF}
while Terminated = false do
begin