HttpBase.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #region License
  2. /*
  3. * HttpBase.cs
  4. *
  5. * The MIT License
  6. *
  7. * Copyright (c) 2012-2022 sta.blockhead
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #endregion
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Collections.Specialized;
  31. using System.IO;
  32. using System.Linq;
  33. using System.Text;
  34. using System.Threading;
  35. using WebSocketSharp.Net;
  36. namespace WebSocketSharp
  37. {
  38. internal abstract class HttpBase
  39. {
  40. #region Private Fields
  41. private NameValueCollection _headers;
  42. private static readonly int _maxMessageHeaderLength;
  43. private string _messageBody;
  44. private byte[] _messageBodyData;
  45. private Version _version;
  46. #endregion
  47. #region Protected Fields
  48. protected static readonly string CrLf;
  49. protected static readonly string CrLfHt;
  50. protected static readonly string CrLfSp;
  51. #endregion
  52. #region Static Constructor
  53. static HttpBase ()
  54. {
  55. _maxMessageHeaderLength = 8192;
  56. CrLf = "\r\n";
  57. CrLfHt = "\r\n\t";
  58. CrLfSp = "\r\n ";
  59. }
  60. #endregion
  61. #region Protected Constructors
  62. protected HttpBase (Version version, NameValueCollection headers)
  63. {
  64. _version = version;
  65. _headers = headers;
  66. }
  67. #endregion
  68. #region Internal Properties
  69. internal byte[] MessageBodyData {
  70. get {
  71. return _messageBodyData;
  72. }
  73. }
  74. #endregion
  75. #region Protected Properties
  76. protected string HeaderSection {
  77. get {
  78. var buff = new StringBuilder (64);
  79. foreach (var key in _headers.AllKeys)
  80. buff.AppendFormat ("{0}: {1}{2}", key, _headers[key], CrLf);
  81. buff.Append (CrLf);
  82. return buff.ToString ();
  83. }
  84. }
  85. #endregion
  86. #region Public Properties
  87. public bool HasMessageBody {
  88. get {
  89. return _messageBodyData != null;
  90. }
  91. }
  92. public NameValueCollection Headers {
  93. get {
  94. return _headers;
  95. }
  96. }
  97. public string MessageBody {
  98. get {
  99. if (_messageBody == null)
  100. _messageBody = getMessageBody ();
  101. return _messageBody;
  102. }
  103. }
  104. public abstract string MessageHeader { get; }
  105. public Version ProtocolVersion {
  106. get {
  107. return _version;
  108. }
  109. }
  110. #endregion
  111. #region Private Methods
  112. private string getMessageBody ()
  113. {
  114. if (_messageBodyData == null || _messageBodyData.LongLength == 0)
  115. return String.Empty;
  116. var contentType = _headers["Content-Type"];
  117. var enc = contentType != null && contentType.Length > 0
  118. ? HttpUtility.GetEncoding (contentType)
  119. : Encoding.UTF8;
  120. return enc.GetString (_messageBodyData);
  121. }
  122. private static byte[] readMessageBodyFrom (Stream stream, string length)
  123. {
  124. long len;
  125. if (!Int64.TryParse (length, out len)) {
  126. var msg = "It cannot be parsed.";
  127. throw new ArgumentException (msg, "length");
  128. }
  129. if (len < 0) {
  130. var msg = "It is less than zero.";
  131. throw new ArgumentOutOfRangeException ("length", msg);
  132. }
  133. return len > 1024
  134. ? stream.ReadBytes (len, 1024)
  135. : len > 0
  136. ? stream.ReadBytes ((int) len)
  137. : null;
  138. }
  139. private static string[] readMessageHeaderFrom (Stream stream)
  140. {
  141. var buff = new List<byte> ();
  142. var cnt = 0;
  143. Action<int> add =
  144. i => {
  145. if (i == -1) {
  146. var msg = "The header could not be read from the data stream.";
  147. throw new EndOfStreamException (msg);
  148. }
  149. buff.Add ((byte) i);
  150. cnt++;
  151. };
  152. var end = false;
  153. do {
  154. end = stream.ReadByte ().IsEqualTo ('\r', add)
  155. && stream.ReadByte ().IsEqualTo ('\n', add)
  156. && stream.ReadByte ().IsEqualTo ('\r', add)
  157. && stream.ReadByte ().IsEqualTo ('\n', add);
  158. if (cnt > _maxMessageHeaderLength) {
  159. var msg = "The length of the header is greater than the max length.";
  160. throw new InvalidOperationException (msg);
  161. }
  162. }
  163. while (!end);
  164. var bytes = buff.ToArray ();
  165. return Encoding.UTF8.GetString (bytes)
  166. .Replace (CrLfSp, " ")
  167. .Replace (CrLfHt, " ")
  168. .Split (new[] { CrLf }, StringSplitOptions.RemoveEmptyEntries);
  169. }
  170. #endregion
  171. #region Internal Methods
  172. internal void WriteTo (Stream stream)
  173. {
  174. var bytes = ToByteArray ();
  175. stream.Write (bytes, 0, bytes.Length);
  176. }
  177. #endregion
  178. #region Protected Methods
  179. protected static T Read<T> (
  180. Stream stream, Func<string[], T> parser, int millisecondsTimeout
  181. )
  182. where T : HttpBase
  183. {
  184. T ret = null;
  185. var timeout = false;
  186. var timer = new Timer (
  187. state => {
  188. timeout = true;
  189. stream.Close ();
  190. },
  191. null,
  192. millisecondsTimeout,
  193. -1
  194. );
  195. Exception exception = null;
  196. try {
  197. var header = readMessageHeaderFrom (stream);
  198. ret = parser (header);
  199. var contentLen = ret.Headers["Content-Length"];
  200. if (contentLen != null && contentLen.Length > 0)
  201. ret._messageBodyData = readMessageBodyFrom (stream, contentLen);
  202. }
  203. catch (Exception ex) {
  204. exception = ex;
  205. }
  206. finally {
  207. timer.Change (-1, -1);
  208. timer.Dispose ();
  209. }
  210. if (timeout) {
  211. var msg = "A timeout has occurred.";
  212. throw new WebSocketException (msg);
  213. }
  214. if (exception != null) {
  215. var msg = "An exception has occurred.";
  216. throw new WebSocketException (msg, exception);
  217. }
  218. return ret;
  219. }
  220. #endregion
  221. #region Public Methods
  222. public byte[] ToByteArray ()
  223. {
  224. var headerData = Encoding.UTF8.GetBytes (MessageHeader);
  225. return _messageBodyData != null
  226. ? headerData.Concat (_messageBodyData).ToArray ()
  227. : headerData;
  228. }
  229. public override string ToString ()
  230. {
  231. return _messageBodyData != null
  232. ? MessageHeader + MessageBody
  233. : MessageHeader;
  234. }
  235. #endregion
  236. }
  237. }