WebHeaderCollection.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. using System;
  11. using System.Collections;
  12. using System.Collections.Specialized;
  13. using System.Runtime.InteropServices;
  14. using System.Runtime.Serialization;
  15. using System.Text;
  16. // See RFC 2068 par 4.2 Message Headers
  17. namespace System.Net
  18. {
  19. [Serializable]
  20. [ComVisible(true)]
  21. public class WebHeaderCollection : NameValueCollection, ISerializable
  22. {
  23. private static readonly Hashtable restricted;
  24. private static readonly Hashtable multiValue;
  25. private bool internallyCreated = false;
  26. // Static Initializer
  27. static WebHeaderCollection ()
  28. {
  29. // the list of restricted header names as defined
  30. // by the ms.net spec
  31. restricted = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
  32. CaseInsensitiveComparer.Default);
  33. restricted.Add ("accept", true);
  34. restricted.Add ("connection", true);
  35. restricted.Add ("content-length", true);
  36. restricted.Add ("content-type", true);
  37. restricted.Add ("date", true);
  38. restricted.Add ("expect", true);
  39. restricted.Add ("host", true);
  40. restricted.Add ("range", true);
  41. restricted.Add ("referer", true);
  42. restricted.Add ("transfer-encoding", true);
  43. restricted.Add ("user-agent", true);
  44. // see par 14 of RFC 2068 to see which header names
  45. // accept multiple values each separated by a comma
  46. multiValue = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
  47. CaseInsensitiveComparer.Default);
  48. multiValue.Add ("accept", true);
  49. multiValue.Add ("accept-charset", true);
  50. multiValue.Add ("accept-encoding", true);
  51. multiValue.Add ("accept-language", true);
  52. multiValue.Add ("accept-ranges", true);
  53. multiValue.Add ("allow", true);
  54. multiValue.Add ("authorization", true);
  55. multiValue.Add ("cache-control", true);
  56. multiValue.Add ("connection", true);
  57. multiValue.Add ("content-encoding", true);
  58. multiValue.Add ("content-language", true);
  59. multiValue.Add ("expect", true);
  60. multiValue.Add ("if-match", true);
  61. multiValue.Add ("if-none-match", true);
  62. multiValue.Add ("proxy-authenticate", true);
  63. multiValue.Add ("public", true);
  64. multiValue.Add ("range", true);
  65. multiValue.Add ("transfer-encoding", true);
  66. multiValue.Add ("upgrade", true);
  67. multiValue.Add ("vary", true);
  68. multiValue.Add ("via", true);
  69. multiValue.Add ("warning", true);
  70. }
  71. // Constructors
  72. public WebHeaderCollection () { }
  73. protected WebHeaderCollection (SerializationInfo serializationInfo,
  74. StreamingContext streamingContext)
  75. {
  76. // TODO: test for compatibility with ms.net
  77. int count = serializationInfo.GetInt32("count");
  78. for (int i = 0; i < count; i++)
  79. this.Add (serializationInfo.GetString ("k" + i),
  80. serializationInfo.GetString ("v" + i));
  81. }
  82. internal WebHeaderCollection (bool internallyCreated)
  83. {
  84. this.internallyCreated = internallyCreated;
  85. }
  86. // Methods
  87. public void Add (string header)
  88. {
  89. if (header == null)
  90. throw new ArgumentNullException ("header");
  91. int pos = header.IndexOf (':');
  92. if (pos == -1)
  93. throw new ArgumentException ("no colon found", "header");
  94. this.Add (header.Substring (0, pos),
  95. header.Substring (pos + 1));
  96. }
  97. public override void Add (string name, string value)
  98. {
  99. if (name == null)
  100. throw new ArgumentNullException ("name");
  101. if (internallyCreated && IsRestricted (name))
  102. throw new ArgumentException ("restricted header");
  103. this.AddWithoutValidate (name, value);
  104. }
  105. protected void AddWithoutValidate (string headerName, string headerValue)
  106. {
  107. if (!IsHeaderName (headerName))
  108. throw new ArgumentException ("invalid header name: " + headerName, "headerName");
  109. if (headerValue == null)
  110. headerValue = String.Empty;
  111. else
  112. headerValue = headerValue.Trim ();
  113. if (!IsHeaderValue (headerValue))
  114. throw new ArgumentException ("invalid header value: " + headerValue, "headerValue");
  115. base.Add (headerName, headerValue);
  116. }
  117. public override string [] GetValues (string header)
  118. {
  119. if (header == null)
  120. throw new ArgumentNullException ("header");
  121. string [] values = base.GetValues (header);
  122. if (values == null || values.Length == 0)
  123. return null;
  124. if (!IsMultiValue (header))
  125. return values;
  126. StringCollection col = new StringCollection ();
  127. for (int i = 0; i < values.Length; i++) {
  128. string [] s = values [i].Split (new char [] {','});
  129. for (int j = 0; j < s.Length; j++)
  130. s [j] = s [j].Trim ();
  131. col.AddRange (s);
  132. }
  133. values = new string [col.Count];
  134. col.CopyTo (values, 0);
  135. return values;
  136. }
  137. public static bool IsRestricted (string headerName)
  138. {
  139. if (headerName == null)
  140. throw new ArgumentNullException ("headerName");
  141. if (headerName == "") // MS throw nullexception here!
  142. throw new ArgumentException ("empty string", "headerName");
  143. return restricted.ContainsKey (headerName);
  144. }
  145. public override void OnDeserialization (object sender)
  146. {
  147. }
  148. public override void Remove (string name)
  149. {
  150. if (name == null)
  151. throw new ArgumentNullException ("name");
  152. if (internallyCreated && IsRestricted (name))
  153. throw new ArgumentException ("restricted header");
  154. base.Remove (name);
  155. }
  156. public override void Set (string name, string value)
  157. {
  158. if (name == null)
  159. throw new ArgumentNullException ("name");
  160. if (internallyCreated && IsRestricted (name))
  161. throw new ArgumentException ("restricted header");
  162. if (!IsHeaderName (name))
  163. throw new ArgumentException ("invalid header name");
  164. if (value == null)
  165. value = String.Empty;
  166. else
  167. value = value.Trim ();
  168. if (!IsHeaderValue (value))
  169. throw new ArgumentException ("invalid header value");
  170. base.Set (name, value);
  171. }
  172. public byte[] ToByteArray ()
  173. {
  174. return Encoding.UTF8.GetBytes(ToString ());
  175. }
  176. public override string ToString ()
  177. {
  178. StringBuilder sb = new StringBuilder();
  179. int count = base.Count;
  180. for (int i = 0; i < count ; i++)
  181. sb.Append (GetKey (i))
  182. .Append (": ")
  183. .Append (Get (i))
  184. .Append ("\r\n");
  185. return sb.Append("\r\n").ToString();
  186. }
  187. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  188. StreamingContext streamingContext)
  189. {
  190. int count = base.Count;
  191. serializationInfo.AddValue ("count", count);
  192. for (int i = 0; i < count ; i++) {
  193. serializationInfo.AddValue ("k" + i, GetKey (i));
  194. serializationInfo.AddValue ("v" + i, Get (i));
  195. }
  196. }
  197. // Internal Methods
  198. internal void SetInternal (string name, string value)
  199. {
  200. if (value == null)
  201. value = String.Empty;
  202. else
  203. value = value.Trim ();
  204. if (!IsHeaderValue (value))
  205. throw new ArgumentException ("invalid header value");
  206. base.Remove (name);
  207. base.Set (name, value);
  208. }
  209. internal void RemoveInternal (string name)
  210. {
  211. if (name == null)
  212. throw new ArgumentNullException ("name");
  213. base.Remove (name);
  214. }
  215. // Private Methods
  216. internal static bool IsMultiValue (string headerName)
  217. {
  218. if (headerName == null || headerName == "")
  219. return false;
  220. return multiValue.ContainsKey (headerName);
  221. }
  222. internal static bool IsHeaderValue (string value)
  223. {
  224. // TEXT any 8 bit value except CTL's (0-31 and 127)
  225. // but including \r\n space and \t
  226. // after a newline at least one space or \t must follow
  227. // certain header fields allow comments ()
  228. int len = value.Length;
  229. for (int i = 0; i < len; i++) {
  230. char c = value [i];
  231. if (c == 127)
  232. return false;
  233. if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t'))
  234. return false;
  235. if (c == '\n' && ++i < len) {
  236. c = value [i];
  237. if (c != ' ' && c != '\t')
  238. return false;
  239. }
  240. }
  241. return true;
  242. }
  243. internal static bool IsHeaderName (string name)
  244. {
  245. // token = 1*<any CHAR except CTLs or tspecials>
  246. // tspecials = "(" | ")" | "<" | ">" | "@"
  247. // | "," | ";" | ":" | "\" | <">
  248. // | "/" | "[" | "]" | "?" | "="
  249. // | "{" | "}" | SP | HT
  250. if (name == null || name.Length == 0)
  251. return false;
  252. int len = name.Length;
  253. for (int i = 0; i < len; i++) {
  254. char c = name [i];
  255. if (c < 0x20 || c >= 0x7f)
  256. return false;
  257. }
  258. return name.IndexOfAny (tspecials) == -1;
  259. }
  260. private static char [] tspecials =
  261. new char [] {'(', ')', '<', '>', '@',
  262. ',', ';', ':', '\\', '"',
  263. '/', '[', ']', '?', '=',
  264. '{', '}', ' ', '\t'};
  265. }
  266. }