WebSocket.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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 bool concatenateFragmentsInto(Stream dest)
  157. {
  158. while (true)
  159. {
  160. var frame = WebSocketFrame.Read(_stream, true);
  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 bool processFragmentedFrame(WebSocketFrame frame)
  315. {
  316. return frame.IsContinuation // Not first fragment
  317. ? true
  318. : processFragments(frame);
  319. }
  320. private bool processFragments(WebSocketFrame first)
  321. {
  322. using (var buff = new MemoryStream())
  323. {
  324. buff.WriteBytes(first.PayloadData.ApplicationData);
  325. if (!concatenateFragmentsInto(buff))
  326. return false;
  327. byte[] data;
  328. if (_compression != CompressionMethod.None)
  329. {
  330. data = buff.DecompressToArray(_compression);
  331. }
  332. else
  333. {
  334. data = buff.ToArray();
  335. }
  336. enqueueToMessageEventQueue(new MessageEventArgs(first.Opcode, data));
  337. return true;
  338. }
  339. }
  340. private bool processPingFrame(WebSocketFrame frame)
  341. {
  342. return true;
  343. }
  344. private bool processPongFrame(WebSocketFrame frame)
  345. {
  346. _receivePong.Set();
  347. return true;
  348. }
  349. private bool processUnsupportedFrame(WebSocketFrame frame, CloseStatusCode code, string reason)
  350. {
  351. processException(new WebSocketException(code, reason), null);
  352. return false;
  353. }
  354. private bool processWebSocketFrame(WebSocketFrame frame)
  355. {
  356. return frame.IsCompressed && _compression == CompressionMethod.None
  357. ? processUnsupportedFrame(
  358. frame,
  359. CloseStatusCode.IncorrectData,
  360. "A compressed data has been received without available decompression method.")
  361. : frame.IsFragmented
  362. ? processFragmentedFrame(frame)
  363. : frame.IsData
  364. ? processDataFrame(frame)
  365. : frame.IsPing
  366. ? processPingFrame(frame)
  367. : frame.IsPong
  368. ? processPongFrame(frame)
  369. : frame.IsClose
  370. ? processCloseFrame(frame)
  371. : processUnsupportedFrame(frame, CloseStatusCode.PolicyViolation, null);
  372. }
  373. private bool send(Opcode opcode, Stream stream)
  374. {
  375. lock (_forSend)
  376. {
  377. var src = stream;
  378. var compressed = false;
  379. var sent = false;
  380. try
  381. {
  382. if (_compression != CompressionMethod.None)
  383. {
  384. stream = stream.Compress(_compression);
  385. compressed = true;
  386. }
  387. sent = send(opcode, Mask.Unmask, stream, compressed);
  388. if (!sent)
  389. error("Sending a data has been interrupted.");
  390. }
  391. catch (Exception ex)
  392. {
  393. error("An exception has occurred while sending a data.", ex);
  394. }
  395. finally
  396. {
  397. if (compressed)
  398. stream.Dispose();
  399. src.Dispose();
  400. }
  401. return sent;
  402. }
  403. }
  404. private bool send(Opcode opcode, Mask mask, Stream stream, bool compressed)
  405. {
  406. var len = stream.Length;
  407. /* Not fragmented */
  408. if (len == 0)
  409. return send(Fin.Final, opcode, mask, new byte[0], compressed);
  410. var quo = len / FragmentLength;
  411. var rem = (int)(len % FragmentLength);
  412. byte[] buff = null;
  413. if (quo == 0)
  414. {
  415. buff = new byte[rem];
  416. return stream.Read(buff, 0, rem) == rem &&
  417. send(Fin.Final, opcode, mask, buff, compressed);
  418. }
  419. buff = new byte[FragmentLength];
  420. if (quo == 1 && rem == 0)
  421. return stream.Read(buff, 0, FragmentLength) == FragmentLength &&
  422. send(Fin.Final, opcode, mask, buff, compressed);
  423. /* Send fragmented */
  424. // Begin
  425. if (stream.Read(buff, 0, FragmentLength) != FragmentLength ||
  426. !send(Fin.More, opcode, mask, buff, compressed))
  427. return false;
  428. var n = rem == 0 ? quo - 2 : quo - 1;
  429. for (long i = 0; i < n; i++)
  430. if (stream.Read(buff, 0, FragmentLength) != FragmentLength ||
  431. !send(Fin.More, Opcode.Cont, mask, buff, compressed))
  432. return false;
  433. // End
  434. if (rem == 0)
  435. rem = FragmentLength;
  436. else
  437. buff = new byte[rem];
  438. return stream.Read(buff, 0, rem) == rem &&
  439. send(Fin.Final, Opcode.Cont, mask, buff, compressed);
  440. }
  441. private bool send(Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
  442. {
  443. lock (_forConn)
  444. {
  445. if (_readyState != WebSocketState.Open)
  446. {
  447. return false;
  448. }
  449. return writeBytes(
  450. WebSocketFrame.CreateWebSocketFrame(fin, opcode, mask, data, compressed).ToByteArray());
  451. }
  452. }
  453. private Task sendAsync(Opcode opcode, Stream stream)
  454. {
  455. var completionSource = new TaskCompletionSource<bool>();
  456. Task.Run(() =>
  457. {
  458. try
  459. {
  460. send(opcode, stream);
  461. completionSource.TrySetResult(true);
  462. }
  463. catch (Exception ex)
  464. {
  465. completionSource.TrySetException(ex);
  466. }
  467. });
  468. return completionSource.Task;
  469. }
  470. // As server
  471. private bool sendHttpResponse(HttpResponse response)
  472. {
  473. return writeBytes(response.ToByteArray());
  474. }
  475. private void startReceiving()
  476. {
  477. if (_messageEventQueue.Count > 0)
  478. _messageEventQueue.Clear();
  479. _exitReceiving = new AutoResetEvent(false);
  480. _receivePong = new AutoResetEvent(false);
  481. Action receive = null;
  482. receive = () => WebSocketFrame.ReadAsync(
  483. _stream,
  484. true,
  485. frame =>
  486. {
  487. if (processWebSocketFrame(frame) && _readyState != WebSocketState.Closed)
  488. {
  489. receive();
  490. if (!frame.IsData)
  491. return;
  492. lock (_forEvent)
  493. {
  494. try
  495. {
  496. var e = dequeueFromMessageEventQueue();
  497. if (e != null && _readyState == WebSocketState.Open)
  498. OnMessage.Emit(this, e);
  499. }
  500. catch (Exception ex)
  501. {
  502. processException(ex, "An exception has occurred while OnMessage.");
  503. }
  504. }
  505. }
  506. else if (_exitReceiving != null)
  507. {
  508. _exitReceiving.Set();
  509. }
  510. },
  511. ex => processException(ex, "An exception has occurred while receiving a message."));
  512. receive();
  513. }
  514. private bool writeBytes(byte[] data)
  515. {
  516. try
  517. {
  518. _stream.Write(data, 0, data.Length);
  519. return true;
  520. }
  521. catch (Exception)
  522. {
  523. return false;
  524. }
  525. }
  526. #endregion
  527. #region Internal Methods
  528. // As server
  529. internal void Close(HttpResponse response)
  530. {
  531. _readyState = WebSocketState.CloseSent;
  532. sendHttpResponse(response);
  533. closeServerResources();
  534. _readyState = WebSocketState.Closed;
  535. }
  536. // As server
  537. internal void Close(HttpStatusCode code)
  538. {
  539. Close(createHandshakeCloseResponse(code));
  540. }
  541. // As server
  542. public void ConnectAsServer()
  543. {
  544. try
  545. {
  546. _readyState = WebSocketState.Open;
  547. open();
  548. }
  549. catch (Exception ex)
  550. {
  551. processException(ex, "An exception has occurred while connecting.");
  552. }
  553. }
  554. #endregion
  555. #region Public Methods
  556. /// <summary>
  557. /// Closes the WebSocket connection, and releases all associated resources.
  558. /// </summary>
  559. public void Close()
  560. {
  561. var msg = _readyState.CheckIfClosable();
  562. if (msg != null)
  563. {
  564. error(msg);
  565. return;
  566. }
  567. var send = _readyState == WebSocketState.Open;
  568. close(new PayloadData(), send, send);
  569. }
  570. /// <summary>
  571. /// Closes the WebSocket connection with the specified <see cref="CloseStatusCode"/>
  572. /// and <see cref="string"/>, and releases all associated resources.
  573. /// </summary>
  574. /// <remarks>
  575. /// This method emits a <see cref="OnError"/> event if the size
  576. /// of <paramref name="reason"/> is greater than 123 bytes.
  577. /// </remarks>
  578. /// <param name="code">
  579. /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
  580. /// indicating the reason for the close.
  581. /// </param>
  582. /// <param name="reason">
  583. /// A <see cref="string"/> that represents the reason for the close.
  584. /// </param>
  585. public void Close(CloseStatusCode code, string reason)
  586. {
  587. byte[] data = null;
  588. var msg = _readyState.CheckIfClosable() ??
  589. (data = ((ushort)code).Append(reason)).CheckIfValidControlData("reason");
  590. if (msg != null)
  591. {
  592. error(msg);
  593. return;
  594. }
  595. var send = _readyState == WebSocketState.Open && !code.IsReserved();
  596. close(new PayloadData(data), send, send);
  597. }
  598. /// <summary>
  599. /// Sends a binary <paramref name="data"/> asynchronously using the WebSocket connection.
  600. /// </summary>
  601. /// <remarks>
  602. /// This method doesn't wait for the send to be complete.
  603. /// </remarks>
  604. /// <param name="data">
  605. /// An array of <see cref="byte"/> that represents the binary data to send.
  606. /// </param>
  607. public Task SendAsync(byte[] data)
  608. {
  609. if (data == null)
  610. {
  611. throw new ArgumentNullException(nameof(data));
  612. }
  613. var msg = _readyState.CheckIfOpen();
  614. if (msg != null)
  615. {
  616. throw new Exception(msg);
  617. }
  618. return sendAsync(Opcode.Binary, new MemoryStream(data));
  619. }
  620. /// <summary>
  621. /// Sends a text <paramref name="data"/> asynchronously using the WebSocket connection.
  622. /// </summary>
  623. /// <remarks>
  624. /// This method doesn't wait for the send to be complete.
  625. /// </remarks>
  626. /// <param name="data">
  627. /// A <see cref="string"/> that represents the text data to send.
  628. /// </param>
  629. public Task SendAsync(string data)
  630. {
  631. if (data == null)
  632. {
  633. throw new ArgumentNullException(nameof(data));
  634. }
  635. var msg = _readyState.CheckIfOpen();
  636. if (msg != null)
  637. {
  638. throw new Exception(msg);
  639. }
  640. return sendAsync(Opcode.Text, new MemoryStream(Encoding.UTF8.GetBytes(data)));
  641. }
  642. #endregion
  643. #region Explicit Interface Implementation
  644. /// <summary>
  645. /// Closes the WebSocket connection, and releases all associated resources.
  646. /// </summary>
  647. /// <remarks>
  648. /// This method closes the WebSocket connection with <see cref="CloseStatusCode.Away"/>.
  649. /// </remarks>
  650. void IDisposable.Dispose()
  651. {
  652. Close(CloseStatusCode.Away, null);
  653. }
  654. #endregion
  655. }
  656. }