-
Notifications
You must be signed in to change notification settings - Fork 2
/
WebSocket.Core.pas
1933 lines (1697 loc) · 64.7 KB
/
WebSocket.Core.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
{==============================================================================|
| Project : Object Pascal WebSocket Client/Server Library |
|==============================================================================|
| Content: Core WebSocket client and server classes |
|==============================================================================|
| Copyright (c) 2023, Vahid Nasehi Oskouei |
| All rights reserved. |
| |
| Remastered and rewritten version which is based on |
| https://github.com/MFernstrom/Bauglir-WebSocket-2 |
| and |
| https://github.com/Robert-112/Bauglir-WebSocket-2 |
| which originally are based on Bronislav Klucka source code as |
| http://code.google.com/p/bauglir-websocket |
| |
| |
| Project download homepage: |
| https://github.com/biot2/libWebSocket.pas |
| WebSocket RFC: |
| http://tools.ietf.org/html/rfc6455 |
| |
| |
|==============================================================================|
| Requirements: Ararat Synapse (http://www.ararat.cz/synapse/) |
|==============================================================================}
unit WebSocket.Core;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$H+}
interface
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes, SysUtils, blcksock, syncobjs, WebSocket.Helper, strutils;
const
{:Constants section defining what kind of data are sent from one pont to another}
{:Continuation frame }
wsCodeContinuation = $0;
{:Text frame }
wsCodeText = $1;
{:Binary frame }
wsCodeBinary = $2;
{:Close frame }
wsCodeClose = $8;
{:Ping frame }
wsCodePing = $9;
{:Frame frame }
wsCodePong = $A;
{:Constants section defining close codes}
{:Normal valid closure, connection purpose was fulfilled}
wsCloseNormal = 1000;
{:Endpoint is going away (like server shutdown) }
wsCloseShutdown = 1001;
{:Protocol error }
wsCloseErrorProtocol = 1002;
{:Unknown frame data type or data type application cannot handle }
wsCloseErrorData = 1003;
{:Reserved }
wsCloseReserved1 = 1004;
{:Close received by peer but without any close code. This close code MUST NOT be sent by application. }
wsCloseNoStatus = 1005;
{:Abnotmal connection shutdown close code. This close code MUST NOT be sent by application. }
wsCloseErrorClose = 1006;
{:Received text data are not valid UTF-8. }
wsCloseErrorUTF8 = 1007;
{:Endpoint is terminating the connection because it has received a message that violates its policy. Generic error. }
wsCloseErrorPolicy = 1008;
{:Too large message received }
wsCloseTooLargeMessage = 1009;
{:Client is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake }
wsCloseClientExtensionError= 1010;
{:Server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request }
wsCloseErrorServerRequest = 1011;
{:Connection was closed due to a failure to perform a TLS handshake. This close code MUST NOT be sent by application. }
wsCloseErrorTLS = 1015;
type
TReadOnlyMemoryStream = class(TCustomMemoryStream)
public
constructor Create(Memory: Pointer; Size: PtrInt);
procedure ResetPointer(Memory: Pointer; Size: PtrInt);
end;
TWSFlag = (FIN, RSV1, RSV2, RSV3);
TWSFlags = set of TWSFlag;
TWebSocketCustomConnection = class;
{:Event procedural type to hook OnOpen events on connection
}
TWebSocketConnectionEvent = procedure(Sender: TWebSocketCustomConnection) of object;
{:Event procedural type to hook OnPing, OnPong events on connection
}
TWebSocketConnectionPingPongEvent = procedure(Sender: TWebSocketCustomConnection; Data: AnsiString) of object;
{:Event procedural type to hook OnClose event on connection
}
TWebSocketConnectionClose = procedure(Sender: TWebSocketCustomConnection; CloseCode: Integer; CloseReason: AnsiString; ClosedByPeer: Boolean) of object;
{:Event procedural type to hook OnRead on OnWrite event on connection
}
TWebSocketConnectionData = procedure(Sender: TWebSocketCustomConnection; Flags: TWSFlags; OpCode: Byte; Data: TMemoryStream) of object;
TWebSocketConnectionDataWrite = procedure(Sender: TWebSocketCustomConnection; Flags: TWSFlags; OpCode: Byte; Data: TStream) of object;
{:Event procedural type to hook OnReadFull
}
TWebSocketConnectionDataFull = procedure(Sender: TWebSocketCustomConnection; OpCode: Byte; Data: TMemoryStream) of object;
{:abstract(WebSocket connection)
class is parent class for server and client connection
}
TWebSocketCustomConnection = class(TCustomConnection)
private
protected
FOnOpen: TWebSocketConnectionEvent;
FOnClose: TWebSocketConnectionClose;
FOnRead: TWebSocketConnectionData;
FOnReadFull: TWebSocketConnectionDataFull;
FOnWrite: TWebSocketConnectionDataWrite;
FOnPing: TWebSocketConnectionPingPongEvent;
FOnPong: TWebSocketConnectionPingPongEvent;
FCookie: AnsiString;
FVersion: Integer;
FProtocol: AnsiString;
FResourceName: AnsiString;
FOrigin: AnsiString;
FExtension: AnsiString;
FPort: AnsiString;
FHost: AnsiString;
FHeaders: TStringList;
FClosedByMe: Boolean;
FClosedByPeer: Boolean;
FMasking: Boolean;
FRequireMasking: Boolean;
FHandshake: Boolean;
FCloseCode: Integer;
FCloseReason: AnsiString;
FClosingByPeer: Boolean;
FSendCriticalSection: TCriticalSection;
FFullDataProcess: Boolean;
FFullDataStream: TMemoryStream;
function GetClosed: Boolean;
function GetClosing: Boolean;
procedure ExecuteConnection; override;
function ReadData(out Flags: TWSFlags; out OpCode: Byte; Data: TMemoryStream): Integer; virtual;
function ValidConnection: Boolean;
procedure DoOpen;
procedure DoClose(CloseCode: Integer; CloseReason: AnsiString; ClosedByPeer: Boolean);
procedure DoPing(Data: AnsiString);
procedure DoPong(Data: AnsiString);
procedure DoRead(Flags: TWSFlags; OpCode: Byte; Data: TMemoryStream);
procedure DoReadFull(OpCode: Byte; Data: TMemoryStream);
procedure DoWrite(Flags: TWSFlags; OpCode: Byte; Data: TStream);
{:Overload this function to process connection close (not at socket level, but as an actual WebSocket frame)
CloseCode represents close code (see wsClose constants)
CloseReason represents textual information transfered with frame (there is no specified format or meaning)
ClosedByPeer whether connection has been closed by this connection object or by peer endpoint
}
procedure ProcessOpen; virtual;
procedure ProcessClose(CloseCode: Integer; CloseReason: AnsiString; ClosedByPeer: Boolean); virtual;
{:Overload this function to process ping frame)
Data represents textual information transfered with frame (there is no specified format or meaning)
}
procedure ProcessPing(Data: AnsiString); virtual;
{:Overload this function to process pong frame)
Data represents textual information transfered with frame (there is no specified format or meaning)
}
procedure ProcessPong(Data: AnsiString); virtual;
{:Overload this function to process data as soon as they are read before other Process<data> function is called
this function should be used by extensions to modify incomming data before the are process based on code
Flags frame flags including FIN and 3 extension bits
Opcode is frame opcode
Data data stream
}
procedure ProcessReadData(var Flags: TWSFlags; var OpCode: Byte; Data: TMemoryStream); virtual;
procedure ProcessReadDataFull(var {%H-}Flags: TWSFlags; var OpCode: Byte; Data: TMemoryStream); virtual;
procedure ProcessWriteData(var Flags: TWSFlags; var OpCode: Byte; Data: TStream); virtual;
public
constructor Create(Socket: TTCPCustomConnectionSocket); override;
destructor Destroy; override;
{:
Whether connection is in active state (not closed, closing, socket, exists, i/o threads not Terminated..)
}
function CanReceiveOrSend: Boolean;
{:Procedure to close connection
CloseCode represents close code (see wsClose constants)
CloseReason represents textual information transfered with frame (there is no specified format or meaning) the AnsiString can only be 123 bytes length
}
procedure Close(CloseCode: Integer; CloseReason: AnsiString); virtual; abstract;
{:Send generic frame
Flags frame flags including FIN and 3 extension bits
OpCode frame opcode
Data data stream or string
}
function SendData(Flags: TWSFlags; OpCode: Byte; Data: TStream): Integer; overload; virtual;
function SendData(Flags: TWSFlags; OpCode: Byte; Data: Pointer; DataSize: Integer): Integer; overload; virtual;
function SendData(Flags: TWSFlags; OpCode: Byte; Data: AnsiString): Integer; overload; virtual;
function SendDataSplitted(OpCode: Byte; Data: Pointer; DataSize: Int64; SplitSize: Integer): Integer; overload;
function SendDataSplitted(OpCode: Byte; Data: TStream; SplitSize: Integer): Integer; overload;
{:Send textual frame
Data data AnsiString (MUST be UTF-8)
Flags frame flags including FIN and 3 extension bits
}
procedure SendText(Data: AnsiString; Flags: TWSFlags = [FIN]);
procedure SendTextSplitted(Data: AnsiString; SplitSize: Integer = 1048576);
{:Send textual continuation frame
Data data AnsiString (MUST be UTF-8)
Flags frame flags including FIN and 3 extension bits
}
procedure SendTextContinuation(Data: AnsiString; Flags: TWSFlags = [FIN]);
{:Send binary frame
Data data stream
Flags frame flags including FIN and 3 extension bits
}
procedure SendBinary(Data: TStream; Flags: TWSFlags = [FIN]);
procedure SendBinarySplitted(Data: TStream; SplitSize: Integer = 1048576);
{:Send binary continuation frame
Data data stream
Flags frame flags including FIN and 3 extension bits
}
procedure SendBinaryContinuation(Data: TStream; Flags: TWSFlags = [FIN]);
{:Send Ping
Data ping informations
}
procedure Ping(Data: AnsiString);
{:Send Pong
Data pong informations
}
procedure Pong(Data: AnsiString);
{:Temination procedure
This method should be called instead of Terminate to terminate thread,
it internally calls Terminate, but can be overloaded,
and can be used for data clean up
}
procedure TerminateThread; override;
{: Whether connection has been closed
(either socket has been closed or thread has been Terminated or WebSocket has been closed by this and peer connection)
}
property Closed: Boolean read GetClosed;
{: Whether WebSocket has been closed by this and peer connection }
property Closing: Boolean read GetClosing;
{: WebSocket connection cookies
Property is regular unparsed Cookie header AnsiString
e.g. cookie1=value1;cookie2=value2
empty AnsiString represents that no cookies are present
}
property Cookie: AnsiString read FCookie;
{: WebSocket connection extensions
Property is regular unparsed Sec-WebSocket-Extensions header AnsiString
e.g. foo, bar; baz=2
On both client and server connection this value represents the extension(s) selected by server to be used
as a Result of extension negotioation
value - represents that no extension was negotiated and no header will be sent to client
it is the default value
}
property Extension: AnsiString read FExtension;
{:Whether to register for full data processing
(callink @link(ProcessFullText), @link(ProcessFullStream) @link(OnFullRead)
those methods/events are called if FullDataProcess is @True and whole message is read (after FIN frame)
}
property FullDataProcess: Boolean read FFullDataProcess write FFullDataProcess;
{:
Whether WebSocket handshake was succecfull (and connection is afer WS handshake)
}
property Handshake: Boolean read FHandshake;
{: WebSocket connection host
Property is regular unparsed Host header AnsiString
e.g. server.example.com
}
property Host: AnsiString read FHost;
{: WebSocket connection origin
Property is regular unparsed Sec-WebSocket-Origin header AnsiString
e.g. http://example.com
}
property Origin: AnsiString read FOrigin;
{: WebSocket connection protocol
Property is regular unparsed Sec-WebSocket-Protocol header AnsiString
e.g. chat, superchat
On both client and server connection this value represents the protocol(s) selected by server to be used
as a Result of protocol negotioation
value - represents that no protocol was negotiated and no header will be sent to client
it is the default value
}
property Protocol: AnsiString read FProtocol;
{: Connection port }
property Port: AnsiString read FPort;
{: Connection resource
e.g. /path1/path2/path3/file.ext
}
property ResourceName: AnsiString read FResourceName;
{: WebSocket version (either 7 or 8 or 13)}
property Version: Integer read FVersion;
{: WebSocket connection successfully }
property OnOpen: TWebSocketConnectionEvent read FOnOpen write FOnOpen;
{: WebSocket Close frame event }
property OnClose: TWebSocketConnectionClose read FOnClose write FOnClose;
{ : WebSocket ping }
property OnPing: TWebSocketConnectionPingPongEvent read FOnPing write FOnPing;
{ : WebSocket pong }
property OnPong: TWebSocketConnectionPingPongEvent read FOnPong write FOnPong;
{: WebSocket frame read }
property OnRead: TWebSocketConnectionData read FOnRead write FOnRead;
{: WebSocket read full data}
property OnReadFull: TWebSocketConnectionDataFull read FOnReadFull write FOnReadFull;
{: WebSocket frame written }
property OnWrite: TWebSocketConnectionDataWrite read FOnWrite write FOnWrite;
end;
{: Class of WebSocket connections }
TWebSocketCustomConnections = class of TWebSocketCustomConnection;
{: WebSocket server connection automatically created by server on incoming connection }
TWebSocketServerConnection = class(TWebSocketCustomConnection)
public
constructor Create(Socket: TTCPCustomConnectionSocket); override;
procedure Close(CloseCode: Integer; CloseReason: AnsiString); override;
procedure TerminateThread; override;
{: List of all headers
keys are lowercased header name
e.g host, connection, sec-websocket-key
}
property Header: TStringList read FHeaders;
end;
{: Class of WebSocket server connections }
TWebSocketServerConnections = class of TWebSocketServerConnection;
{: WebSocket client connection, this object shoud be created to establish client to server connection }
TWebSocketClient = class(TWebSocketCustomConnection)
private
FEvent: TSimpleEvent;
protected
function BeforeExecuteConnection: Boolean; override;
procedure Execute; override;
procedure DoConnect;
public
{: construstor to create connection,
parameters has the same meaning as corresponging connection properties (see 2 differences below) and
should be formated according to headers values
Protocol and Extension in constructor represents protocol(s) and extension(s)
client is trying to negotiate, obejst properties then represents
protocol(s) and extension(s) the server is supporting (the negotiation Result)
Version must be >= 8
}
constructor Create(Host, Port, ResourceName: AnsiString; Origin: AnsiString = '-'; Protocol: AnsiString = '-'; Extension: AnsiString = '-'; Cookie: AnsiString = '-'; Version: Integer = 13); reintroduce; virtual;
constructor CreateFromURL(URL: AnsiString; Origin: AnsiString = '-'; Protocol: AnsiString = '-'; Extension: AnsiString = '-'; Cookie: AnsiString = '-'; Version: Integer = 13); virtual;
destructor Destroy; override;
procedure Close(CloseCode: Integer; CloseReason: AnsiString); override;
function WaitForConnect(Timeout: Cardinal): Boolean;
end;
TWebSocketServer = class;
{:Event procedural type to hook OnReceiveConnection events on server
every time new server connection is about to be created (client is connecting to server)
this event is called
properties are representing connection properties as defined in @link(TWebSocketServerConnection)
Protocol and Extension represents corresponding headers sent by client, as their out value
server must define what kind of protocol(s) and extension(s) server is supporting, if event
is not implemented, both values are considered as - (no value at all)
HttpResult represents the HTTP Result to be send in response, if connection is about to be
accepted, the value MUST BE 101, any other value meand that the client will be informed about the
Result (using the HTTP code meaning) and connection will be closed, if event is not implemented
101 is used as a default value
}
TWebSocketServerReceiveConnection = procedure(Server: TWebSocketServer;
Socket: TTCPCustomConnectionSocket;
Header: TStringList;
ResourceName, Host, Port, Origin, Cookie: AnsiString;
HttpResult: Integer;
Protocol, Extensions: AnsiString) of object;
TWebSocketServer = class(TCustomServer)
protected
{CreateServerConnection sync variables}
FNCSocket: TTCPCustomConnectionSocket;
FNCResourceName: AnsiString;
FNCHost: AnsiString;
FNCPort: AnsiString;
FNCOrigin: AnsiString;
FNCProtocol: AnsiString;
FNCExtensions: AnsiString;
FNCCookie: AnsiString;
FNCHeaders: AnsiString;
FNCResultHttp: Integer;
FOnReceiveConnection: TWebSocketServerReceiveConnection; protected
function CreateServerConnection(Socket: TTCPCustomConnectionSocket): TCustomConnection; override;
procedure DoSyncReceiveConnection;
procedure SyncReceiveConnection;
property Terminated;
{:This function defines what kind of TWebSocketServerConnection implementation should be used as
a connection object.
The servers default return value is TWebSocketServerConnection.
If new connection class based on TWebSocketServerConnection is implemented,
new server should be implemented as well with this method overloaded
properties are representing connection properties as defined in @link(TWebSocketServerConnection)
Protocol and Extension represents corresponding headers sent by client, as their out value
server must define what kind of protocol(s) and extension(s) server is supporting, if event
is not implemented, both values are cosidered as - (no value at all)
HttpResult represents the HTTP Result to be send in response, if connection is about to be
accepted, the value MUST BE 101, any other value meand that the client will be informed about the
Result (using the HTTP code meaning) and connection will be closed, if event is not implemented
101 is used as a default value
}
function GetWebSocketConnectionClass({%H-}Socket: TTCPCustomConnectionSocket;
{%H-}Header: TStringList;
{%H-}ResourceName, {%H-}Host, {%H-}Port, {%H-}Origin, {%H-}Cookie: AnsiString;
out {%H-}HttpResult: Integer;
var {%H-}Protocol, {%H-}Extensions: AnsiString): TWebSocketServerConnections; virtual;
public
{: WebSocket connection received }
property OnReceiveConnection: TWebSocketServerReceiveConnection read FOnReceiveConnection write FOnReceiveConnection;
{: close all connections
for parameters see connection Close method
}
procedure CloseAllConnections(CloseCode: Integer; Reason: AnsiString);
{:Temination procedure
This method should be called instead of Terminate to terminate thread,
it internally calls Terminate, but can be overloaded,
and can be used for data clean up
}
procedure TerminateThread; override;
{: Method to send binary data to all connected clients
see @link(TWebSocketServerConnection.SendBinary) for parameters description
}
procedure BroadcastBinary(Data: TStream; Flags: TWSFlags = [FIN]);
{: Method to send text data to all connected clients
see @link(TWebSocketServerConnection.SendText) for parameters description
}
procedure BroadcastText(Data: AnsiString; Flags: TWSFlags = [FIN]);
end;
implementation
uses
Math, synautil, synacode, synsock {$IFDEF Win32}, Windows{$ENDIF Win32},
synachar;
{$IFDEF Win32} {$O-} {$ENDIF Win32}
function HTTPCodeToText(HTTPCode: Integer): AnsiString;
begin
case HTTPCode of
100: Result := 'Continue';
101: Result := 'Switching Protocols';
200: Result := 'OK';
201: Result := 'Created';
202: Result := 'Accepted';
203: Result := 'Non-Authoritative Information';
204: Result := 'No Content';
205: Result := 'Reset Content';
206: Result := 'Partial Content';
300: Result := 'Multiple Choices';
301: Result := 'Moved Permanently';
302: Result := 'Found';
303: Result := 'See Other';
304: Result := 'Not Modified';
305: Result := 'Use Proxy';
307: Result := 'Temporary Redirect';
400: Result := 'Bad Request';
401: Result := 'Unauthorized';
402: Result := 'Payment Required';
403: Result := 'Forbidden';
404: Result := 'Not Found';
405: Result := 'Method Not Allowed';
406: Result := 'Not Acceptable';
407: Result := 'Proxy Authentication Required';
408: Result := 'Request Time-out';
409: Result := 'Conflict';
410: Result := 'Gone';
411: Result := 'Length Required';
412: Result := 'Precondition Failed';
413: Result := 'Request Entity Too Large';
414: Result := 'Request-URI Too Large';
415: Result := 'Unsupported Media Type';
416: Result := 'Requested range not satisfiable';
417: Result := 'Expectation Failed';
500: Result := 'Internal Server Error';
501: Result := 'Not Implemented';
502: Result := 'Bad Gateway';
503: Result := 'Service Unavailable';
504: Result := 'Gateway Time-out';
else
Result := 'unknown code: $code';
end;
end;
function ReadHttpHeaders(Socket: TTCPCustomConnectionSocket; out Data: AnsiString; Headers: TStrings): Boolean;
var
s, name: AnsiString;
begin
Data := '';
Headers.Clear;
Result := True;
repeat
Socket.MaxLineLength := 1024 * 1024; // not to attack memory on server
s := Socket.RecvString(30 * 1000); // not to hang up connection
if (Socket.LastError <> 0) then
begin
Result := False;
break;
end;
if (s = '') then
break;
if (Data = '') then
Data := s
else
begin
name := LowerCase(trim(SeparateLeft(s, ':')));
if (Headers.Values[name] = '') then
Headers.Values[name] := trim(SeparateRight(s, ':'))
else
Headers.Values[name] := Headers.Values[name] + ',' + trim(SeparateRight(s, ':'));
end;
until {IsTerminated} False;
Socket.MaxLineLength := 0;
end;
procedure ODS({%H-}Str: AnsiString); overload;
begin
{$IFDEF Win32}
OutputDebugString(pChar(FormatDateTime('yyyy-mm-dd hh:nn:ss', now) + ': ' + Str));
{$ENDIF Win32}
end;
procedure ODS({%H-}Str: AnsiString; {%H-}Data: array of const); overload;
begin
{$IFDEF Win32}
ODS(Format(Str, Data));
{$ENDIF Win32}
end;
{ TReadOnlyMemoryStream }
constructor TReadOnlyMemoryStream.Create(Memory: Pointer; Size: PtrInt);
begin
inherited Create;
SetPointer(Memory, Size);
end;
procedure TReadOnlyMemoryStream.ResetPointer(Memory: Pointer; Size: PtrInt);
begin
SetPointer(Memory, Size);
Position := 0;
end;
{ TWebSocketServer }
procedure TWebSocketServer.BroadcastBinary(Data: TStream; Flags: TWSFlags);
var
i: Integer;
begin
LockTermination;
for i := 0 to FConnections.Count - 1 do
begin
if (not TWebSocketServerConnection(FConnections[i]).IsTerminated) then
TWebSocketServerConnection(FConnections[i]).SendBinary(Data, Flags);
end;
UnLockTermination;
end;
procedure TWebSocketServer.BroadcastText(Data: AnsiString; Flags: TWSFlags);
var
i: Integer;
begin
LockTermination;
for i := 0 to FConnections.Count - 1 do
begin
if (not TWebSocketServerConnection(FConnections[i]).IsTerminated) then
TWebSocketServerConnection(FConnections[i]).SendText(Data, Flags);
end;
UnLockTermination;
end;
procedure TWebSocketServer.CloseAllConnections(CloseCode: Integer; Reason: AnsiString);
var
i: Integer;
begin
LockTermination;
//for i := 0 to FConnections.Count - 1 do
for i := FConnections.Count - 1 downto 0 do
begin
if (not TWebSocketServerConnection(FConnections[i]).IsTerminated) then
TWebSocketServerConnection(FConnections[i]).Close(CloseCode, Reason);// SendBinary(Data, IsFinal, aRes1, aRes2, aRes3);
end;
UnLockTermination;
end;
function TWebSocketServer.CreateServerConnection(Socket: TTCPCustomConnectionSocket): TCustomConnection;
var
headers, hrs: TStringList;
data: AnsiString;
s{, resName, host, port}, key, version{, origin, protocol, extensions, cookie}, tmpExtension, tmpWord, extensionKey, extensionValue: AnsiString;
iversion, vv, extCounter: Integer;
res: Boolean;
r: TWebSocketServerConnections;
begin
FNCSocket := Socket;
Result := inherited CreateServerConnection(Socket);
headers := TStringList.Create;
try
res := ReadHttpHeaders(Socket, data, headers);
if (res) then
begin
res := False;
try
//CHECK HTTP data
if ((Pos('GET ', Uppercase(data)) <> 0) and (Pos(' HTTP/1.1', Uppercase(data)) <> 0)) then
begin
FNCResourceName := SeparateRight(data, ' ');
FNCResourceName := SeparateLeft(FNCResourceName, ' ');
end
else Exit;
FNCResourceName := trim(FNCResourceName);
{
: AnsiString;
: AnsiString;
: AnsiString;
: AnsiString;
: AnsiString;
: AnsiString;
: AnsiString;
FNCHeaders: AnsiString;
}
//CHECK HOST AND PORT
s := headers.Values['host'];
if (s <> '') then
begin
FNCHost := trim(s);
FNCPort := SeparateRight(FNCHost, ':');
FNCHost := SeparateLeft(FNCHost, ':');
end;
FNCHost := trim(FNCHost);
FNCPort := trim(FNCPort);
if (FNCHost = '') then Exit;
//if (FNCPort <> '') and (FNCPort <> Self.port) then Exit;
{
if (Self.host <> '0.0.0.0') and (Self.Host <> '127.0.0.1') and
(Self.host <> 'localhost') and (FNCHost <> Self.host) then Exit;
}
//WEBSOCKET KEY
s := headers.Values['sec-websocket-key'];
if (s <> '') then
begin
if (Length(DecodeBase64(s)) = 16) then
begin
key := s;
end;
end;
if (key = '') then Exit;
key := trim(key);
//WEBSOCKET VERSION
s := headers.Values['sec-websocket-version'];
if (s <> '') then
begin
vv := StrToIntDef(s, -1);
if ((vv >= 7) and (vv <= 13)) then
begin
version := s;
end;
end;
if (version = '') then Exit;
version := trim(version);
iversion := StrToIntDef(version, 13);
if (LowerCase(headers.Values['upgrade']) <> LowerCase('websocket')) or (pos('upgrade', LowerCase(headers.Values['connection'])) = 0) then
Exit;
//COOKIES
FNCProtocol := '-';
tmpExtension := '-';
FNCCookie := '-';
FNCOrigin := '-';
if (iversion < 13) then
begin
if (headers.IndexOfName('sec-websocket-origin') > -1) then
FNCOrigin := trim(headers.Values['sec-websocket-origin']);
end
else begin
if (headers.IndexOfName('origin') > -1) then
FNCOrigin := trim(headers.Values['origin']);
end;
if (headers.IndexOfName('sec-websocket-protocol') > -1) then
FNCProtocol := trim(headers.Values['sec-websocket-protocol']);
if (headers.IndexOfName('sec-websocket-extensions') > -1) then
tmpExtension := trim(headers.Values['sec-websocket-extensions']);
if (headers.IndexOfName('cookie') > -1) then
FNCCookie := trim(headers.Values['cookie']);
FNCHeaders := trim(headers.text);
{
ODS(data);
ODS(FNCHeaders);
ODS('ResourceName: %s', [FNCResourceName]);
ODS('Host: %s', [FNCHost]);
ODS('Post: %s', [FNCPort]);
ODS('Key: %s', [key]);
ODS('Version: %s', [version]);
ODS('Origin: %s', [FNCOrigin]);
ODS('Protocol: %s', [FNCProtocol]);
ODS('Extensions: %s', [FNCExtensions]);
ODS('Cookie: %s', [FNCCookie]);
{}
// Account for client_max_window_bits, probably add more later on
for extCounter := 1 to WordCount(tmpExtension, [';']) do begin
tmpWord := ExtractWord(extCounter, tmpExtension, [' ', ';']);
extensionKey := ExtractWord(1, tmpWord, ['=']);
extensionValue := ExtractWord(2, tmpWord, ['=']);
if Not IsWordPresent(extensionKey, FNCExtensions, [' ', ';', '=']) then begin
FNCExtensions := FNCExtensions + extensionKey;
if (extensionKey = 'client_max_window_bits') and (length(extensionValue) = 0) then
FNCExtensions := FNCExtensions + '=15;'
else begin
if length(extensionValue) > 0 then
FNCExtensions := FNCExtensions + '=' + extensionValue + ';'
else
FNCExtensions := FNCExtensions + ';'
end;
end;
end;
if FNCExtensions[length(FNCExtensions)] = ';' then
Delete(FNCExtensions, Length(FNCExtensions), 1);
res := True;
finally
if (res) then
begin
FNCResultHttp := 101;
hrs := TStringList.Create;
hrs.Assign(headers);
r := GetWebSocketConnectionClass(
FNCSocket,
hrs,
FNCResourceName, FNCHost, FNCPort, FNCOrigin, FNCCookie,
FNCResultHttp, FNCProtocol, FNCExtensions
);
if (Assigned(r)) then
begin
DoSyncReceiveConnection;
if (FNCResultHttp <> 101) then //HTTP ERROR FALLBACK
begin
Socket.SendString(Format('HTTP/1.1 %d %s'+#13#10, [FNCResultHttp, HTTPCodeToText(FNCResultHttp)]));
Socket.SendString(Format('%d %s'+#13#10#13#10, [FNCResultHttp, HTTPCodeToText(FNCResultHttp)]));
end
else
begin
key := EncodeBase64(SHA1(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'));
s := 'HTTP/1.1 101 Switching Protocols' + #13#10;
s := s + 'Upgrade: websocket' + #13#10;
s := s + 'Connection: Upgrade' + #13#10;
s := s + 'Sec-WebSocket-Accept: ' + key + #13#10;
if (FNCProtocol <> '-') then
begin
s := s + 'Sec-WebSocket-Protocol: ' + FNCProtocol + #13#10;
end;
if (FNCExtensions <> '-') then
begin
s := s + 'Sec-WebSocket-Extensions: ' + FNCExtensions + #13#10;
end;
s := s + #13#10;
Socket.SendString(s);
if (Socket.LastError = 0) then
begin
Result := r.Create(Socket);
TWebSocketCustomConnection(Result).fCookie := FNCCookie;
TWebSocketCustomConnection(Result).fVersion := StrToInt(version);
TWebSocketCustomConnection(Result).fProtocol := FNCProtocol;
TWebSocketCustomConnection(Result).fResourceName := FNCResourceName;
TWebSocketCustomConnection(Result).fOrigin := FNCOrigin;
TWebSocketCustomConnection(Result).fExtension := FNCExtensions;
TWebSocketCustomConnection(Result).fPort := FNCPort;
TWebSocketCustomConnection(Result).fHost := FNCHost;
TWebSocketCustomConnection(Result).fHeaders.Assign(headers);
TWebSocketCustomConnection(Result).fHandshake := True;
end;
end;
end;
hrs.Free;
end;
end;
end;
finally
headers.Free;
end;
end;
procedure TWebSocketServer.DoSyncReceiveConnection;
begin
if (Assigned(FOnReceiveConnection)) then
Synchronize(SyncReceiveConnection)
end;
function TWebSocketServer.GetWebSocketConnectionClass(Socket: TTCPCustomConnectionSocket;
Header: TStringList;
ResourceName, Host, Port, Origin, Cookie: AnsiString;
out HttpResult: Integer;
var Protocol, Extensions: AnsiString): TWebSocketServerConnections;
begin
Result := TWebSocketServerConnection;
end;
procedure TWebSocketServer.SyncReceiveConnection;
var
h: TStringList;
begin
if (Assigned(FOnReceiveConnection)) then
begin
h := TStringList.Create;
try
h.Text := FNCHeaders;
FOnReceiveConnection(Self, FNCSocket, h, FNCResourceName,
FNCHost, FNCPort, FNCOrigin, FNCCookie, FNCResultHttp, FNCProtocol, FNCExtensions);
finally
h.Free;
end;
end;
end;
procedure TWebSocketServer.TerminateThread;
begin
if Terminated then Exit;
FOnReceiveConnection := nil;
inherited;
end;
{ TWebSocketCustomConnection }
function TWebSocketCustomConnection.CanReceiveOrSend: Boolean;
begin
Result := ValidConnection and not (FClosedByMe or FClosedByPeer) and FHandshake;
end;
function TWebSocketCustomConnection.SendData(Flags: TWSFlags; OpCode: Byte; Data: Pointer; DataSize: Integer): Integer;
var
ms : TReadOnlyMemoryStream;
begin
ms := TReadOnlyMemoryStream.Create(Data, DataSize);
try
Result := SendData(Flags, OpCode, ms);
finally
ms.Free;
end;
end;
constructor TWebSocketCustomConnection.Create(Socket: TTCPCustomConnectionSocket);
begin
FHeaders := TStringList.Create;
FCookie := '';
FVersion := 0;
FProtocol := '-';
FResourceName := '';
FOrigin := '';
FExtension := '-';
FPort := '';
FHost := '';
FClosedByMe := False;
FClosedByPeer := False;
FMasking := False;
FClosingByPeer := False;
FRequireMasking := False;
FFullDataProcess := False;
FFullDataStream := TMemoryStream.Create;
FSendCriticalSection := TCriticalSection.Create;
FHandshake := False;
inherited;
end;
destructor TWebSocketCustomConnection.Destroy;
begin
inherited;
FSendCriticalSection.Free;
FFullDataStream.Free;
FHeaders.Free;
end;
procedure TWebSocketCustomConnection.DoOpen;
begin
if Assigned(FOnOpen) then
FOnOpen(Self);
end;