-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsstream.pas
970 lines (880 loc) · 25.6 KB
/
wsstream.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
unit wsstream;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ssockets, wsmessages, wsutils, Sockets, base64, sha1;
type
{ EWebsocketError }
EWebsocketError = class(Exception)
private
FCode: integer;
public
constructor Create(const msg: string; ACode: integer);
property Code: integer read FCode;
end;
EWebsocketWriteError = class(EWebsocketError);
EWebsocketReadError = class(EWebsocketError);
EUnsupportedMessageTypeException = class(Exception);
TNetAddress = record
Address: string;
Port: integer;
end;
{ TLockedSocketStream }
TLockedSocketStream = class
private
FLocalAddress: TNetAddress;
FRemoteAddress: TNetAddress;
FStream: TSocketStream;
FReadLock: TRTLCriticalSection;
FWriteLock: TRTLCriticalSection;
function isOpen: boolean;
public
constructor Create(const AStream: TSocketStream);
destructor Destroy; override;
function LockRead: TSocketStream;
procedure UnlockRead;
function LockWrite: TSocketStream;
procedure UnlockWrite;
procedure CloseStream;
property Open: boolean read isOpen;
property RemoteAddress: TNetAddress read FRemoteAddress;
property LocalAddress: TNetAddress read FLocalAddress;
end;
TWebsocketCommunicator = class;
{ TWebsocketMessageStream }
TWebsocketMessageStream = class(TStream)
private
FCommunicator: TWebsocketCommunicator;
FMaxFrameSize: int64;
FMessageType: TWebsocketMessageType;
FBuffer: TBytes;
FCurrentLen: int64;
FFirstWrite: boolean;
FDoMask: Boolean;
function GenerateMask: Cardinal;
procedure WriteDataFrame(Finished: boolean = False);
public
constructor Create(const ACommunicator: TWebsocketCommunicator;
AMessageType: TWebsocketMessageType; AMaxFrameLen: int64;
ADoMask: Boolean);
destructor Destroy; override;
function Seek(Offset: longint; Origin: word): longint; override;
function Read(var Buffer; Count: longint): longint; override;
function Write(const Buffer; Count: longint): longint; override;
end;
TLockedEvent = specialize TThreadedData<TNotifyEvent>;
{ TWebsocketCommunicator }
TWebsocketCommunicator = class
private
FStream: TLockedSocketStream;
FMessages: TLockedWebsocketMessageList;
FMaskMessages: boolean;
FAssumeMaskedMessages: boolean;
FOnReceiveMessage: TLockedEvent;
FOnClose: TLockedEvent;
FExpectClose: boolean;
FReceiveMessageThread: TThread;
FCustomReceiveMessageThread: Boolean;
function GetOnClose: TNotifyEvent;
function GetOnReceiveMessage: TNotifyEvent;
function GetOpen: boolean;
procedure SetOnClose(AValue: TNotifyEvent);
procedure SetOnReceiveMessage(AValue: TNotifyEvent);
public
procedure AddMessageToList(Message: TWebsocketMessage);
constructor Create(AStream: TLockedSocketStream; AMaskMessage: boolean;
AssumeMaskedMessages: boolean);
destructor Destroy; override;
procedure Close(ForceClose: boolean = False);
function ReceiveMessage: TWebsocketMessage;
function SetCustomReceiveMessageThread(CustomReceiveMessageThread: TThread): Boolean; inline;
procedure StartReceiveMessageThread;
procedure StopReceiveMessageThread; inline;
function ReceiveMessageThreadRunning: Boolean; inline;
function InReceiveMessageThread: Boolean; inline;
function HasMessages: Boolean;
function GetUnprocessedMessages(const MsgList: TWebsocketMessageOwnerList): integer;
function WaitForMessage(MessageTypes: TWebsocketMessageTypes=[wmtString, wmtBinary, wmtPong]
): TWebsocketMessage;
function WaitForStringMessage: TWebsocketStringMessage; inline;
function WaitForBinaryMessage: TWebsocketBinaryMessage; inline;
function WaitForPongMessage: TWebsocketPongMessage; inline;
function WriteMessage(MessageType: TWebsocketMessageType = wmtString;
MaxFrameLength: int64 = Word.MaxValue): TWebsocketMessageStream;
procedure WriteRawMessage(const AMessage; ALength: SizeInt;
AMessageType: TWebsocketMessageType = wmtString); inline;
procedure WriteStringMessage(const AMessage: String); inline;
procedure WriteBinaryMessage(const AMessage: TBytes); inline;
property OnReceiveMessage: TNotifyEvent read GetOnReceiveMessage
write SetOnReceiveMessage;
property OnClose: TNotifyEvent read GetOnClose write SetOnClose;
property SocketStream: TLockedSocketStream read FStream;
property Open: boolean read GetOpen;
end;
{ TReceiveMessageThread }
TReceiveMessageThread = class(TThread)
private
FCommunicator: TWebsocketCommunicator;
protected
procedure Execute; override;
public
constructor Create(Communicator: TWebsocketCommunicator);
end;
function GenerateAcceptingKey(const Key: string): string; inline;
implementation
const
// Fixme check if it is really 0 on unix
ConnectionRestCode = {$IfDef UNIX}0{$ELSE}10054{$ENDIF};
ConnectionIsDeadCode = {$IfDef UNIX}0{$ELSE}10053{$ENDIF};
{*------------------------------------------------------------------------------
* extension of htons and htonl for qwords (ll: long long from C)
*-----------------------------------------------------------------------------}
function htonll(host: QWord): QWord; inline;
begin
{$ifdef FPC_BIG_ENDIAN}
Result := host;
{$else}
Result := SwapEndian(host);
{$endif}
end;
function ntohll(net: QWord): QWord; inline;
begin
{$ifdef FPC_BIG_ENDIAN}
Result := net;
{$else}
Result := SwapEndian(net);
{$endif}
end;
type
{ Protocol specific types }
TWebsocketFrameHeader = record
Fin: boolean;
OPCode: TWebsocketMessageType;
Mask: boolean;
PayloadLen: byte;
end;
TMaskRec = record
case boolean of
True: (Bytes: array[0..3] of byte);
False: (Key: Cardinal);
end;
TWordRec = record
case boolean of
True: (Bytes: array[0..1] of byte);
False: (Value: word);
end;
function WordToFrameHeader(Data: word): TWebsocketFrameHeader; inline;
var
wordRec: TWordRec;
begin
wordRec.Value := Data;
Result.Fin := (wordRec.Bytes[0] and 128) = 128;
Result.OPCode := TWebsocketMessageType(wordRec.Bytes[0] and %1111);
Result.Mask := (wordRec.Bytes[1] and 128) = 128;
Result.PayloadLen := wordRec.Bytes[1] and %1111111;
end;
function boolToBit(b: boolean; Bit: byte): byte; inline;
begin
Result := 0;
if b then
Result := 1 shl Bit;
end;
function FrameHEaderToWord(const Header: TWebsocketFrameHeader): word; inline;
var
wordRec: TWordRec;
begin
wordRec.Bytes[0] := boolToBit(Header.Fin, 7) or (Ord(Header.OPCode) and %1111);
wordRec.Bytes[1] := boolToBit(Header.Mask, 7) or (Header.PayloadLen and %1111111);
Result := wordRec.Value;
end;
{ TReceiveMessageThread }
procedure TReceiveMessageThread.Execute;
var
msg: TWebsocketMessage;
begin
while not Terminated and FCommunicator.Open do
begin
msg := FCommunicator.ReceiveMessage;
if Assigned(msg) then
FCommunicator.AddMessageToList(msg);
sleep(10);
end;
FCommunicator.FReceiveMessageThread := nil;
end;
constructor TReceiveMessageThread.Create(Communicator: TWebsocketCommunicator);
begin
inherited Create(True);
FCommunicator := Communicator;
FreeOnTerminate := True;
end;
{ EWebsocketError }
constructor EWebsocketError.Create(const msg: string; ACode: integer);
begin
inherited Create(msg);
FCode := ACode;
end;
{ TLockedSocketStream }
function TLockedSocketStream.isOpen: boolean;
begin
// Simply reading don't need locks
// If you want to do anything afterwards you still need to lock and check if
// the stream is assigned
Result := Assigned(FStream);
end;
constructor TLockedSocketStream.Create(const AStream: TSocketStream);
begin
FLocalAddress.Address := NetAddrToStr(AStream.LocalAddress.sin_addr);
FLocalAddress.Port := AStream.LocalAddress.sin_port;
FRemoteAddress.Address := NetAddrToStr(AStream.RemoteAddress.sin_addr);
FRemoteAddress.Port := AStream.LocalAddress.sin_port;
FStream := AStream;
InitCriticalSection(FReadLock);
InitCriticalSection(FWriteLock);
end;
destructor TLockedSocketStream.Destroy;
begin
CloseStream;
DoneCriticalsection(FWriteLock);
DoneCriticalsection(FReadLock);
inherited Destroy;
end;
function TLockedSocketStream.LockRead: TSocketStream;
begin
EnterCriticalsection(FReadLock);
Result := FStream;
end;
procedure TLockedSocketStream.UnlockRead;
begin
LeaveCriticalsection(FReadLock);
end;
function TLockedSocketStream.LockWrite: TSocketStream;
begin
EnterCriticalsection(FWriteLock);
Result := FStream;
end;
procedure TLockedSocketStream.UnlockWrite;
begin
LeaveCriticalsection(FWriteLock);
end;
procedure TLockedSocketStream.CloseStream;
begin
LockRead;
try
LockWrite;
try
FreeAndNil(FStream);
finally
UnlockWrite;
end;
finally
UnlockRead;
end;
end;
{ TWebsocketCommunicator }
function TWebsocketCommunicator.GetOpen: boolean;
begin
Result := FStream.Open;
end;
function TWebsocketCommunicator.GetOnClose: TNotifyEvent;
begin
try
Result := FOnClose.Lock^;
finally
FOnClose.Unlock;
end;
end;
function TWebsocketCommunicator.GetOnReceiveMessage: TNotifyEvent;
begin
try
Result := FOnReceiveMessage.Lock^;
finally
FOnReceiveMessage.Unlock;
end;
end;
procedure TWebsocketCommunicator.SetOnClose(AValue: TNotifyEvent);
begin
try
FOnClose.Lock^ := AValue;
finally
FOnClose.Unlock;
end;
end;
procedure TWebsocketCommunicator.SetOnReceiveMessage(AValue: TNotifyEvent);
begin
try
FOnReceiveMessage.Lock^ := AValue;
finally
FOnReceiveMessage.Unlock;
end;
end;
procedure TWebsocketCommunicator.AddMessageToList(Message: TWebsocketMessage);
var
lst: TWebsocketMessageList;
OnReceiveMessageEvent: TNotifyEvent;
begin
if Assigned(Message) then
begin
lst := FMessages.Lock;
try
lst.Add(Message);
finally
FMessages.Unlock;
end;
OnReceiveMessageEvent := OnReceiveMessage;
if Assigned(OnReceiveMessageEvent) then
begin
OnReceiveMessageEvent(Self);
end;
end;
end;
constructor TWebsocketCommunicator.Create(AStream: TLockedSocketStream;
AMaskMessage: boolean; AssumeMaskedMessages: boolean);
begin
FStream := AStream;
FMaskMessages := AMaskMessage;
FAssumeMaskedMessages := AssumeMaskedMessages;
FMessages := TLockedWebsocketMessageList.Create(TWebsocketMessageList.Create);
FOnReceiveMessage.Init(nil);
FOnClose.Init(nil);
FExpectClose := False;
end;
destructor TWebsocketCommunicator.Destroy;
begin
// Ending communication => Close stream
Close(True);
FStream.Free;
FMessages.Free;
FOnReceiveMessage.Done;
FOnClose.Done;
inherited Destroy;
end;
procedure TWebsocketCommunicator.Close(ForceClose: boolean);
var
OnCloseEvent: TNotifyEvent;
begin
if not Open then
Exit;
if not ForceClose then
begin
WriteMessage(wmtClose).Free;
FExpectClose := True;
Exit;
end;
OnCloseEvent := OnClose;
if Assigned(OnCloseEvent) then
OnCloseEvent(Self);
FStream.CloseStream;
end;
function TWebsocketCommunicator.ReceiveMessage: TWebsocketMessage;
procedure ReadData(var buffer; const len: int64);
var
ToRead: longint;
Read: longint;
LeftToRead: int64;
TotalRead: int64;
oldTO: integer;
Stream: TSocketStream;
const
IOTimeoutError = {$IFDEF UNIX}11{$ELSE}10060{$EndIf};
WaitingTime = 10;
begin
TotalRead := 0;
repeat
// how much we are trying to read at a time
LeftToRead := len - TotalRead;
if LeftToRead > ToRead.MaxValue then
ToRead := ToRead.MaxValue
else
ToRead := LeftToRead;
// Reading
Stream := FStream.LockRead;
try
if not Assigned(Stream) then
begin
raise EWebsocketReadError.Create('Socket already closed', 0);
end;
oldTO := Stream.IOTimeout;
Stream.IOTimeout := 1;
try
Read := Stream.Read(PByte(@buffer)[TotalRead], ToRead);
if Read < 0 then
begin
// on Error
if (Stream.LastError <> IOTimeoutError) and (Stream.LastError <> 0) then
raise EWebsocketReadError.Create('error reading from stream',
Stream.LastError);
end
else
begin
// Increase the amount to read
TotalRead += Read;
end;
finally
Stream.IOTimeout := oldTO;
end;
finally
FStream.UnlockRead;
end;
if (TotalRead < len) and (Read <> ToRead) then // not finished, wait for some data
Sleep(WaitingTime);
until TotalRead >= len;
end;
function ProcessSpecialMessages(messageType: TWebsocketMessageType;
var buffer; const buffLen: int64): boolean;
var
str: UTF8String;
begin
Result := True;
case messageType of
wmtClose:
begin
// If we didn't send the original close, return the message
if not FExpectClose then
WriteMessage(wmtClose).Free;
// Close the stream (true to not send a message)
Close(True);
end;
wmtPing:
begin
// On ping send pong, with same content
with WriteMessage(wmtPong) do
try
if buffLen > 0 then
Write(PByte(@buffer)[0], buffLen);
finally
Free;
end;
end;
wmtPong:
begin
// lift pong message to message queue, so user can handle it
SetLength(str, buffLen);
if buffLen > 0 then
Move(buffer, str[1], buffLen);
AddMessageToList(TWebsocketPongMessage.Create(str));
end
else
Result := False;
end;
end;
var
Header: TWebsocketFrameHeader;
len64: int64;
len16: word;
len: int64;
MaskRec: TMaskRec;
buffer: TBytes;
i: int64;
outputStream: TMemoryStream;
messageType: TWebsocketMessageType;
msgType: TWebsocketMessageType;
str: UTF8String;
w: word;
begin
Result := nil;
outputStream := TMemoryStream.Create;
msgType:=wmtContinue;
try
try
repeat
if not Open then
Exit;
ReadData(w, 2);
Header := WordToFrameHeader(w);
if Header.OPCode <> wmtContinue then
messageType := TWebsocketMessageType(Header.OPCode);
if Header.PayloadLen < 126 then
len := Header.PayloadLen
else if Header.PayloadLen = 126 then
begin
ReadData(len16, SizeOf(len16));
len := NToHs(len16);
end
else
begin
ReadData(len64, SizeOf(len64));
len := ntohll(len64);
end;
if Header.Mask then
begin
ReadData(MaskRec.Key, SizeOf(MaskRec.Key));
end
else if FAssumeMaskedMessages then
begin
Close(True);
Exit;
end;
// Read payload
SetLength(buffer, len);
if len > 0 then
begin
ReadData(buffer[0], len);
if Header.Mask then
begin
// As this is 64 bit, to be 32 bit compatible we can't use a for loop
i := 0;
while i < len do
begin
buffer[i] := buffer[i] xor MaskRec.Bytes[i mod 4];
Inc(i);
end;
end;
end;
// Handling special messages
if ProcessSpecialMessages(messageType, PByte(buffer)^, len) then
begin
// am i in the middle of a communication?
// If so dont use the fin in the end
if msgType <> wmtContinue then Continue;
end
else
begin
if messageType <> wmtContinue then
msgType:=messageType;
// This is a dataframe, so save data for concatination of fragments
if len > 0 then
outputStream.WriteBuffer(buffer[0], len);
end;
until Header.Fin;
// Read whole message
outputStream.Seek(0, soBeginning);
case msgType of
wmtString:
begin
SetLength(str, outputStream.Size);
outputStream.ReadBuffer(str[1], outputStream.Size);
Result := TWebsocketStringMessage.Create(str);
end;
wmtBinary:
begin
SetLength(buffer, outputStream.Size);
outputStream.ReadBuffer(buffer[0], outputStream.Size);
Result := TWebsocketBinaryMessage.Create(buffer);
end;
end;
finally
outputStream.Free;
end;
except
On e: EWebsocketReadError do
begin
if (e.Code = 0) or (e.Code = ConnectionIsDeadCode) or
(e.Code = ConnectionRestCode) then
begin
// Stream has been closed
Close(True);
end;
end;
end;
end;
function TWebsocketCommunicator.SetCustomReceiveMessageThread(
CustomReceiveMessageThread: TThread): Boolean;
begin
Result := not (Assigned(FReceiveMessageThread) and Assigned(CustomReceiveMessageThread));
FCustomReceiveMessageThread := True;
if Result then
FReceiveMessageThread := CustomReceiveMessageThread;
end;
procedure TWebsocketCommunicator.StartReceiveMessageThread;
begin
if not Assigned(FReceiveMessageThread) then
begin
FCustomReceiveMessageThread := False;;
FReceiveMessageThread := TReceiveMessageThread.Create(Self);
FReceiveMessageThread.Start;
end;
end;
procedure TWebsocketCommunicator.StopReceiveMessageThread;
begin
if Assigned(FReceiveMessageThread) then
begin
if FCustomReceiveMessageThread then
raise EInvalidOperation.Create('Can''t stop a custom receive message thread. Stop it yourself!');
FReceiveMessageThread.Terminate;
end;
end;
function TWebsocketCommunicator.ReceiveMessageThreadRunning: Boolean;
begin
Result := Assigned(FReceiveMessageThread);
end;
function TWebsocketCommunicator.InReceiveMessageThread: Boolean;
begin
Result := ReceiveMessageThreadRunning and (TThread.CurrentThread.ThreadID = FReceiveMessageThread.ThreadID);
end;
function TWebsocketCommunicator.HasMessages: Boolean;
begin
try
Result := FMessages.Lock.Count > 0;
finally
FMessages.Unlock;
end;
end;
function TWebsocketCommunicator.WriteMessage(MessageType: TWebsocketMessageType;
MaxFrameLength: int64): TWebsocketMessageStream;
begin
Result := TWebsocketMessageStream.Create(Self, MessageType,
MaxFrameLength, FMaskMessages);
end;
procedure TWebsocketCommunicator.WriteRawMessage(const AMessage;
ALength: SizeInt; AMessageType: TWebsocketMessageType);
begin
with WriteMessage(AMessageType, ALength) do
try
Write(AMessage, ALength);
finally
Free;
end;
end;
procedure TWebsocketCommunicator.WriteStringMessage(const AMessage: String);
begin
WriteRawMessage(AMessage[1], AMessage.Length);
end;
procedure TWebsocketCommunicator.WriteBinaryMessage(const AMessage: TBytes);
begin
WriteRawMessage(AMessage[0], Length(AMessage), wmtBinary);
end;
function TWebsocketCommunicator.GetUnprocessedMessages(
const MsgList: TWebsocketMessageOwnerList): integer;
var
lst: TWebsocketMessageList;
m: TWebsocketMessage;
begin
lst := FMessages.Lock;
try
Result := lst.Count;
for m in lst do
MsgList.Add(m);
lst.Clear;
finally
FMessages.Unlock;
end;
end;
function TWebsocketCommunicator.WaitForMessage(
MessageTypes: TWebsocketMessageTypes): TWebsocketMessage;
var
oldEvent: TNotifyEvent;
msg: TWebsocketMessage;
MsgList: TWebsocketMessageList;
i: SizeInt;
MessageType: TWebsocketMessageType;
begin
for MessageType in MessageTypes do
if not (MessageType in [wmtString, wmtBinary, wmtPong]) then
raise EUnsupportedMessageTypeException.Create('Can only wait for String, Binary or Pong messages');
Result := nil;
oldEvent := OnReceiveMessage;
OnReceiveMessage := nil;
try
while Open and not Assigned(Result) do
begin
if ReceiveMessageThreadRunning then
Sleep(100) // wait for messages on different thread
else
begin // else receive message
msg := ReceiveMessage;
if Assigned(msg) then
AddMessageToList(msg);
end;
// now check message queue
MsgList := FMessages.Lock;
try
for i:=0 to MsgList.Count-1 do
begin
msg := MsgList[i];
if msg.MessageType in MessageTypes then
begin
MsgList.Delete(i);
Result := msg;
end;
end;
finally
FMessages.Unlock;
end;
end;
finally
OnReceiveMessage := oldEvent;
// if other messages where received, call the event
// note there is a slim chance that between these lines, a message was received,
// so the event will be fired twice. But handling this with critical sections
// may introduce deadlocks when trying to receive messages within the handler
// so it seems more reasonable to have the user ignore empty events
if HasMessages and Assigned(oldEvent) then
oldEvent(Self);
end;
end;
function TWebsocketCommunicator.WaitForStringMessage: TWebsocketStringMessage;
begin
Result := WaitForMessage([wmtString]) as TWebsocketStringMessage;
end;
function TWebsocketCommunicator.WaitForBinaryMessage: TWebsocketBinaryMessage;
begin
Result := WaitForMessage([wmtBinary]) as TWebsocketBinaryMessage;
end;
function TWebsocketCommunicator.WaitForPongMessage: TWebsocketPongMessage;
begin
Result := WaitForMessage([wmtPong]) as TWebsocketPongMessage;
end;
{ TWebsocketMessageStream }
function TWebsocketMessageStream.GenerateMask: Cardinal;
begin
Result := Random(Cardinal.MaxValue + 1);
end;
procedure TWebsocketMessageStream.WriteDataFrame(Finished: boolean);
var
Header: TWebsocketFrameHeader;
i: int64;
MaskRec: TMaskRec;
Stream: TSocketStream;
begin
try
Stream := FCommunicator.SocketStream.LockWrite;
try
if not Assigned(Stream) then
begin
raise EWebsocketWriteError.Create('Stream already closed', 0);
end;
try
Header.Fin := Finished;
Header.Mask := FDoMask;
if FFirstWrite then
Header.OPCode := FMessageType
else
Header.OPCode := wmtContinue;
// Compute size
if FCurrentLen < 126 then
Header.PayloadLen := FCurrentLen
else if FCurrentLen <= word.MaxValue then
Header.PayloadLen := 126
else
Header.PayloadLen := 127;
// Write header
Stream.WriteWord(FrameHEaderToWord(Header));
// Write size if it exceeds 125
if (FCurrentLen > 125) then
begin
if (FCurrentLen <= word.MaxValue) then
Stream.WriteWord(htons(word(FCurrentLen)))
else
Stream.WriteQWord(htonll(QWord(FCurrentLen)));
end;
if Header.Mask then
begin
// If we use a mask
MaskRec.Key := generateMask;
// First: Transmit mask Key
Stream.WriteBuffer(MaskRec.Key, SizeOf(MaskRec.Key));
// 2. Encode Message
// As this is 64 bit, to be 32 bit compatible we can't use a for loop
i := 0;
while i < FCurrentLen do
begin
FBuffer[i] := FBuffer[i] xor MaskRec.Bytes[i mod 4];
Inc(i);
end;
end;
if FCurrentLen > 0 then
begin
// Write Message payload
Stream.WriteBuffer(FBuffer[0], FCurrentLen);
end;
// Reset state for next data
FCurrentLen := 0;
except
on E: EWriteError do
raise EWebsocketWriteError.Create(e.Message, Stream.LastError);
end;
finally
FCommunicator.SocketStream.UnlockWrite;
end;
if Finished and (FMessageType = wmtClose) then
FCommunicator.FExpectClose := True;
except
on E: EWebsocketWriteError do
begin
if (e.Code = 0) or (e.Code = ConnectionIsDeadCode) or
(e.Code = ConnectionRestCode) then
FCommunicator.Close(True);
raise;
end;
end;
end;
constructor TWebsocketMessageStream.Create(
const ACommunicator: TWebsocketCommunicator;
AMessageType: TWebsocketMessageType; AMaxFrameLen: int64; ADoMask: Boolean);
begin
FCommunicator := ACommunicator;
FMaxFrameSize := AMaxFrameLen;
FMessageType := AMessageType;
SetLength(FBuffer, AMaxFrameLen);
FCurrentLen := 0;
FFirstWrite := True;
FDoMask := ADoMask;
end;
destructor TWebsocketMessageStream.Destroy;
begin
WriteDataFrame(True);
inherited Destroy;
end;
function TWebsocketMessageStream.Seek(Offset: longint; Origin: word): longint;
begin
// We cant seek
Result := 0;
end;
function TWebsocketMessageStream.Read(var Buffer; Count: longint): longint;
begin
// Write only stream
Result := 0;
end;
function TWebsocketMessageStream.Write(const Buffer; Count: longint): longint;
var
ToWrite: integer;
begin
// FIXME: Result is longint but FMaxFrameSize is int64, so technically this
// function does not fully support 64 bit messages
Result := 0;
while FCurrentLen + Count > FMaxFrameSize do
begin
// Doesn't fit into one dataframe
// So we split it up into multiple
ToWrite := FMaxFrameSize - FCurrentLen;
Move(PByte(@Buffer)[Result], FBuffer[FCurrentLen], ToWrite);
FCurrentLen := FMaxFrameSize;
WriteDataFrame(False);
// Now FCurrentLen should be 0 again
// Only decrese the count
Dec(Count, ToWrite);
Inc(Result, ToWrite);
end;
Move(PByte(@Buffer)[Result], FBuffer[FCurrentLen], Count);
FCurrentLen += Count;
Inc(Result, Count);
end;
function GenerateAcceptingKey(const Key: string): string; inline;
var
concatKey: string;
keyHash: TSHA1Digest;
OutputStream: TStringStream;
b64Encoder: TBase64EncodingStream;
const
WebsocketMagicString = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
begin
// Key = Base64(SHA1(Key + MagicString))
concatKey := Key + WebsocketMagicString;
keyHash := SHA1String(concatKey);
OutputStream := TStringStream.Create('');
try
b64Encoder := TBase64EncodingStream.Create(OutputStream);
try
b64Encoder.WriteBuffer(keyHash[low(keyHash)], Length(keyHash));
b64Encoder.Flush;
Result := OutputStream.DataString;
finally
b64Encoder.Free;
end;
finally
OutputStream.Free;
end;
end;
initialization
Randomize;
end.