HttpRequestParser.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 (pos + 1 >= value.Length)
  113. {
  114. m_log.Write(this, LogPrio.Warning, "Invalid request line, missing HTTP-Version. Line: " + value);
  115. throw new BadRequestException("Invalid request line, missing HTTP-Version. Line: " + value);
  116. }
  117. string version = value.Substring(pos + 1);
  118. if (version.Length < 4 || string.Compare(version.Substring(0, 4), "HTTP", true) != 0)
  119. {
  120. m_log.Write(this, LogPrio.Warning, "Invalid HTTP version in request line. Line: " + value);
  121. throw new BadRequestException("Invalid HTTP version in Request line. Line: " + value);
  122. }
  123. m_requestLineArgs.HttpMethod = method;
  124. m_requestLineArgs.HttpVersion = version;
  125. m_requestLineArgs.UriPath = path;
  126. RequestLineReceived(this, m_requestLineArgs);
  127. }
  128. /// <summary>
  129. /// We've parsed a new header.
  130. /// </summary>
  131. /// <param name="name">Name in lower case</param>
  132. /// <param name="value">Value, unmodified.</param>
  133. /// <exception cref="BadRequestException">If content length cannot be parsed.</exception>
  134. protected void OnHeader(string name, string value)
  135. {
  136. m_headerArgs.Name = name;
  137. m_headerArgs.Value = value;
  138. if (string.Compare(name, "content-length", true) == 0)
  139. {
  140. if (!int.TryParse(value, out m_bodyBytesLeft))
  141. throw new BadRequestException("Content length is not a number.");
  142. }
  143. HeaderReceived?.Invoke(this, m_headerArgs);
  144. }
  145. private void OnRequestCompleted()
  146. {
  147. RequestCompleted?.Invoke(this, EventArgs.Empty);
  148. }
  149. #region IHttpRequestParser Members
  150. /// <summary>
  151. /// Current state in parser.
  152. /// </summary>
  153. public RequestParserState CurrentState { get; private set; }
  154. /// <summary>
  155. /// Parse a message
  156. /// </summary>
  157. /// <param name="buffer">bytes to parse.</param>
  158. /// <param name="offset">where in buffer that parsing should start</param>
  159. /// <param name="count">number of bytes to parse, starting on <paramref name="offset"/>.</param>
  160. /// <returns>offset (where to start parsing next).</returns>
  161. /// <exception cref="BadRequestException"><c>BadRequestException</c>.</exception>
  162. public int Parse(byte[] buffer, int offset, int count)
  163. {
  164. // add body bytes
  165. if (CurrentState == RequestParserState.Body)
  166. {
  167. return AddToBody(buffer, offset, count);
  168. }
  169. #if DEBUG
  170. string temp = Encoding.ASCII.GetString(buffer, offset, count);
  171. _log.Write(this, LogPrio.Trace, "\r\n\r\n HTTP MESSAGE: " + temp + "\r\n");
  172. #endif
  173. int currentLine = 1;
  174. int startPos = -1;
  175. // set start pos since this is from an partial request
  176. if (CurrentState == RequestParserState.HeaderValue)
  177. startPos = 0;
  178. int endOfBufferPos = offset + count;
  179. //<summary>
  180. // Handled bytes are used to keep track of the number of bytes processed.
  181. // We do this since we can handle partial requests (to be able to check headers and abort
  182. // invalid requests directly without having to process the whole header / body).
  183. // </summary>
  184. int handledBytes = 0;
  185. for (int currentPos = offset; currentPos < endOfBufferPos; ++currentPos)
  186. {
  187. var ch = (char)buffer[currentPos];
  188. char nextCh = endOfBufferPos > currentPos + 1 ? (char)buffer[currentPos + 1] : char.MinValue;
  189. if (ch == '\r')
  190. ++currentLine;
  191. switch (CurrentState)
  192. {
  193. case RequestParserState.FirstLine:
  194. if (currentPos == 8191)
  195. {
  196. m_log.Write(this, LogPrio.Warning, "HTTP Request is too large.");
  197. throw new BadRequestException("Too large request line.");
  198. }
  199. if (char.IsLetterOrDigit(ch) && startPos == -1)
  200. startPos = currentPos;
  201. if (startPos == -1 && (ch != '\r' || nextCh != '\n'))
  202. {
  203. m_log.Write(this, LogPrio.Warning, "Request line is not found.");
  204. throw new BadRequestException("Invalid request line.");
  205. }
  206. if (startPos != -1 && (ch == '\r' || ch == '\n'))
  207. {
  208. int size = GetLineBreakSize(buffer, currentPos);
  209. OnFirstLine(Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos));
  210. CurrentState = CurrentState + 1;
  211. currentPos += size - 1;
  212. handledBytes = currentPos + size - 1;
  213. startPos = -1;
  214. }
  215. break;
  216. case RequestParserState.HeaderName:
  217. if (ch == '\r' || ch == '\n')
  218. {
  219. currentPos += GetLineBreakSize(buffer, currentPos);
  220. if (m_bodyBytesLeft == 0)
  221. {
  222. CurrentState = RequestParserState.FirstLine;
  223. m_log.Write(this, LogPrio.Trace, "Request parsed successfully (no content).");
  224. OnRequestCompleted();
  225. Clear();
  226. return currentPos;
  227. }
  228. CurrentState = RequestParserState.Body;
  229. if (currentPos + 1 < endOfBufferPos)
  230. {
  231. m_log.Write(this, LogPrio.Trace, "Adding bytes to the body");
  232. return AddToBody(buffer, currentPos, endOfBufferPos - currentPos);
  233. }
  234. return currentPos;
  235. }
  236. if (char.IsWhiteSpace(ch) || ch == ':')
  237. {
  238. if (startPos == -1)
  239. {
  240. m_log.Write(this, LogPrio.Warning,
  241. "Expected header name, got colon on line " + currentLine);
  242. throw new BadRequestException("Expected header name, got colon on line " + currentLine);
  243. }
  244. m_curHeaderName = Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos);
  245. handledBytes = currentPos + 1;
  246. startPos = -1;
  247. CurrentState = CurrentState + 1;
  248. if (ch == ':')
  249. CurrentState = CurrentState + 1;
  250. }
  251. else if (startPos == -1)
  252. startPos = currentPos;
  253. else if (!char.IsLetterOrDigit(ch) && ch != '-')
  254. {
  255. m_log.Write(this, LogPrio.Warning, "Invalid character in header name on line " + currentLine);
  256. throw new BadRequestException("Invalid character in header name on line " + currentLine);
  257. }
  258. if (startPos != -1 && currentPos - startPos > 200)
  259. {
  260. m_log.Write(this, LogPrio.Warning, "Invalid header name on line " + currentLine);
  261. throw new BadRequestException("Invalid header name on line " + currentLine);
  262. }
  263. break;
  264. case RequestParserState.AfterName:
  265. if (ch == ':')
  266. {
  267. handledBytes = currentPos + 1;
  268. CurrentState = CurrentState + 1;
  269. }
  270. break;
  271. case RequestParserState.Between:
  272. {
  273. if (ch == ' ' || ch == '\t')
  274. continue;
  275. int newLineSize = GetLineBreakSize(buffer, currentPos);
  276. if (newLineSize > 0 && currentPos + newLineSize < endOfBufferPos &&
  277. char.IsWhiteSpace((char)buffer[currentPos + newLineSize]))
  278. {
  279. ++currentPos;
  280. continue;
  281. }
  282. startPos = currentPos;
  283. CurrentState = CurrentState + 1;
  284. handledBytes = currentPos;
  285. continue;
  286. }
  287. case RequestParserState.HeaderValue:
  288. {
  289. if (ch != '\r' && ch != '\n')
  290. continue;
  291. int newLineSize = GetLineBreakSize(buffer, currentPos);
  292. if (startPos == -1)
  293. continue; // allow new lines before start of value
  294. if (m_curHeaderName == string.Empty)
  295. throw new BadRequestException("Missing header on line " + currentLine);
  296. if (startPos == -1)
  297. {
  298. m_log.Write(this, LogPrio.Warning, "Missing header value for '" + m_curHeaderName);
  299. throw new BadRequestException("Missing header value for '" + m_curHeaderName);
  300. }
  301. if (currentPos - startPos > 8190)
  302. {
  303. m_log.Write(this, LogPrio.Warning, "Too large header value on line " + currentLine);
  304. throw new BadRequestException("Too large header value on line " + currentLine);
  305. }
  306. // Header fields can be extended over multiple lines by preceding each extra line with at
  307. // least one SP or HT.
  308. if (endOfBufferPos > currentPos + newLineSize
  309. && (buffer[currentPos + newLineSize] == ' ' || buffer[currentPos + newLineSize] == '\t'))
  310. {
  311. if (startPos != -1)
  312. m_curHeaderValue = Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos);
  313. m_log.Write(this, LogPrio.Trace, "Header value is on multiple lines.");
  314. CurrentState = RequestParserState.Between;
  315. startPos = -1;
  316. currentPos += newLineSize - 1;
  317. handledBytes = currentPos + newLineSize - 1;
  318. continue;
  319. }
  320. m_curHeaderValue += Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos);
  321. m_log.Write(this, LogPrio.Trace, "Header [" + m_curHeaderName + ": " + m_curHeaderValue + "]");
  322. OnHeader(m_curHeaderName, m_curHeaderValue);
  323. startPos = -1;
  324. CurrentState = RequestParserState.HeaderName;
  325. m_curHeaderValue = string.Empty;
  326. m_curHeaderName = string.Empty;
  327. ++currentPos;
  328. handledBytes = currentPos + 1;
  329. // Check if we got a colon so we can cut header name, or crlf for end of header.
  330. bool canContinue = false;
  331. for (int j = currentPos; j < endOfBufferPos; ++j)
  332. {
  333. if (buffer[j] != ':' && buffer[j] != '\r' && buffer[j] != '\n') continue;
  334. canContinue = true;
  335. break;
  336. }
  337. if (!canContinue)
  338. {
  339. m_log.Write(this, LogPrio.Trace, "Cant continue, no colon.");
  340. return currentPos + 1;
  341. }
  342. }
  343. break;
  344. }
  345. }
  346. return handledBytes;
  347. }
  348. int GetLineBreakSize(byte[] buffer, int offset)
  349. {
  350. if (buffer[offset] == '\r')
  351. {
  352. if (buffer.Length > offset + 1 && buffer[offset + 1] == '\n')
  353. return 2;
  354. else
  355. throw new BadRequestException("Got invalid linefeed.");
  356. }
  357. else if (buffer[offset] == '\n')
  358. {
  359. if (buffer.Length == offset + 1)
  360. return 1; // linux line feed
  361. if (buffer[offset + 1] != '\r')
  362. return 1; // linux line feed
  363. else
  364. return 2; // win line feed
  365. }
  366. else
  367. return 0;
  368. }
  369. /// <summary>
  370. /// A request have been successfully parsed.
  371. /// </summary>
  372. public event EventHandler RequestCompleted;
  373. #endregion
  374. }
  375. }