WebSocketFrameReader.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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.PlatformSupport.Memory;
  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 unsafe 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 = BufferPool.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. BufferPool.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 = BufferPool.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. BufferPool.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 = BufferPool.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 = BufferPool.Get((long)Length, true);
  87. else
  88. if (Length == 0)
  89. Data = BufferPool.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. fixed (byte* pData = Data, pmask = mask)
  106. {
  107. // Here, instead of byte by byte, we reinterpret cast the data as uints and apply the masking so.
  108. // This way, we can mask 4 bytes in one cycle, instead of just 1
  109. ulong localLength = this.Length / 4;
  110. if (localLength > 0)
  111. {
  112. uint* upData = (uint*)pData;
  113. uint umask = *(uint*)pmask;
  114. unchecked
  115. {
  116. for (ulong i = 0; i < localLength; ++i)
  117. upData[i] = upData[i] ^ umask;
  118. }
  119. }
  120. // Because data might not be exactly dividable by 4, we have to mask the remaining 0..3 too.
  121. ulong from = localLength * 4;
  122. localLength = from + this.Length % 4;
  123. for (ulong i = from; i < localLength; ++i)
  124. pData[i] = (byte)(pData[i] ^ pmask[i % 4]);
  125. }
  126. BufferPool.Release(mask);
  127. }
  128. }
  129. private byte ReadByte(Stream stream)
  130. {
  131. int read = stream.ReadByte();
  132. if (read < 0)
  133. throw ExceptionHelper.ServerClosedTCPStream();
  134. return (byte)read;
  135. }
  136. #endregion
  137. #region Public Functions
  138. /// <summary>
  139. /// Assembles all fragments into a final frame. Call this on the last fragment of a frame.
  140. /// </summary>
  141. /// <param name="fragments">The list of previously downloaded and parsed fragments of the frame</param>
  142. public void Assemble(List<WebSocketFrameReader> fragments)
  143. {
  144. // this way the following algorithms will handle this fragment's data too
  145. fragments.Add(this);
  146. UInt64 finalLength = 0;
  147. for (int i = 0; i < fragments.Count; ++i)
  148. finalLength += fragments[i].Length;
  149. byte[] buffer = fragments[0].Type == WebSocketFrameTypes.Text ? BufferPool.Get((long)finalLength, true) : new byte[finalLength];
  150. UInt64 pos = 0;
  151. for (int i = 0; i < fragments.Count; ++i)
  152. {
  153. Array.Copy(fragments[i].Data, 0, buffer, (int)pos, (int)fragments[i].Length);
  154. fragments[i].ReleaseData();
  155. pos += fragments[i].Length;
  156. }
  157. // All fragments of a message are of the same type, as set by the first fragment's opcode.
  158. this.Type = fragments[0].Type;
  159. // Reserver flags may be contained only in the first fragment
  160. this.Header = fragments[0].Header;
  161. this.Length = finalLength;
  162. this.Data = buffer;
  163. }
  164. /// <summary>
  165. /// This function will decode the received data incrementally with the associated websocket's extensions.
  166. /// </summary>
  167. public void DecodeWithExtensions(WebSocket webSocket)
  168. {
  169. if (webSocket.Extensions != null)
  170. for (int i = 0; i < webSocket.Extensions.Length; ++i)
  171. {
  172. var ext = webSocket.Extensions[i];
  173. if (ext != null)
  174. {
  175. var newData = ext.Decode(this.Header, this.Data, (int)this.Length);
  176. if (this.Data != newData)
  177. {
  178. this.ReleaseData();
  179. this.Data = newData;
  180. this.Length = (ulong)newData.Length;
  181. }
  182. }
  183. }
  184. if (this.Type == WebSocketFrameTypes.Text && this.Data != null)
  185. {
  186. this.DataAsText = System.Text.Encoding.UTF8.GetString(this.Data, 0, (int)this.Length);
  187. this.ReleaseData();
  188. }
  189. }
  190. public void ReleaseData()
  191. {
  192. if (this.Data != null)
  193. {
  194. BufferPool.Release(this.Data);
  195. this.Data = null;
  196. }
  197. }
  198. #endregion
  199. }
  200. }
  201. #endif