WebSocket.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using SocketHttpListener.Net.WebSockets;
  11. using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
  12. using WebSocketState = System.Net.WebSockets.WebSocketState;
  13. namespace SocketHttpListener
  14. {
  15. /// <summary>
  16. /// Implements the WebSocket interface.
  17. /// </summary>
  18. /// <remarks>
  19. /// The WebSocket class provides a set of methods and properties for two-way communication using
  20. /// the WebSocket protocol (<see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>).
  21. /// </remarks>
  22. public class WebSocket : IDisposable
  23. {
  24. #region Private Fields
  25. private Action _closeContext;
  26. private CompressionMethod _compression;
  27. private WebSocketContext _context;
  28. private CookieCollection _cookies;
  29. private AutoResetEvent _exitReceiving;
  30. private object _forConn;
  31. private object _forEvent;
  32. private object _forMessageEventQueue;
  33. private object _forSend;
  34. private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  35. private Queue<MessageEventArgs> _messageEventQueue;
  36. private string _protocol;
  37. private volatile WebSocketState _readyState;
  38. private AutoResetEvent _receivePong;
  39. private bool _secure;
  40. private Stream _stream;
  41. private const string _version = "13";
  42. #endregion
  43. #region Internal Fields
  44. internal const int FragmentLength = 1016; // Max value is int.MaxValue - 14.
  45. #endregion
  46. #region Internal Constructors
  47. // As server
  48. internal WebSocket(string protocol)
  49. {
  50. _protocol = protocol;
  51. }
  52. public void SetContext(HttpListenerWebSocketContext context, Action closeContextFn, Stream stream)
  53. {
  54. _context = context;
  55. _closeContext = closeContextFn;
  56. _secure = context.IsSecureConnection;
  57. _stream = stream;
  58. init();
  59. }
  60. // In the .NET Framework, this pulls the value from a P/Invoke. Here we just hardcode it to a reasonable default.
  61. public static TimeSpan DefaultKeepAliveInterval => TimeSpan.FromSeconds(30);
  62. #endregion
  63. /// <summary>
  64. /// Gets the state of the WebSocket connection.
  65. /// </summary>
  66. /// <value>
  67. /// One of the <see cref="WebSocketState"/> enum values, indicates the state of the WebSocket
  68. /// connection. The default value is <see cref="WebSocketState.Connecting"/>.
  69. /// </value>
  70. public WebSocketState ReadyState => _readyState;
  71. #region Public Events
  72. /// <summary>
  73. /// Occurs when the WebSocket connection has been closed.
  74. /// </summary>
  75. public event EventHandler<CloseEventArgs> OnClose;
  76. /// <summary>
  77. /// Occurs when the <see cref="WebSocket"/> gets an error.
  78. /// </summary>
  79. public event EventHandler<ErrorEventArgs> OnError;
  80. /// <summary>
  81. /// Occurs when the <see cref="WebSocket"/> receives a message.
  82. /// </summary>
  83. public event EventHandler<MessageEventArgs> OnMessage;
  84. /// <summary>
  85. /// Occurs when the WebSocket connection has been established.
  86. /// </summary>
  87. public event EventHandler OnOpen;
  88. #endregion
  89. #region Private Methods
  90. private void close(CloseStatusCode code, string reason, bool wait)
  91. {
  92. close(new PayloadData(((ushort)code).Append(reason)), !code.IsReserved(), wait);
  93. }
  94. private void close(PayloadData payload, bool send, bool wait)
  95. {
  96. lock (_forConn)
  97. {
  98. if (_readyState == WebSocketState.CloseSent || _readyState == WebSocketState.Closed)
  99. {
  100. return;
  101. }
  102. _readyState = WebSocketState.CloseSent;
  103. }
  104. var e = new CloseEventArgs(payload);
  105. e.WasClean =
  106. closeHandshake(
  107. send ? WebSocketFrame.CreateCloseFrame(Mask.Unmask, payload).ToByteArray() : null,
  108. wait ? 1000 : 0);
  109. _readyState = WebSocketState.Closed;
  110. try
  111. {
  112. OnClose.Emit(this, e);
  113. }
  114. catch (Exception ex)
  115. {
  116. error("An exception has occurred while OnClose.", ex);
  117. }
  118. }
  119. private bool closeHandshake(byte[] frameAsBytes, int millisecondsTimeout)
  120. {
  121. var sent = frameAsBytes != null && writeBytes(frameAsBytes);
  122. var received =
  123. millisecondsTimeout == 0 ||
  124. (sent && _exitReceiving != null && _exitReceiving.WaitOne(millisecondsTimeout));
  125. closeServerResources();
  126. if (_receivePong != null)
  127. {
  128. _receivePong.Dispose();
  129. _receivePong = null;
  130. }
  131. if (_exitReceiving != null)
  132. {
  133. _exitReceiving.Dispose();
  134. _exitReceiving = null;
  135. }
  136. var result = sent && received;
  137. return result;
  138. }
  139. // As server
  140. private void closeServerResources()
  141. {
  142. if (_closeContext == null)
  143. return;
  144. try
  145. {
  146. _closeContext();
  147. }
  148. catch (SocketException)
  149. {
  150. // it could be unable to send the handshake response
  151. }
  152. _closeContext = null;
  153. _stream = null;
  154. _context = null;
  155. }
  156. private async Task<bool> ConcatenateFragmentsIntoAsync(Stream dest)
  157. {
  158. while (true)
  159. {
  160. var frame = await WebSocketFrame.ReadAsync(_stream, true).ConfigureAwait(false);
  161. if (frame.IsFinal)
  162. {
  163. /* FINAL */
  164. // CONT
  165. if (frame.IsContinuation)
  166. {
  167. dest.WriteBytes(frame.PayloadData.ApplicationData);
  168. break;
  169. }
  170. // PING
  171. if (frame.IsPing)
  172. {
  173. processPingFrame(frame);
  174. continue;
  175. }
  176. // PONG
  177. if (frame.IsPong)
  178. {
  179. processPongFrame(frame);
  180. continue;
  181. }
  182. // CLOSE
  183. if (frame.IsClose)
  184. return processCloseFrame(frame);
  185. }
  186. else
  187. {
  188. /* MORE */
  189. // CONT
  190. if (frame.IsContinuation)
  191. {
  192. dest.WriteBytes(frame.PayloadData.ApplicationData);
  193. continue;
  194. }
  195. }
  196. // ?
  197. return processUnsupportedFrame(
  198. frame,
  199. CloseStatusCode.IncorrectData,
  200. "An incorrect data has been received while receiving fragmented data.");
  201. }
  202. return true;
  203. }
  204. // As server
  205. private HttpResponse createHandshakeCloseResponse(HttpStatusCode code)
  206. {
  207. var res = HttpResponse.CreateCloseResponse(code);
  208. res.Headers["Sec-WebSocket-Version"] = _version;
  209. return res;
  210. }
  211. private MessageEventArgs dequeueFromMessageEventQueue()
  212. {
  213. lock (_forMessageEventQueue)
  214. return _messageEventQueue.Count > 0
  215. ? _messageEventQueue.Dequeue()
  216. : null;
  217. }
  218. private void enqueueToMessageEventQueue(MessageEventArgs e)
  219. {
  220. lock (_forMessageEventQueue)
  221. _messageEventQueue.Enqueue(e);
  222. }
  223. private void error(string message, Exception exception)
  224. {
  225. try
  226. {
  227. if (exception != null)
  228. {
  229. message += ". Exception.Message: " + exception.Message;
  230. }
  231. OnError.Emit(this, new ErrorEventArgs(message));
  232. }
  233. catch (Exception)
  234. {
  235. }
  236. }
  237. private void error(string message)
  238. {
  239. try
  240. {
  241. OnError.Emit(this, new ErrorEventArgs(message));
  242. }
  243. catch (Exception)
  244. {
  245. }
  246. }
  247. private void init()
  248. {
  249. _compression = CompressionMethod.None;
  250. _cookies = new CookieCollection();
  251. _forConn = new object();
  252. _forEvent = new object();
  253. _forSend = new object();
  254. _messageEventQueue = new Queue<MessageEventArgs>();
  255. _forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot;
  256. _readyState = WebSocketState.Connecting;
  257. }
  258. private void open()
  259. {
  260. try
  261. {
  262. startReceiving();
  263. lock (_forEvent)
  264. {
  265. try
  266. {
  267. if (OnOpen != null)
  268. {
  269. OnOpen(this, EventArgs.Empty);
  270. }
  271. }
  272. catch (Exception ex)
  273. {
  274. processException(ex, "An exception has occurred while OnOpen.");
  275. }
  276. }
  277. }
  278. catch (Exception ex)
  279. {
  280. processException(ex, "An exception has occurred while opening.");
  281. }
  282. }
  283. private bool processCloseFrame(WebSocketFrame frame)
  284. {
  285. var payload = frame.PayloadData;
  286. close(payload, !payload.ContainsReservedCloseStatusCode, false);
  287. return false;
  288. }
  289. private bool processDataFrame(WebSocketFrame frame)
  290. {
  291. var e = frame.IsCompressed
  292. ? new MessageEventArgs(
  293. frame.Opcode, frame.PayloadData.ApplicationData.Decompress(_compression))
  294. : new MessageEventArgs(frame.Opcode, frame.PayloadData);
  295. enqueueToMessageEventQueue(e);
  296. return true;
  297. }
  298. private void processException(Exception exception, string message)
  299. {
  300. var code = CloseStatusCode.Abnormal;
  301. var reason = message;
  302. if (exception is WebSocketException)
  303. {
  304. var wsex = (WebSocketException)exception;
  305. code = wsex.Code;
  306. reason = wsex.Message;
  307. }
  308. error(message ?? code.GetMessage(), exception);
  309. if (_readyState == WebSocketState.Connecting)
  310. Close(HttpStatusCode.BadRequest);
  311. else
  312. close(code, reason ?? code.GetMessage(), false);
  313. }
  314. private Task<bool> ProcessFragmentedFrameAsync(WebSocketFrame frame)
  315. {
  316. return frame.IsContinuation // Not first fragment
  317. ? Task.FromResult(true)
  318. : ProcessFragmentsAsync(frame);
  319. }
  320. private async Task<bool> ProcessFragmentsAsync(WebSocketFrame first)
  321. {
  322. using (var buff = new MemoryStream())
  323. {
  324. buff.WriteBytes(first.PayloadData.ApplicationData);
  325. if (!await ConcatenateFragmentsIntoAsync(buff).ConfigureAwait(false))
  326. {
  327. return false;
  328. }
  329. byte[] data;
  330. if (_compression != CompressionMethod.None)
  331. {
  332. data = buff.DecompressToArray(_compression);
  333. }
  334. else
  335. {
  336. data = buff.ToArray();
  337. }
  338. enqueueToMessageEventQueue(new MessageEventArgs(first.Opcode, data));
  339. return true;
  340. }
  341. }
  342. private bool processPingFrame(WebSocketFrame frame)
  343. {
  344. return true;
  345. }
  346. private bool processPongFrame(WebSocketFrame frame)
  347. {
  348. _receivePong.Set();
  349. return true;
  350. }
  351. private bool processUnsupportedFrame(WebSocketFrame frame, CloseStatusCode code, string reason)
  352. {
  353. processException(new WebSocketException(code, reason), null);
  354. return false;
  355. }
  356. private async Task<bool> ProcessWebSocketFrameAsync(WebSocketFrame frame)
  357. {
  358. return frame.IsCompressed && _compression == CompressionMethod.None
  359. ? processUnsupportedFrame(
  360. frame,
  361. CloseStatusCode.IncorrectData,
  362. "A compressed data has been received without available decompression method.")
  363. : frame.IsFragmented
  364. ? await ProcessFragmentedFrameAsync(frame).ConfigureAwait(false)
  365. : frame.IsData
  366. ? processDataFrame(frame)
  367. : frame.IsPing
  368. ? processPingFrame(frame)
  369. : frame.IsPong
  370. ? processPongFrame(frame)
  371. : frame.IsClose
  372. ? processCloseFrame(frame)
  373. : processUnsupportedFrame(frame, CloseStatusCode.PolicyViolation, null);
  374. }
  375. private bool send(Opcode opcode, Stream stream)
  376. {
  377. lock (_forSend)
  378. {
  379. var src = stream;
  380. var compressed = false;
  381. var sent = false;
  382. try
  383. {
  384. if (_compression != CompressionMethod.None)
  385. {
  386. stream = stream.Compress(_compression);
  387. compressed = true;
  388. }
  389. sent = send(opcode, Mask.Unmask, stream, compressed);
  390. if (!sent)
  391. error("Sending a data has been interrupted.");
  392. }
  393. catch (Exception ex)
  394. {
  395. error("An exception has occurred while sending a data.", ex);
  396. }
  397. finally
  398. {
  399. if (compressed)
  400. stream.Dispose();
  401. src.Dispose();
  402. }
  403. return sent;
  404. }
  405. }
  406. private bool send(Opcode opcode, Mask mask, Stream stream, bool compressed)
  407. {
  408. var len = stream.Length;
  409. /* Not fragmented */
  410. if (len == 0)
  411. return send(Fin.Final, opcode, mask, new byte[0], compressed);
  412. var quo = len / FragmentLength;
  413. var rem = (int)(len % FragmentLength);
  414. byte[] buff = null;
  415. if (quo == 0)
  416. {
  417. buff = new byte[rem];
  418. return stream.Read(buff, 0, rem) == rem &&
  419. send(Fin.Final, opcode, mask, buff, compressed);
  420. }
  421. buff = new byte[FragmentLength];
  422. if (quo == 1 && rem == 0)
  423. return stream.Read(buff, 0, FragmentLength) == FragmentLength &&
  424. send(Fin.Final, opcode, mask, buff, compressed);
  425. /* Send fragmented */
  426. // Begin
  427. if (stream.Read(buff, 0, FragmentLength) != FragmentLength ||
  428. !send(Fin.More, opcode, mask, buff, compressed))
  429. return false;
  430. var n = rem == 0 ? quo - 2 : quo - 1;
  431. for (long i = 0; i < n; i++)
  432. if (stream.Read(buff, 0, FragmentLength) != FragmentLength ||
  433. !send(Fin.More, Opcode.Cont, mask, buff, compressed))
  434. return false;
  435. // End
  436. if (rem == 0)
  437. rem = FragmentLength;
  438. else
  439. buff = new byte[rem];
  440. return stream.Read(buff, 0, rem) == rem &&
  441. send(Fin.Final, Opcode.Cont, mask, buff, compressed);
  442. }
  443. private bool send(Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
  444. {
  445. lock (_forConn)
  446. {
  447. if (_readyState != WebSocketState.Open)
  448. {
  449. return false;
  450. }
  451. return writeBytes(
  452. WebSocketFrame.CreateWebSocketFrame(fin, opcode, mask, data, compressed).ToByteArray());
  453. }
  454. }
  455. private Task sendAsync(Opcode opcode, Stream stream)
  456. {
  457. var completionSource = new TaskCompletionSource<bool>();
  458. Task.Run(() =>
  459. {
  460. try
  461. {
  462. send(opcode, stream);
  463. completionSource.TrySetResult(true);
  464. }
  465. catch (Exception ex)
  466. {
  467. completionSource.TrySetException(ex);
  468. }
  469. });
  470. return completionSource.Task;
  471. }
  472. // As server
  473. private bool sendHttpResponse(HttpResponse response)
  474. {
  475. return writeBytes(response.ToByteArray());
  476. }
  477. private void startReceiving()
  478. {
  479. if (_messageEventQueue.Count > 0)
  480. {
  481. _messageEventQueue.Clear();
  482. }
  483. _exitReceiving = new AutoResetEvent(false);
  484. _receivePong = new AutoResetEvent(false);
  485. Action receive = null;
  486. receive = async () => await WebSocketFrame.ReadAsync(
  487. _stream,
  488. true,
  489. async frame =>
  490. {
  491. if (await ProcessWebSocketFrameAsync(frame).ConfigureAwait(false) && _readyState != WebSocketState.Closed)
  492. {
  493. receive();
  494. if (!frame.IsData)
  495. return;
  496. lock (_forEvent)
  497. {
  498. try
  499. {
  500. var e = dequeueFromMessageEventQueue();
  501. if (e != null && _readyState == WebSocketState.Open)
  502. OnMessage.Emit(this, e);
  503. }
  504. catch (Exception ex)
  505. {
  506. processException(ex, "An exception has occurred while OnMessage.");
  507. }
  508. }
  509. }
  510. else if (_exitReceiving != null)
  511. {
  512. _exitReceiving.Set();
  513. }
  514. },
  515. ex => processException(ex, "An exception has occurred while receiving a message."));
  516. receive();
  517. }
  518. private bool writeBytes(byte[] data)
  519. {
  520. try
  521. {
  522. _stream.Write(data, 0, data.Length);
  523. return true;
  524. }
  525. catch (Exception)
  526. {
  527. return false;
  528. }
  529. }
  530. #endregion
  531. #region Internal Methods
  532. // As server
  533. internal void Close(HttpResponse response)
  534. {
  535. _readyState = WebSocketState.CloseSent;
  536. sendHttpResponse(response);
  537. closeServerResources();
  538. _readyState = WebSocketState.Closed;
  539. }
  540. // As server
  541. internal void Close(HttpStatusCode code)
  542. {
  543. Close(createHandshakeCloseResponse(code));
  544. }
  545. // As server
  546. public void ConnectAsServer()
  547. {
  548. try
  549. {
  550. _readyState = WebSocketState.Open;
  551. open();
  552. }
  553. catch (Exception ex)
  554. {
  555. processException(ex, "An exception has occurred while connecting.");
  556. }
  557. }
  558. #endregion
  559. #region Public Methods
  560. /// <summary>
  561. /// Closes the WebSocket connection, and releases all associated resources.
  562. /// </summary>
  563. public void Close()
  564. {
  565. var msg = _readyState.CheckIfClosable();
  566. if (msg != null)
  567. {
  568. error(msg);
  569. return;
  570. }
  571. var send = _readyState == WebSocketState.Open;
  572. close(new PayloadData(), send, send);
  573. }
  574. /// <summary>
  575. /// Closes the WebSocket connection with the specified <see cref="CloseStatusCode"/>
  576. /// and <see cref="string"/>, and releases all associated resources.
  577. /// </summary>
  578. /// <remarks>
  579. /// This method emits a <see cref="OnError"/> event if the size
  580. /// of <paramref name="reason"/> is greater than 123 bytes.
  581. /// </remarks>
  582. /// <param name="code">
  583. /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
  584. /// indicating the reason for the close.
  585. /// </param>
  586. /// <param name="reason">
  587. /// A <see cref="string"/> that represents the reason for the close.
  588. /// </param>
  589. public void Close(CloseStatusCode code, string reason)
  590. {
  591. byte[] data = null;
  592. var msg = _readyState.CheckIfClosable() ??
  593. (data = ((ushort)code).Append(reason)).CheckIfValidControlData("reason");
  594. if (msg != null)
  595. {
  596. error(msg);
  597. return;
  598. }
  599. var send = _readyState == WebSocketState.Open && !code.IsReserved();
  600. close(new PayloadData(data), send, send);
  601. }
  602. /// <summary>
  603. /// Sends a binary <paramref name="data"/> asynchronously using the WebSocket connection.
  604. /// </summary>
  605. /// <remarks>
  606. /// This method doesn't wait for the send to be complete.
  607. /// </remarks>
  608. /// <param name="data">
  609. /// An array of <see cref="byte"/> that represents the binary data to send.
  610. /// </param>
  611. public Task SendAsync(byte[] data)
  612. {
  613. if (data == null)
  614. {
  615. throw new ArgumentNullException(nameof(data));
  616. }
  617. var msg = _readyState.CheckIfOpen();
  618. if (msg != null)
  619. {
  620. throw new Exception(msg);
  621. }
  622. return sendAsync(Opcode.Binary, new MemoryStream(data));
  623. }
  624. /// <summary>
  625. /// Sends a text <paramref name="data"/> asynchronously using the WebSocket connection.
  626. /// </summary>
  627. /// <remarks>
  628. /// This method doesn't wait for the send to be complete.
  629. /// </remarks>
  630. /// <param name="data">
  631. /// A <see cref="string"/> that represents the text data to send.
  632. /// </param>
  633. public Task SendAsync(string data)
  634. {
  635. if (data == null)
  636. {
  637. throw new ArgumentNullException(nameof(data));
  638. }
  639. var msg = _readyState.CheckIfOpen();
  640. if (msg != null)
  641. {
  642. throw new Exception(msg);
  643. }
  644. return sendAsync(Opcode.Text, new MemoryStream(Encoding.UTF8.GetBytes(data)));
  645. }
  646. #endregion
  647. #region Explicit Interface Implementation
  648. /// <summary>
  649. /// Closes the WebSocket connection, and releases all associated resources.
  650. /// </summary>
  651. /// <remarks>
  652. /// This method closes the WebSocket connection with <see cref="CloseStatusCode.Away"/>.
  653. /// </remarks>
  654. void IDisposable.Dispose()
  655. {
  656. Close(CloseStatusCode.Away, null);
  657. }
  658. #endregion
  659. }
  660. }