-
Notifications
You must be signed in to change notification settings - Fork 1
/
corewebsocket.pas
326 lines (309 loc) · 10.3 KB
/
corewebsocket.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
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
unit corewebsocket;
interface
uses
corenetwork, sysutils;
//{$DEFINE WEBSOCKET_VERBOSE}
type
TWebSocket = class(TNetworkSocket)
protected
type
TWebSocketState = (wsRequestLine,
wsFieldTrailingEnd, wsFieldEnd, wsFieldNameStart, wsFieldName, wsFieldSeparator, wsFieldValue, wsHandshakeEnd,
wsFrameByte1, wsFrameByte2, wsFrameExtendedLength16, wsFrameExtendedLength64, wsFrameMask, wsFramePayload,
wsError);
TWebSocketFrameType = (ftContinuation := $00, ftText := $01, ftBinary := $02, ftClose := $08, ftPing := $09, ftPong := $0A);
TWebSocketFrame = record
FrameType: TWebSocketFrameType;
FinalFrame: Boolean;
MaskKey: array[0..3] of Byte;
Length, Index: Cardinal;
Data: RawByteString;
end;
var
FState: TWebSocketState;
FCanWriteFrames: Boolean;
FCurrentFrame: TWebSocketFrame;
FBufferType: TWebSocketFrameType;
FBuffer: RawByteString;
FCurrentFieldName, FCurrentFieldValue, FHandshakeKey: RawByteString;
function InternalRead(Data: array of Byte): Boolean; override;
procedure CheckField(); virtual;
procedure Handshake(); virtual;
function ProcessFrame(): Boolean; // return false if frame is bogus and we should disconnect
// API for subclasses:
procedure HandleMessage(s: UTF8String); virtual; abstract;
procedure WriteLength(const Length: Int64);
public
constructor Create(Listener: TListenerSocket);
procedure WriteFrame(const s: UTF8String); {$IFDEF DEBUG} virtual; {$ENDIF} overload; // UTF-8 frame
procedure WriteFrame(const Buf; const Length: Cardinal); {$IFDEF DEBUG} virtual; {$ENDIF} overload; // binary frame
property Ready: Boolean read FCanWriteFrames;
end;
implementation
uses
sha1, base64encoder, utf8;
constructor TWebSocket.Create(Listener: TListenerSocket);
begin
inherited Create(Listener);
FState := wsRequestLine;
end;
function TWebSocket.InternalRead(Data: array of Byte): Boolean;
var
Index: Cardinal;
c: Byte;
begin
Result := True;
Assert(Length(Data) > 0);
for Index := 0 to Length(Data)-1 do {BOGUS Warning: Type size mismatch, possible loss of data / range check error}
begin
c := Data[Index];
case FState of
wsRequestLine, wsFieldTrailingEnd:
case c of
$0D: FState := wsFieldEnd;
end;
wsFieldEnd:
case c of
$0A: FState := wsFieldNameStart;
else
FState := wsError;
Result := False;
Exit;
end;
wsFieldNameStart:
case c of
$0D: FState := wsHandshakeEnd;
Ord(':'): FState := wsFieldTrailingEnd;
else
FCurrentFieldName := Chr(c);
FState := wsFieldName;
end;
wsFieldName:
case c of
Ord(':'): FState := wsFieldSeparator;
$0D: FState := wsFieldEnd;
else
FCurrentFieldName := FCurrentFieldName + Chr(c);
end;
wsFieldSeparator:
case c of
Ord(' '): begin FState := wsFieldValue; FCurrentFieldValue := ''; end;
$0D: FState := wsFieldEnd;
else
FState := wsError;
Result := False;
Exit;
end;
wsFieldValue:
case c of
$0D: begin FState := wsFieldEnd; CheckField(); end;
else
FCurrentFieldValue := FCurrentFieldValue + Chr(c);
end;
wsHandshakeEnd:
case c of
$0A: begin FState := wsFrameByte1; Handshake(); end;
else
FState := wsError;
Result := False;
Exit;
end;
wsFrameByte1:
begin
FCurrentFrame.FrameType := TWebSocketFrameType(c and $0F);
// assume bits 5, 6, and 7 are zero (extension bits, we don't negotiate any extensions)
FCurrentFrame.FinalFrame := (c and $80) = $80;
FState := wsFrameByte2;
end;
wsFrameByte2:
begin
FCurrentFrame.Length := Cardinal(Byte(c and $7F));
// assume bit 8 is set (masking bit, client must mask)
FCurrentFrame.Index := 0;
case (FCurrentFrame.Length) of
0..125: FState := wsFrameMask;
126: begin FCurrentFrame.Length := 0; FCurrentFrame.Index := 2; FState := wsFrameExtendedLength16; end;
127: begin FCurrentFrame.Length := 0; FCurrentFrame.Index := 8; FState := wsFrameExtendedLength64; end;
else Assert(False);
end;
end;
wsFrameExtendedLength16, wsFrameExtendedLength64:
begin
Dec(FCurrentFrame.Index);
FCurrentFrame.Length := FCurrentFrame.Length or (c shl (FCurrentFrame.Index * 8));
if (FCurrentFrame.Index = 0) then
FState := wsFrameMask;
end;
wsFrameMask:
begin
FCurrentFrame.MaskKey[FCurrentFrame.Index] := c;
Inc(FCurrentFrame.Index);
if (FCurrentFrame.Index = 4) then
begin
if (FCurrentFrame.Length > 16384) then
begin
FState := wsError;
Result := False;
Exit;
end
else
begin
SetLength(FCurrentFrame.Data, FCurrentFrame.Length);
if (FCurrentFrame.Length > 0) then
begin
FCurrentFrame.Index := 1;
FState := wsFramePayload;
end
else
begin
if (not ProcessFrame()) then
begin
FState := wsError;
Result := False;
exit;
end;
FState := wsFrameByte1;
end;
end;
end;
end;
wsFramePayload:
begin
FCurrentFrame.Data[FCurrentFrame.Index] := Chr(c xor FCurrentFrame.MaskKey[(FCurrentFrame.Index-1) mod 4]);
Inc(FCurrentFrame.Index);
if (FCurrentFrame.Index > FCurrentFrame.Length) then
begin
if (not ProcessFrame()) then
begin
FState := wsError;
Result := False;
exit;
end;
FState := wsFrameByte1;
end;
end;
else Assert(False);
end;
end;
end;
procedure TWebSocket.CheckField();
begin
if (UpperCase(FCurrentFieldName) = 'SEC-WEBSOCKET-KEY') then
FHandshakeKey := FCurrentFieldValue
{ ... Host, Origin, Sec-WebSocket-Protocol, ... }
end;
procedure TWebSocket.Handshake();
var
Challenge, Response: RawByteString;
Digest: TSHA1Digest;
Index: Cardinal;
begin
Challenge := FHandshakeKey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
Digest := SHA1String(Challenge);
Response := '';
for Index := Low(Digest) to High(Digest) do
Response := Response + Chr(Digest[Index]);
Response := Base64(Response);
Write('HTTP/1.1 101 WebSocket Protocol Handshake'#13#10);
Write('Upgrade: WebSocket'#13#10);
Write('Connection: Upgrade'#13#10);
Write('Sec-WebSocket-Accept: ' + Response + #13#10);
Write(#13#10);
FCanWriteFrames := True;
end;
function TWebSocket.ProcessFrame(): Boolean;
function HandleTextMessage(const CompleteData: RawByteString): Boolean;
begin
FBuffer := '';
if (not IsValidUTF8(CompleteData)) then
begin
Result := False;
exit;
end;
Result := True;
HandleMessage(CompleteData);
end;
begin
Result := True;
case (FCurrentFrame.FrameType) of {BOGUS Warning: Case statement does not handle all possible cases}
ftContinuation:
begin
FBuffer := FBuffer + FCurrentFrame.Data;
if ((FCurrentFrame.FinalFrame) and (FBufferType = ftText)) then
Result := HandleTextMessage(FBuffer);
end;
ftText:
begin
FBuffer := FCurrentFrame.Data;
FBufferType := ftText;
if (FCurrentFrame.FinalFrame) then
Result := HandleTextMessage(FBuffer);
end;
ftBinary:
begin
// we don't support binary frames, just ignore it
FBuffer := '';
FBufferType := ftBinary;
end;
ftClose:
begin
// we don't support this per spec, just close the connection
{$IFDEF WEBSOCKET_NETWORK} Writeln('Received close frame.'); {$ENDIF}
Disconnect();
end;
ftPing:
begin
{$IFDEF WEBSOCKET_NETWORK} Writeln('Received ping frame.'); {$ENDIF}
Write([$8A, $00]); // pong, no data
// We don't echo the application data (this violates the spec),
// because we don't want to send attacker-controlled bytes.
end;
ftPong:
begin
{$IFDEF WEBSOCKET_NETWORK} Writeln('Received pong frame.'); {$ENDIF}
// nothing to do for pong frames
end;
end;
end;
procedure TWebSocket.WriteLength(const Length: Int64);
begin
if (Length > 65535) then
Write([127,
Byte((Length shr (8*7)) and $FF),
Byte((Length shr (8*6)) and $FF),
Byte((Length shr (8*5)) and $FF),
Byte((Length shr (8*4)) and $FF),
Byte((Length shr (8*3)) and $FF),
Byte((Length shr (8*2)) and $FF),
Byte((Length shr (8*1)) and $FF),
Byte((Length ) and $FF)])
else // 126..65535
if (Length >= 126) then
Write([126,
Byte((Length shr (8*1)) and $FF),
Byte((Length ) and $FF)])
else // 0..126
Write([Byte(Length)]);
end;
procedure TWebSocket.WriteFrame(const s: UTF8String);
begin
{$IFDEF WEBSOCKET_VERBOSE} Writeln('Sending: ', s); {$ENDIF}
Assert(IsValidUTF8(s));
Assert(FCanWriteFrames);
Write([$81]); // unfragmented text frame
WriteLength(Length(s)); // $R-
if (Length(s) > 0) then
Write(s);
end;
procedure TWebSocket.WriteFrame(const Buf; const Length: Cardinal);
begin
{$IFDEF WEBSOCKET_VERBOSE} Writeln('Sending ', Length, ' bytes'); {$ENDIF}
Assert(FCanWriteFrames);
Write([$82]); // unfragmented binary frame
WriteLength(Length);
if (Length > 0) then
Write(@Buf, Length);
end;
end.