WebSocket.cs 24 KB

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