WebsocketServerHandler.cs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.Net;
  31. using System.Security.Cryptography;
  32. using System.Text;
  33. using System.Threading;
  34. using OSHttpServer;
  35. namespace OpenSim.Framework.Servers.HttpServer
  36. {
  37. // Sealed class. If you're going to unseal it, implement IDisposable.
  38. /// <summary>
  39. /// This class implements websockets. It grabs the network context from C#Webserver and utilizes it directly as a tcp streaming service
  40. /// </summary>
  41. public sealed class WebSocketHttpServerHandler : BaseRequestHandler
  42. {
  43. private class WebSocketState
  44. {
  45. public List<byte> ReceivedBytes;
  46. public int ExpectedBytes;
  47. public WebsocketFrameHeader Header;
  48. public bool FrameComplete;
  49. public WebSocketFrame ContinuationFrame;
  50. }
  51. /// <summary>
  52. /// Binary Data will trigger this event
  53. /// </summary>
  54. public event DataDelegate OnData;
  55. /// <summary>
  56. /// Textual Data will trigger this event
  57. /// </summary>
  58. public event TextDelegate OnText;
  59. /// <summary>
  60. /// A ping request form the other side will trigger this event.
  61. /// This class responds to the ping automatically. You shouldn't send a pong.
  62. /// it's informational.
  63. /// </summary>
  64. public event PingDelegate OnPing;
  65. /// <summary>
  66. /// This is a response to a ping you sent.
  67. /// </summary>
  68. public event PongDelegate OnPong;
  69. /// <summary>
  70. /// This is a regular HTTP Request... This may be removed in the future.
  71. /// </summary>
  72. // public event RegularHttpRequestDelegate OnRegularHttpRequest;
  73. /// <summary>
  74. /// When the upgrade from a HTTP request to a Websocket is completed, this will be fired
  75. /// </summary>
  76. public event UpgradeCompletedDelegate OnUpgradeCompleted;
  77. /// <summary>
  78. /// If the upgrade failed, this will be fired
  79. /// </summary>
  80. public event UpgradeFailedDelegate OnUpgradeFailed;
  81. /// <summary>
  82. /// When the websocket is closed, this will be fired.
  83. /// </summary>
  84. public event CloseDelegate OnClose;
  85. /// <summary>
  86. /// Set this delegate to allow your module to validate the origin of the
  87. /// Websocket request. Primary line of defense against cross site scripting
  88. /// </summary>
  89. public ValidateHandshake HandshakeValidateMethodOverride = null;
  90. private ManualResetEvent _receiveDone = new ManualResetEvent(false);
  91. private OSHttpRequest _request;
  92. private HTTPNetworkContext _networkContext;
  93. private IHttpClientContext _clientContext;
  94. private int _pingtime = 0;
  95. private byte[] _buffer;
  96. private int _bufferPosition;
  97. private int _bufferLength;
  98. private bool _closing;
  99. private bool _upgraded;
  100. private int _maxPayloadBytes = 41943040;
  101. private int _initialMsgTimeout = 0;
  102. private int _defaultReadTimeout = 10000;
  103. private const string HandshakeAcceptText =
  104. "HTTP/1.1 101 Switching Protocols\r\n" +
  105. "upgrade: websocket\r\n" +
  106. "Connection: Upgrade\r\n" +
  107. "sec-websocket-accept: {0}\r\n\r\n";// +
  108. //"{1}";
  109. private const string HandshakeDeclineText =
  110. "HTTP/1.1 {0} {1}\r\n" +
  111. "Connection: close\r\n\r\n";
  112. /// <summary>
  113. /// Mysterious constant defined in RFC6455 to append to the client provided security key
  114. /// </summary>
  115. private const string WebsocketHandshakeAcceptHashConstant = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  116. public WebSocketHttpServerHandler(OSHttpRequest preq, int bufferlen)
  117. : base(preq.HttpMethod, preq.Url.OriginalString)
  118. {
  119. _request = preq;
  120. _networkContext = preq.IHttpClientContext.GiveMeTheNetworkStreamIKnowWhatImDoing();
  121. _networkContext.Stream.ReadTimeout = _defaultReadTimeout;
  122. _clientContext = preq.IHttpClientContext;
  123. _bufferLength = bufferlen;
  124. _buffer = new byte[_bufferLength];
  125. }
  126. // Sealed class implments destructor and an internal dispose method. complies with C# unmanaged resource best practices.
  127. ~WebSocketHttpServerHandler()
  128. {
  129. Dispose();
  130. }
  131. /// <summary>
  132. /// Sets the length of the stream buffer
  133. /// </summary>
  134. /// <param name="pChunk">Byte length.</param>
  135. public void SetChunksize(int pChunk)
  136. {
  137. if (!_upgraded)
  138. {
  139. _buffer = new byte[pChunk];
  140. }
  141. else
  142. {
  143. throw new InvalidOperationException("You must set the chunksize before the connection is upgraded");
  144. }
  145. }
  146. /// <summary>
  147. /// This is the famous nagle.
  148. /// </summary>
  149. public bool NoDelay_TCP_Nagle
  150. {
  151. get
  152. {
  153. if (_networkContext != null && _networkContext.Socket != null)
  154. {
  155. return _networkContext.Socket.NoDelay;
  156. }
  157. else
  158. {
  159. throw new InvalidOperationException("The socket has been shutdown");
  160. }
  161. }
  162. set
  163. {
  164. if (_networkContext != null && _networkContext.Socket != null)
  165. _networkContext.Socket.NoDelay = value;
  166. else
  167. {
  168. throw new InvalidOperationException("The socket has been shutdown");
  169. }
  170. }
  171. }
  172. /// <summary>
  173. /// This triggers the websocket to start the upgrade process...
  174. /// This is a Generalized Networking 'common sense' helper method. Some people expect to call Start() instead
  175. /// of the more context appropriate HandshakeAndUpgrade()
  176. /// </summary>
  177. public void Start()
  178. {
  179. HandshakeAndUpgrade();
  180. }
  181. /// <summary>
  182. /// Max Payload Size in bytes. Defaults to 40MB, but could be set upon connection before calling handshake and upgrade.
  183. /// </summary>
  184. public int MaxPayloadSize
  185. {
  186. get { return _maxPayloadBytes; }
  187. set { _maxPayloadBytes = value; }
  188. }
  189. /// <summary>
  190. /// Set this to the maximum amount of milliseconds to wait for the first complete message to be sent or received on the websocket after upgrading
  191. /// Default, it waits forever. Use this when your Websocket consuming code opens a connection and waits for a message from the other side to avoid a Denial of Service vector.
  192. /// </summary>
  193. public int InitialMsgTimeout
  194. {
  195. get { return _initialMsgTimeout; }
  196. set { _initialMsgTimeout = value; }
  197. }
  198. /// <summary>
  199. /// This triggers the websocket start the upgrade process
  200. /// </summary>
  201. public void HandshakeAndUpgrade()
  202. {
  203. string webOrigin = string.Empty;
  204. string websocketKey = string.Empty;
  205. string acceptKey = string.Empty;
  206. string accepthost = string.Empty;
  207. if (!string.IsNullOrEmpty(_request.Headers["origin"]))
  208. webOrigin = _request.Headers["origin"];
  209. if (!string.IsNullOrEmpty(_request.Headers["sec-websocket-key"]))
  210. websocketKey = _request.Headers["sec-websocket-key"];
  211. if (!string.IsNullOrEmpty(_request.Headers["host"]))
  212. accepthost = _request.Headers["host"];
  213. if (string.IsNullOrEmpty(_request.Headers["upgrade"]))
  214. {
  215. FailUpgrade(HttpStatusCode.BadRequest, "no upgrade request submitted");
  216. }
  217. string connectionheader = _request.Headers["upgrade"];
  218. if (connectionheader.ToLower() != "websocket")
  219. {
  220. FailUpgrade(HttpStatusCode.BadRequest, "no connection upgrade request submitted");
  221. }
  222. // If the object consumer provided a method to validate the origin, we should call it and give the client a success or fail.
  223. // If not.. we should accept any. The assumption here is that there would be no Websocket handlers registered in baseHTTPServer unless
  224. // Something asked for it...
  225. if (HandshakeValidateMethodOverride != null)
  226. {
  227. if (HandshakeValidateMethodOverride(webOrigin, websocketKey, accepthost))
  228. {
  229. acceptKey = GenerateAcceptKey(websocketKey);
  230. string rawaccept = string.Format(HandshakeAcceptText, acceptKey);
  231. SendUpgradeSuccess(rawaccept);
  232. }
  233. else
  234. {
  235. FailUpgrade(HttpStatusCode.Forbidden, "Origin Validation Failed");
  236. }
  237. }
  238. else
  239. {
  240. acceptKey = GenerateAcceptKey(websocketKey);
  241. string rawaccept = string.Format(HandshakeAcceptText, acceptKey);
  242. SendUpgradeSuccess(rawaccept);
  243. }
  244. }
  245. public IPEndPoint GetRemoteIPEndpoint()
  246. {
  247. return _request.RemoteIPEndPoint;
  248. }
  249. /// <summary>
  250. /// Generates a handshake response key string based on the client's
  251. /// provided key to prove to the client that we're allowing the Websocket
  252. /// upgrade of our own free will and we were not coerced into doing it.
  253. /// </summary>
  254. /// <param name="key">Client provided security key</param>
  255. /// <returns></returns>
  256. private static string GenerateAcceptKey(string key)
  257. {
  258. if (string.IsNullOrEmpty(key))
  259. return string.Empty;
  260. string acceptkey = key + WebsocketHandshakeAcceptHashConstant;
  261. SHA1 hashobj = SHA1.Create();
  262. string ret = Convert.ToBase64String(hashobj.ComputeHash(Encoding.UTF8.GetBytes(acceptkey)));
  263. hashobj.Clear();
  264. return ret;
  265. }
  266. /// <summary>
  267. /// Informs the otherside that we accepted their upgrade request
  268. /// </summary>
  269. /// <param name="pHandshakeResponse">The HTTP 1.1 101 response that says Yay \o/ </param>
  270. private void SendUpgradeSuccess(string pHandshakeResponse)
  271. {
  272. // Create a new websocket state so we can keep track of data in between network reads.
  273. WebSocketState socketState = new WebSocketState() { ReceivedBytes = new List<byte>(), Header = WebsocketFrameHeader.HeaderDefault(), FrameComplete = true};
  274. byte[] bhandshakeResponse = Encoding.UTF8.GetBytes(pHandshakeResponse);
  275. try
  276. {
  277. if (_initialMsgTimeout > 0)
  278. {
  279. _receiveDone.Reset();
  280. }
  281. // Begin reading the TCP stream before writing the Upgrade success message to the other side of the stream.
  282. _networkContext.Stream.BeginRead(_buffer, 0, _bufferLength, OnReceive, socketState);
  283. // Write the upgrade handshake success message
  284. _networkContext.Stream.Write(bhandshakeResponse, 0, bhandshakeResponse.Length);
  285. _networkContext.Stream.Flush();
  286. _upgraded = true;
  287. UpgradeCompletedDelegate d = OnUpgradeCompleted;
  288. if (d != null)
  289. d(this, new UpgradeCompletedEventArgs());
  290. if (_initialMsgTimeout > 0)
  291. {
  292. if (!_receiveDone.WaitOne(TimeSpan.FromMilliseconds(_initialMsgTimeout)))
  293. Close(string.Empty);
  294. }
  295. }
  296. catch (IOException)
  297. {
  298. Close(string.Empty);
  299. }
  300. catch (ObjectDisposedException)
  301. {
  302. Close(string.Empty);
  303. }
  304. }
  305. /// <summary>
  306. /// The server has decided not to allow the upgrade to a websocket for some reason. The Http 1.1 response that says Nay >:(
  307. /// </summary>
  308. /// <param name="pCode">HTTP Status reflecting the reason why</param>
  309. /// <param name="pMessage">Textual reason for the upgrade fail</param>
  310. private void FailUpgrade(HttpStatusCode pCode, string pMessage )
  311. {
  312. string handshakeResponse = string.Format(HandshakeDeclineText, (int)pCode, pMessage.Replace("\n", string.Empty).Replace("\r", string.Empty));
  313. byte[] bhandshakeResponse = Encoding.UTF8.GetBytes(handshakeResponse);
  314. _networkContext.Stream.Write(bhandshakeResponse, 0, bhandshakeResponse.Length);
  315. _networkContext.Stream.Flush();
  316. _networkContext.Stream.Dispose();
  317. UpgradeFailedDelegate d = OnUpgradeFailed;
  318. if (d != null)
  319. d(this,new UpgradeFailedEventArgs());
  320. }
  321. /// <summary>
  322. /// This is our ugly Async OnReceive event handler.
  323. /// This chunks the input stream based on the length of the provided buffer and processes out
  324. /// as many frames as it can. It then moves the unprocessed data to the beginning of the buffer.
  325. /// </summary>
  326. /// <param name="ar">Our Async State from beginread</param>
  327. private void OnReceive(IAsyncResult ar)
  328. {
  329. WebSocketState _socketState = ar.AsyncState as WebSocketState;
  330. try
  331. {
  332. int bytesRead = _networkContext.Stream.EndRead(ar);
  333. if (bytesRead == 0)
  334. {
  335. // Do Disconnect
  336. _networkContext.Stream.Dispose();
  337. _networkContext = null;
  338. return;
  339. }
  340. _bufferPosition += bytesRead;
  341. if (_bufferPosition > _bufferLength)
  342. {
  343. // Message too big for chunksize.. not sure how this happened...
  344. //Close(string.Empty);
  345. }
  346. int offset = 0;
  347. bool headerread = true;
  348. int headerforwardposition = 0;
  349. while (headerread && offset < bytesRead)
  350. {
  351. if (_socketState.FrameComplete)
  352. {
  353. WebsocketFrameHeader pheader = WebsocketFrameHeader.ZeroHeader;
  354. headerread = WebSocketReader.TryReadHeader(_buffer, offset, _bufferPosition - offset, out pheader,
  355. out headerforwardposition);
  356. offset += headerforwardposition;
  357. if (headerread)
  358. {
  359. _socketState.FrameComplete = false;
  360. if (pheader.PayloadLen > (ulong) _maxPayloadBytes)
  361. {
  362. Close("Invalid Payload size");
  363. return;
  364. }
  365. if (pheader.PayloadLen > 0)
  366. {
  367. if ((int) pheader.PayloadLen > _bufferPosition - offset)
  368. {
  369. byte[] writebytes = new byte[_bufferPosition - offset];
  370. Buffer.BlockCopy(_buffer, offset, writebytes, 0, (int) _bufferPosition - offset);
  371. _socketState.ExpectedBytes = (int) pheader.PayloadLen;
  372. _socketState.ReceivedBytes.AddRange(writebytes);
  373. _socketState.Header = pheader; // We need to add the header so that we can unmask it
  374. offset += (int) _bufferPosition - offset;
  375. }
  376. else
  377. {
  378. byte[] writebytes = new byte[pheader.PayloadLen];
  379. Buffer.BlockCopy(_buffer, offset, writebytes, 0, (int) pheader.PayloadLen);
  380. WebSocketReader.Mask(pheader.Mask, writebytes);
  381. pheader.IsMasked = false;
  382. _socketState.FrameComplete = true;
  383. _socketState.ReceivedBytes.AddRange(writebytes);
  384. _socketState.Header = pheader;
  385. offset += (int) pheader.PayloadLen;
  386. }
  387. }
  388. else
  389. {
  390. pheader.Mask = 0;
  391. _socketState.FrameComplete = true;
  392. _socketState.Header = pheader;
  393. }
  394. if (_socketState.FrameComplete)
  395. {
  396. ProcessFrame(_socketState);
  397. _socketState.Header.SetDefault();
  398. _socketState.ReceivedBytes.Clear();
  399. _socketState.ExpectedBytes = 0;
  400. }
  401. }
  402. }
  403. else
  404. {
  405. WebsocketFrameHeader frameHeader = _socketState.Header;
  406. int bytesleft = _socketState.ExpectedBytes - _socketState.ReceivedBytes.Count;
  407. if (bytesleft > _bufferPosition)
  408. {
  409. byte[] writebytes = new byte[_bufferPosition];
  410. Buffer.BlockCopy(_buffer, offset, writebytes, 0, (int) _bufferPosition);
  411. _socketState.ReceivedBytes.AddRange(writebytes);
  412. _socketState.Header = frameHeader; // We need to add the header so that we can unmask it
  413. offset += (int) _bufferPosition;
  414. }
  415. else
  416. {
  417. byte[] writebytes = new byte[_bufferPosition];
  418. Buffer.BlockCopy(_buffer, offset, writebytes, 0, (int) _bufferPosition);
  419. _socketState.FrameComplete = true;
  420. _socketState.ReceivedBytes.AddRange(writebytes);
  421. _socketState.Header = frameHeader;
  422. offset += (int) _bufferPosition;
  423. }
  424. if (_socketState.FrameComplete)
  425. {
  426. ProcessFrame(_socketState);
  427. _socketState.Header.SetDefault();
  428. _socketState.ReceivedBytes.Clear();
  429. _socketState.ExpectedBytes = 0;
  430. // do some processing
  431. }
  432. }
  433. }
  434. if (offset > 0)
  435. {
  436. // If the buffer is maxed out.. we can just move the cursor. Nothing to move to the beginning.
  437. if (offset <_buffer.Length)
  438. Buffer.BlockCopy(_buffer, offset, _buffer, 0, _bufferPosition - offset);
  439. _bufferPosition -= offset;
  440. }
  441. if (_networkContext.Stream != null && _networkContext.Stream.CanRead && !_closing)
  442. {
  443. _networkContext.Stream.BeginRead(_buffer, _bufferPosition, _bufferLength - _bufferPosition, OnReceive,
  444. _socketState);
  445. }
  446. else
  447. {
  448. // We can't read the stream anymore...
  449. }
  450. }
  451. catch (IOException)
  452. {
  453. Close(string.Empty);
  454. }
  455. catch (ObjectDisposedException)
  456. {
  457. Close(string.Empty);
  458. }
  459. }
  460. /// <summary>
  461. /// Sends a string to the other side
  462. /// </summary>
  463. /// <param name="message">the string message that is to be sent</param>
  464. public void SendMessage(string message)
  465. {
  466. if (_initialMsgTimeout > 0)
  467. {
  468. _receiveDone.Set();
  469. _initialMsgTimeout = 0;
  470. }
  471. byte[] messagedata = Encoding.UTF8.GetBytes(message);
  472. WebSocketFrame textMessageFrame = new WebSocketFrame() { Header = WebsocketFrameHeader.HeaderDefault(), WebSocketPayload = messagedata };
  473. textMessageFrame.Header.Opcode = WebSocketReader.OpCode.Text;
  474. textMessageFrame.Header.IsEnd = true;
  475. SendSocket(textMessageFrame.ToBytes());
  476. }
  477. public void SendData(byte[] data)
  478. {
  479. if (_initialMsgTimeout > 0)
  480. {
  481. _receiveDone.Set();
  482. _initialMsgTimeout = 0;
  483. }
  484. WebSocketFrame dataMessageFrame = new WebSocketFrame() { Header = WebsocketFrameHeader.HeaderDefault(), WebSocketPayload = data};
  485. dataMessageFrame.Header.IsEnd = true;
  486. dataMessageFrame.Header.Opcode = WebSocketReader.OpCode.Binary;
  487. SendSocket(dataMessageFrame.ToBytes());
  488. }
  489. /// <summary>
  490. /// Writes raw bytes to the websocket. Unframed data will cause disconnection
  491. /// </summary>
  492. /// <param name="data"></param>
  493. private void SendSocket(byte[] data)
  494. {
  495. if (!_closing)
  496. {
  497. try
  498. {
  499. _networkContext.Stream.Write(data, 0, data.Length);
  500. }
  501. catch (IOException)
  502. {
  503. }
  504. }
  505. }
  506. /// <summary>
  507. /// Sends a Ping check to the other side. The other side SHOULD respond as soon as possible with a pong frame. This interleaves with incoming fragmented frames.
  508. /// </summary>
  509. public void SendPingCheck()
  510. {
  511. if (_initialMsgTimeout > 0)
  512. {
  513. _receiveDone.Set();
  514. _initialMsgTimeout = 0;
  515. }
  516. WebSocketFrame pingFrame = new WebSocketFrame() { Header = WebsocketFrameHeader.HeaderDefault(), WebSocketPayload = Array.Empty<byte>()
  517. };
  518. pingFrame.Header.Opcode = WebSocketReader.OpCode.Ping;
  519. pingFrame.Header.IsEnd = true;
  520. _pingtime = Util.EnvironmentTickCount();
  521. SendSocket(pingFrame.ToBytes());
  522. }
  523. /// <summary>
  524. /// Closes the websocket connection. Sends a close message to the other side if it hasn't already done so.
  525. /// </summary>
  526. /// <param name="message"></param>
  527. public void Close(string message)
  528. {
  529. if (_initialMsgTimeout > 0)
  530. {
  531. _receiveDone.Set();
  532. _initialMsgTimeout = 0;
  533. }
  534. if (_networkContext == null)
  535. return;
  536. if (_networkContext.Stream != null)
  537. {
  538. if (_networkContext.Stream.CanWrite)
  539. {
  540. byte[] messagedata = Encoding.UTF8.GetBytes(message);
  541. WebSocketFrame closeResponseFrame = new WebSocketFrame()
  542. {
  543. Header = WebsocketFrameHeader.HeaderDefault(),
  544. WebSocketPayload = messagedata
  545. };
  546. closeResponseFrame.Header.Opcode = WebSocketReader.OpCode.Close;
  547. closeResponseFrame.Header.PayloadLen = (ulong) messagedata.Length;
  548. closeResponseFrame.Header.IsEnd = true;
  549. SendSocket(closeResponseFrame.ToBytes());
  550. }
  551. }
  552. CloseDelegate closeD = OnClose;
  553. if (closeD != null)
  554. {
  555. closeD(this, new CloseEventArgs());
  556. }
  557. _closing = true;
  558. }
  559. /// <summary>
  560. /// Processes a websocket frame and triggers consumer events
  561. /// </summary>
  562. /// <param name="psocketState">We need to modify the websocket state here depending on the frame</param>
  563. private void ProcessFrame(WebSocketState psocketState)
  564. {
  565. if (psocketState.Header.IsMasked)
  566. {
  567. byte[] unmask = psocketState.ReceivedBytes.ToArray();
  568. WebSocketReader.Mask(psocketState.Header.Mask, unmask);
  569. psocketState.ReceivedBytes = new List<byte>(unmask);
  570. }
  571. if (psocketState.Header.Opcode != WebSocketReader.OpCode.Continue && _initialMsgTimeout > 0)
  572. {
  573. _receiveDone.Set();
  574. _initialMsgTimeout = 0;
  575. }
  576. switch (psocketState.Header.Opcode)
  577. {
  578. case WebSocketReader.OpCode.Ping:
  579. PingDelegate pingD = OnPing;
  580. if (pingD != null)
  581. {
  582. pingD(this, new PingEventArgs());
  583. }
  584. WebSocketFrame pongFrame = new WebSocketFrame(){Header = WebsocketFrameHeader.HeaderDefault(),WebSocketPayload = Array.Empty<byte>()};
  585. pongFrame.Header.Opcode = WebSocketReader.OpCode.Pong;
  586. pongFrame.Header.IsEnd = true;
  587. SendSocket(pongFrame.ToBytes());
  588. break;
  589. case WebSocketReader.OpCode.Pong:
  590. PongDelegate pongD = OnPong;
  591. if (pongD != null)
  592. {
  593. pongD(this, new PongEventArgs(){PingResponseMS = Util.EnvironmentTickCountSubtract(Util.EnvironmentTickCount(),_pingtime)});
  594. }
  595. break;
  596. case WebSocketReader.OpCode.Binary:
  597. if (!psocketState.Header.IsEnd) // Not done, so we need to store this and wait for the end frame.
  598. {
  599. psocketState.ContinuationFrame = new WebSocketFrame
  600. {
  601. Header = psocketState.Header,
  602. WebSocketPayload =
  603. psocketState.ReceivedBytes.ToArray()
  604. };
  605. }
  606. else
  607. {
  608. // Send Done Event!
  609. DataDelegate dataD = OnData;
  610. if (dataD != null)
  611. {
  612. dataD(this,new WebsocketDataEventArgs(){Data = psocketState.ReceivedBytes.ToArray()});
  613. }
  614. }
  615. break;
  616. case WebSocketReader.OpCode.Text:
  617. if (!psocketState.Header.IsEnd) // Not done, so we need to store this and wait for the end frame.
  618. {
  619. psocketState.ContinuationFrame = new WebSocketFrame
  620. {
  621. Header = psocketState.Header,
  622. WebSocketPayload =
  623. psocketState.ReceivedBytes.ToArray()
  624. };
  625. }
  626. else
  627. {
  628. TextDelegate textD = OnText;
  629. if (textD != null)
  630. {
  631. textD(this, new WebsocketTextEventArgs() { Data = Encoding.UTF8.GetString(psocketState.ReceivedBytes.ToArray()) });
  632. }
  633. // Send Done Event!
  634. }
  635. break;
  636. case WebSocketReader.OpCode.Continue: // Continuation. Multiple frames worth of data for one message. Only valid when not using Control Opcodes
  637. //Console.WriteLine("currhead " + psocketState.Header.IsEnd);
  638. //Console.WriteLine("Continuation! " + psocketState.ContinuationFrame.Header.IsEnd);
  639. byte[] combineddata = new byte[psocketState.ReceivedBytes.Count+psocketState.ContinuationFrame.WebSocketPayload.Length];
  640. byte[] newdata = psocketState.ReceivedBytes.ToArray();
  641. Buffer.BlockCopy(psocketState.ContinuationFrame.WebSocketPayload, 0, combineddata, 0, psocketState.ContinuationFrame.WebSocketPayload.Length);
  642. Buffer.BlockCopy(newdata, 0, combineddata,
  643. psocketState.ContinuationFrame.WebSocketPayload.Length, newdata.Length);
  644. psocketState.ContinuationFrame.WebSocketPayload = combineddata;
  645. psocketState.Header.PayloadLen = (ulong)combineddata.Length;
  646. if (psocketState.Header.IsEnd)
  647. {
  648. if (psocketState.ContinuationFrame.Header.Opcode == WebSocketReader.OpCode.Text)
  649. {
  650. // Send Done event
  651. TextDelegate textD = OnText;
  652. if (textD != null)
  653. {
  654. textD(this, new WebsocketTextEventArgs() { Data = Encoding.UTF8.GetString(combineddata) });
  655. }
  656. }
  657. else if (psocketState.ContinuationFrame.Header.Opcode == WebSocketReader.OpCode.Binary)
  658. {
  659. // Send Done event
  660. DataDelegate dataD = OnData;
  661. if (dataD != null)
  662. {
  663. dataD(this, new WebsocketDataEventArgs() { Data = combineddata });
  664. }
  665. }
  666. else
  667. {
  668. // protocol violation
  669. }
  670. psocketState.ContinuationFrame = null;
  671. }
  672. break;
  673. case WebSocketReader.OpCode.Close:
  674. Close(string.Empty);
  675. break;
  676. }
  677. psocketState.Header.SetDefault();
  678. psocketState.ReceivedBytes.Clear();
  679. psocketState.ExpectedBytes = 0;
  680. }
  681. public void Dispose()
  682. {
  683. if (_initialMsgTimeout > 0)
  684. {
  685. _receiveDone.Set();
  686. _initialMsgTimeout = 0;
  687. }
  688. if (_networkContext != null && _networkContext.Stream != null)
  689. {
  690. if (_networkContext.Stream.CanWrite)
  691. _networkContext.Stream.Flush();
  692. _networkContext.Stream.Close();
  693. _networkContext.Stream.Dispose();
  694. _networkContext.Stream = null;
  695. }
  696. if (_request != null && _request.InputStream != null)
  697. {
  698. _request.InputStream.Close();
  699. _request.InputStream.Dispose();
  700. _request = null;
  701. }
  702. if (_clientContext != null)
  703. {
  704. _clientContext.Close();
  705. _clientContext = null;
  706. }
  707. }
  708. }
  709. /// <summary>
  710. /// Reads a byte stream and returns Websocket frames.
  711. /// </summary>
  712. public class WebSocketReader
  713. {
  714. /// <summary>
  715. /// Bit to determine if the frame read on the stream is the last frame in a sequence of fragmented frames
  716. /// </summary>
  717. private const byte EndBit = 0x80;
  718. /// <summary>
  719. /// These are the Frame Opcodes
  720. /// </summary>
  721. public enum OpCode
  722. {
  723. // Data Opcodes
  724. Continue = 0x0,
  725. Text = 0x1,
  726. Binary = 0x2,
  727. // Control flow Opcodes
  728. Close = 0x8,
  729. Ping = 0x9,
  730. Pong = 0xA
  731. }
  732. /// <summary>
  733. /// Masks and Unmasks data using the frame mask. Mask is applied per octal
  734. /// Note: Frames from clients MUST be masked
  735. /// Note: Frames from servers MUST NOT be masked
  736. /// </summary>
  737. /// <param name="pMask">Int representing 32 bytes of mask data. Mask is applied per octal</param>
  738. /// <param name="pBuffer"></param>
  739. public static void Mask(int pMask, byte[] pBuffer)
  740. {
  741. byte[] maskKey = BitConverter.GetBytes(pMask);
  742. int currentMaskIndex = 0;
  743. for (int i = 0; i < pBuffer.Length; i++)
  744. {
  745. pBuffer[i] = (byte)(pBuffer[i] ^ maskKey[currentMaskIndex]);
  746. if (currentMaskIndex == 3)
  747. {
  748. currentMaskIndex = 0;
  749. }
  750. else
  751. {
  752. currentMaskIndex++;
  753. }
  754. }
  755. }
  756. /// <summary>
  757. /// Attempts to read a header off the provided buffer. Returns true, exports a WebSocketFrameheader,
  758. /// and an int to move the buffer forward when it reads a header. False when it can't read a header
  759. /// </summary>
  760. /// <param name="pBuffer">Bytes read from the stream</param>
  761. /// <param name="pOffset">Starting place in the stream to begin trying to read from</param>
  762. /// <param name="length">Lenth in the stream to try and read from. Provided for cases where the
  763. /// buffer's length is larger then the data in it</param>
  764. /// <param name="oHeader">Outputs the read WebSocket frame header</param>
  765. /// <param name="moveBuffer">Informs the calling stream to move the buffer forward</param>
  766. /// <returns>True if it got a header, False if it didn't get a header</returns>
  767. public static bool TryReadHeader(byte[] pBuffer, int pOffset, int length, out WebsocketFrameHeader oHeader,
  768. out int moveBuffer)
  769. {
  770. oHeader = WebsocketFrameHeader.ZeroHeader;
  771. int minumheadersize = 2;
  772. if (length > pBuffer.Length - pOffset)
  773. throw new ArgumentOutOfRangeException("The Length specified was larger the byte array supplied");
  774. if (length < minumheadersize)
  775. {
  776. moveBuffer = 0;
  777. return false;
  778. }
  779. byte nibble1 = (byte)(pBuffer[pOffset] & 0xF0); //FIN/RSV1/RSV2/RSV3
  780. byte nibble2 = (byte)(pBuffer[pOffset] & 0x0F); // Opcode block
  781. oHeader = new WebsocketFrameHeader();
  782. oHeader.SetDefault();
  783. if ((nibble1 & WebSocketReader.EndBit) == WebSocketReader.EndBit)
  784. {
  785. oHeader.IsEnd = true;
  786. }
  787. else
  788. {
  789. oHeader.IsEnd = false;
  790. }
  791. //Opcode
  792. oHeader.Opcode = (WebSocketReader.OpCode)nibble2;
  793. //Mask
  794. oHeader.IsMasked = Convert.ToBoolean((pBuffer[pOffset + 1] & 0x80) >> 7);
  795. // Payload length
  796. oHeader.PayloadLen = (byte)(pBuffer[pOffset + 1] & 0x7F);
  797. int index = 2; // LargerPayload length starts at byte 3
  798. switch (oHeader.PayloadLen)
  799. {
  800. case 126:
  801. minumheadersize += 2;
  802. if (length < minumheadersize)
  803. {
  804. moveBuffer = 0;
  805. return false;
  806. }
  807. Array.Reverse(pBuffer, pOffset + index, 2); // two bytes
  808. oHeader.PayloadLen = BitConverter.ToUInt16(pBuffer, pOffset + index);
  809. index += 2;
  810. break;
  811. case 127: // we got more this is a bigger frame
  812. // 8 bytes - uint64 - most significant bit 0 network byte order
  813. minumheadersize += 8;
  814. if (length < minumheadersize)
  815. {
  816. moveBuffer = 0;
  817. return false;
  818. }
  819. Array.Reverse(pBuffer, pOffset + index, 8);
  820. oHeader.PayloadLen = BitConverter.ToUInt64(pBuffer, pOffset + index);
  821. index += 8;
  822. break;
  823. }
  824. //oHeader.PayloadLeft = oHeader.PayloadLen; // Start the count in case it's chunked over the network. This is different then frame fragmentation
  825. if (oHeader.IsMasked)
  826. {
  827. minumheadersize += 4;
  828. if (length < minumheadersize)
  829. {
  830. moveBuffer = 0;
  831. return false;
  832. }
  833. oHeader.Mask = BitConverter.ToInt32(pBuffer, pOffset + index);
  834. index += 4;
  835. }
  836. moveBuffer = index;
  837. return true;
  838. }
  839. }
  840. /// <summary>
  841. /// RFC6455 Websocket Frame
  842. /// </summary>
  843. public class WebSocketFrame
  844. {
  845. /*
  846. * RFC6455
  847. nib 0 1 2 3 4 5 6 7
  848. byt 0 1 2 3
  849. dec 0 1 2 3
  850. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  851. +-+-+-+-+-------+-+-------------+-------------------------------+
  852. |F|R|R|R| opcode|M| Payload len | Extended payload length |
  853. |I|S|S|S| (4) |A| (7) | (16/64) +
  854. |N|V|V|V| |S| | (if payload len==126/127) |
  855. | |1|2|3| |K| | +
  856. +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
  857. | Extended payload length continued, if payload len == 127 |
  858. + - - - - - - - - - - - - - - - +-------------------------------+
  859. | |Masking-key, if MASK set to 1 |
  860. +-------------------------------+-------------------------------+
  861. | Masking-key (continued) | Payload Data |
  862. +-------------------------------- - - - - - - - - - - - - - - - +
  863. : Payload Data continued ... :
  864. + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
  865. | Payload Data continued ... |
  866. +---------------------------------------------------------------+
  867. * When reading these, the frames are possibly fragmented and interleaved with control frames
  868. * the fragmented frames are not interleaved with data frames. Just control frames
  869. */
  870. public static readonly WebSocketFrame DefaultFrame = new WebSocketFrame(){Header = new WebsocketFrameHeader(),WebSocketPayload = Array.Empty<byte>()};
  871. public WebsocketFrameHeader Header;
  872. public byte[] WebSocketPayload;
  873. public byte[] ToBytes()
  874. {
  875. Header.PayloadLen = (ulong)WebSocketPayload.Length;
  876. return Header.ToBytes(WebSocketPayload);
  877. }
  878. }
  879. public struct WebsocketFrameHeader
  880. {
  881. //public byte CurrentMaskIndex;
  882. /// <summary>
  883. /// The last frame in a sequence of fragmented frames or the one and only frame for this message.
  884. /// </summary>
  885. public bool IsEnd;
  886. /// <summary>
  887. /// Returns whether the payload data is masked or not. Data from Clients MUST be masked, Data from Servers MUST NOT be masked
  888. /// </summary>
  889. public bool IsMasked;
  890. /// <summary>
  891. /// A set of cryptologically sound random bytes XoR-ed against the payload octally. Looped
  892. /// </summary>
  893. public int Mask;
  894. /*
  895. byt 0 1 2 3
  896. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  897. +---------------+---------------+---------------+---------------+
  898. | Octal 1 | Octal 2 | Octal 3 | Octal 4 |
  899. +---------------+---------------+---------------+---------------+
  900. */
  901. public WebSocketReader.OpCode Opcode;
  902. public UInt64 PayloadLen;
  903. //public UInt64 PayloadLeft;
  904. // Payload is X + Y
  905. //public UInt64 ExtensionDataLength;
  906. //public UInt64 ApplicationDataLength;
  907. public static readonly WebsocketFrameHeader ZeroHeader = WebsocketFrameHeader.HeaderDefault();
  908. public void SetDefault()
  909. {
  910. //CurrentMaskIndex = 0;
  911. IsEnd = true;
  912. IsMasked = true;
  913. Mask = 0;
  914. Opcode = WebSocketReader.OpCode.Close;
  915. // PayloadLeft = 0;
  916. PayloadLen = 0;
  917. // ExtensionDataLength = 0;
  918. // ApplicationDataLength = 0;
  919. }
  920. /// <summary>
  921. /// Returns a byte array representing the Frame header
  922. /// </summary>
  923. /// <param name="payload">This is the frame data payload. The header describes the size of the payload.
  924. /// If payload is null, a Zero sized payload is assumed</param>
  925. /// <returns>Returns a byte array representing the frame header</returns>
  926. public byte[] ToBytes(byte[] payload)
  927. {
  928. List<byte> result = new List<byte>();
  929. // Squeeze in our opcode and our ending bit.
  930. result.Add((byte)((byte)Opcode | (IsEnd?0x80:0x00) ));
  931. // Again with the three different byte interpretations of size..
  932. //bytesize
  933. if (PayloadLen <= 125)
  934. {
  935. result.Add((byte) PayloadLen);
  936. } //Uint16
  937. else if (PayloadLen <= ushort.MaxValue)
  938. {
  939. result.Add(126);
  940. byte[] payloadLengthByte = BitConverter.GetBytes(Convert.ToUInt16(PayloadLen));
  941. Array.Reverse(payloadLengthByte);
  942. result.AddRange(payloadLengthByte);
  943. } //UInt64
  944. else
  945. {
  946. result.Add(127);
  947. byte[] payloadLengthByte = BitConverter.GetBytes(PayloadLen);
  948. Array.Reverse(payloadLengthByte);
  949. result.AddRange(payloadLengthByte);
  950. }
  951. // Only add a payload if it's not null
  952. if (payload != null)
  953. {
  954. result.AddRange(payload);
  955. }
  956. return result.ToArray();
  957. }
  958. /// <summary>
  959. /// A Helper method to define the defaults
  960. /// </summary>
  961. /// <returns></returns>
  962. public static WebsocketFrameHeader HeaderDefault()
  963. {
  964. return new WebsocketFrameHeader
  965. {
  966. //CurrentMaskIndex = 0,
  967. IsEnd = false,
  968. IsMasked = true,
  969. Mask = 0,
  970. Opcode = WebSocketReader.OpCode.Close,
  971. //PayloadLeft = 0,
  972. PayloadLen = 0,
  973. // ExtensionDataLength = 0,
  974. // ApplicationDataLength = 0
  975. };
  976. }
  977. }
  978. public delegate void DataDelegate(object sender, WebsocketDataEventArgs data);
  979. public delegate void TextDelegate(object sender, WebsocketTextEventArgs text);
  980. public delegate void PingDelegate(object sender, PingEventArgs pingdata);
  981. public delegate void PongDelegate(object sender, PongEventArgs pongdata);
  982. public delegate void RegularHttpRequestDelegate(object sender, RegularHttpRequestEvnetArgs request);
  983. public delegate void UpgradeCompletedDelegate(object sender, UpgradeCompletedEventArgs completeddata);
  984. public delegate void UpgradeFailedDelegate(object sender, UpgradeFailedEventArgs faileddata);
  985. public delegate void CloseDelegate(object sender, CloseEventArgs closedata);
  986. public delegate bool ValidateHandshake(string pWebOrigin, string pWebSocketKey, string pHost);
  987. public class WebsocketDataEventArgs : EventArgs
  988. {
  989. public byte[] Data;
  990. }
  991. public class WebsocketTextEventArgs : EventArgs
  992. {
  993. public string Data;
  994. }
  995. public class PingEventArgs : EventArgs
  996. {
  997. /// <summary>
  998. /// The ping event can arbitrarily contain data
  999. /// </summary>
  1000. public byte[] Data;
  1001. }
  1002. public class PongEventArgs : EventArgs
  1003. {
  1004. /// <summary>
  1005. /// The pong event can arbitrarily contain data
  1006. /// </summary>
  1007. public byte[] Data;
  1008. public int PingResponseMS;
  1009. }
  1010. public class RegularHttpRequestEvnetArgs : EventArgs
  1011. {
  1012. }
  1013. public class UpgradeCompletedEventArgs : EventArgs
  1014. {
  1015. }
  1016. public class UpgradeFailedEventArgs : EventArgs
  1017. {
  1018. }
  1019. public class CloseEventArgs : EventArgs
  1020. {
  1021. }
  1022. }