HttpHeadersWebHeaderCollection.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. // <copyright>
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. // </copyright>
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Collections.Specialized;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Http;
  12. using System.Runtime;
  13. using System.Text;
  14. /// <summary>
  15. /// The HttpHeadersWebHeaderCollection is an implementation of the <see cref="WebHeaderCollection"/> class
  16. /// that uses the HttpHeader collections on an <see cref="HttpRequestMessage"/> or an <see cref="HttpResponseMessage"/>
  17. /// instance to hold the header data instead of the traditional <see cref="NameValueCollection"/> of the
  18. /// <see cref="WebHeaderCollection"/>. This is because the <see cref="HttpRequestMessage"/> or
  19. /// <see cref="HttpResponseMessage"/> is the true data structure holding the HTTP information of the request/response
  20. /// being processed and we want to avoid copying header information between the <see cref="HttpRequestMessage"/> or
  21. /// <see cref="HttpResponseMessage"/> and a <see cref="NameValueCollection"/>.
  22. /// </summary>
  23. internal class HttpHeadersWebHeaderCollection : WebHeaderCollection
  24. {
  25. private const string HasKeysHeader = "hk";
  26. private static readonly string[] emptyStringArray = new string[] { string.Empty };
  27. private static readonly string[] stringSplitArray = new string[] { ", " };
  28. // Cloned from WebHeaderCollection
  29. private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
  30. private static readonly char[] InvalidParamChars = new char[] { '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '\'', '/', '[', ']', '?', '=', '{', '}', ' ', '\t', '\r', '\n' };
  31. private HttpRequestMessage httpRequestMessage;
  32. private HttpResponseMessage httpResponseMessage;
  33. private bool hasKeys;
  34. public HttpHeadersWebHeaderCollection(HttpRequestMessage httpRequestMessage)
  35. {
  36. Fx.Assert(httpRequestMessage != null, "The 'httpRequestMessage' parameter should never be null.");
  37. this.httpRequestMessage = httpRequestMessage;
  38. this.EnsureBaseHasKeysIsAccurate();
  39. }
  40. public HttpHeadersWebHeaderCollection(HttpResponseMessage httpResponseMessage)
  41. {
  42. Fx.Assert(httpResponseMessage != null, "The 'httpResponseMessage' parameter should never be null.");
  43. this.httpResponseMessage = httpResponseMessage;
  44. this.EnsureBaseHasKeysIsAccurate();
  45. }
  46. public override string[] AllKeys
  47. {
  48. get
  49. {
  50. return this.AllHeaders.Select(header => header.Key).ToArray();
  51. }
  52. }
  53. public override int Count
  54. {
  55. get
  56. {
  57. return this.AllHeaders.Count();
  58. }
  59. }
  60. public override KeysCollection Keys
  61. {
  62. get
  63. {
  64. // The perf here will be awful as we have to create a NameValueCollection and copy all the
  65. // headers over into it in order to get an instance of type KeysCollection; so framework
  66. // code should never use the Keys property.
  67. NameValueCollection collection = new NameValueCollection();
  68. foreach (KeyValuePair<string, IEnumerable<string>> header in this.AllHeaders)
  69. {
  70. string[] values = header.Value.ToArray();
  71. if (values.Length == 0)
  72. {
  73. collection.Add(header.Key, string.Empty);
  74. }
  75. else
  76. {
  77. foreach (string value in values)
  78. {
  79. collection.Add(header.Key, value);
  80. }
  81. }
  82. }
  83. return collection.Keys;
  84. }
  85. }
  86. private IEnumerable<KeyValuePair<string, IEnumerable<string>>> AllHeaders
  87. {
  88. get
  89. {
  90. HttpContent content = null;
  91. IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers;
  92. if (this.httpRequestMessage != null)
  93. {
  94. headers = this.httpRequestMessage.Headers;
  95. content = this.httpRequestMessage.Content;
  96. }
  97. else
  98. {
  99. Fx.Assert(this.httpResponseMessage != null, "Either the 'httpRequestMessage' field or the 'httpResponseMessage' field should be non-null.");
  100. headers = this.httpResponseMessage.Headers;
  101. content = this.httpResponseMessage.Content;
  102. }
  103. if (content != null)
  104. {
  105. headers = headers.Concat(content.Headers);
  106. }
  107. return headers;
  108. }
  109. }
  110. public override void Add(string name, string value)
  111. {
  112. name = CheckBadChars(name, false);
  113. value = CheckBadChars(value, true);
  114. if (this.httpRequestMessage != null)
  115. {
  116. this.httpRequestMessage.AddHeader(name, value);
  117. }
  118. else
  119. {
  120. Fx.Assert(this.httpResponseMessage != null, "Either the 'httpRequestMessage' field or the 'httpResponseMessage' field should be non-null.");
  121. this.httpResponseMessage.AddHeader(name, value);
  122. }
  123. this.EnsureBaseHasKeysIsAccurate();
  124. }
  125. public override void Clear()
  126. {
  127. HttpContent content = null;
  128. if (this.httpRequestMessage != null)
  129. {
  130. this.httpRequestMessage.Headers.Clear();
  131. content = this.httpRequestMessage.Content;
  132. }
  133. else
  134. {
  135. Fx.Assert(this.httpResponseMessage != null, "Either the 'httpRequestMessage' field or the 'httpResponseMessage' field should be non-null.");
  136. this.httpResponseMessage.Headers.Clear();
  137. content = this.httpResponseMessage.Content;
  138. }
  139. if (content != null)
  140. {
  141. content.Headers.Clear();
  142. }
  143. this.EnsureBaseHasKeysIsAccurate();
  144. }
  145. public override void Remove(string name)
  146. {
  147. name = CheckBadChars(name, false);
  148. if (this.httpRequestMessage != null)
  149. {
  150. this.httpRequestMessage.RemoveHeader(name);
  151. }
  152. else
  153. {
  154. this.httpResponseMessage.RemoveHeader(name);
  155. }
  156. this.EnsureBaseHasKeysIsAccurate();
  157. }
  158. public override void Set(string name, string value)
  159. {
  160. name = CheckBadChars(name, false);
  161. value = CheckBadChars(value, true);
  162. if (this.httpRequestMessage != null)
  163. {
  164. this.httpRequestMessage.SetHeader(name, value);
  165. }
  166. else
  167. {
  168. Fx.Assert(this.httpResponseMessage != null, "Either the 'httpRequestMessage' field or the 'httpResponseMessage' field should be non-null.");
  169. this.httpResponseMessage.SetHeader(name, value);
  170. }
  171. this.EnsureBaseHasKeysIsAccurate();
  172. }
  173. public override IEnumerator GetEnumerator()
  174. {
  175. return new HttpHeadersEnumerator(this.AllKeys);
  176. }
  177. public override string Get(int index)
  178. {
  179. string[] values = this.GetValues(index);
  180. return GetSingleValue(values);
  181. }
  182. public override string GetKey(int index)
  183. {
  184. return this.GetHeaderAt(index).Key;
  185. }
  186. public override string[] GetValues(int index)
  187. {
  188. return this.GetHeaderAt(index).Value.ToArray();
  189. }
  190. public override string Get(string name)
  191. {
  192. string[] values = this.GetValues(name);
  193. return GetSingleValue(values);
  194. }
  195. public override string ToString()
  196. {
  197. StringBuilder builder = new StringBuilder();
  198. foreach (var header in this.AllHeaders)
  199. {
  200. if (!string.IsNullOrEmpty(header.Key))
  201. {
  202. builder.Append(header.Key);
  203. builder.Append(": ");
  204. builder.AppendLine(GetSingleValue(header.Value.ToArray()));
  205. }
  206. }
  207. return builder.ToString();
  208. }
  209. public override string[] GetValues(string header)
  210. {
  211. IEnumerable<string> values = null;
  212. if (this.httpRequestMessage != null)
  213. {
  214. values = this.httpRequestMessage.GetHeader(header);
  215. }
  216. else
  217. {
  218. Fx.Assert(this.httpResponseMessage != null, "Either the 'httpRequestMessage' field or the 'httpResponseMessage' field should be non-null.");
  219. values = this.httpResponseMessage.GetHeader(header);
  220. }
  221. if (values == null)
  222. {
  223. return emptyStringArray;
  224. }
  225. return values.SelectMany(str => str.Split(stringSplitArray, StringSplitOptions.None)).ToArray();
  226. }
  227. private static string GetSingleValue(string[] values)
  228. {
  229. if (values == null)
  230. {
  231. return null;
  232. }
  233. if (values.Length == 1)
  234. {
  235. return values[0];
  236. }
  237. // The current implemenation of the base WebHeaderCollection joins the string values
  238. // using a comma with no whitespace
  239. return string.Join(",", values);
  240. }
  241. // Cloned from WebHeaderCollection
  242. [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.WrapExceptionsRule,
  243. Justification = "This code is being used to reproduce behavior from the WebHeaderCollection, which does not trace exceptions via FxTrace.")]
  244. private static string CheckBadChars(string name, bool isHeaderValue)
  245. {
  246. if (name == null || name.Length == 0)
  247. {
  248. // emtpy name is invlaid
  249. if (!isHeaderValue)
  250. {
  251. throw name == null ?
  252. new ArgumentNullException("name") :
  253. new ArgumentException(SR.GetString(SR.WebHeaderEmptyStringCall, "name"), "name");
  254. }
  255. // empty value is OK
  256. return string.Empty;
  257. }
  258. if (isHeaderValue)
  259. {
  260. // VALUE check
  261. // Trim spaces from both ends
  262. name = name.Trim(HttpTrimCharacters);
  263. // First, check for correctly formed multi-line value
  264. // Second, check for absenece of CTL characters
  265. int crlf = 0;
  266. for (int i = 0; i < name.Length; ++i)
  267. {
  268. char c = (char)(0x000000ff & (uint)name[i]);
  269. switch (crlf)
  270. {
  271. case 0:
  272. if (c == '\r')
  273. {
  274. crlf = 1;
  275. }
  276. else if (c == '\n')
  277. {
  278. // Technically this is bad HTTP. But it would be a breaking change to throw here.
  279. // Is there an exploit?
  280. crlf = 2;
  281. }
  282. else if (c == 127 || (c < ' ' && c != '\t'))
  283. {
  284. throw new ArgumentException(SR.GetString(SR.WebHeaderInvalidControlChars), "value");
  285. }
  286. break;
  287. case 1:
  288. if (c == '\n')
  289. {
  290. crlf = 2;
  291. break;
  292. }
  293. throw new ArgumentException(SR.GetString(SR.WebHeaderInvalidCRLFChars), "value");
  294. case 2:
  295. if (c == ' ' || c == '\t')
  296. {
  297. crlf = 0;
  298. break;
  299. }
  300. throw new ArgumentException(SR.GetString(SR.WebHeaderInvalidCRLFChars), "value");
  301. }
  302. }
  303. if (crlf != 0)
  304. {
  305. throw new ArgumentException(SR.GetString(SR.WebHeaderInvalidCRLFChars), "value");
  306. }
  307. }
  308. else
  309. {
  310. // NAME check
  311. // First, check for absence of separators and spaces
  312. if (name.IndexOfAny(InvalidParamChars) != -1)
  313. {
  314. throw new ArgumentException(SR.GetString(SR.WebHeaderInvalidHeaderChars), "name");
  315. }
  316. // Second, check for non CTL ASCII-7 characters (32-126)
  317. if (ContainsNonAsciiChars(name))
  318. {
  319. throw new ArgumentException(SR.GetString(SR.WebHeaderInvalidNonAsciiChars), "name");
  320. }
  321. }
  322. return name;
  323. }
  324. // Cloned from WebHeaderCollection
  325. private static bool ContainsNonAsciiChars(string token)
  326. {
  327. for (int i = 0; i < token.Length; ++i)
  328. {
  329. if ((token[i] < 0x20) || (token[i] > 0x7e))
  330. {
  331. return true;
  332. }
  333. }
  334. return false;
  335. }
  336. private void EnsureBaseHasKeysIsAccurate()
  337. {
  338. bool originalHasKeys = this.hasKeys;
  339. this.hasKeys = this.BackingHttpHeadersHasKeys();
  340. if (originalHasKeys && !this.hasKeys)
  341. {
  342. base.Remove(HasKeysHeader);
  343. }
  344. else if (!originalHasKeys && this.hasKeys)
  345. {
  346. this.AddWithoutValidate(HasKeysHeader, string.Empty);
  347. }
  348. }
  349. private bool BackingHttpHeadersHasKeys()
  350. {
  351. return this.httpRequestMessage != null ?
  352. this.httpRequestMessage.Headers.Any() || (this.httpRequestMessage.Content != null && this.httpRequestMessage.Content.Headers.Any()) :
  353. this.httpResponseMessage.Headers.Any() || (this.httpResponseMessage.Content != null && this.httpResponseMessage.Content.Headers.Any());
  354. }
  355. [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.WrapExceptionsRule,
  356. Justification = "This code is being used to reproduce behavior from the WebHeaderCollection, which does not trace exceptions via FxTrace.")]
  357. private KeyValuePair<string, IEnumerable<string>> GetHeaderAt(int index)
  358. {
  359. if (index >= 0)
  360. {
  361. foreach (KeyValuePair<string, IEnumerable<string>> header in this.AllHeaders)
  362. {
  363. if (index == 0)
  364. {
  365. return header;
  366. }
  367. index--;
  368. }
  369. }
  370. throw new ArgumentOutOfRangeException("index", SR.WebHeaderArgumentOutOfRange);
  371. }
  372. private class HttpHeadersEnumerator : IEnumerator
  373. {
  374. private string[] keys;
  375. private int position;
  376. public HttpHeadersEnumerator(string[] keys)
  377. {
  378. this.keys = keys;
  379. this.position = -1;
  380. }
  381. [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.WrapExceptionsRule,
  382. Justification = "This code is being used to reproduce behavior from the WebHeaderCollection, which does not trace exceptions via FxTrace.")]
  383. public object Current
  384. {
  385. get
  386. {
  387. if ((this.position < 0) || (this.position >= this.keys.Length))
  388. {
  389. throw new InvalidOperationException(SR.GetString(SR.WebHeaderEnumOperationCantHappen));
  390. }
  391. return this.keys[this.position];
  392. }
  393. }
  394. public bool MoveNext()
  395. {
  396. if (this.position < (this.keys.Length - 1))
  397. {
  398. this.position++;
  399. return true;
  400. }
  401. this.position = this.keys.Length;
  402. return false;
  403. }
  404. public void Reset()
  405. {
  406. this.position = -1;
  407. }
  408. }
  409. }
  410. }