forked from andremussche/DelphiWebsockets
-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
IdIOHandlerWebSocketSSL.pas
1437 lines (1303 loc) · 44.7 KB
/
IdIOHandlerWebSocketSSL.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 IdIOHandlerWebSocketSSL;
{.$DEFINE DEBUG_WS}
{$WARN SYMBOL_DEPRECATED OFF}
{$WARN SYMBOL_PLATFORM OFF}
//The WebSocket Protocol, RFC 6455
//http://datatracker.ietf.org/doc/rfc6455/?include_text=1
interface
{$I wsdefines.pas}
uses
System.Classes, System.SyncObjs, System.Generics.Collections,
IdIOHandlerStack, IdGlobal, IdException, IdBuffer, IdSSLOpenSSL,
IdSocketHandle, IdIIOHandlerWebSocket, IdWebSocketTypes, System.SysUtils;
type
EIdWebSocketHandleError = class(EIdSocketHandleError);
{$IF CompilerVersion >= 26} //XE5
TIdTextEncoding = IIdTextEncoding;
{$ENDIF}
TIdIOHandlerWebSocketSSL = class(TIdSSLIOHandlerSocketOpenSSL,
IIOHandlerWebSocket, ISetWebSocketClosing)
protected
FBusyUpgrading: Boolean;
FCloseCode, FCloseTimeout: Integer;
FCloseCodeSend, FCloseReceived: Boolean;
FCloseReason, FPeerCloseReason, FRoleName: string;
FClosing: Boolean;
FExtensionBits: TWSExtensionBits;
FIsServerSide: Boolean;
FIsWebSocket: Boolean;
FLastActivityTime: TDateTime;
FLastPingTime: TDateTime;
FLock: TCriticalSection;
FMessageStream: TMemoryStream;
FOnNotifyClosed, FOnNotifyClosing: TProc;
FOnWebSocketClosing: TOnWebSocketClosing;
FPayloadInfo: TIOWSPayloadInfo;
FPendingWriteCount: Integer;
FSelectLock: TCriticalSection;
FWSInputBuffer: TIdBuffer;
class var FUseSingleWriteThread: Boolean;
procedure DoBeforeConnect(ASender: TIdSSLIOHandlerSocketOpenSSL); override;
function GetBinding: TIdSocketHandle;
function GetBusyUpgrading: Boolean;
function GetClosedGracefully: Boolean;
function GetCloseReason: string;
function GetConnected: Boolean;
function GetInputBuffer: TIdBuffer;
function GetIsWebSocket: Boolean;
function GetLastActivityTime: TDateTime;
function GetLastPingTime: TDateTime;
function GetOnNotifyClosed: TProc;
function GetOnNotifyClosing: TProc;
procedure SetBusyUpgrading(const Value: Boolean);
procedure SetClosedGracefully(const Value: Boolean);
procedure SetCloseReason(const AReason: string);
procedure SetIsWebSocket(const Value: Boolean);
procedure SetLastActivityTime(const Value: TDateTime);
procedure SetLastPingTime(const Value: TDateTime);
procedure SetOnNotifyClosed(const Value: TProc);
procedure SetOnNotifyClosing(const Value: TProc);
procedure SetUseNagle(const Value: Boolean);
function InternalReadDataFromSource(var VBuffer: TIdBytes;
ARaiseExceptionOnTimeout: Boolean): Integer;
function ReadDataFromSource(var VBuffer: TIdBytes): Integer; override;
function WriteDataToTarget (const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; override;
function ReadFrame(out aFIN, aRSV1, aRSV2, aRSV3: boolean;
out aDataCode: TWSDataCode; out aData: TIdBytes): Integer;
function ReadMessage(var aBuffer: TIdBytes; out aDataCode: TWSDataCode): Integer;
{$IF CompilerVersion >= 26} //XE5
function UTF8Encoding: IIdTextEncoding;
{$ELSE}
function UTF8Encoding: TEncoding;
{$ENDIF}
procedure InitComponent; override;
procedure SetWebSocketClosing(const AValue: TOnWebSocketClosing);
procedure EnsureIsWebSocket;
public
ExitConnectedCheck: Boolean;
property BusyUpgrading : Boolean read FBusyUpgrading write FBusyUpgrading;
property ClientExtensionBits : TWSExtensionBits read FExtensionBits write FExtensionBits;
property IsWebSocket : Boolean read FIsWebSocket write SetIsWebSocket;
property IsServerSide : Boolean read FIsServerSide write FIsServerSide;
property RoleName: string read FRoleName write FRoleName;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
function TryLock: Boolean;
function HasData: Boolean;
procedure Clear;
function Readable(AMSec: Integer = IdTimeoutDefault): Boolean; override;
function Connected: Boolean; override;
procedure Close; override;
procedure CloseWithReason(const AReason: string);
///<summary> Closing is true if we initiated the close. </summary>
property Closing : Boolean read FClosing;
property CloseCode : Integer read FCloseCode write FCloseCode;
property CloseReason: string read FCloseReason write FCloseReason;
property CloseTimeout: Integer read FCloseTimeout write FCloseTimeout;
procedure NotifyClosed;
procedure NotifyClosing;
property OnWebSocketClosing: TOnWebSocketClosing read FOnWebSocketClosing
write FOnWebSocketClosing;
// text/string writes
procedure Write(const AOut: string; AEncoding: TIdTextEncoding = nil); overload; override;
procedure Write(AValue: TStrings; AWriteLinesCount: Boolean = False;
AEncoding: TIdTextEncoding = nil); overload; override;
procedure Write(AStream: TStream; aType: TWSDataType); overload;
procedure WriteBin(const ABytes: TArray<Byte>);
procedure WriteBufferFlush(AByteCount: Integer); override;
function WriteData(const aData: TIdBytes; aType: TWSDataCode;
aFIN: boolean = true; aRSV1: boolean = false; aRSV2: boolean = false;
aRSV3: boolean = false): integer;
procedure WriteLn(const AOut: string; AEncoding: TIdTextEncoding = nil); overload; override;
procedure WriteLnRFC(const AOut: string = ''; AEncoding: TIdTextEncoding = nil); override;
procedure ReadBytes(var VBuffer: TIdBytes; AByteCount: Integer; AAppend: Boolean = True); override;
property LastActivityTime: TDateTime read FLastActivityTime write FLastActivityTime;
property LastPingTime: TDateTime read FLastPingTime write FLastPingTime;
property OnNotifyClosed: TProc read GetOnNotifyClosed write SetOnNotifyClosed;
property OnNotifyClosing: TProc read GetOnNotifyClosing write SetOnNotifyClosing;
class property UseSingleWriteThread: Boolean read FUseSingleWriteThread
write FUseSingleWriteThread;
end;
TIdBuffer_Ext = class(TIdBuffer);
implementation
uses
System.Math,
IdStream, IdStack, IdExceptionCore,
IdResourceStrings, IdResourceStringsCore, WSDebugger,
{$IF DEFINED(MSWINDOWS)}
Winapi.Windows,
{$ELSE}
IdSSLOpenSSLHeaders, FMX.Platform,
{$ENDIF}
System.IOUtils, System.DateUtils, IdStackConsts, IdWebSocketConsts;
function BytesToStringRaw(const AValue: TIdBytes; aSize: Integer = -1): string;
var
i: Integer;
begin
//SetLength(Result, Length(aValue));
for i := 0 to High(AValue) do
begin
if (AValue[i] = 0) and (aSize < 0) then
Exit;
if (AValue[i] < 33) or
( (AValue[i] > 126) and
(AValue[i] < 161) )
then
Result := Result + '#' + IntToStr(AValue[i])
else
Result := Result + Char(AValue[i]);
if (aSize > 0) and (i > aSize) then
Break;
end;
end;
//{ TIOWSPayloadInfo }
//
//procedure TIOWSPayloadInfo.Initialize(iTextMode: Boolean; iPayloadLength: Cardinal);
//begin
// PayloadLength := iPayloadLength;
// if iTextMode then
// DataCode := wdcText else
// DataCode := wdcBinary;
//end;
//
//procedure TIOWSPayloadInfo.Clear;
//begin
// PayloadLength := 0;
// DataCode := wdcBinary;
//end;
//
//function TIOWSPayloadInfo.DecLength(AValue: Cardinal):boolean;
//begin
// if PayloadLength >= AValue then
// begin
// PayloadLength := PayloadLength - AValue;
// end
// else PayloadLength := 0;
// DataCode := wdcContinuation;
// Result := PayloadLength = 0;
//end;
procedure TIdIOHandlerWebSocketSSL.Clear;
begin
FWSInputBuffer.Clear;
InputBuffer.Clear;
FBusyUpgrading := False;
FIsWebSocket := False;
FClosing := False;
FExtensionBits := [];
FCloseReason := '';
FCloseCode := 0;
FLastActivityTime := 0;
FLastPingTime := 0;
FPayloadInfo.Clear;
FCloseCodeSend := False;
FPendingWriteCount := 0;
end;
procedure TIdIOHandlerWebSocketSSL.Close;
const
SO_ERROR = $1007; // get error status and clear
var
LWriteBuffer: TIdBytes;
LReason: UTF8String;
LBufferLen, iOptVal: Integer;
LConnected: Boolean;
begin
try
// valid connection?
LConnected := Opened and SourceIsAvailable and not ClosedGracefully;
// no socket error? connection closed by software abort, connection reset by peer, etc
try
iOptVal := 1; // random value, as long as it's not 0.
{$IF DEFINED(MSWINDOWS)}
if LConnected then
GStack.GetSocketOption(Binding.Handle, Id_SOL_SOCKET, SO_ERROR, iOptVal);
LConnected := LConnected and (iOptVal = 0);
{$ELSEIF DEFINED(POSIX)}
if LConnected then
Binding.GetSockOpt(Id_SOL_SOCKET, SO_ERROR, iOptVal);
LConnected := LConnected and (iOptVal = 0);
{$ENDIF}
except
LConnected := False;
end;
// LConnected := LConnected and
// (IdWinsock2.getsockopt(Self.Binding.Handle, SOL_SOCKET, SO_ERROR, PAnsiChar(@iOptVal), iOptLen)) and
// (iOptVal = 0);
if LConnected and IsWebSocket then
begin
// close message must be responded with a close message back
// or initiated with a close message
if not FCloseCodeSend then
begin
FCloseCodeSend := True;
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString(RoleName, 'FCloseReceived: ' + FCloseReceived.ToString(TUseBoolStrs.True));
{$ENDIF}
// we initiate the close? then write reason etc
// we didn't receive the close, so send out our reason
if not FClosing then
begin
// the first party that sends the close enters this code
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString(RoleName, 'Closing');
{$ENDIF}
LBufferLen := 2;
if CloseReason <> '' then
begin
LReason := UTF8String(Format('%s - %s', [RoleName, CloseReason]));
Inc(LBufferLen, Length(LReason));
end else
begin
LReason := UTF8String(Format('%s - doesn''t wanna talk', [RoleName]));
Inc(LBufferLen, Length(LReason));
end;
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString(RoleName, Format('reason: "%s"', [LReason]));
{$ENDIF}
SetLength(LWriteBuffer, LBufferLen);
if CloseCode < C_FrameClose_Normal then
CloseCode := C_FrameClose_Normal;
LWriteBuffer[0] := Byte(CloseCode shr 8);
LWriteBuffer[1] := Byte(CloseCode);
if LReason <> '' then
begin
Move(LReason[1], LWriteBuffer[2], Length(LReason));
end;
end else
begin
// we received the close from the other party, so just send back ok...
// just send normal close response back
{$IF DEFINED(DEBUG_WS)}
var LMsg := Format('Thread %s sending response to close...', [TThread.Current.ThreadID.ToString]);
WSDebugger.OutputDebugString(RoleName, LMsg);
{$ENDIF}
LBufferLen := 2;
LReason := UTF8String(Format('%s - ok', [RoleName]));
Inc(LBufferLen, Length(LReason));
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString(RoleName, Format('reason: "%s"', [LReason]));
{$ENDIF}
SetLength(LWriteBuffer, LBufferLen);
LWriteBuffer[0] := Byte(C_FrameClose_Normal shr 8);
LWriteBuffer[1] := Byte(C_FrameClose_Normal);
if LReason <> '' then
begin
Move(LReason[1], LWriteBuffer[2], Length(LReason));
end;
end;
WriteData(LWriteBuffer, wdcClose); //send close + code back
WriteBufferFlush;
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString(RoleName, 'Close sent!');
{$ENDIF}
end;
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString(Format('%s ConnectTimeout: %d ReadTimeout: %d SingleWriteThread: %s',
[RoleName, ConnectTimeout, ReadTimeout, BoolToStr(UseSingleWriteThread, True)]));
// we did initiate the close? then wait (a little) for close response
WSDebugger.OutputDebugString(RoleName, 'Closing: ' + BoolToStr(Closing, True));
{$ENDIF}
// not Closing = we initiated the close
// so, wait for the other party to send their close response...
if not FClosing then
begin
{$IF DEFINED(DEBUG_WS)}
var LMsg := Format('Thread %s waiting for response...', [TThread.Current.ThreadID.ToString]);
WSDebugger.OutputDebugString(RoleName, LMsg);
var LoopCount := 0;
{$ENDIF}
CheckForDisconnect();
//wait till client respond with close message back
//but a pending message can be in the buffer, so process this too
while (not FCloseReceived) and (not ClosedGracefully) do
begin
FClosing := True; // Ensure this is not called back...
// ReadMessage will be called in ReadFromSource which
// will cause a re-entrant call to Close if we're not careful...
try
ReadFromSource(False{no disconnect error}, 1000, False); //response within 1s?
except
on E: Exception do
begin
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString(Format('LClose1Exception %s', [E.Message]));
{$ENDIF}
FClosedGracefully := True;
end;
end;
if FCloseReceived then
Break;
{$IF DEFINED(DEBUG_WS)}
Inc(LoopCount);
{$ENDIF}
end;
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString(RoleName, 'CloseResponse received - '+FCloseReceived.ToString(TUseBoolStrs.True));
WSDebugger.OutputDebugString('LoopCount is: '+LoopCount.ToString);
{$ENDIF}
end;
InputBuffer.Clear; // Otherwise, Connected (up in ancestor) will return true...
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString(RoleName, 'if not Closing done');
{$ENDIF}
end;
except
// ignore, it's possible that the client is disconnected already (crashed etc)
{$IF DEFINED(DEBUG_WS)}
on E: Exception do
WSDebugger.OutputDebugString(RoleName, 'exception: ' + E.Message);
{$ENDIF}
end;
IsWebSocket := False;
BusyUpgrading := False;
try
inherited Close;
except
{$IF DEFINED(DEBUG_WS)}
WSDebugger.OutputDebugString('LClose2Exception');
{$ENDIF}
end;
end;
procedure TIdIOHandlerWebSocketSSL.CloseWithReason(const AReason: string);
begin
FCloseReason := AReason;
Close;
end;
function TIdIOHandlerWebSocketSSL.Connected: Boolean;
begin
Lock; // chuacw: is there a need to lock to check for connection???
try
Result := inherited Connected;
finally
Unlock;
end;
end;
destructor TIdIOHandlerWebSocketSSL.Destroy;
begin
TIdStack.DecUsage;
while FPendingWriteCount > 0 do
Sleep(1);
FLock.Enter;
FSelectLock.Enter;
FLock.Free;
FSelectLock.Free;
FWSInputBuffer.Free;
FMessageStream.Free;
inherited;
end;
procedure TIdIOHandlerWebSocketSSL.DoBeforeConnect(ASender: TIdSSLIOHandlerSocketOpenSSL);
begin
inherited;
// if Assigned(fSSLContext) then FreeAndNil(fSSLContext);
// if Assigned(fSSLSocket) then FreeAndNil(fSSLSocket);
// Init;
end;
procedure TIdIOHandlerWebSocketSSL.EnsureIsWebSocket;
begin
if not IsWebSocket then
raise EIdWebSocketException.Create('Needs to be a web socket before sending!');
end;
function TIdIOHandlerWebSocketSSL.GetBinding: TIdSocketHandle;
begin
Result := FBinding;
end;
function TIdIOHandlerWebSocketSSL.GetBusyUpgrading: Boolean;
begin
Result := FBusyUpgrading;
end;
function TIdIOHandlerWebSocketSSL.GetClosedGracefully: Boolean;
begin
Result := FClosedGracefully;
end;
function TIdIOHandlerWebSocketSSL.GetCloseReason: string;
begin
Result := FCloseReason;
end;
function TIdIOHandlerWebSocketSSL.GetConnected: Boolean;
begin
Result := Self.Connected;
end;
function TIdIOHandlerWebSocketSSL.GetInputBuffer: TIdBuffer;
begin
Result := FInputBuffer;
end;
function TIdIOHandlerWebSocketSSL.GetIsWebSocket: Boolean;
begin
Result := FIsWebSocket;
end;
function TIdIOHandlerWebSocketSSL.GetLastActivityTime: TDateTime;
begin
Result := FLastActivityTime;
end;
function TIdIOHandlerWebSocketSSL.GetLastPingTime: TDateTime;
begin
Result := FLastPingTime;
end;
function TIdIOHandlerWebSocketSSL.GetOnNotifyClosed: TProc;
begin
Result := FOnNotifyClosed;
end;
function TIdIOHandlerWebSocketSSL.GetOnNotifyClosing: TProc;
begin
Result := FOnNotifyClosing;
end;
procedure TIdIOHandlerWebSocketSSL.SetOnNotifyClosed(const Value: TProc);
begin
FOnNotifyClosed := Value;
end;
procedure TIdIOHandlerWebSocketSSL.SetOnNotifyClosing(const Value: TProc);
begin
FOnNotifyClosing := Value;
end;
function TIdIOHandlerWebSocketSSL.HasData: Boolean;
begin
// buffered data available? (more data from previous read)
Result := (FWSInputBuffer.Size > 0) or not InputBufferIsEmpty;
end;
function TIdIOHandlerWebSocketSSL.InternalReadDataFromSource(
var VBuffer: TIdBytes; ARaiseExceptionOnTimeout: Boolean): Integer;
begin
SetLength(VBuffer, 0);
CheckForDisconnect;
if not Readable(ReadTimeout) or not Opened or not SourceIsAvailable then
begin
CheckForDisconnect; // disconnected during wait in "Readable()"?
if not Opened then
raise EIdNotConnected.Create(RSNotConnected)
else if not SourceIsAvailable then
raise EIdClosedSocket.Create(RSStatusDisconnected);
GStack.CheckForSocketError(GStack.WSGetLastError); // check for socket error
if ARaiseExceptionOnTimeout then
raise EIdReadTimeout.Create(RSIdNoDataToRead) // exit, no data can be received
else
Exit(0);
end;
SetLength(VBuffer, RecvBufferSize);
Result := inherited ReadDataFromSource(VBuffer);
if Result = 0 then
begin
CheckForDisconnect; // disconnected in the mean time?
GStack.CheckForSocketError(GStack.WSGetLastError); // check for socket error
if ARaiseExceptionOnTimeout then
raise EIdNoDataToRead.Create(RSIdNoDataToRead); // nothing read? then connection is probably closed -> exit
end;
SetLength(VBuffer, Result);
end;
procedure TIdIOHandlerWebSocketSSL.WriteLn(const AOut:string; AEncoding: TIdTextEncoding);
begin
if UseSingleWriteThread and IsWebSocket and
(TThread.Current.ThreadID <> TIdWebSocketWriteThread.Instance.ThreadID) then
begin
TInterlocked.Increment(FPendingWriteCount);
TIdWebSocketWriteThread.Instance.QueueEvent(
procedure
begin
TInterlocked.Decrement(FPendingWriteCount);
WriteLn(AOut, AEncoding);
end)
end
else
begin
Lock;
try
FPayloadInfo.Initialize(True,0);
inherited WriteLn(AOut, UTF8Encoding); // must be UTF8!
finally
FPayloadInfo.Clear;
Unlock;
end;
end;
end;
procedure TIdIOHandlerWebSocketSSL.WriteLnRFC(const AOut: string;
AEncoding: TIdTextEncoding);
begin
if UseSingleWriteThread and IsWebSocket and
(TThread.Current.ThreadID <> TIdWebSocketWriteThread.Instance.ThreadID) then
begin
TInterlocked.Increment(FPendingWriteCount);
TIdWebSocketWriteThread.Instance.QueueEvent(
procedure
begin
TInterlocked.Decrement(FPendingWriteCount);
WriteLnRFC(AOut, AEncoding);
end)
end
else
begin
Lock;
try
FPayloadInfo.Initialize(True,0);
inherited WriteLnRFC(AOut, UTF8Encoding); //must be UTF8!
finally
FPayloadInfo.Clear;
Unlock;
end;
end;
end;
procedure TIdIOHandlerWebSocketSSL.Write(const AOut: string;
AEncoding: TIdTextEncoding);
begin
if UseSingleWriteThread and IsWebSocket and
(TThread.Current.ThreadID <> TIdWebSocketWriteThread.Instance.ThreadID) then
begin
TInterlocked.Increment(FPendingWriteCount);
TIdWebSocketWriteThread.Instance.QueueEvent(
procedure
begin
TInterlocked.Decrement(FPendingWriteCount);
Write(AOut, AEncoding);
end)
end
else
begin
Lock;
try
FPayloadInfo.Initialize(True,0);
inherited Write(AOut, UTF8Encoding); // must be UTF8!
finally
FPayloadInfo.Clear;
Unlock;
end;
end;
end;
procedure TIdIOHandlerWebSocketSSL.Write(AValue: TStrings;
AWriteLinesCount: Boolean; AEncoding: TIdTextEncoding);
begin
if UseSingleWriteThread and IsWebSocket and
(TThread.Current.ThreadID <> TIdWebSocketWriteThread.Instance.ThreadID) then
begin
TInterlocked.Increment(FPendingWriteCount);
TIdWebSocketWriteThread.Instance.QueueEvent(
procedure
begin
TInterlocked.Decrement(FPendingWriteCount);
Write(AValue, AWriteLinesCount, AEncoding);
end)
end
else
begin
Lock;
try
FPayloadInfo.Initialize(True,0);
inherited Write(AValue, AWriteLinesCount, UTF8Encoding); //must be UTF8!
finally
FPayloadInfo.Clear;
Unlock;
end;
end;
end;
procedure TIdIOHandlerWebSocketSSL.Write(AStream: TStream;
aType: TWSDataType);
begin
if UseSingleWriteThread and IsWebSocket and
(TThread.Current.ThreadID <> TIdWebSocketWriteThread.Instance.ThreadID) then
begin
TInterlocked.Increment(FPendingWriteCount);
TIdWebSocketWriteThread.Instance.QueueEvent(
procedure
begin
TInterlocked.Decrement(FPendingWriteCount);
Write(AStream, aType);
end)
end
else
begin
Lock;
try
FPayloadInfo.Initialize((aType = wdtText),AStream.Size);
inherited Write(AStream);
finally
FPayloadInfo.Clear;
Unlock;
end;
end;
end;
procedure TIdIOHandlerWebSocketSSL.WriteBin(const ABytes: TArray<Byte>);
begin
if UseSingleWriteThread and IsWebSocket and
(TThread.Current.ThreadID <> TIdWebSocketWriteThread.Instance.ThreadID) then
begin
TInterlocked.Increment(FPendingWriteCount);
TIdWebSocketWriteThread.Instance.QueueEvent(
procedure
begin
TInterlocked.Decrement(FPendingWriteCount);
WriteBin(ABytes);
end)
end
else
begin
Lock;
try
FPayloadInfo.Initialize(False, 0);
inherited Write(TIdBytes(ABytes));
finally
FPayloadInfo.Clear;
Unlock;
end;
end;
end;
procedure TIdIOHandlerWebSocketSSL.WriteBufferFlush(AByteCount: Integer);
begin
if (FWriteBuffer = nil) or (FWriteBuffer.Size <= 0) then Exit;
if UseSingleWriteThread and IsWebSocket and
(TThread.Current.ThreadID <> TIdWebSocketWriteThread.Instance.ThreadID) then
begin
TInterlocked.Increment(FPendingWriteCount);
TIdWebSocketWriteThread.Instance.QueueEvent(
procedure
begin
TInterlocked.Decrement(FPendingWriteCount);
WriteBufferFlush(AByteCount);
end)
end
else
inherited WriteBufferFlush(AByteCount);
end;
function TIdIOHandlerWebSocketSSL.WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer;
var data: TIdBytes; DataCode:TWSDataCode; fin:boolean;
begin
if UseSingleWriteThread and IsWebSocket and (TThread.Current.ThreadID <> TIdWebSocketWriteThread.Instance.ThreadID) then
Assert(False, 'Write done in different thread than TIdWebSocketWriteThread!');
Lock;
try
// Result := -1; // commented out due to H2077 Value assigned never used...
if not IsWebSocket then
begin
{$IFDEF DEBUG_WS}
if DebugHook > 0 then
OutputDebugString(PChar(Format('Send (non ws, TID:%d, P:%d): %s',
[TThread.Current.ThreadID, Self.Binding.PeerPort, BytesToStringRaw(ABuffer)])));
{$ENDIF}
Result := inherited WriteDataToTarget(ABuffer, AOffset, ALength)
end
else
begin
data := ToBytes(ABuffer, ALength, AOffset);
{$IFDEF DEBUG_WS}
if DebugHook > 0 then
OutputDebugString(PChar(Format('Send (ws, TID:%d, P:%d): %s',
[TThread.Current.ThreadID, Self.Binding.PeerPort, BytesToStringRaw(data)])));
{$ENDIF}
try
DataCode := FPayloadInfo.DataCode;
fin := FPayloadInfo.DecLength(ALength);
Result := WriteData(data, DataCode, fin,webBit1 in ClientExtensionBits, webBit2 in ClientExtensionBits, webBit3 in ClientExtensionBits);
except
FClosedGracefully := True;
raise;
end;
end;
finally
Unlock;
end;
end;
function TIdIOHandlerWebSocketSSL.Readable(AMSec: Integer): Boolean;
begin
if FWSInputBuffer.Size > 0 then
Exit(True);
if not FSelectLock.TryEnter then
begin
// WSDebugger.OutputDebugString('FSelectLock Failed', TThread.Current.ThreadID.ToString);
Exit(False);
end;
try
Result := inherited Readable(AMSec);
finally
// WSDebugger.OutputDebugString('FSelectLock Leave', TThread.Current.ThreadID.ToString);
FSelectLock.Leave;
end;
end;
procedure TIdIOHandlerWebSocketSSL.ReadBytes(var VBuffer: TIdBytes;
AByteCount: Integer; AAppend: Boolean);
begin
inherited;
{$IFDEF DEBUG_WS}
if IsWebSocket then
if DebugHook > 0 then
begin
OutputDebugString(PChar(Format('%d Bytes read(TID:%d): %s',
[AByteCount, TThread.Current.ThreadID, BytesToStringRaw(VBuffer, AByteCount)])));
OutputDebugString(PChar(Format('Buffer (HeadIndex:%d): %s',
[TIdBuffer_Ext(InputBuffer).FHeadIndex,
BytesToStringRaw(TIdBuffer_Ext(InputBuffer).FBytes,
InputBuffer.Size + TIdBuffer_Ext(InputBuffer).FHeadIndex)])));
end;
{$ENDIF}
end;
function TIdIOHandlerWebSocketSSL.ReadDataFromSource(
var VBuffer: TIdBytes): Integer;
var
wscode: TWSDataCode;
begin
// the first time something is read AFTER upgrading, we switch to WS
// (so partial writes can be done, till a read is done)
if BusyUpgrading then
begin
BusyUpgrading := False;
IsWebSocket := True;
end;
// Result := -1; // commented out due to H2077 Value assigned never used...
Lock;
try
if not IsWebSocket then
begin
Result := inherited ReadDataFromSource(VBuffer);
{$IFDEF DEBUG_WS}
if DebugHook > 0 then
OutputDebugString(PChar(Format('Received (non ws, TID:%d, P:%d): %s',
[TThread.Current.ThreadID, Self.Binding.PeerPort,
BytesToStringRaw(VBuffer, Result)])));
{$ENDIF}
end
else
begin
try
//we wait till we have a full message here (can be fragmented in several frames)
Result := ReadMessage(VBuffer, wscode);
{$IFDEF DEBUG_WS}
if DebugHook > 0 then
OutputDebugString(PChar(Format('Received (ws, TID:%d, P:%d): %s',
[TThread.Current.ThreadID, Self.Binding.PeerPort, BytesToStringRaw(VBuffer)])));
{$ENDIF}
// first write the data code (text or binary, ping, pong)
FInputBuffer.Write(LongWord(Ord(wscode)));
// we write message size here, vbuffer is written after this. This way we can use ReadStream to get 1 single message (in case multiple messages in FInputBuffer)
if LargeStream then
FInputBuffer.Write(Int64(Result))
else
FInputBuffer.Write(LongWord(Result))
except
FClosedGracefully := True; // closed (but not gracefully?)
raise;
end;
end;
finally
Unlock; // normal unlock (no double try finally)
end;
end;
function TIdIOHandlerWebSocketSSL.ReadMessage(var aBuffer: TIdBytes; out aDataCode: TWSDataCode): Integer;
var
iReadCount: Integer;
iaReadBuffer: TIdBytes;
bFIN, bRSV1, bRSV2, bRSV3: boolean;
lDataCode: TWSDataCode;
lFirstDataCode: TWSDataCode;
// closeCode: integer;
// closeResult: string;
begin
Result := 0;
(* ...all fragments of a message are of
the same type, as set by the first fragment's opcode. Since
control frames cannot be fragmented, the type for all fragments in
a message MUST be either text, binary, or one of the reserved
opcodes. *)
lFirstDataCode := wdcNone;
FMessageStream.Clear;
repeat
// read a single frame
iReadCount := ReadFrame(bFIN, bRSV1, bRSV2, bRSV3, lDataCode, iaReadBuffer);
if (iReadCount > 0) or
(lDataCode <> wdcNone) then
begin
Assert(Length(iaReadBuffer) = iReadCount);
// store client extension bits
if Self.IsServerSide then
begin
ClientExtensionBits := [];
if bRSV1 then ClientExtensionBits := ClientExtensionBits + [webBit1];
if bRSV2 then ClientExtensionBits := ClientExtensionBits + [webBit2];
if bRSV3 then ClientExtensionBits := ClientExtensionBits + [webBit3];
end;
// process frame
case lDataCode of
wdcText, wdcBinary:
begin
if lFirstDataCode <> wdcNone then
raise EIdWebSocketHandleError.Create('Invalid frame: specified data code only allowed for the first frame. Data = ' + BytesToStringRaw(iaReadBuffer));
lFirstDataCode := lDataCode;
FMessageStream.Clear;
TIdStreamHelper.Write(FMessageStream, iaReadBuffer);
end;
wdcContinuation:
begin
if not (lFirstDataCode in [wdcText, wdcBinary]) then
raise EIdWebSocketHandleError.Create('Invalid frame continuation. Data = ' + BytesToStringRaw(iaReadBuffer));
TIdStreamHelper.Write(FMessageStream, iaReadBuffer);
end;
wdcClose:
begin
FCloseCode := C_FrameClose_Normal;
// "If there is a body, the first two bytes of the body MUST be a 2-byte
// unsigned integer (in network byte order) representing a status code"
if Length(iaReadBuffer) > 1 then
begin
FCloseCode := (iaReadBuffer[0] shl 8) +
iaReadBuffer[1];
if Length(iaReadBuffer) > 2 then
begin
FCloseReason := BytesToString(iaReadBuffer, 2, Length(iaReadBuffer), UTF8Encoding);
FPeerCloseReason := FCloseReason;
end;
end;
FCloseReceived := True;
if not Closing then
begin
FClosing := True;
TThread.CreateAnonymousThread(procedure
begin
TThread.NameThreadForDebugging('NotifyClosing', TThread.Current.ThreadID);
NotifyClosing;
end).Start;
Close;
NotifyClosed;
bFIN := True;
end;
end;
// Note: control frames can be send between fragmented frames
wdcPing:
begin
WriteData(iaReadBuffer, wdcPong); //send pong + same data back
lFirstDataCode := lDataCode;
// bFIN := False; // ignore ping when we wait for data?
end;
wdcPong:
begin
// pong received, ignore;
lFirstDataCode := lDataCode;
end;
end;
end
else
Break;
until bFIN;
// done?
if bFIN then
begin
if (lFirstDataCode in [wdcText, wdcBinary]) then
begin
// result
FMessageStream.Position := 0;
TIdStreamHelper.ReadBytes(FMessageStream, aBuffer);
Result := FMessageStream.Size;
aDataCode := lFirstDataCode
end
else if (lFirstDataCode in [wdcPing, wdcPong]) then
begin
// result
FMessageStream.Position := 0;
TIdStreamHelper.ReadBytes(FMessageStream, aBuffer);
SetLength(aBuffer, FMessageStream.Size);
// dummy data: there *must* be some data read otherwise connection is closed by Indy!
if Length(aBuffer) <= 0 then
begin
SetLength(aBuffer, 1);
aBuffer[0] := Ord(lFirstDataCode);
end;
Result := Length(aBuffer);
aDataCode := lFirstDataCode
end;
end;
end;
procedure TIdIOHandlerWebSocketSSL.SetBusyUpgrading(const Value: Boolean);
begin
FBusyUpgrading := Value;
end;
procedure TIdIOHandlerWebSocketSSL.SetClosedGracefully(const Value: Boolean);