HttpParserBase.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Http;
  5. namespace Rssdp.Infrastructure
  6. {
  7. /// <summary>
  8. /// A base class for the <see cref="HttpResponseParser"/> and <see cref="HttpRequestParser"/> classes. Not intended for direct use.
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. public abstract class HttpParserBase<T> where T : new()
  12. {
  13. #region Fields
  14. private readonly string[] LineTerminators = new string[] { "\r\n", "\n" };
  15. private readonly char[] SeparatorCharacters = new char[] { ',', ';' };
  16. #endregion
  17. #region Public Methods
  18. /// <summary>
  19. /// Parses the <paramref name="data"/> provided into either a <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object.
  20. /// </summary>
  21. /// <param name="data">A string containing the HTTP message to parse.</param>
  22. /// <returns>Either a <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object containing the parsed data.</returns>
  23. public abstract T Parse(string data);
  24. /// <summary>
  25. /// Parses a string containing either an HTTP request or response into a <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object.
  26. /// </summary>
  27. /// <param name="message">A <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object representing the parsed message.</param>
  28. /// <param name="headers">A reference to the <see cref="System.Net.Http.Headers.HttpHeaders"/> collection for the <paramref name="message"/> object.</param>
  29. /// <param name="data">A string containing the data to be parsed.</param>
  30. /// <returns>An <see cref="HttpContent"/> object containing the content of the parsed message.</returns>
  31. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Honestly, it's fine. MemoryStream doesn't mind.")]
  32. protected virtual void Parse(T message, System.Net.Http.Headers.HttpHeaders headers, string data)
  33. {
  34. if (data == null) throw new ArgumentNullException(nameof(data));
  35. if (data.Length == 0) throw new ArgumentException("data cannot be an empty string.", nameof(data));
  36. if (!LineTerminators.Any(data.Contains)) throw new ArgumentException("data is not a valid request, it does not contain any CRLF/LF terminators.", nameof(data));
  37. using (var retVal = new ByteArrayContent(Array.Empty<byte>()))
  38. {
  39. var lines = data.Split(LineTerminators, StringSplitOptions.None);
  40. //First line is the 'request' line containing http protocol details like method, uri, http version etc.
  41. ParseStatusLine(lines[0], message);
  42. ParseHeaders(headers, retVal.Headers, lines);
  43. }
  44. }
  45. /// <summary>
  46. /// Used to parse the first line of an HTTP request or response and assign the values to the appropriate properties on the <paramref name="message"/>.
  47. /// </summary>
  48. /// <param name="data">The first line of the HTTP message to be parsed.</param>
  49. /// <param name="message">Either a <see cref="HttpResponseMessage"/> or <see cref="HttpRequestMessage"/> to assign the parsed values to.</param>
  50. protected abstract void ParseStatusLine(string data, T message);
  51. /// <summary>
  52. /// Returns a boolean indicating whether the specified HTTP header name represents a content header (true), or a message header (false).
  53. /// </summary>
  54. /// <param name="headerName">A string containing the name of the header to return the type of.</param>
  55. protected abstract bool IsContentHeader(string headerName);
  56. /// <summary>
  57. /// Parses the HTTP version text from an HTTP request or response status line and returns a <see cref="Version"/> object representing the parsed values.
  58. /// </summary>
  59. /// <param name="versionData">A string containing the HTTP version, from the message status line.</param>
  60. /// <returns>A <see cref="Version"/> object containing the parsed version data.</returns>
  61. protected Version ParseHttpVersion(string versionData)
  62. {
  63. if (versionData == null) throw new ArgumentNullException(nameof(versionData));
  64. var versionSeparatorIndex = versionData.IndexOf('/');
  65. if (versionSeparatorIndex <= 0 || versionSeparatorIndex == versionData.Length) throw new ArgumentException("request header line is invalid. Http Version not supplied or incorrect format.", nameof(versionData));
  66. return Version.Parse(versionData.Substring(versionSeparatorIndex + 1));
  67. }
  68. #endregion
  69. #region Private Methods
  70. /// <summary>
  71. /// Parses a line from an HTTP request or response message containing a header name and value pair.
  72. /// </summary>
  73. /// <param name="line">A string containing the data to be parsed.</param>
  74. /// <param name="headers">A reference to a <see cref="System.Net.Http.Headers.HttpHeaders"/> collection to which the parsed header will be added.</param>
  75. /// <param name="contentHeaders">A reference to a <see cref="System.Net.Http.Headers.HttpHeaders"/> collection for the message content, to which the parsed header will be added.</param>
  76. private void ParseHeader(string line, System.Net.Http.Headers.HttpHeaders headers, System.Net.Http.Headers.HttpHeaders contentHeaders)
  77. {
  78. //Header format is
  79. //name: value
  80. var headerKeySeparatorIndex = line.IndexOf(":", StringComparison.OrdinalIgnoreCase);
  81. var headerName = line.Substring(0, headerKeySeparatorIndex).Trim();
  82. var headerValue = line.Substring(headerKeySeparatorIndex + 1).Trim();
  83. //Not sure how to determine where request headers and and content headers begin,
  84. //at least not without a known set of headers (general headers first the content headers)
  85. //which seems like a bad way of doing it. So we'll assume if it's a known content header put it there
  86. //else use request headers.
  87. var values = ParseValues(headerValue);
  88. var headersToAddTo = IsContentHeader(headerName) ? contentHeaders : headers;
  89. if (values.Count > 1)
  90. headersToAddTo.TryAddWithoutValidation(headerName, values);
  91. else
  92. headersToAddTo.TryAddWithoutValidation(headerName, values.First());
  93. }
  94. private int ParseHeaders(System.Net.Http.Headers.HttpHeaders headers, System.Net.Http.Headers.HttpHeaders contentHeaders, string[] lines)
  95. {
  96. //Blank line separates headers from content, so read headers until we find blank line.
  97. int lineIndex = 1;
  98. string line = null, nextLine = null;
  99. while (lineIndex + 1 < lines.Length && !String.IsNullOrEmpty((line = lines[lineIndex++])))
  100. {
  101. //If the following line starts with space or tab (or any whitespace), it is really part of this header but split for human readability.
  102. //Combine these lines into a single comma separated style header for easier parsing.
  103. while (lineIndex < lines.Length && !String.IsNullOrEmpty((nextLine = lines[lineIndex])))
  104. {
  105. if (nextLine.Length > 0 && Char.IsWhiteSpace(nextLine[0]))
  106. {
  107. line += "," + nextLine.TrimStart();
  108. lineIndex++;
  109. }
  110. else
  111. break;
  112. }
  113. ParseHeader(line, headers, contentHeaders);
  114. }
  115. return lineIndex;
  116. }
  117. private IList<string> ParseValues(string headerValue)
  118. {
  119. // This really should be better and match the HTTP 1.1 spec,
  120. // but this should actually be good enough for SSDP implementations
  121. // I think.
  122. var values = new List<string>();
  123. if (headerValue == "\"\"")
  124. {
  125. values.Add(String.Empty);
  126. return values;
  127. }
  128. var indexOfSeparator = headerValue.IndexOfAny(SeparatorCharacters);
  129. if (indexOfSeparator <= 0)
  130. values.Add(headerValue);
  131. else
  132. {
  133. var segments = headerValue.Split(SeparatorCharacters);
  134. if (headerValue.Contains("\""))
  135. {
  136. for (int segmentIndex = 0; segmentIndex < segments.Length; segmentIndex++)
  137. {
  138. var segment = segments[segmentIndex];
  139. if (segment.Trim().StartsWith("\"", StringComparison.OrdinalIgnoreCase))
  140. segment = CombineQuotedSegments(segments, ref segmentIndex, segment);
  141. values.Add(segment);
  142. }
  143. }
  144. else
  145. values.AddRange(segments);
  146. }
  147. return values;
  148. }
  149. private string CombineQuotedSegments(string[] segments, ref int segmentIndex, string segment)
  150. {
  151. var trimmedSegment = segment.Trim();
  152. for (int index = segmentIndex; index < segments.Length; index++)
  153. {
  154. if (trimmedSegment == "\"\"" ||
  155. (
  156. trimmedSegment.EndsWith("\"", StringComparison.OrdinalIgnoreCase)
  157. && !trimmedSegment.EndsWith("\"\"", StringComparison.OrdinalIgnoreCase)
  158. && !trimmedSegment.EndsWith("\\\"", StringComparison.OrdinalIgnoreCase))
  159. )
  160. {
  161. segmentIndex = index;
  162. return trimmedSegment.Substring(1, trimmedSegment.Length - 2);
  163. }
  164. if (index + 1 < segments.Length)
  165. trimmedSegment += "," + segments[index + 1].TrimEnd();
  166. }
  167. segmentIndex = segments.Length;
  168. if (trimmedSegment.StartsWith("\"", StringComparison.OrdinalIgnoreCase) && trimmedSegment.EndsWith("\"", StringComparison.OrdinalIgnoreCase))
  169. return trimmedSegment.Substring(1, trimmedSegment.Length - 2);
  170. else
  171. return trimmedSegment;
  172. }
  173. #endregion
  174. }
  175. }