forked from chronoxor/NetCoreServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocket.cs
More file actions
546 lines (481 loc) · 20.2 KB
/
Copy pathWebSocket.cs
File metadata and controls
546 lines (481 loc) · 20.2 KB
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
using System;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Generic;
namespace NetCoreServer
{
/// <summary>
/// WebSocket utility class
/// </summary>
public class WebSocket : IWebSocket
{
private readonly IWebSocket _wsHandler;
public WebSocket(IWebSocket wsHandler) { _wsHandler = wsHandler; ClearWsBuffers(); }
/// <summary>
/// Final frame
/// </summary>
public const byte WS_FIN = 0x80;
/// <summary>
/// Text frame
/// </summary>
public const byte WS_TEXT = 0x01;
/// <summary>
/// Binary frame
/// </summary>
public const byte WS_BINARY = 0x02;
/// <summary>
/// Close frame
/// </summary>
public const byte WS_CLOSE = 0x08;
/// <summary>
/// Ping frame
/// </summary>
public const byte WS_PING = 0x09;
/// <summary>
/// Pong frame
/// </summary>
public const byte WS_PONG = 0x0A;
/// <summary>
/// Perform WebSocket client upgrade
/// </summary>
/// <param name="response">WebSocket upgrade HTTP response</param>
/// <param name="id">WebSocket client Id</param>
/// <returns>'true' if the WebSocket was successfully upgrade, 'false' if the WebSocket was not upgrade</returns>
public bool PerformClientUpgrade(HttpResponse response, Guid id)
{
if (response.Status != 101)
return false;
bool error = false;
bool accept = false;
bool connection = false;
bool upgrade = false;
// Validate WebSocket handshake headers
for (int i = 0; i < response.Headers; ++i)
{
var header = response.Header(i);
var key = header.Item1;
var value = header.Item2;
if (key == "Connection")
{
if (value != "Upgrade")
{
error = true;
_wsHandler.OnWsError("Invalid WebSocket handshaked response: 'Connection' header value must be 'Upgrade'");
break;
}
connection = true;
}
else if (key == "Upgrade")
{
if (value != "websocket")
{
error = true;
_wsHandler.OnWsError("Invalid WebSocket handshaked response: 'Upgrade' header value must be 'websocket'");
break;
}
upgrade = true;
}
else if (key == "Sec-WebSocket-Accept")
{
// Calculate the original WebSocket hash
string wskey = Convert.ToBase64String(Encoding.UTF8.GetBytes(id.ToString())) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
string wshash;
using (SHA1Managed sha1 = new SHA1Managed())
{
wshash = Encoding.UTF8.GetString(sha1.ComputeHash(Encoding.UTF8.GetBytes(wskey)));
}
// Get the received WebSocket hash
wskey = Encoding.UTF8.GetString(Convert.FromBase64String(value));
// Compare original and received hashes
if (string.Compare(wskey, wshash, StringComparison.InvariantCulture) != 0)
{
error = true;
_wsHandler.OnWsError("Invalid WebSocket handshaked response: 'Sec-WebSocket-Accept' value validation failed");
break;
}
accept = true;
}
}
// Failed to perform WebSocket handshake
if (!accept || !connection || !upgrade)
{
if (!error)
_wsHandler.OnWsError("Invalid WebSocket response");
return false;
}
// WebSocket successfully handshaked!
WsHandshaked = true;
Random rnd = new Random();
rnd.NextBytes(WsSendMask);
_wsHandler.OnWsConnected(response);
return true;
}
/// <summary>
/// Perform WebSocket server upgrade
/// </summary>
/// <param name="request">WebSocket upgrade HTTP request</param>
/// <param name="response">WebSocket upgrade HTTP response</param>
/// <returns>'true' if the WebSocket was successfully upgrade, 'false' if the WebSocket was not upgrade</returns>
public bool PerformServerUpgrade(HttpRequest request, HttpResponse response)
{
if (request.Method != "GET")
return false;
bool error = false;
bool connection = false;
bool upgrade = false;
bool wsKey = false;
bool wsVersion = false;
string accept = "";
// Validate WebSocket handshake headers
for (int i = 0; i < request.Headers; ++i)
{
var header = request.Header(i);
var key = header.Item1;
var value = header.Item2;
if (key == "Connection")
{
if ((value != "Upgrade") && (value != "keep-alive, Upgrade"))
{
error = true;
response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Connection' header value must be 'Upgrade' or 'keep-alive, Upgrade'", 400);
break;
}
connection = true;
}
else if (key == "Upgrade")
{
if (value != "websocket")
{
error = true;
response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Upgrade' header value must be 'websocket'", 400);
break;
}
upgrade = true;
}
else if (key == "Sec-WebSocket-Key")
{
if (string.IsNullOrEmpty(value))
{
error = true;
response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Sec-WebSocket-Key' header value must be non empty", 400);
break;
}
// Calculate the original WebSocket hash
string wskey = value + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
byte[] wshash;
using (SHA1Managed sha1 = new SHA1Managed())
{
wshash = sha1.ComputeHash(Encoding.UTF8.GetBytes(wskey));
}
accept = Convert.ToBase64String(wshash);
wsKey = true;
}
else if (key == "Sec-WebSocket-Version")
{
if (value != "13")
{
error = true;
response.MakeErrorResponse("Invalid WebSocket handshaked request: 'Sec-WebSocket-Version' header value must be '13'", 400);
break;
}
wsVersion = true;
}
}
// Filter out non WebSocket handshake requests
if (!connection && !upgrade && !wsKey && !wsVersion)
return false;
// Failed to perform WebSocket handshake
if (!connection || !upgrade || !wsKey || !wsVersion)
{
if (!error)
response.MakeErrorResponse("Invalid WebSocket response", 400);
_wsHandler.SendResponse(response);
return false;
}
// Prepare WebSocket upgrade success response
response.Clear();
response.SetBegin(101);
response.SetHeader("Connection", "Upgrade");
response.SetHeader("Upgrade", "websocket");
response.SetHeader("Sec-WebSocket-Accept", accept);
response.SetBody();
// Validate WebSocket upgrade request and response
if (!_wsHandler.OnWsConnecting(request, response))
return false;
// Send WebSocket upgrade response
_wsHandler.SendResponse(response);
// WebSocket successfully handshaked!
WsHandshaked = true;
Array.Fill(WsSendMask, (byte)0);
_wsHandler.OnWsConnected(request);
return true;
}
/// <summary>
/// Prepare WebSocket send frame
/// </summary>
/// <param name="opcode">WebSocket opcode</param>
/// <param name="mask">WebSocket mask</param>
/// <param name="buffer">Buffer to send</param>
/// <param name="offset">Buffer offset</param>
/// <param name="size">Buffer size</param>
/// <param name="status">WebSocket status (default is 0)</param>
public void PrepareSendFrame(byte opcode, bool mask, byte[] buffer, long offset, long size, int status = 0)
{
// Clear the previous WebSocket send buffer
WsSendBuffer.Clear();
// Append WebSocket frame opcode
WsSendBuffer.Add(opcode);
// Append WebSocket frame size
if (size <= 125)
WsSendBuffer.Add((byte)(((int)size & 0xFF) | (mask ? 0x80 : 0)));
else if (size <= 65535)
{
WsSendBuffer.Add((byte)(126 | (mask ? 0x80 : 0)));
WsSendBuffer.Add((byte)((size >> 8) & 0xFF));
WsSendBuffer.Add((byte)(size & 0xFF));
}
else
{
WsSendBuffer.Add((byte)(127 | (mask ? 0x80 : 0)));
for (int i = 7; i >= 0; --i)
WsSendBuffer.Add((byte)((size >> (8 * i)) & 0xFF));
}
if (mask)
{
// Append WebSocket frame mask
WsSendBuffer.Add(WsSendMask[0]);
WsSendBuffer.Add(WsSendMask[1]);
WsSendBuffer.Add(WsSendMask[2]);
WsSendBuffer.Add(WsSendMask[3]);
}
// Resize WebSocket frame buffer
int bufferOffset = WsSendBuffer.Count;
WsSendBuffer.AddRange(new byte[size]);
// Mask WebSocket frame content
for (int i = 0; i < size; ++i)
WsSendBuffer[bufferOffset + i] = (byte) (buffer[offset + i] ^ WsSendMask[i % 4]);
}
/// <summary>
/// Prepare WebSocket send frame
/// </summary>
/// <param name="buffer">Buffer to send</param>
/// <param name="offset">Buffer offset</param>
/// <param name="size">Buffer size</param>
public void PrepareReceiveFrame(byte[] buffer, long offset, long size)
{
lock (WsReceiveLock)
{
var index = 0;
// Clear received data after WebSocket frame was processed
if (WsReceived)
{
WsReceived = false;
WsHeaderSize = 0;
WsPayloadSize = 0;
WsReceiveBuffer.Clear();
Array.Clear(WsReceiveMask, 0, WsReceiveMask.Length);
}
while (size > 0)
{
// Clear received data after WebSocket frame was processed
if (WsReceived)
{
WsReceived = false;
WsHeaderSize = 0;
WsPayloadSize = 0;
WsReceiveBuffer.Clear();
Array.Clear(WsReceiveMask, 0, WsReceiveMask.Length);
}
// Prepare WebSocket frame opcode and mask flag
if (WsReceiveBuffer.Count < 2)
{
for (int i = 0; i < 2; ++i, ++index, --size)
{
if (size == 0)
return;
WsReceiveBuffer.Add(buffer[offset + index]);
}
}
byte opcode = (byte) (WsReceiveBuffer[0] & 0x0F);
bool fin = ((WsReceiveBuffer[0] >> 7) & 0x01) != 0;
bool mask = ((WsReceiveBuffer[1] >> 7) & 0x01) != 0;
int payload = WsReceiveBuffer[1] & (~0x80);
// Prepare WebSocket frame size
if (payload <= 125)
{
WsHeaderSize = 2 + (mask ? 4 : 0);
WsPayloadSize = payload;
WsReceiveBuffer.Capacity = WsHeaderSize + WsPayloadSize;
}
else if (payload == 126)
{
if (WsReceiveBuffer.Count < 4)
{
for (int i = 0; i < 2; ++i, ++index, --size)
{
if (size == 0)
return;
WsReceiveBuffer.Add(buffer[offset + index]);
}
}
payload = ((WsReceiveBuffer[2] << 8) | (WsReceiveBuffer[3] << 0));
WsHeaderSize = 4 + (mask ? 4 : 0);
WsPayloadSize = payload;
WsReceiveBuffer.Capacity = WsHeaderSize + WsPayloadSize;
}
else if (payload == 127)
{
if (WsReceiveBuffer.Count < 10)
{
for (int i = 0; i < 8; ++i, ++index, --size)
{
if (size == 0)
return;
WsReceiveBuffer.Add(buffer[offset + index]);
}
}
payload = ((WsReceiveBuffer[2] << 56) | (WsReceiveBuffer[3] << 48) | (WsReceiveBuffer[4] << 40) | (WsReceiveBuffer[5] << 32) | (WsReceiveBuffer[6] << 24) | (WsReceiveBuffer[7] << 16) | (WsReceiveBuffer[8] << 8) | (WsReceiveBuffer[9] << 0));
WsHeaderSize = 10 + (mask ? 4 : 0);
WsPayloadSize = payload;
WsReceiveBuffer.Capacity = WsHeaderSize + WsPayloadSize;
}
// Prepare WebSocket frame mask
if (mask)
{
if (WsReceiveBuffer.Count < WsHeaderSize)
{
for (int i = 0; i < 4; ++i, ++index, --size)
{
if (size == 0)
return;
WsReceiveBuffer.Add(buffer[offset + index]);
WsReceiveMask[i] = buffer[offset + index];
}
}
}
int total = WsHeaderSize + WsPayloadSize;
int length = Math.Min(total - WsReceiveBuffer.Count, (int)size);
// Prepare WebSocket frame payload
WsReceiveBuffer.AddRange(buffer[((int)offset + index)..((int)offset + index + length)]);
index += length;
size -= length;
// Process WebSocket frame
if (WsReceiveBuffer.Count == total)
{
int bufferOffset = WsHeaderSize;
// Unmask WebSocket frame content
if (mask)
for (int i = 0; i < WsPayloadSize; ++i)
WsReceiveBuffer[bufferOffset + i] ^= WsReceiveMask[i % 4];
WsReceived = true;
if ((opcode & WS_PING) == WS_PING)
{
// Call the WebSocket ping handler
_wsHandler.OnWsPing(WsReceiveBuffer.ToArray(), bufferOffset, WsPayloadSize);
}
else if ((opcode & WS_PONG) == WS_PONG)
{
// Call the WebSocket pong handler
_wsHandler.OnWsPong(WsReceiveBuffer.ToArray(), bufferOffset, WsPayloadSize);
}
else if ((opcode & WS_CLOSE) == WS_CLOSE)
{
// Call the WebSocket close handler
_wsHandler.OnWsClose(WsReceiveBuffer.ToArray(), bufferOffset, WsPayloadSize);
}
else if (((opcode & WS_TEXT) == WS_TEXT) || ((opcode & WS_BINARY) == WS_BINARY))
{
// Call the WebSocket received handler
_wsHandler.OnWsReceived(WsReceiveBuffer.ToArray(), bufferOffset, WsPayloadSize);
}
}
}
}
}
/// <summary>
/// Required WebSocket receive frame size
/// </summary>
public int RequiredReceiveFrameSize()
{
lock (WsReceiveLock)
{
if (WsReceived)
return 0;
// Required WebSocket frame opcode and mask flag
if (WsReceiveBuffer.Count < 2)
return 2 - WsReceiveBuffer.Count;
bool mask = ((WsReceiveBuffer[1] >> 7) & 0x01) != 0;
int payload = WsReceiveBuffer[1] & (~0x80);
// Required WebSocket frame size
if ((payload == 126) && (WsReceiveBuffer.Count < 4))
return 4 - WsReceiveBuffer.Count;
if ((payload == 127) && (WsReceiveBuffer.Count < 10))
return 10 - WsReceiveBuffer.Count;
// Required WebSocket frame mask
if ((mask) && (WsReceiveBuffer.Count < WsHeaderSize))
return WsHeaderSize - WsReceiveBuffer.Count;
// Required WebSocket frame payload
return WsHeaderSize + WsPayloadSize - WsReceiveBuffer.Count;
}
}
/// <summary>
/// Clear WebSocket send/receive buffers
/// </summary>
public void ClearWsBuffers()
{
lock (WsReceiveLock)
{
WsReceived = false;
WsHeaderSize = 0;
WsPayloadSize = 0;
WsReceiveBuffer.Clear();
Array.Clear(WsReceiveMask, 0, WsReceiveMask.Length);
}
lock (WsSendLock)
{
WsSendBuffer.Clear();
Array.Clear(WsSendMask, 0, WsSendMask.Length);
}
}
/// <summary>
/// Handshaked flag
/// </summary>
internal bool WsHandshaked;
/// <summary>
/// Received frame flag
/// </summary>
internal bool WsReceived;
/// <summary>
/// Received frame header size
/// </summary>
internal int WsHeaderSize;
/// <summary>
/// Received frame payload size
/// </summary>
internal int WsPayloadSize;
/// <summary>
/// Receive buffer lock
/// </summary>
internal readonly object WsReceiveLock = new object();
/// <summary>
/// Receive buffer
/// </summary>
internal readonly List<byte> WsReceiveBuffer = new List<byte>();
/// <summary>
/// Receive mask
/// </summary>
internal readonly byte[] WsReceiveMask = new byte[4];
/// <summary>
/// Send buffer lock
/// </summary>
internal readonly object WsSendLock = new object();
/// <summary>
/// Send buffer
/// </summary>
internal readonly List<byte> WsSendBuffer = new List<byte>();
/// <summary>
/// Send mask
/// </summary>
internal readonly byte[] WsSendMask = new byte[4];
}
}