WebSocket.cs 24 KB

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