HttpListenerRequest.Managed.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using MediaBrowser.Model.Services;
  5. namespace SocketHttpListener.Net
  6. {
  7. public sealed partial class HttpListenerRequest
  8. {
  9. private long _contentLength;
  10. private bool _clSet;
  11. private WebHeaderCollection _headers;
  12. private string _method;
  13. private Stream _inputStream;
  14. private HttpListenerContext _context;
  15. private bool _isChunked;
  16. private static byte[] s_100continue = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");
  17. internal HttpListenerRequest(HttpListenerContext context)
  18. {
  19. _context = context;
  20. _headers = new WebHeaderCollection();
  21. _version = HttpVersion.Version10;
  22. }
  23. private static readonly char[] s_separators = new char[] { ' ' };
  24. internal void SetRequestLine(string req)
  25. {
  26. string[] parts = req.Split(s_separators, 3);
  27. if (parts.Length != 3)
  28. {
  29. _context.ErrorMessage = "Invalid request line (parts).";
  30. return;
  31. }
  32. _method = parts[0];
  33. foreach (char c in _method)
  34. {
  35. int ic = (int)c;
  36. if ((ic >= 'A' && ic <= 'Z') ||
  37. (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
  38. c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
  39. c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
  40. c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
  41. continue;
  42. _context.ErrorMessage = "(Invalid verb)";
  43. return;
  44. }
  45. _rawUrl = parts[1];
  46. if (parts[2].Length != 8 || !parts[2].StartsWith("HTTP/"))
  47. {
  48. _context.ErrorMessage = "Invalid request line (version).";
  49. return;
  50. }
  51. try
  52. {
  53. _version = new Version(parts[2].Substring(5));
  54. }
  55. catch
  56. {
  57. _context.ErrorMessage = "Invalid request line (version).";
  58. return;
  59. }
  60. if (_version.Major < 1)
  61. {
  62. _context.ErrorMessage = "Invalid request line (version).";
  63. return;
  64. }
  65. if (_version.Major > 1)
  66. {
  67. _context.ErrorStatus = (int)HttpStatusCode.HttpVersionNotSupported;
  68. _context.ErrorMessage = HttpStatusDescription.Get(HttpStatusCode.HttpVersionNotSupported);
  69. return;
  70. }
  71. }
  72. private static bool MaybeUri(string s)
  73. {
  74. int p = s.IndexOf(':');
  75. if (p == -1)
  76. return false;
  77. if (p >= 10)
  78. return false;
  79. return IsPredefinedScheme(s.Substring(0, p));
  80. }
  81. private static bool IsPredefinedScheme(string scheme)
  82. {
  83. if (scheme == null || scheme.Length < 3)
  84. return false;
  85. char c = scheme[0];
  86. if (c == 'h')
  87. return (scheme == UriScheme.Http || scheme == UriScheme.Https);
  88. if (c == 'f')
  89. return (scheme == UriScheme.File || scheme == UriScheme.Ftp);
  90. if (c == 'n')
  91. {
  92. c = scheme[1];
  93. if (c == 'e')
  94. return (scheme == UriScheme.News || scheme == UriScheme.NetPipe || scheme == UriScheme.NetTcp);
  95. if (scheme == UriScheme.Nntp)
  96. return true;
  97. return false;
  98. }
  99. if ((c == 'g' && scheme == UriScheme.Gopher) || (c == 'm' && scheme == UriScheme.Mailto))
  100. return true;
  101. return false;
  102. }
  103. internal void FinishInitialization()
  104. {
  105. string host = UserHostName;
  106. if (_version > HttpVersion.Version10 && (host == null || host.Length == 0))
  107. {
  108. _context.ErrorMessage = "Invalid host name";
  109. return;
  110. }
  111. string path;
  112. Uri raw_uri = null;
  113. if (MaybeUri(_rawUrl.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri))
  114. path = raw_uri.PathAndQuery;
  115. else
  116. path = _rawUrl;
  117. if ((host == null || host.Length == 0))
  118. host = UserHostAddress;
  119. if (raw_uri != null)
  120. host = raw_uri.Host;
  121. int colon = host.IndexOf(']') == -1 ? host.IndexOf(':') : host.LastIndexOf(':');
  122. if (colon >= 0)
  123. host = host.Substring(0, colon);
  124. string base_uri = string.Format("{0}://{1}:{2}", RequestScheme, host, LocalEndPoint.Port);
  125. if (!Uri.TryCreate(base_uri + path, UriKind.Absolute, out _requestUri))
  126. {
  127. _context.ErrorMessage = System.Net.WebUtility.HtmlEncode("Invalid url: " + base_uri + path);
  128. return;
  129. }
  130. _requestUri = HttpListenerRequestUriBuilder.GetRequestUri(_rawUrl, _requestUri.Scheme,
  131. _requestUri.Authority, _requestUri.LocalPath, _requestUri.Query);
  132. if (_version >= HttpVersion.Version11)
  133. {
  134. string t_encoding = Headers[HttpKnownHeaderNames.TransferEncoding];
  135. _isChunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase));
  136. // 'identity' is not valid!
  137. if (t_encoding != null && !_isChunked)
  138. {
  139. _context.Connection.SendError(null, 501);
  140. return;
  141. }
  142. }
  143. if (!_isChunked && !_clSet)
  144. {
  145. if (string.Equals(_method, "POST", StringComparison.OrdinalIgnoreCase) ||
  146. string.Equals(_method, "PUT", StringComparison.OrdinalIgnoreCase))
  147. {
  148. _context.Connection.SendError(null, 411);
  149. return;
  150. }
  151. }
  152. if (string.Compare(Headers[HttpKnownHeaderNames.Expect], "100-continue", StringComparison.OrdinalIgnoreCase) == 0)
  153. {
  154. HttpResponseStream output = _context.Connection.GetResponseStream();
  155. output.InternalWrite(s_100continue, 0, s_100continue.Length);
  156. }
  157. }
  158. internal static string Unquote(string str)
  159. {
  160. int start = str.IndexOf('\"');
  161. int end = str.LastIndexOf('\"');
  162. if (start >= 0 && end >= 0)
  163. str = str.Substring(start + 1, end - 1);
  164. return str.Trim();
  165. }
  166. internal void AddHeader(string header)
  167. {
  168. int colon = header.IndexOf(':');
  169. if (colon == -1 || colon == 0)
  170. {
  171. _context.ErrorMessage = HttpStatusDescription.Get(400);
  172. _context.ErrorStatus = 400;
  173. return;
  174. }
  175. string name = header.Substring(0, colon).Trim();
  176. string val = header.Substring(colon + 1).Trim();
  177. if (name.Equals("content-length", StringComparison.OrdinalIgnoreCase))
  178. {
  179. // To match Windows behavior:
  180. // Content lengths >= 0 and <= long.MaxValue are accepted as is.
  181. // Content lengths > long.MaxValue and <= ulong.MaxValue are treated as 0.
  182. // Content lengths < 0 cause the requests to fail.
  183. // Other input is a failure, too.
  184. long parsedContentLength =
  185. ulong.TryParse(val, out ulong parsedUlongContentLength) ? (parsedUlongContentLength <= long.MaxValue ? (long)parsedUlongContentLength : 0) :
  186. long.Parse(val);
  187. if (parsedContentLength < 0 || (_clSet && parsedContentLength != _contentLength))
  188. {
  189. _context.ErrorMessage = "Invalid Content-Length.";
  190. }
  191. else
  192. {
  193. _contentLength = parsedContentLength;
  194. _clSet = true;
  195. }
  196. }
  197. else if (name.Equals("transfer-encoding", StringComparison.OrdinalIgnoreCase))
  198. {
  199. if (Headers[HttpKnownHeaderNames.TransferEncoding] != null)
  200. {
  201. _context.ErrorStatus = (int)HttpStatusCode.NotImplemented;
  202. _context.ErrorMessage = HttpStatusDescription.Get(HttpStatusCode.NotImplemented);
  203. }
  204. }
  205. if (_context.ErrorMessage == null)
  206. {
  207. _headers.Set(name, val);
  208. }
  209. }
  210. // returns true is the stream could be reused.
  211. internal bool FlushInput()
  212. {
  213. if (!HasEntityBody)
  214. return true;
  215. int length = 2048;
  216. if (_contentLength > 0)
  217. length = (int)Math.Min(_contentLength, (long)length);
  218. byte[] bytes = new byte[length];
  219. while (true)
  220. {
  221. try
  222. {
  223. IAsyncResult ares = InputStream.BeginRead(bytes, 0, length, null, null);
  224. if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne(1000))
  225. return false;
  226. if (InputStream.EndRead(ares) <= 0)
  227. return true;
  228. }
  229. catch (ObjectDisposedException)
  230. {
  231. _inputStream = null;
  232. return true;
  233. }
  234. catch
  235. {
  236. return false;
  237. }
  238. }
  239. }
  240. public long ContentLength64
  241. {
  242. get
  243. {
  244. if (_isChunked)
  245. _contentLength = -1;
  246. return _contentLength;
  247. }
  248. }
  249. public bool HasEntityBody => (_contentLength > 0 || _isChunked);
  250. public QueryParamCollection Headers => _headers;
  251. public string HttpMethod => _method;
  252. public Stream InputStream
  253. {
  254. get
  255. {
  256. if (_inputStream == null)
  257. {
  258. if (_isChunked || _contentLength > 0)
  259. _inputStream = _context.Connection.GetRequestStream(_isChunked, _contentLength);
  260. else
  261. _inputStream = Stream.Null;
  262. }
  263. return _inputStream;
  264. }
  265. }
  266. public bool IsAuthenticated => false;
  267. public bool IsSecureConnection => _context.Connection.IsSecure;
  268. public System.Net.IPEndPoint LocalEndPoint => _context.Connection.LocalEndPoint;
  269. public System.Net.IPEndPoint RemoteEndPoint => _context.Connection.RemoteEndPoint;
  270. public Guid RequestTraceIdentifier { get; } = Guid.NewGuid();
  271. public string ServiceName => null;
  272. private Uri RequestUri => _requestUri;
  273. private bool SupportsWebSockets => true;
  274. }
  275. }