-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebSocketSession.cs
337 lines (282 loc) · 12.4 KB
/
WebSocketSession.cs
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
// Copyright 2019 Wildbook
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
public class WebSocketSession : IDisposable
{
private static readonly Random Random = new Random();
private TcpClient Client { get; }
private Stream ClientStream { get; }
public string Id { get; }
public bool IsMasking { get; private set; }
public event EventHandler<WebSocketSession> HandshakeCompleted;
public event EventHandler<WebSocketSession> Disconnected;
public event EventHandler<Exception> Error;
public event EventHandler<byte[]> AnyMessageReceived;
public event EventHandler<string> TextMessageReceived;
public event EventHandler<byte[]> BinaryMessageReceived;
public WebSocketSession(TcpClient client)
{
Client = client;
ClientStream = client.GetStream();
Id = Guid.NewGuid().ToString();
}
/// <summary>
/// Internal, do not use :)
/// </summary>
internal void Start()
{
ThreadPool.QueueUserWorkItem(_ =>
{
if (!DoHandshake())
{
Error?.Invoke(this, new Exception("Handshake Failed."));
Disconnected?.Invoke(this, this);
return;
}
HandshakeCompleted?.Invoke(this, this);
StartMessageLoop();
});
}
private void StartMessageLoop()
{
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
MessageLoop();
}
catch (Exception e)
{
Error?.Invoke(this, e);
}
finally
{
Disconnected?.Invoke(this, this);
}
});
}
private bool DoHandshake()
{
while (Client.Available == 0 && Client.Connected) { }
if (!Client.Connected) return false;
byte[] handshake;
using (var handshakeBuffer = new MemoryStream())
{
while (Client.Available > 0)
{
var buffer = new byte[Client.Available];
ClientStream.Read(buffer, 0, buffer.Length);
handshakeBuffer.Write(buffer, 0, buffer.Length);
}
handshake = handshakeBuffer.ToArray();
}
if (!Encoding.UTF8.GetString(handshake).StartsWith("GET")) return false;
var response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new Regex("Sec-WebSocket-Key: (.*)").Match(Encoding.UTF8.GetString(handshake)).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + Environment.NewLine
+ Environment.NewLine);
ClientStream.Write(response, 0, response.Length);
return true;
}
private void MessageLoop()
{
var session = this;
var client = session.Client;
var stream = session.ClientStream;
var packet = new List<byte>();
var messageOpcode = 0x0;
using (var messageBuffer = new MemoryStream())
while (client.Connected)
{
packet.Clear();
var ab = client.Available;
if (ab == 0) continue;
packet.Add((byte)stream.ReadByte());
var fin = (packet[0] & (1 << 7)) != 0;
var rsv1 = (packet[0] & (1 << 6)) != 0;
var rsv2 = (packet[0] & (1 << 5)) != 0;
var rsv3 = (packet[0] & (1 << 4)) != 0;
// Must error if is set.
//if (rsv1 || rsv2 || rsv3)
// return;
var opcode = packet[0] & ((1 << 4) - 1);
switch (opcode)
{
case 0x0: // Continuation Frame
break;
case 0x1: // Text
case 0x2: // Binary
case 0x8: // Connection Close
messageOpcode = opcode;
break;
case 0x9:
continue; // Ping
case 0xA:
continue; // Pong
default:
continue; // Reserved
}
packet.Add((byte)stream.ReadByte());
var masked = IsMasking = (packet[1] & (1 << 7)) != 0;
var pseudoLength = packet[1] - (masked ? 128 : 0);
ulong actualLength = 0;
if (pseudoLength > 0 && pseudoLength < 125) actualLength = (ulong)pseudoLength;
else if (pseudoLength == 126)
{
var length = new byte[2];
stream.Read(length, 0, length.Length);
packet.AddRange(length);
Array.Reverse(length);
actualLength = BitConverter.ToUInt16(length, 0);
}
else if (pseudoLength == 127)
{
var length = new byte[8];
stream.Read(length, 0, length.Length);
packet.AddRange(length);
Array.Reverse(length);
actualLength = BitConverter.ToUInt64(length, 0);
}
var mask = new byte[4];
if (masked)
{
stream.Read(mask, 0, mask.Length);
packet.AddRange(mask);
}
if (actualLength > 0)
{
var data = new byte[actualLength];
stream.Read(data, 0, data.Length);
packet.AddRange(data);
if (masked)
data = ApplyMask(data, mask);
messageBuffer.Write(data, 0, data.Length);
}
Console.WriteLine($@"RECV: {BitConverter.ToString(packet.ToArray())}");
if (!fin) continue;
var message = messageBuffer.ToArray();
switch (messageOpcode)
{
case 0x1:
AnyMessageReceived?.Invoke(session, message);
TextMessageReceived?.Invoke(session, Encoding.UTF8.GetString(message));
break;
case 0x2:
AnyMessageReceived?.Invoke(session, message);
BinaryMessageReceived?.Invoke(session, message);
break;
case 0x8:
Close();
break;
default:
throw new Exception("Invalid opcode: " + messageOpcode);
}
messageBuffer.SetLength(0);
}
}
public void Close()
{
if (!Client.Connected) return;
var mask = new byte[4];
if (IsMasking) Random.NextBytes(mask);
SendMessage(new byte[] { }, 0x8, IsMasking, mask);
Client.Close();
}
public void SendMessage(string payload) => SendMessage(Client, payload, IsMasking);
public void SendMessage(byte[] payload, bool isBinary = false) => SendMessage(Client, payload, isBinary, IsMasking);
public void SendMessage(byte[] payload, bool isBinary = false, bool masking = false) => SendMessage(Client, payload, isBinary, masking);
public void SendMessage(byte[] payload, int opcode, bool masking, byte[] mask) => SendMessage(Client, payload, opcode, masking, mask);
static void SendMessage(TcpClient client, string payload, bool masking = false) =>
SendMessage(client, Encoding.UTF8.GetBytes(payload), false, masking);
static void SendMessage(TcpClient client, byte[] payload, bool isBinary = false, bool masking = false)
{
var mask = new byte[4];
if (masking) Random.NextBytes(mask);
SendMessage(client, payload, isBinary ? 0x2 : 0x1, masking, mask);
}
static void SendMessage(TcpClient client, byte[] payload, int opcode, bool masking, byte[] mask)
{
if (masking && mask == null) throw new ArgumentException(nameof(mask));
using (var packet = new MemoryStream())
{
byte firstbyte = 0b0_0_0_0_0000; // fin | rsv1 | rsv2 | rsv3 | [ OPCODE | OPCODE | OPCODE | OPCODE ]
firstbyte |= 0b1_0_0_0_0000; // fin
//firstbyte |= 0b0_1_0_0_0000; // rsv1
//firstbyte |= 0b0_0_1_0_0000; // rsv2
//firstbyte |= 0b0_0_0_1_0000; // rsv3
firstbyte += (byte)opcode; // Text
packet.WriteByte(firstbyte);
// Set bit: bytes[byteIndex] |= mask;
byte secondbyte = 0b0_0000000; // mask | [SIZE | SIZE | SIZE | SIZE | SIZE | SIZE | SIZE]
if (masking)
secondbyte |= 0b1_0000000; // mask
if (payload.LongLength <= 0b0_1111101) // 125
{
secondbyte |= (byte)payload.Length;
packet.WriteByte(secondbyte);
}
else if (payload.LongLength <= UInt16.MaxValue) // If length takes 2 bytes
{
secondbyte |= 0b0_1111110; // 126
packet.WriteByte(secondbyte);
var len = BitConverter.GetBytes(payload.LongLength);
Array.Reverse(len, 0, 2);
packet.Write(len, 0, 2);
}
else // if (payload.LongLength <= Int64.MaxValue) // If length takes 8 bytes
{
secondbyte |= 0b0_1111111; // 127
packet.WriteByte(secondbyte);
var len = BitConverter.GetBytes(payload.LongLength);
Array.Reverse(len, 0, 8);
packet.Write(len, 0, 8);
}
if (masking)
{
packet.Write(mask, 0, 4);
payload = ApplyMask(payload, mask);
}
// Write all data to the packet
packet.Write(payload, 0, payload.Length);
// Get client's stream
var stream = client.GetStream();
var finalPacket = packet.ToArray();
Console.WriteLine($@"SENT: {BitConverter.ToString(finalPacket)}");
// Send the packet
foreach (var b in finalPacket)
stream.WriteByte(b);
}
}
static byte[] ApplyMask(IReadOnlyList<byte> msg, IReadOnlyList<byte> mask)
{
var decoded = new byte[msg.Count];
for (var i = 0; i < msg.Count; i++)
decoded[i] = (byte)(msg[i] ^ mask[i % 4]);
return decoded;
}
public void Dispose()
{
Close();
((IDisposable)Client)?.Dispose();
ClientStream?.Dispose();
}
}