WebHeaderCollection.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 ("if-modified-since", true);
  61. restricted.Add ("range", true);
  62. restricted.Add ("referer", true);
  63. restricted.Add ("transfer-encoding", true);
  64. restricted.Add ("user-agent", true);
  65. // see par 14 of RFC 2068 to see which header names
  66. // accept multiple values each separated by a comma
  67. multiValue = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
  68. CaseInsensitiveComparer.Default);
  69. multiValue.Add ("accept", true);
  70. multiValue.Add ("accept-charset", true);
  71. multiValue.Add ("accept-encoding", true);
  72. multiValue.Add ("accept-language", true);
  73. multiValue.Add ("accept-ranges", true);
  74. multiValue.Add ("allow", true);
  75. multiValue.Add ("authorization", true);
  76. multiValue.Add ("cache-control", true);
  77. multiValue.Add ("connection", true);
  78. multiValue.Add ("content-encoding", true);
  79. multiValue.Add ("content-language", true);
  80. multiValue.Add ("expect", true);
  81. multiValue.Add ("if-match", true);
  82. multiValue.Add ("if-none-match", true);
  83. multiValue.Add ("proxy-authenticate", true);
  84. multiValue.Add ("public", true);
  85. multiValue.Add ("range", true);
  86. multiValue.Add ("transfer-encoding", true);
  87. multiValue.Add ("upgrade", true);
  88. multiValue.Add ("vary", true);
  89. multiValue.Add ("via", true);
  90. multiValue.Add ("warning", true);
  91. // Extra
  92. multiValue.Add ("set-cookie", true);
  93. multiValue.Add ("set-cookie2", true);
  94. }
  95. // Constructors
  96. public WebHeaderCollection () { }
  97. protected WebHeaderCollection (SerializationInfo serializationInfo,
  98. StreamingContext streamingContext)
  99. {
  100. // TODO: test for compatibility with ms.net
  101. int count = serializationInfo.GetInt32("count");
  102. for (int i = 0; i < count; i++)
  103. this.Add (serializationInfo.GetString ("k" + i),
  104. serializationInfo.GetString ("v" + i));
  105. }
  106. internal WebHeaderCollection (bool internallyCreated)
  107. {
  108. this.internallyCreated = internallyCreated;
  109. }
  110. // Methods
  111. public void Add (string header)
  112. {
  113. if (header == null)
  114. throw new ArgumentNullException ("header");
  115. int pos = header.IndexOf (':');
  116. if (pos == -1)
  117. throw new ArgumentException ("no colon found", "header");
  118. this.Add (header.Substring (0, pos),
  119. header.Substring (pos + 1));
  120. }
  121. public override void Add (string name, string value)
  122. {
  123. if (name == null)
  124. throw new ArgumentNullException ("name");
  125. if (internallyCreated && IsRestricted (name))
  126. throw new ArgumentException ("This header must be modified with the appropiate property.");
  127. this.AddWithoutValidate (name, value);
  128. }
  129. protected void AddWithoutValidate (string headerName, string headerValue)
  130. {
  131. if (!IsHeaderName (headerName))
  132. throw new ArgumentException ("invalid header name: " + headerName, "headerName");
  133. if (headerValue == null)
  134. headerValue = String.Empty;
  135. else
  136. headerValue = headerValue.Trim ();
  137. if (!IsHeaderValue (headerValue))
  138. throw new ArgumentException ("invalid header value: " + headerValue, "headerValue");
  139. base.Add (headerName, headerValue);
  140. }
  141. public override string [] GetValues (string header)
  142. {
  143. if (header == null)
  144. throw new ArgumentNullException ("header");
  145. string [] values = base.GetValues (header);
  146. if (values == null || values.Length == 0)
  147. return null;
  148. /*
  149. if (IsMultiValue (header)) {
  150. values = GetMultipleValues (values);
  151. }
  152. */
  153. return values;
  154. }
  155. /* Now i wonder why this is here...
  156. static string [] GetMultipleValues (string [] values)
  157. {
  158. ArrayList mvalues = new ArrayList (values.Length);
  159. StringBuilder sb = null;
  160. for (int i = 0; i < values.Length; ++i) {
  161. string val = values [i];
  162. if (val.IndexOf (',') == -1) {
  163. mvalues.Add (val);
  164. continue;
  165. }
  166. if (sb == null)
  167. sb = new StringBuilder ();
  168. bool quote = false;
  169. for (int k = 0; k < val.Length; k++) {
  170. char c = val [k];
  171. if (c == '"') {
  172. quote = !quote;
  173. } else if (!quote && c == ',') {
  174. mvalues.Add (sb.ToString ().Trim ());
  175. sb.Length = 0;
  176. continue;
  177. }
  178. sb.Append (c);
  179. }
  180. if (sb.Length > 0) {
  181. mvalues.Add (sb.ToString ().Trim ());
  182. sb.Length = 0;
  183. }
  184. }
  185. return (string []) mvalues.ToArray (typeof (string));
  186. }
  187. */
  188. public static bool IsRestricted (string headerName)
  189. {
  190. if (headerName == null)
  191. throw new ArgumentNullException ("headerName");
  192. if (headerName == "") // MS throw nullexception here!
  193. throw new ArgumentException ("empty string", "headerName");
  194. return restricted.ContainsKey (headerName);
  195. }
  196. public override void OnDeserialization (object sender)
  197. {
  198. }
  199. public override void Remove (string name)
  200. {
  201. if (name == null)
  202. throw new ArgumentNullException ("name");
  203. if (internallyCreated && IsRestricted (name))
  204. throw new ArgumentException ("restricted header");
  205. base.Remove (name);
  206. }
  207. public override void Set (string name, string value)
  208. {
  209. if (name == null)
  210. throw new ArgumentNullException ("name");
  211. if (internallyCreated && IsRestricted (name))
  212. throw new ArgumentException ("restricted header");
  213. if (!IsHeaderName (name))
  214. throw new ArgumentException ("invalid header name");
  215. if (value == null)
  216. value = String.Empty;
  217. else
  218. value = value.Trim ();
  219. if (!IsHeaderValue (value))
  220. throw new ArgumentException ("invalid header value");
  221. base.Set (name, value);
  222. }
  223. public byte[] ToByteArray ()
  224. {
  225. return Encoding.UTF8.GetBytes(ToString ());
  226. }
  227. public override string ToString ()
  228. {
  229. StringBuilder sb = new StringBuilder();
  230. int count = base.Count;
  231. for (int i = 0; i < count ; i++)
  232. sb.Append (GetKey (i))
  233. .Append (": ")
  234. .Append (Get (i))
  235. .Append ("\r\n");
  236. return sb.Append("\r\n").ToString();
  237. }
  238. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  239. StreamingContext streamingContext)
  240. {
  241. int count = base.Count;
  242. serializationInfo.AddValue ("count", count);
  243. for (int i = 0; i < count ; i++) {
  244. serializationInfo.AddValue ("k" + i, GetKey (i));
  245. serializationInfo.AddValue ("v" + i, Get (i));
  246. }
  247. }
  248. // Internal Methods
  249. // With this we don't check for invalid characters in header. See bug #55994.
  250. internal void SetInternal (string header)
  251. {
  252. int pos = header.IndexOf (':');
  253. if (pos == -1)
  254. throw new ArgumentException ("no colon found", "header");
  255. SetInternal (header.Substring (0, pos), header.Substring (pos + 1));
  256. }
  257. internal void SetInternal (string name, string value)
  258. {
  259. if (value == null)
  260. value = String.Empty;
  261. else
  262. value = value.Trim ();
  263. if (!IsHeaderValue (value))
  264. throw new ArgumentException ("invalid header value");
  265. if (IsMultiValue (name)) {
  266. base.Add (name, value);
  267. } else {
  268. base.Remove (name);
  269. base.Set (name, value);
  270. }
  271. }
  272. internal void RemoveAndAdd (string name, string value)
  273. {
  274. if (value == null)
  275. value = String.Empty;
  276. else
  277. value = value.Trim ();
  278. base.Remove (name);
  279. base.Set (name, value);
  280. }
  281. internal void RemoveInternal (string name)
  282. {
  283. if (name == null)
  284. throw new ArgumentNullException ("name");
  285. base.Remove (name);
  286. }
  287. // Private Methods
  288. internal static bool IsMultiValue (string headerName)
  289. {
  290. if (headerName == null || headerName == "")
  291. return false;
  292. return multiValue.ContainsKey (headerName);
  293. }
  294. internal static bool IsHeaderValue (string value)
  295. {
  296. // TEXT any 8 bit value except CTL's (0-31 and 127)
  297. // but including \r\n space and \t
  298. // after a newline at least one space or \t must follow
  299. // certain header fields allow comments ()
  300. int len = value.Length;
  301. for (int i = 0; i < len; i++) {
  302. char c = value [i];
  303. if (c == 127)
  304. return false;
  305. if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t'))
  306. return false;
  307. if (c == '\n' && ++i < len) {
  308. c = value [i];
  309. if (c != ' ' && c != '\t')
  310. return false;
  311. }
  312. }
  313. return true;
  314. }
  315. internal static bool IsHeaderName (string name)
  316. {
  317. // token = 1*<any CHAR except CTLs or tspecials>
  318. // tspecials = "(" | ")" | "<" | ">" | "@"
  319. // | "," | ";" | ":" | "\" | <">
  320. // | "/" | "[" | "]" | "?" | "="
  321. // | "{" | "}" | SP | HT
  322. if (name == null || name.Length == 0)
  323. return false;
  324. int len = name.Length;
  325. for (int i = 0; i < len; i++) {
  326. char c = name [i];
  327. if (c < 0x20 || c >= 0x7f)
  328. return false;
  329. }
  330. return name.IndexOfAny (tspecials) == -1;
  331. }
  332. private static char [] tspecials =
  333. new char [] {'(', ')', '<', '>', '@',
  334. ',', ';', ':', '\\', '"',
  335. '/', '[', ']', '?', '=',
  336. '{', '}', ' ', '\t'};
  337. }
  338. }