WebSocket.cs 24 KB

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