HttpRequestParser.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using System;
  2. using System.Text;
  3. using OSHttpServer.Exceptions;
  4. namespace OSHttpServer.Parser
  5. {
  6. /// <summary>
  7. /// Parses a HTTP request directly from a stream
  8. /// </summary>
  9. public class HttpRequestParser : IHttpRequestParser
  10. {
  11. private ILogWriter m_log;
  12. private readonly BodyEventArgs m_bodyArgs = new BodyEventArgs();
  13. private readonly HeaderEventArgs m_headerArgs = new HeaderEventArgs();
  14. private readonly RequestLineEventArgs m_requestLineArgs = new RequestLineEventArgs();
  15. private string m_curHeaderName = string.Empty;
  16. private string m_curHeaderValue = string.Empty;
  17. private int m_bodyBytesLeft;
  18. /// <summary>
  19. /// More body bytes have been received.
  20. /// </summary>
  21. public event EventHandler<BodyEventArgs> BodyBytesReceived;
  22. /// <summary>
  23. /// Request line have been received.
  24. /// </summary>
  25. public event EventHandler<RequestLineEventArgs> RequestLineReceived;
  26. /// <summary>
  27. /// A header have been received.
  28. /// </summary>
  29. public event EventHandler<HeaderEventArgs> HeaderReceived;
  30. /// <summary>
  31. /// Create a new request parser
  32. /// </summary>
  33. /// <param name="logWriter">delegate receiving log entries.</param>
  34. public HttpRequestParser(ILogWriter logWriter)
  35. {
  36. m_log = logWriter ?? NullLogWriter.Instance;
  37. }
  38. /// <summary>
  39. /// Add a number of bytes to the body
  40. /// </summary>
  41. /// <param name="buffer">buffer containing more body bytes.</param>
  42. /// <param name="offset">starting offset in buffer</param>
  43. /// <param name="count">number of bytes, from offset, to read.</param>
  44. /// <returns>offset to continue from.</returns>
  45. private int AddToBody(byte[] buffer, int offset, int count)
  46. {
  47. // got all bytes we need, or just a few of them?
  48. int bytesUsed = count > m_bodyBytesLeft ? m_bodyBytesLeft : count;
  49. m_bodyArgs.Buffer = buffer;
  50. m_bodyArgs.Offset = offset;
  51. m_bodyArgs.Count = bytesUsed;
  52. BodyBytesReceived?.Invoke(this, m_bodyArgs);
  53. m_bodyBytesLeft -= bytesUsed;
  54. if (m_bodyBytesLeft == 0)
  55. {
  56. // got a complete request.
  57. m_log.Write(this, LogPrio.Trace, "Request parsed successfully.");
  58. OnRequestCompleted();
  59. Clear();
  60. }
  61. return offset + bytesUsed;
  62. }
  63. /// <summary>
  64. /// Remove all state information for the request.
  65. /// </summary>
  66. public void Clear()
  67. {
  68. m_bodyBytesLeft = 0;
  69. m_curHeaderName = string.Empty;
  70. m_curHeaderValue = string.Empty;
  71. CurrentState = RequestParserState.FirstLine;
  72. }
  73. /// <summary>
  74. /// Gets or sets the log writer.
  75. /// </summary>
  76. public ILogWriter LogWriter
  77. {
  78. get { return m_log; }
  79. set { m_log = value ?? NullLogWriter.Instance; }
  80. }
  81. /// <summary>
  82. /// Parse request line
  83. /// </summary>
  84. /// <param name="value"></param>
  85. /// <exception cref="BadRequestException">If line is incorrect</exception>
  86. /// <remarks>Expects the following format: "Method SP Request-URI SP HTTP-Version CRLF"</remarks>
  87. protected void OnFirstLine(string value)
  88. {
  89. //
  90. //todo: In the interest of robustness, servers SHOULD ignore any empty line(s) received where a Request-Line is expected.
  91. // In other words, if the server is reading the protocol stream at the beginning of a message and receives a CRLF first, it should ignore the CRLF.
  92. //
  93. m_log.Write(this, LogPrio.Debug, "Got request: " + value);
  94. //Request-Line = Method SP Request-URI SP HTTP-Version CRLF
  95. int pos = value.IndexOf(' ');
  96. if (pos == -1 || pos + 1 >= value.Length)
  97. {
  98. m_log.Write(this, LogPrio.Warning, "Invalid request line, missing Method. Line: " + value);
  99. throw new BadRequestException("Invalid request line, missing Method. Line: " + value);
  100. }
  101. string method = value.Substring(0, pos).ToUpper();
  102. int oldPos = pos + 1;
  103. pos = value.IndexOf(' ', oldPos);
  104. if (pos == -1)
  105. {
  106. m_log.Write(this, LogPrio.Warning, "Invalid request line, missing URI. Line: " + value);
  107. throw new BadRequestException("Invalid request line, missing URI. Line: " + value);
  108. }
  109. string path = value.Substring(oldPos, pos - oldPos);
  110. if (path.Length > 4196)
  111. throw new BadRequestException("Too long URI.");
  112. if (path == "*")
  113. throw new BadRequestException("Not supported URI.");
  114. if (pos + 1 >= value.Length)
  115. {
  116. m_log.Write(this, LogPrio.Warning, "Invalid request line, missing HTTP-Version. Line: " + value);
  117. throw new BadRequestException("Invalid request line, missing HTTP-Version. Line: " + value);
  118. }
  119. string version = value.Substring(pos + 1);
  120. if (version.Length < 4 || string.Compare(version.Substring(0, 4), "HTTP", true) != 0)
  121. {
  122. m_log.Write(this, LogPrio.Warning, "Invalid HTTP version in request line. Line: " + value);
  123. throw new BadRequestException("Invalid HTTP version in Request line. Line: " + value);
  124. }
  125. m_requestLineArgs.HttpMethod = method;
  126. m_requestLineArgs.HttpVersion = version;
  127. m_requestLineArgs.UriPath = path;
  128. RequestLineReceived(this, m_requestLineArgs);
  129. }
  130. /// <summary>
  131. /// We've parsed a new header.
  132. /// </summary>
  133. /// <param name="name">Name in lower case</param>
  134. /// <param name="value">Value, unmodified.</param>
  135. /// <exception cref="BadRequestException">If content length cannot be parsed.</exception>
  136. protected void OnHeader(string name, string value)
  137. {
  138. m_headerArgs.Name = name;
  139. m_headerArgs.Value = value;
  140. if (string.Compare(name, "content-length", true) == 0)
  141. {
  142. if (!int.TryParse(value, out m_bodyBytesLeft))
  143. throw new BadRequestException("Content length is not a number.");
  144. }
  145. HeaderReceived?.Invoke(this, m_headerArgs);
  146. }
  147. private void OnRequestCompleted()
  148. {
  149. RequestCompleted?.Invoke(this, EventArgs.Empty);
  150. }
  151. #region IHttpRequestParser Members
  152. /// <summary>
  153. /// Current state in parser.
  154. /// </summary>
  155. public RequestParserState CurrentState { get; private set; }
  156. /// <summary>
  157. /// Parse a message
  158. /// </summary>
  159. /// <param name="buffer">bytes to parse.</param>
  160. /// <param name="offset">where in buffer that parsing should start</param>
  161. /// <param name="count">number of bytes to parse, starting on <paramref name="offset"/>.</param>
  162. /// <returns>offset (where to start parsing next).</returns>
  163. /// <exception cref="BadRequestException"><c>BadRequestException</c>.</exception>
  164. public int Parse(byte[] buffer, int offset, int count)
  165. {
  166. // add body bytes
  167. if (CurrentState == RequestParserState.Body)
  168. {
  169. return AddToBody(buffer, offset, count);
  170. }
  171. int currentLine = 1;
  172. int startPos = -1;
  173. // set start pos since this is from an partial request
  174. if (CurrentState == RequestParserState.HeaderValue)
  175. startPos = 0;
  176. int endOfBufferPos = offset + count;
  177. //<summary>
  178. // Handled bytes are used to keep track of the number of bytes processed.
  179. // We do this since we can handle partial requests (to be able to check headers and abort
  180. // invalid requests directly without having to process the whole header / body).
  181. // </summary>
  182. int handledBytes = 0;
  183. for (int currentPos = offset; currentPos < endOfBufferPos; ++currentPos)
  184. {
  185. var ch = (char)buffer[currentPos];
  186. char nextCh = endOfBufferPos > currentPos + 1 ? (char)buffer[currentPos + 1] : char.MinValue;
  187. if (ch == '\r')
  188. ++currentLine;
  189. switch (CurrentState)
  190. {
  191. case RequestParserState.FirstLine:
  192. if (currentPos == 8191)
  193. {
  194. m_log.Write(this, LogPrio.Warning, "HTTP Request is too large.");
  195. throw new BadRequestException("Too large request line.");
  196. }
  197. if (char.IsLetterOrDigit(ch) && startPos == -1)
  198. startPos = currentPos;
  199. if (startPos == -1 && (ch != '\r' || nextCh != '\n'))
  200. {
  201. m_log.Write(this, LogPrio.Warning, "Request line is not found.");
  202. throw new BadRequestException("Invalid request line.");
  203. }
  204. if (startPos != -1 && (ch == '\r' || ch == '\n'))
  205. {
  206. int size = GetLineBreakSize(buffer, currentPos);
  207. OnFirstLine(Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos));
  208. CurrentState = CurrentState + 1;
  209. currentPos += size - 1;
  210. handledBytes = currentPos + size - 1;
  211. startPos = -1;
  212. }
  213. break;
  214. case RequestParserState.HeaderName:
  215. if (ch == '\r' || ch == '\n')
  216. {
  217. currentPos += GetLineBreakSize(buffer, currentPos);
  218. if (m_bodyBytesLeft == 0)
  219. {
  220. CurrentState = RequestParserState.FirstLine;
  221. m_log.Write(this, LogPrio.Trace, "Request parsed successfully (no content).");
  222. OnRequestCompleted();
  223. Clear();
  224. return currentPos;
  225. }
  226. CurrentState = RequestParserState.Body;
  227. if (currentPos + 1 < endOfBufferPos)
  228. {
  229. m_log.Write(this, LogPrio.Trace, "Adding bytes to the body");
  230. return AddToBody(buffer, currentPos, endOfBufferPos - currentPos);
  231. }
  232. return currentPos;
  233. }
  234. if (char.IsWhiteSpace(ch) || ch == ':')
  235. {
  236. if (startPos == -1)
  237. {
  238. m_log.Write(this, LogPrio.Warning,
  239. "Expected header name, got colon on line " + currentLine);
  240. throw new BadRequestException("Expected header name, got colon on line " + currentLine);
  241. }
  242. m_curHeaderName = Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos);
  243. handledBytes = currentPos + 1;
  244. startPos = -1;
  245. CurrentState = CurrentState + 1;
  246. if (ch == ':')
  247. CurrentState = CurrentState + 1;
  248. }
  249. else if (startPos == -1)
  250. startPos = currentPos;
  251. else if (!char.IsLetterOrDigit(ch) && ch != '-')
  252. {
  253. m_log.Write(this, LogPrio.Warning, "Invalid character in header name on line " + currentLine);
  254. throw new BadRequestException("Invalid character in header name on line " + currentLine);
  255. }
  256. if (startPos != -1 && currentPos - startPos > 200)
  257. {
  258. m_log.Write(this, LogPrio.Warning, "Invalid header name on line " + currentLine);
  259. throw new BadRequestException("Invalid header name on line " + currentLine);
  260. }
  261. break;
  262. case RequestParserState.AfterName:
  263. if (ch == ':')
  264. {
  265. handledBytes = currentPos + 1;
  266. CurrentState = CurrentState + 1;
  267. }
  268. break;
  269. case RequestParserState.Between:
  270. {
  271. if (ch == ' ' || ch == '\t')
  272. continue;
  273. int newLineSize = GetLineBreakSize(buffer, currentPos);
  274. if (newLineSize > 0 && currentPos + newLineSize < endOfBufferPos &&
  275. char.IsWhiteSpace((char)buffer[currentPos + newLineSize]))
  276. {
  277. ++currentPos;
  278. continue;
  279. }
  280. startPos = currentPos;
  281. CurrentState = CurrentState + 1;
  282. handledBytes = currentPos;
  283. continue;
  284. }
  285. case RequestParserState.HeaderValue:
  286. {
  287. if (ch != '\r' && ch != '\n')
  288. continue;
  289. int newLineSize = GetLineBreakSize(buffer, currentPos);
  290. if (startPos == -1)
  291. continue; // allow new lines before start of value
  292. if (m_curHeaderName == string.Empty)
  293. throw new BadRequestException("Missing header on line " + currentLine);
  294. if (startPos == -1)
  295. {
  296. m_log.Write(this, LogPrio.Warning, "Missing header value for '" + m_curHeaderName);
  297. throw new BadRequestException("Missing header value for '" + m_curHeaderName);
  298. }
  299. if (currentPos - startPos > 8190)
  300. {
  301. m_log.Write(this, LogPrio.Warning, "Too large header value on line " + currentLine);
  302. throw new BadRequestException("Too large header value on line " + currentLine);
  303. }
  304. // Header fields can be extended over multiple lines by preceding each extra line with at
  305. // least one SP or HT.
  306. if (endOfBufferPos > currentPos + newLineSize
  307. && (buffer[currentPos + newLineSize] == ' ' || buffer[currentPos + newLineSize] == '\t'))
  308. {
  309. if (startPos != -1)
  310. m_curHeaderValue = Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos);
  311. m_log.Write(this, LogPrio.Trace, "Header value is on multiple lines.");
  312. CurrentState = RequestParserState.Between;
  313. startPos = -1;
  314. currentPos += newLineSize - 1;
  315. handledBytes = currentPos + newLineSize - 1;
  316. continue;
  317. }
  318. m_curHeaderValue += Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos);
  319. m_log.Write(this, LogPrio.Trace, "Header [" + m_curHeaderName + ": " + m_curHeaderValue + "]");
  320. OnHeader(m_curHeaderName, m_curHeaderValue);
  321. startPos = -1;
  322. CurrentState = RequestParserState.HeaderName;
  323. m_curHeaderValue = string.Empty;
  324. m_curHeaderName = string.Empty;
  325. ++currentPos;
  326. handledBytes = currentPos + 1;
  327. // Check if we got a colon so we can cut header name, or crlf for end of header.
  328. bool canContinue = false;
  329. for (int j = currentPos; j < endOfBufferPos; ++j)
  330. {
  331. if (buffer[j] != ':' && buffer[j] != '\r' && buffer[j] != '\n') continue;
  332. canContinue = true;
  333. break;
  334. }
  335. if (!canContinue)
  336. {
  337. m_log.Write(this, LogPrio.Trace, "Cant continue, no colon.");
  338. return currentPos + 1;
  339. }
  340. }
  341. break;
  342. }
  343. }
  344. return handledBytes;
  345. }
  346. int GetLineBreakSize(byte[] buffer, int offset)
  347. {
  348. if (buffer[offset] == '\r')
  349. {
  350. if (buffer.Length > offset + 1 && buffer[offset + 1] == '\n')
  351. return 2;
  352. else
  353. throw new BadRequestException("Got invalid linefeed.");
  354. }
  355. else if (buffer[offset] == '\n')
  356. {
  357. if (buffer.Length == offset + 1)
  358. return 1; // linux line feed
  359. if (buffer[offset + 1] != '\r')
  360. return 1; // linux line feed
  361. else
  362. return 2; // win line feed
  363. }
  364. else
  365. return 0;
  366. }
  367. /// <summary>
  368. /// A request have been successfully parsed.
  369. /// </summary>
  370. public event EventHandler RequestCompleted;
  371. #endregion
  372. }
  373. }