WebHeaderCollection.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. }
  91. // Constructors
  92. public WebHeaderCollection () { }
  93. protected WebHeaderCollection (SerializationInfo serializationInfo,
  94. StreamingContext streamingContext)
  95. {
  96. // TODO: test for compatibility with ms.net
  97. int count = serializationInfo.GetInt32("count");
  98. for (int i = 0; i < count; i++)
  99. this.Add (serializationInfo.GetString ("k" + i),
  100. serializationInfo.GetString ("v" + i));
  101. }
  102. internal WebHeaderCollection (bool internallyCreated)
  103. {
  104. this.internallyCreated = internallyCreated;
  105. }
  106. // Methods
  107. public void Add (string header)
  108. {
  109. if (header == null)
  110. throw new ArgumentNullException ("header");
  111. int pos = header.IndexOf (':');
  112. if (pos == -1)
  113. throw new ArgumentException ("no colon found", "header");
  114. this.Add (header.Substring (0, pos),
  115. header.Substring (pos + 1));
  116. }
  117. public override void Add (string name, string value)
  118. {
  119. if (name == null)
  120. throw new ArgumentNullException ("name");
  121. if (internallyCreated && IsRestricted (name))
  122. throw new ArgumentException ("restricted header");
  123. this.AddWithoutValidate (name, value);
  124. }
  125. protected void AddWithoutValidate (string headerName, string headerValue)
  126. {
  127. if (!IsHeaderName (headerName))
  128. throw new ArgumentException ("invalid header name: " + headerName, "headerName");
  129. if (headerValue == null)
  130. headerValue = String.Empty;
  131. else
  132. headerValue = headerValue.Trim ();
  133. if (!IsHeaderValue (headerValue))
  134. throw new ArgumentException ("invalid header value: " + headerValue, "headerValue");
  135. base.Add (headerName, headerValue);
  136. }
  137. public override string [] GetValues (string header)
  138. {
  139. if (header == null)
  140. throw new ArgumentNullException ("header");
  141. string [] values = base.GetValues (header);
  142. if (values == null || values.Length == 0)
  143. return null;
  144. if (!IsMultiValue (header))
  145. return values;
  146. StringCollection col = new StringCollection ();
  147. for (int i = 0; i < values.Length; i++) {
  148. string [] s = values [i].Split (new char [] {','});
  149. for (int j = 0; j < s.Length; j++)
  150. s [j] = s [j].Trim ();
  151. col.AddRange (s);
  152. }
  153. values = new string [col.Count];
  154. col.CopyTo (values, 0);
  155. return values;
  156. }
  157. public static bool IsRestricted (string headerName)
  158. {
  159. if (headerName == null)
  160. throw new ArgumentNullException ("headerName");
  161. if (headerName == "") // MS throw nullexception here!
  162. throw new ArgumentException ("empty string", "headerName");
  163. return restricted.ContainsKey (headerName);
  164. }
  165. public override void OnDeserialization (object sender)
  166. {
  167. }
  168. public override void Remove (string name)
  169. {
  170. if (name == null)
  171. throw new ArgumentNullException ("name");
  172. if (internallyCreated && IsRestricted (name))
  173. throw new ArgumentException ("restricted header");
  174. base.Remove (name);
  175. }
  176. public override void Set (string name, string value)
  177. {
  178. if (name == null)
  179. throw new ArgumentNullException ("name");
  180. if (internallyCreated && IsRestricted (name))
  181. throw new ArgumentException ("restricted header");
  182. if (!IsHeaderName (name))
  183. throw new ArgumentException ("invalid header name");
  184. if (value == null)
  185. value = String.Empty;
  186. else
  187. value = value.Trim ();
  188. if (!IsHeaderValue (value))
  189. throw new ArgumentException ("invalid header value");
  190. base.Set (name, value);
  191. }
  192. public byte[] ToByteArray ()
  193. {
  194. return Encoding.UTF8.GetBytes(ToString ());
  195. }
  196. public override string ToString ()
  197. {
  198. StringBuilder sb = new StringBuilder();
  199. int count = base.Count;
  200. for (int i = 0; i < count ; i++)
  201. sb.Append (GetKey (i))
  202. .Append (": ")
  203. .Append (Get (i))
  204. .Append ("\r\n");
  205. return sb.Append("\r\n").ToString();
  206. }
  207. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  208. StreamingContext streamingContext)
  209. {
  210. int count = base.Count;
  211. serializationInfo.AddValue ("count", count);
  212. for (int i = 0; i < count ; i++) {
  213. serializationInfo.AddValue ("k" + i, GetKey (i));
  214. serializationInfo.AddValue ("v" + i, Get (i));
  215. }
  216. }
  217. // Internal Methods
  218. // With this we don't check for invalid characters in header. See bug #55994.
  219. internal void SetInternal (string header)
  220. {
  221. int pos = header.IndexOf (':');
  222. if (pos == -1)
  223. throw new ArgumentException ("no colon found", "header");
  224. SetInternal (header.Substring (0, pos), header.Substring (pos + 1));
  225. }
  226. internal void SetInternal (string name, string value)
  227. {
  228. if (value == null)
  229. value = String.Empty;
  230. else
  231. value = value.Trim ();
  232. if (!IsHeaderValue (value))
  233. throw new ArgumentException ("invalid header value");
  234. base.Remove (name);
  235. base.Set (name, value);
  236. }
  237. internal void RemoveInternal (string name)
  238. {
  239. if (name == null)
  240. throw new ArgumentNullException ("name");
  241. base.Remove (name);
  242. }
  243. // Private Methods
  244. internal static bool IsMultiValue (string headerName)
  245. {
  246. if (headerName == null || headerName == "")
  247. return false;
  248. return multiValue.ContainsKey (headerName);
  249. }
  250. internal static bool IsHeaderValue (string value)
  251. {
  252. // TEXT any 8 bit value except CTL's (0-31 and 127)
  253. // but including \r\n space and \t
  254. // after a newline at least one space or \t must follow
  255. // certain header fields allow comments ()
  256. int len = value.Length;
  257. for (int i = 0; i < len; i++) {
  258. char c = value [i];
  259. if (c == 127)
  260. return false;
  261. if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t'))
  262. return false;
  263. if (c == '\n' && ++i < len) {
  264. c = value [i];
  265. if (c != ' ' && c != '\t')
  266. return false;
  267. }
  268. }
  269. return true;
  270. }
  271. internal static bool IsHeaderName (string name)
  272. {
  273. // token = 1*<any CHAR except CTLs or tspecials>
  274. // tspecials = "(" | ")" | "<" | ">" | "@"
  275. // | "," | ";" | ":" | "\" | <">
  276. // | "/" | "[" | "]" | "?" | "="
  277. // | "{" | "}" | SP | HT
  278. if (name == null || name.Length == 0)
  279. return false;
  280. int len = name.Length;
  281. for (int i = 0; i < len; i++) {
  282. char c = name [i];
  283. if (c < 0x20 || c >= 0x7f)
  284. return false;
  285. }
  286. return name.IndexOfAny (tspecials) == -1;
  287. }
  288. private static char [] tspecials =
  289. new char [] {'(', ')', '<', '>', '@',
  290. ',', ';', ':', '\\', '"',
  291. '/', '[', ']', '?', '=',
  292. '{', '}', ' ', '\t'};
  293. }
  294. }