WebHeaderCollection.cs 11 KB

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