WebSocket.cs 24 KB

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