WebSocketFrameReader.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using BestHTTP.Extensions;
  6. using BestHTTP.WebSocket.Extensions;
  7. namespace BestHTTP.WebSocket.Frames
  8. {
  9. /// <summary>
  10. /// Represents an incoming WebSocket Frame.
  11. /// </summary>
  12. public struct WebSocketFrameReader
  13. {
  14. #region Properties
  15. public byte Header { get; private set; }
  16. /// <summary>
  17. /// True if it's a final Frame in a sequence, or the only one.
  18. /// </summary>
  19. public bool IsFinal { get; private set; }
  20. /// <summary>
  21. /// The type of the Frame.
  22. /// </summary>
  23. public WebSocketFrameTypes Type { get; private set; }
  24. /// <summary>
  25. /// Indicates if there are any mask sent to decode the data.
  26. /// </summary>
  27. public bool HasMask { get; private set; }
  28. /// <summary>
  29. /// The length of the Data.
  30. /// </summary>
  31. public UInt64 Length { get; private set; }
  32. /// <summary>
  33. /// The decoded array of bytes.
  34. /// </summary>
  35. public byte[] Data { get; private set; }
  36. /// <summary>
  37. /// Textual representation of the received Data.
  38. /// </summary>
  39. public string DataAsText { get; private set; }
  40. #endregion
  41. #region Internal & Private Functions
  42. internal void Read(Stream stream)
  43. {
  44. // For the complete documentation for this section see:
  45. // http://tools.ietf.org/html/rfc6455#section-5.2
  46. this.Header = ReadByte(stream);
  47. // The first byte is the Final Bit and the type of the frame
  48. IsFinal = (this.Header & 0x80) != 0;
  49. Type = (WebSocketFrameTypes)(this.Header & 0xF);
  50. byte maskAndLength = ReadByte(stream);
  51. // The second byte is the Mask Bit and the length of the payload data
  52. HasMask = (maskAndLength & 0x80) != 0;
  53. // if 0-125, that is the payload length.
  54. Length = (UInt64)(maskAndLength & 127);
  55. // If 126, the following 2 bytes interpreted as a 16-bit unsigned integer are the payload length.
  56. if (Length == 126)
  57. {
  58. byte[] rawLen = VariableSizedBufferPool.Get(2, true);
  59. stream.ReadBuffer(rawLen, 2);
  60. if (BitConverter.IsLittleEndian)
  61. Array.Reverse(rawLen, 0, 2);
  62. Length = (UInt64)BitConverter.ToUInt16(rawLen, 0);
  63. VariableSizedBufferPool.Release(rawLen);
  64. }
  65. else if (Length == 127)
  66. {
  67. // If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the
  68. // most significant bit MUST be 0) are the payload length.
  69. byte[] rawLen = VariableSizedBufferPool.Get(8, true);
  70. stream.ReadBuffer(rawLen, 8);
  71. if (BitConverter.IsLittleEndian)
  72. Array.Reverse(rawLen, 0, 8);
  73. Length = (UInt64)BitConverter.ToUInt64(rawLen, 0);
  74. VariableSizedBufferPool.Release(rawLen);
  75. }
  76. // The sent byte array as a mask to decode the data.
  77. byte[] mask = null;
  78. // Read the Mask, if has any
  79. if (HasMask)
  80. {
  81. mask = VariableSizedBufferPool.Get(4, true);
  82. if (stream.Read(mask, 0, 4) < mask.Length)
  83. throw ExceptionHelper.ServerClosedTCPStream();
  84. }
  85. if (Type == WebSocketFrameTypes.Text || Type == WebSocketFrameTypes.Continuation)
  86. Data = VariableSizedBufferPool.Get((long)Length, true);
  87. else
  88. if (Length == 0)
  89. Data = VariableSizedBufferPool.NoData;
  90. else
  91. Data = new byte[Length];
  92. //Data = Type == WebSocketFrameTypes.Text ? VariableSizedBufferPool.Get((long)Length, true) : new byte[Length];
  93. if (Length == 0L)
  94. return;
  95. uint readLength = 0;
  96. do
  97. {
  98. int read = stream.Read(Data, (int)readLength, (int)(Length - readLength));
  99. if (read <= 0)
  100. throw ExceptionHelper.ServerClosedTCPStream();
  101. readLength += (uint)read;
  102. } while (readLength < Length);
  103. if (HasMask)
  104. {
  105. for (uint i = 0; i < Length; ++i)
  106. Data[i] = (byte)(Data[i] ^ mask[i % 4]);
  107. VariableSizedBufferPool.Release(mask);
  108. }
  109. }
  110. private byte ReadByte(Stream stream)
  111. {
  112. int read = stream.ReadByte();
  113. if (read < 0)
  114. throw ExceptionHelper.ServerClosedTCPStream();
  115. return (byte)read;
  116. }
  117. #endregion
  118. #region Public Functions
  119. /// <summary>
  120. /// Assembles all fragments into a final frame. Call this on the last fragment of a frame.
  121. /// </summary>
  122. /// <param name="fragments">The list of previously downloaded and parsed fragments of the frame</param>
  123. public void Assemble(List<WebSocketFrameReader> fragments)
  124. {
  125. // this way the following algorithms will handle this fragment's data too
  126. fragments.Add(this);
  127. UInt64 finalLength = 0;
  128. for (int i = 0; i < fragments.Count; ++i)
  129. finalLength += fragments[i].Length;
  130. byte[] buffer = fragments[0].Type == WebSocketFrameTypes.Text ? VariableSizedBufferPool.Get((long)finalLength, true) : new byte[finalLength];
  131. UInt64 pos = 0;
  132. for (int i = 0; i < fragments.Count; ++i)
  133. {
  134. Array.Copy(fragments[i].Data, 0, buffer, (int)pos, (int)fragments[i].Length);
  135. VariableSizedBufferPool.Release(fragments[i].Data);
  136. pos += fragments[i].Length;
  137. }
  138. // All fragments of a message are of the same type, as set by the first fragment's opcode.
  139. this.Type = fragments[0].Type;
  140. // Reserver flags may be contained only in the first fragment
  141. this.Header = fragments[0].Header;
  142. this.Length = finalLength;
  143. this.Data = buffer;
  144. }
  145. /// <summary>
  146. /// This function will decode the received data incrementally with the associated websocket's extensions.
  147. /// </summary>
  148. public void DecodeWithExtensions(WebSocket webSocket)
  149. {
  150. if (webSocket.Extensions != null)
  151. for (int i = 0; i < webSocket.Extensions.Length; ++i)
  152. {
  153. var ext = webSocket.Extensions[i];
  154. if (ext != null)
  155. {
  156. var newData = ext.Decode(this.Header, this.Data, (int)this.Length);
  157. if (this.Data != newData)
  158. {
  159. VariableSizedBufferPool.Release(this.Data);
  160. this.Data = newData;
  161. this.Length = (ulong)newData.Length;
  162. }
  163. }
  164. }
  165. if (this.Type == WebSocketFrameTypes.Text && this.Data != null)
  166. {
  167. this.DataAsText = System.Text.Encoding.UTF8.GetString(this.Data, 0, (int)this.Length);
  168. VariableSizedBufferPool.Release(this.Data);
  169. this.Data = null;
  170. }
  171. }
  172. #endregion
  173. }
  174. }
  175. #endif