2
0

HttpParserBase.cs 10 KB

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