WebHeaderCollection.cs 8.8 KB

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