WebHeaderCollection.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. /*
  148. if (IsMultiValue (header)) {
  149. values = GetMultipleValues (values);
  150. }
  151. */
  152. return values;
  153. }
  154. /* Now i wonder why this is here...
  155. static string [] GetMultipleValues (string [] values)
  156. {
  157. ArrayList mvalues = new ArrayList (values.Length);
  158. StringBuilder sb = null;
  159. for (int i = 0; i < values.Length; ++i) {
  160. string val = values [i];
  161. if (val.IndexOf (',') == -1) {
  162. mvalues.Add (val);
  163. continue;
  164. }
  165. if (sb == null)
  166. sb = new StringBuilder ();
  167. bool quote = false;
  168. for (int k = 0; k < val.Length; k++) {
  169. char c = val [k];
  170. if (c == '"') {
  171. quote = !quote;
  172. } else if (!quote && c == ',') {
  173. mvalues.Add (sb.ToString ().Trim ());
  174. sb.Length = 0;
  175. continue;
  176. }
  177. sb.Append (c);
  178. }
  179. if (sb.Length > 0) {
  180. mvalues.Add (sb.ToString ().Trim ());
  181. sb.Length = 0;
  182. }
  183. }
  184. return (string []) mvalues.ToArray (typeof (string));
  185. }
  186. */
  187. public static bool IsRestricted (string headerName)
  188. {
  189. if (headerName == null)
  190. throw new ArgumentNullException ("headerName");
  191. if (headerName == "") // MS throw nullexception here!
  192. throw new ArgumentException ("empty string", "headerName");
  193. return restricted.ContainsKey (headerName);
  194. }
  195. public override void OnDeserialization (object sender)
  196. {
  197. }
  198. public override void Remove (string name)
  199. {
  200. if (name == null)
  201. throw new ArgumentNullException ("name");
  202. if (internallyCreated && IsRestricted (name))
  203. throw new ArgumentException ("restricted header");
  204. base.Remove (name);
  205. }
  206. public override void Set (string name, string value)
  207. {
  208. if (name == null)
  209. throw new ArgumentNullException ("name");
  210. if (internallyCreated && IsRestricted (name))
  211. throw new ArgumentException ("restricted header");
  212. if (!IsHeaderName (name))
  213. throw new ArgumentException ("invalid header name");
  214. if (value == null)
  215. value = String.Empty;
  216. else
  217. value = value.Trim ();
  218. if (!IsHeaderValue (value))
  219. throw new ArgumentException ("invalid header value");
  220. base.Set (name, value);
  221. }
  222. public byte[] ToByteArray ()
  223. {
  224. return Encoding.UTF8.GetBytes(ToString ());
  225. }
  226. public override string ToString ()
  227. {
  228. StringBuilder sb = new StringBuilder();
  229. int count = base.Count;
  230. for (int i = 0; i < count ; i++)
  231. sb.Append (GetKey (i))
  232. .Append (": ")
  233. .Append (Get (i))
  234. .Append ("\r\n");
  235. return sb.Append("\r\n").ToString();
  236. }
  237. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  238. StreamingContext streamingContext)
  239. {
  240. int count = base.Count;
  241. serializationInfo.AddValue ("count", count);
  242. for (int i = 0; i < count ; i++) {
  243. serializationInfo.AddValue ("k" + i, GetKey (i));
  244. serializationInfo.AddValue ("v" + i, Get (i));
  245. }
  246. }
  247. // Internal Methods
  248. // With this we don't check for invalid characters in header. See bug #55994.
  249. internal void SetInternal (string header)
  250. {
  251. int pos = header.IndexOf (':');
  252. if (pos == -1)
  253. throw new ArgumentException ("no colon found", "header");
  254. SetInternal (header.Substring (0, pos), header.Substring (pos + 1));
  255. }
  256. internal void SetInternal (string name, string value)
  257. {
  258. if (value == null)
  259. value = String.Empty;
  260. else
  261. value = value.Trim ();
  262. if (!IsHeaderValue (value))
  263. throw new ArgumentException ("invalid header value");
  264. if (IsMultiValue (name)) {
  265. base.Add (name, value);
  266. } else {
  267. base.Remove (name);
  268. base.Set (name, value);
  269. }
  270. }
  271. internal void RemoveAndAdd (string name, string value)
  272. {
  273. if (value == null)
  274. value = String.Empty;
  275. else
  276. value = value.Trim ();
  277. base.Remove (name);
  278. base.Set (name, value);
  279. }
  280. internal void RemoveInternal (string name)
  281. {
  282. if (name == null)
  283. throw new ArgumentNullException ("name");
  284. base.Remove (name);
  285. }
  286. // Private Methods
  287. internal static bool IsMultiValue (string headerName)
  288. {
  289. if (headerName == null || headerName == "")
  290. return false;
  291. return multiValue.ContainsKey (headerName);
  292. }
  293. internal static bool IsHeaderValue (string value)
  294. {
  295. // TEXT any 8 bit value except CTL's (0-31 and 127)
  296. // but including \r\n space and \t
  297. // after a newline at least one space or \t must follow
  298. // certain header fields allow comments ()
  299. int len = value.Length;
  300. for (int i = 0; i < len; i++) {
  301. char c = value [i];
  302. if (c == 127)
  303. return false;
  304. if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t'))
  305. return false;
  306. if (c == '\n' && ++i < len) {
  307. c = value [i];
  308. if (c != ' ' && c != '\t')
  309. return false;
  310. }
  311. }
  312. return true;
  313. }
  314. internal static bool IsHeaderName (string name)
  315. {
  316. // token = 1*<any CHAR except CTLs or tspecials>
  317. // tspecials = "(" | ")" | "<" | ">" | "@"
  318. // | "," | ";" | ":" | "\" | <">
  319. // | "/" | "[" | "]" | "?" | "="
  320. // | "{" | "}" | SP | HT
  321. if (name == null || name.Length == 0)
  322. return false;
  323. int len = name.Length;
  324. for (int i = 0; i < len; i++) {
  325. char c = name [i];
  326. if (c < 0x20 || c >= 0x7f)
  327. return false;
  328. }
  329. return name.IndexOfAny (tspecials) == -1;
  330. }
  331. private static char [] tspecials =
  332. new char [] {'(', ')', '<', '>', '@',
  333. ',', ';', ':', '\\', '"',
  334. '/', '[', ']', '?', '=',
  335. '{', '}', ' ', '\t'};
  336. }
  337. }