WebHeaderCollection.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. //
  2. // System.Net.WebHeaderCollection
  3. //
  4. // Authors:
  5. // Lawrence Pit ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. //
  8. // (c) 2003 Ximian, Inc. (http://www.ximian.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Collections;
  32. using System.Collections.Specialized;
  33. using System.Runtime.InteropServices;
  34. using System.Runtime.Serialization;
  35. using System.Text;
  36. // See RFC 2068 par 4.2 Message Headers
  37. namespace System.Net
  38. {
  39. [Serializable]
  40. [ComVisible(true)]
  41. public class WebHeaderCollection : NameValueCollection, ISerializable
  42. {
  43. private static readonly Hashtable restricted;
  44. private static readonly Hashtable multiValue;
  45. private bool internallyCreated = false;
  46. // Static Initializer
  47. static WebHeaderCollection ()
  48. {
  49. // the list of restricted header names as defined
  50. // by the ms.net spec
  51. restricted = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
  52. CaseInsensitiveComparer.Default);
  53. restricted.Add ("accept", true);
  54. restricted.Add ("connection", true);
  55. restricted.Add ("content-length", true);
  56. restricted.Add ("content-type", true);
  57. restricted.Add ("date", true);
  58. restricted.Add ("expect", true);
  59. restricted.Add ("host", true);
  60. restricted.Add ("range", true);
  61. restricted.Add ("referer", true);
  62. restricted.Add ("transfer-encoding", true);
  63. restricted.Add ("user-agent", true);
  64. // see par 14 of RFC 2068 to see which header names
  65. // accept multiple values each separated by a comma
  66. multiValue = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
  67. CaseInsensitiveComparer.Default);
  68. multiValue.Add ("accept", true);
  69. multiValue.Add ("accept-charset", true);
  70. multiValue.Add ("accept-encoding", true);
  71. multiValue.Add ("accept-language", true);
  72. multiValue.Add ("accept-ranges", true);
  73. multiValue.Add ("allow", true);
  74. multiValue.Add ("authorization", true);
  75. multiValue.Add ("cache-control", true);
  76. multiValue.Add ("connection", true);
  77. multiValue.Add ("content-encoding", true);
  78. multiValue.Add ("content-language", true);
  79. multiValue.Add ("expect", true);
  80. multiValue.Add ("if-match", true);
  81. multiValue.Add ("if-none-match", true);
  82. multiValue.Add ("proxy-authenticate", true);
  83. multiValue.Add ("public", true);
  84. multiValue.Add ("range", true);
  85. multiValue.Add ("transfer-encoding", true);
  86. multiValue.Add ("upgrade", true);
  87. multiValue.Add ("vary", true);
  88. multiValue.Add ("via", true);
  89. multiValue.Add ("warning", true);
  90. // Extra
  91. multiValue.Add ("set-cookie", true);
  92. multiValue.Add ("set-cookie2", true);
  93. }
  94. // Constructors
  95. public WebHeaderCollection () { }
  96. protected WebHeaderCollection (SerializationInfo serializationInfo,
  97. StreamingContext streamingContext)
  98. {
  99. // TODO: test for compatibility with ms.net
  100. int count = serializationInfo.GetInt32("count");
  101. for (int i = 0; i < count; i++)
  102. this.Add (serializationInfo.GetString ("k" + i),
  103. serializationInfo.GetString ("v" + i));
  104. }
  105. internal WebHeaderCollection (bool internallyCreated)
  106. {
  107. this.internallyCreated = internallyCreated;
  108. }
  109. // Methods
  110. public void Add (string header)
  111. {
  112. if (header == null)
  113. throw new ArgumentNullException ("header");
  114. int pos = header.IndexOf (':');
  115. if (pos == -1)
  116. throw new ArgumentException ("no colon found", "header");
  117. this.Add (header.Substring (0, pos),
  118. header.Substring (pos + 1));
  119. }
  120. public override void Add (string name, string value)
  121. {
  122. if (name == null)
  123. throw new ArgumentNullException ("name");
  124. if (internallyCreated && IsRestricted (name))
  125. throw new ArgumentException ("restricted header");
  126. this.AddWithoutValidate (name, value);
  127. }
  128. protected void AddWithoutValidate (string headerName, string headerValue)
  129. {
  130. if (!IsHeaderName (headerName))
  131. throw new ArgumentException ("invalid header name: " + headerName, "headerName");
  132. if (headerValue == null)
  133. headerValue = String.Empty;
  134. else
  135. headerValue = headerValue.Trim ();
  136. if (!IsHeaderValue (headerValue))
  137. throw new ArgumentException ("invalid header value: " + headerValue, "headerValue");
  138. base.Add (headerName, headerValue);
  139. }
  140. public override string [] GetValues (string header)
  141. {
  142. if (header == null)
  143. throw new ArgumentNullException ("header");
  144. string [] values = base.GetValues (header);
  145. if (values == null || values.Length == 0)
  146. return null;
  147. return values;
  148. }
  149. public static bool IsRestricted (string headerName)
  150. {
  151. if (headerName == null)
  152. throw new ArgumentNullException ("headerName");
  153. if (headerName == "") // MS throw nullexception here!
  154. throw new ArgumentException ("empty string", "headerName");
  155. return restricted.ContainsKey (headerName);
  156. }
  157. public override void OnDeserialization (object sender)
  158. {
  159. }
  160. public override void Remove (string name)
  161. {
  162. if (name == null)
  163. throw new ArgumentNullException ("name");
  164. if (internallyCreated && IsRestricted (name))
  165. throw new ArgumentException ("restricted header");
  166. base.Remove (name);
  167. }
  168. public override void Set (string name, string value)
  169. {
  170. if (name == null)
  171. throw new ArgumentNullException ("name");
  172. if (internallyCreated && IsRestricted (name))
  173. throw new ArgumentException ("restricted header");
  174. if (!IsHeaderName (name))
  175. throw new ArgumentException ("invalid header name");
  176. if (value == null)
  177. value = String.Empty;
  178. else
  179. value = value.Trim ();
  180. if (!IsHeaderValue (value))
  181. throw new ArgumentException ("invalid header value");
  182. base.Set (name, value);
  183. }
  184. public byte[] ToByteArray ()
  185. {
  186. return Encoding.UTF8.GetBytes(ToString ());
  187. }
  188. public override string ToString ()
  189. {
  190. StringBuilder sb = new StringBuilder();
  191. int count = base.Count;
  192. for (int i = 0; i < count ; i++)
  193. sb.Append (GetKey (i))
  194. .Append (": ")
  195. .Append (Get (i))
  196. .Append ("\r\n");
  197. return sb.Append("\r\n").ToString();
  198. }
  199. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  200. StreamingContext streamingContext)
  201. {
  202. int count = base.Count;
  203. serializationInfo.AddValue ("count", count);
  204. for (int i = 0; i < count ; i++) {
  205. serializationInfo.AddValue ("k" + i, GetKey (i));
  206. serializationInfo.AddValue ("v" + i, Get (i));
  207. }
  208. }
  209. // Internal Methods
  210. // With this we don't check for invalid characters in header. See bug #55994.
  211. internal void SetInternal (string header)
  212. {
  213. int pos = header.IndexOf (':');
  214. if (pos == -1)
  215. throw new ArgumentException ("no colon found", "header");
  216. SetInternal (header.Substring (0, pos), header.Substring (pos + 1));
  217. }
  218. internal void SetInternal (string name, string value)
  219. {
  220. if (value == null)
  221. value = String.Empty;
  222. else
  223. value = value.Trim ();
  224. if (!IsHeaderValue (value))
  225. throw new ArgumentException ("invalid header value");
  226. if (IsMultiValue (name)) {
  227. base.Add (name, value);
  228. } else {
  229. base.Remove (name);
  230. base.Set (name, value);
  231. }
  232. }
  233. internal void RemoveAndAdd (string name, string value)
  234. {
  235. if (value == null)
  236. value = String.Empty;
  237. else
  238. value = value.Trim ();
  239. base.Remove (name);
  240. base.Set (name, value);
  241. }
  242. internal void RemoveInternal (string name)
  243. {
  244. if (name == null)
  245. throw new ArgumentNullException ("name");
  246. base.Remove (name);
  247. }
  248. // Private Methods
  249. internal static bool IsMultiValue (string headerName)
  250. {
  251. if (headerName == null || headerName == "")
  252. return false;
  253. return multiValue.ContainsKey (headerName);
  254. }
  255. internal static bool IsHeaderValue (string value)
  256. {
  257. // TEXT any 8 bit value except CTL's (0-31 and 127)
  258. // but including \r\n space and \t
  259. // after a newline at least one space or \t must follow
  260. // certain header fields allow comments ()
  261. int len = value.Length;
  262. for (int i = 0; i < len; i++) {
  263. char c = value [i];
  264. if (c == 127)
  265. return false;
  266. if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t'))
  267. return false;
  268. if (c == '\n' && ++i < len) {
  269. c = value [i];
  270. if (c != ' ' && c != '\t')
  271. return false;
  272. }
  273. }
  274. return true;
  275. }
  276. internal static bool IsHeaderName (string name)
  277. {
  278. // token = 1*<any CHAR except CTLs or tspecials>
  279. // tspecials = "(" | ")" | "<" | ">" | "@"
  280. // | "," | ";" | ":" | "\" | <">
  281. // | "/" | "[" | "]" | "?" | "="
  282. // | "{" | "}" | SP | HT
  283. if (name == null || name.Length == 0)
  284. return false;
  285. int len = name.Length;
  286. for (int i = 0; i < len; i++) {
  287. char c = name [i];
  288. if (c < 0x20 || c >= 0x7f)
  289. return false;
  290. }
  291. return name.IndexOfAny (tspecials) == -1;
  292. }
  293. private static char [] tspecials =
  294. new char [] {'(', ')', '<', '>', '@',
  295. ',', ';', ':', '\\', '"',
  296. '/', '[', ']', '?', '=',
  297. '{', '}', ' ', '\t'};
  298. }
  299. }