WebSocket.cs 24 KB

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