CookieContainer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. //
  2. // System.Net.CookieContainer
  3. //
  4. // Authors:
  5. // Lawrence Pit ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Sebastien Pouliot <[email protected]>
  8. //
  9. // (c) 2003 Ximian, Inc. (http://www.ximian.com)
  10. // (c) Copyright 2004 Ximian, Inc. (http://www.ximian.com)
  11. // Copyright (C) 2009 Novell, Inc (http://www.novell.com)
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.Collections;
  34. using System.Globalization;
  35. using System.Runtime.Serialization;
  36. using System.Text;
  37. using System.Text.RegularExpressions;
  38. namespace System.Net
  39. {
  40. [Serializable]
  41. #if NET_2_1
  42. public sealed class CookieContainer {
  43. #else
  44. public class CookieContainer {
  45. #endif
  46. public const int DefaultCookieLengthLimit = 4096;
  47. public const int DefaultCookieLimit = 300;
  48. public const int DefaultPerDomainCookieLimit = 20;
  49. int capacity = DefaultCookieLimit;
  50. int perDomainCapacity = DefaultPerDomainCookieLimit;
  51. int maxCookieSize = DefaultCookieLengthLimit;
  52. CookieCollection cookies;
  53. // ctors
  54. public CookieContainer ()
  55. {
  56. }
  57. public CookieContainer (int capacity)
  58. {
  59. if (capacity <= 0)
  60. #if NET_2_0
  61. throw new ArgumentException ("Must be greater than zero", "Capacity");
  62. #else
  63. throw new ArgumentException ("Capacity");
  64. #endif
  65. this.capacity = capacity;
  66. }
  67. public CookieContainer (int capacity, int perDomainCapacity, int maxCookieSize)
  68. : this (capacity)
  69. {
  70. if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity))
  71. #if NET_2_0
  72. throw new ArgumentOutOfRangeException ("perDomainCapacity",
  73. string.Format ("PerDomainCapacity must be " +
  74. "greater than {0} and less than {1}.", 0,
  75. capacity));
  76. #else
  77. throw new ArgumentException ("PerDomainCapacity");
  78. #endif
  79. if (maxCookieSize <= 0)
  80. #if NET_2_0
  81. throw new ArgumentException ("Must be greater than zero", "MaxCookieSize");
  82. #else
  83. throw new ArgumentException ("MaxCookieSize");
  84. #endif
  85. this.perDomainCapacity = perDomainCapacity;
  86. this.maxCookieSize = maxCookieSize;
  87. }
  88. // properties
  89. public int Count {
  90. get { return (cookies == null) ? 0 : cookies.Count; }
  91. }
  92. public int Capacity {
  93. get { return capacity; }
  94. set {
  95. if (value < 0 || (value < perDomainCapacity && perDomainCapacity != Int32.MaxValue))
  96. throw new ArgumentOutOfRangeException ("value",
  97. string.Format ("Capacity must be greater " +
  98. "than {0} and less than {1}.", 0,
  99. perDomainCapacity));
  100. capacity = value;
  101. }
  102. }
  103. public int MaxCookieSize {
  104. get { return maxCookieSize; }
  105. set {
  106. if (value <= 0)
  107. throw new ArgumentOutOfRangeException ("value");
  108. maxCookieSize = value;
  109. }
  110. }
  111. public int PerDomainCapacity {
  112. get { return perDomainCapacity; }
  113. set {
  114. if (value != Int32.MaxValue && (value <= 0 || value > capacity))
  115. throw new ArgumentOutOfRangeException ("value");
  116. perDomainCapacity = value;
  117. }
  118. }
  119. public void Add (Cookie cookie)
  120. {
  121. if (cookie == null)
  122. throw new ArgumentNullException ("cookie");
  123. if (cookie.Domain.Length == 0)
  124. #if NET_2_0
  125. throw new ArgumentException ("Cookie domain not set.", "cookie.Domain");
  126. #else
  127. throw new ArgumentException ("cookie.Domain");
  128. #endif
  129. if (cookie.Value.Length > maxCookieSize)
  130. throw new CookieException ("value is larger than MaxCookieSize.");
  131. // .NET's Add (Cookie) is fundamentally broken and does not copy properties
  132. // like Secure, HttpOnly and Expires so we clone the parts that .NET
  133. // does keep before calling AddCookie
  134. Cookie c = new Cookie (cookie.Name, cookie.Value);
  135. c.Path = (cookie.Path.Length == 0) ? "/" : cookie.Path;
  136. c.Domain = cookie.Domain;
  137. c.ExactDomain = cookie.ExactDomain;
  138. c.Version = cookie.Version;
  139. AddCookie (c);
  140. }
  141. void AddCookie (Cookie cookie)
  142. {
  143. if (cookies == null)
  144. cookies = new CookieCollection ();
  145. if (cookies.Count >= capacity)
  146. RemoveOldest (null);
  147. // try to avoid counting per-domain
  148. if (cookies.Count >= perDomainCapacity) {
  149. if (CountDomain (cookie.Domain) >= perDomainCapacity)
  150. RemoveOldest (cookie.Domain);
  151. }
  152. // clone the important parts of the cookie
  153. Cookie c = new Cookie (cookie.Name, cookie.Value);
  154. c.Path = (cookie.Path.Length == 0) ? "/" : cookie.Path;
  155. c.Domain = cookie.Domain;
  156. c.ExactDomain = cookie.ExactDomain;
  157. c.Version = cookie.Version;
  158. c.Expires = cookie.Expires;
  159. c.CommentUri = cookie.CommentUri;
  160. c.Comment = cookie.Comment;
  161. c.Discard = cookie.Discard;
  162. c.HttpOnly = cookie.HttpOnly;
  163. c.Secure = cookie.Secure;
  164. cookies.Add (c);
  165. CheckExpiration ();
  166. }
  167. int CountDomain (string domain)
  168. {
  169. int count = 0;
  170. foreach (Cookie c in cookies) {
  171. if (CheckDomain (domain, c.Domain, true))
  172. count++;
  173. }
  174. return count;
  175. }
  176. void RemoveOldest (string domain)
  177. {
  178. int n = 0;
  179. DateTime oldest = DateTime.MaxValue;
  180. for (int i = 0; i < cookies.Count; i++) {
  181. Cookie c = cookies [i];
  182. if ((c.TimeStamp < oldest) && ((domain == null) || (domain == c.Domain))) {
  183. oldest = c.TimeStamp;
  184. n = i;
  185. }
  186. }
  187. cookies.List.RemoveAt (n);
  188. }
  189. // Only needs to be called from AddCookie (Cookie) and GetCookies (Uri)
  190. void CheckExpiration ()
  191. {
  192. if (cookies == null)
  193. return;
  194. for (int i = cookies.Count - 1; i >= 0; i--) {
  195. Cookie cookie = cookies [i];
  196. if (cookie.Expired)
  197. cookies.List.RemoveAt (i);
  198. }
  199. }
  200. public void Add (CookieCollection cookies)
  201. {
  202. if (cookies == null)
  203. throw new ArgumentNullException ("cookies");
  204. foreach (Cookie cookie in cookies)
  205. Add (cookie);
  206. }
  207. void Cook (Uri uri, Cookie cookie)
  208. {
  209. if (String.IsNullOrEmpty (cookie.Name))
  210. throw new CookieException ("Invalid cookie: name");
  211. if (cookie.Value == null)
  212. throw new CookieException ("Invalid cookie: value");
  213. if (uri != null && cookie.Domain.Length == 0)
  214. cookie.Domain = uri.Host;
  215. if (cookie.Version == 0 && String.IsNullOrEmpty (cookie.Path)) {
  216. if (uri != null) {
  217. cookie.Path = uri.AbsolutePath;
  218. } else {
  219. cookie.Path = "/";
  220. }
  221. }
  222. if (cookie.Port.Length == 0 && uri != null && !uri.IsDefaultPort) {
  223. cookie.Port = "\"" + uri.Port.ToString () + "\"";
  224. }
  225. }
  226. public void Add (Uri uri, Cookie cookie)
  227. {
  228. if (uri == null)
  229. throw new ArgumentNullException ("uri");
  230. if (cookie == null)
  231. throw new ArgumentNullException ("cookie");
  232. if (!cookie.Expired) {
  233. Cook (uri, cookie);
  234. AddCookie (cookie);
  235. }
  236. }
  237. public void Add (Uri uri, CookieCollection cookies)
  238. {
  239. if (uri == null)
  240. throw new ArgumentNullException ("uri");
  241. if (cookies == null)
  242. throw new ArgumentNullException ("cookies");
  243. foreach (Cookie cookie in cookies) {
  244. if (!cookie.Expired) {
  245. Cook (uri, cookie);
  246. AddCookie (cookie);
  247. }
  248. }
  249. }
  250. public string GetCookieHeader (Uri uri)
  251. {
  252. if (uri == null)
  253. throw new ArgumentNullException ("uri");
  254. CookieCollection coll = GetCookies (uri);
  255. if (coll.Count == 0)
  256. return "";
  257. StringBuilder result = new StringBuilder ();
  258. foreach (Cookie cookie in coll) {
  259. // don't include the domain since it can be infered from the URI
  260. // include empty path as '/'
  261. result.Append (cookie.ToString (uri));
  262. result.Append ("; ");
  263. }
  264. if (result.Length > 0)
  265. result.Length -= 2; // remove trailing semicolon and space
  266. return result.ToString ();
  267. }
  268. static bool CheckDomain (string domain, string host, bool exact)
  269. {
  270. if (domain.Length == 0)
  271. return false;
  272. if (exact)
  273. return (String.Compare (host, domain, StringComparison.InvariantCultureIgnoreCase) == 0);
  274. // check for allowed sub-domains - without string allocations
  275. if (!host.EndsWith (domain, StringComparison.InvariantCultureIgnoreCase))
  276. return false;
  277. // mono.com -> www.mono.com is OK but supermono.com NOT OK
  278. if (domain [0] == '.')
  279. return true;
  280. int p = host.Length - domain.Length - 1;
  281. if (p < 0)
  282. return false;
  283. return (host [p] == '.');
  284. }
  285. public CookieCollection GetCookies (Uri uri)
  286. {
  287. if (uri == null)
  288. throw new ArgumentNullException ("uri");
  289. CheckExpiration ();
  290. CookieCollection coll = new CookieCollection ();
  291. if (cookies == null)
  292. return coll;
  293. foreach (Cookie cookie in cookies) {
  294. string domain = cookie.Domain;
  295. if (!CheckDomain (domain, uri.Host, cookie.ExactDomain))
  296. continue;
  297. if (cookie.Port.Length > 0 && cookie.Ports != null && uri.Port != -1) {
  298. if (Array.IndexOf (cookie.Ports, uri.Port) == -1)
  299. continue;
  300. }
  301. string path = cookie.Path;
  302. string uripath = uri.AbsolutePath;
  303. if (path != "" && path != "/") {
  304. if (uripath != path) {
  305. if (!uripath.StartsWith (path))
  306. continue;
  307. if (path [path.Length - 1] != '/' && uripath.Length > path.Length &&
  308. uripath [path.Length] != '/')
  309. continue;
  310. }
  311. }
  312. if (cookie.Secure && uri.Scheme != "https")
  313. continue;
  314. coll.Add (cookie);
  315. }
  316. coll.Sort ();
  317. return coll;
  318. }
  319. public void SetCookies (Uri uri, string cookieHeader)
  320. {
  321. if (uri == null)
  322. throw new ArgumentNullException ("uri");
  323. if (cookieHeader == null)
  324. throw new ArgumentNullException ("cookieHeader");
  325. if (cookieHeader.Length == 0)
  326. return;
  327. // Cookies must be separated by ',' (like documented on MSDN)
  328. // but expires uses DAY, DD-MMM-YYYY HH:MM:SS GMT, so simple ',' search is wrong.
  329. // See http://msdn.microsoft.com/en-us/library/aa384321%28VS.85%29.aspx
  330. string [] jar = cookieHeader.Split (',');
  331. string tmpCookie;
  332. for (int i = 0; i < jar.Length; i++) {
  333. tmpCookie = jar [i];
  334. if (jar.Length > i + 1
  335. && Regex.IsMatch (jar[i],
  336. @".*expires\s*=\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)",
  337. RegexOptions.IgnoreCase)
  338. && Regex.IsMatch (jar[i+1],
  339. @"\s\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4} \d{2}:\d{2}:\d{2} GMT",
  340. RegexOptions.IgnoreCase)) {
  341. tmpCookie = new StringBuilder (tmpCookie).Append (",").Append (jar [++i]).ToString ();
  342. }
  343. try {
  344. Cookie c = Parse (tmpCookie);
  345. // add default values from URI if missing from the string
  346. if (c.Path.Length == 0) {
  347. c.Path = uri.AbsolutePath;
  348. } else if (!uri.AbsolutePath.StartsWith (c.Path)) {
  349. string msg = String.Format ("'Path'='{0}' is invalid with URI", c.Path);
  350. throw new CookieException (msg);
  351. }
  352. if (c.Domain.Length == 0) {
  353. c.Domain = uri.Host;
  354. // don't consider domain "a.b.com" as ".a.b.com"
  355. c.ExactDomain = true;
  356. }
  357. AddCookie (c);
  358. }
  359. catch (Exception e) {
  360. string msg = String.Format ("Could not parse cookies for '{0}'.", uri);
  361. throw new CookieException (msg, e);
  362. }
  363. }
  364. }
  365. static Cookie Parse (string s)
  366. {
  367. string [] parts = s.Split (';');
  368. Cookie c = new Cookie ();
  369. for (int i = 0; i < parts.Length; i++) {
  370. string key, value;
  371. int sep = parts[i].IndexOf ('=');
  372. if (sep == -1) {
  373. key = parts [i].Trim ();
  374. value = String.Empty;
  375. } else {
  376. key = parts [i].Substring (0, sep).Trim ();
  377. value = parts [i].Substring (sep + 1).Trim ();
  378. }
  379. switch (key.ToLowerInvariant ()) {
  380. case "path":
  381. case "$path":
  382. if (c.Path.Length == 0)
  383. c.Path = value;
  384. break;
  385. case "domain":
  386. case "$domain":
  387. if (c.Domain.Length == 0) {
  388. c.Domain = value;
  389. // here mono.com means "*.mono.com"
  390. c.ExactDomain = false;
  391. }
  392. break;
  393. case "expires":
  394. case "$expires":
  395. if (c.Expires == DateTime.MinValue)
  396. c.Expires = DateTime.SpecifyKind (DateTime.ParseExact (value,
  397. @"ddd, dd-MMM-yyyy HH:mm:ss G\MT", CultureInfo.InvariantCulture), DateTimeKind.Utc);
  398. break;
  399. case "httponly":
  400. c.HttpOnly = true;
  401. break;
  402. case "secure":
  403. c.Secure = true;
  404. break;
  405. default:
  406. if (c.Name.Length == 0) {
  407. c.Name = key;
  408. c.Value = value;
  409. }
  410. break;
  411. }
  412. }
  413. return c;
  414. }
  415. }
  416. }