WebSocketFrameReader.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 sealed class 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 sent byte array as a mask to decode the data.
  34. /// </summary>
  35. public byte[] Mask { get; private set; }
  36. /// <summary>
  37. /// The decoded array of bytes.
  38. /// </summary>
  39. public byte[] Data { get; private set; }
  40. /// <summary>
  41. /// Textual representation of the received Data.
  42. /// </summary>
  43. public string DataAsText { get; private set; }
  44. #endregion
  45. #region Internal & Private Functions
  46. internal void Read(Stream stream)
  47. {
  48. // For the complete documentation for this section see:
  49. // http://tools.ietf.org/html/rfc6455#section-5.2
  50. this.Header = ReadByte(stream);
  51. // The first byte is the Final Bit and the type of the frame
  52. IsFinal = (this.Header & 0x80) != 0;
  53. Type = (WebSocketFrameTypes)(this.Header & 0xF);
  54. byte maskAndLength = ReadByte(stream);
  55. // The second byte is the Mask Bit and the length of the payload data
  56. HasMask = (maskAndLength & 0x80) != 0;
  57. // if 0-125, that is the payload length.
  58. Length = (UInt64)(maskAndLength & 127);
  59. // If 126, the following 2 bytes interpreted as a 16-bit unsigned integer are the payload length.
  60. if (Length == 126)
  61. {
  62. byte[] rawLen = new byte[2];
  63. stream.ReadBuffer(rawLen);
  64. if (BitConverter.IsLittleEndian)
  65. Array.Reverse(rawLen, 0, rawLen.Length);
  66. Length = (UInt64)BitConverter.ToUInt16(rawLen, 0);
  67. }
  68. else if (Length == 127)
  69. {
  70. // If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the
  71. // most significant bit MUST be 0) are the payload length.
  72. byte[] rawLen = new byte[8];
  73. stream.ReadBuffer(rawLen);
  74. if (BitConverter.IsLittleEndian)
  75. Array.Reverse(rawLen, 0, rawLen.Length);
  76. Length = (UInt64)BitConverter.ToUInt64(rawLen, 0);
  77. }
  78. // Read the Mask, if has any
  79. if (HasMask)
  80. {
  81. Mask = new byte[4];
  82. if (stream.Read(Mask, 0, 4) < Mask.Length)
  83. throw ExceptionHelper.ServerClosedTCPStream();
  84. }
  85. Data = new byte[Length];
  86. if (Length == 0L)
  87. return;
  88. int readLength = 0;
  89. do
  90. {
  91. int read = stream.Read(Data, readLength, Data.Length - readLength);
  92. if (read <= 0)
  93. throw ExceptionHelper.ServerClosedTCPStream();
  94. readLength += read;
  95. } while (readLength < Data.Length);
  96. // It would be great to speed this up with SSE
  97. if (HasMask)
  98. for (int i = 0; i < Data.Length; ++i)
  99. Data[i] = (byte)(Data[i] ^ Mask[i % 4]);
  100. }
  101. private byte ReadByte(Stream stream)
  102. {
  103. int read = stream.ReadByte();
  104. if (read < 0)
  105. throw ExceptionHelper.ServerClosedTCPStream();
  106. return (byte)read;
  107. }
  108. #endregion
  109. #region Public Functions
  110. /// <summary>
  111. /// Assembles all fragments into a final frame. Call this on the last fragment of a frame.
  112. /// </summary>
  113. /// <param name="fragments">The list of previously downloaded and parsed fragments of the frame</param>
  114. public void Assemble(List<WebSocketFrameReader> fragments)
  115. {
  116. // this way the following algorithms will handle this fragment's data too
  117. fragments.Add(this);
  118. UInt64 finalLength = 0;
  119. for (int i = 0; i < fragments.Count; ++i)
  120. finalLength += fragments[i].Length;
  121. byte[] buffer = new byte[finalLength];
  122. UInt64 pos = 0;
  123. for (int i = 0; i < fragments.Count; ++i)
  124. {
  125. Array.Copy(fragments[i].Data, 0, buffer, (int)pos, (int)fragments[i].Length);
  126. pos += fragments[i].Length;
  127. }
  128. // All fragments of a message are of the same type, as set by the first fragment's opcode.
  129. this.Type = fragments[0].Type;
  130. // Reserver flags may be contained only in the first fragment
  131. this.Header = fragments[0].Header;
  132. this.Length = finalLength;
  133. this.Data = buffer;
  134. }
  135. /// <summary>
  136. /// This function will decode the received data incrementally with the associated websocket's extensions.
  137. /// </summary>
  138. public void DecodeWithExtensions(WebSocket webSocket)
  139. {
  140. if (webSocket.Extensions != null)
  141. for (int i = 0; i < webSocket.Extensions.Length; ++i)
  142. {
  143. var ext = webSocket.Extensions[i];
  144. if (ext != null)
  145. this.Data = ext.Decode(this.Header, this.Data);
  146. }
  147. if (this.Type == WebSocketFrameTypes.Text && this.Data != null)
  148. this.DataAsText = System.Text.Encoding.UTF8.GetString(this.Data, 0, this.Data.Length);
  149. }
  150. #endregion
  151. }
  152. }
  153. #endif