2 // System.Net.CookieContainer
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
9 // (c) Copyright 2004 Ximian, Inc. (http://www.ximian.com)
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:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
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.
34 using System.Collections;
35 using System.Globalization;
36 using System.Runtime.Serialization;
42 [MonoTODO ("Need to remove older/unused cookies if it reaches the maximum capacity")]
44 public sealed class CookieContainer {
46 public class CookieContainer {
48 public const int DefaultCookieLengthLimit = 4096;
49 public const int DefaultCookieLimit = 300;
50 public const int DefaultPerDomainCookieLimit = 20;
53 int capacity = DefaultCookieLimit;
54 int perDomainCapacity = DefaultPerDomainCookieLimit;
55 int maxCookieSize = DefaultCookieLengthLimit;
56 CookieCollection cookies;
59 public CookieContainer ()
63 public CookieContainer (int capacity)
67 throw new ArgumentException ("Must be greater than zero", "Capacity");
69 throw new ArgumentException ("Capacity");
72 this.capacity = capacity;
75 public CookieContainer (int capacity, int perDomainCapacity, int maxCookieSize)
78 if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity))
80 throw new ArgumentOutOfRangeException ("perDomainCapacity",
81 string.Format ("PerDomainCapacity must be " +
82 "greater than {0} and less than {1}.", 0,
85 throw new ArgumentException ("PerDomainCapacity");
88 if (maxCookieSize <= 0)
90 throw new ArgumentException ("Must be greater than zero", "MaxCookieSize");
92 throw new ArgumentException ("MaxCookieSize");
95 this.perDomainCapacity = perDomainCapacity;
96 this.maxCookieSize = maxCookieSize;
102 get { return count; }
105 public int Capacity {
106 get { return capacity; }
108 if (value < 0 || (value < perDomainCapacity && perDomainCapacity != Int32.MaxValue))
109 throw new ArgumentOutOfRangeException ("value",
110 string.Format ("Capacity must be greater " +
111 "than {0} and less than {1}.", 0,
117 public int MaxCookieSize {
118 get { return maxCookieSize; }
121 throw new ArgumentOutOfRangeException ("value");
122 maxCookieSize = value;
126 public int PerDomainCapacity {
127 get { return perDomainCapacity; }
129 if (value != Int32.MaxValue && (value <= 0 || value > capacity))
130 throw new ArgumentOutOfRangeException ("value");
131 perDomainCapacity = value;
135 public void Add (Cookie cookie)
138 throw new ArgumentNullException ("cookie");
140 if (cookie.Domain == "")
142 throw new ArgumentException ("Cookie domain not set.", "cookie.Domain");
144 throw new ArgumentException ("cookie.Domain");
147 if (cookie.Value.Length > maxCookieSize)
148 throw new CookieException ("value is larger than MaxCookieSize.");
153 void AddCookie (Cookie cookie)
156 cookies = new CookieCollection ();
158 if (count + 1 > capacity)
159 throw new CookieException ("Capacity exceeded");
161 cookies.Add (cookie);
162 count = cookies.Count;
167 // Only needs to be called from AddCookie (Cookie) and GetCookies (Uri)
168 void CheckExpiration ()
173 ArrayList removed = null;
174 for (int i = cookies.Count - 1; i >= 0; i--) {
175 Cookie cookie = cookies [i];
176 if (cookie.Expired) {
178 removed = new ArrayList ();
183 if (removed != null) {
184 // We went backwards above, so this works.
185 ArrayList list = cookies.List;
186 foreach (int n in removed) {
192 public void Add (CookieCollection cookies)
195 throw new ArgumentNullException ("cookies");
197 foreach (Cookie cookie in cookies)
201 void Cook (Uri uri, Cookie cookie)
203 if (cookie.Name == null || cookie.Name == "")
204 throw new CookieException ("Invalid cookie: name");
206 if (cookie.Value == null)
207 throw new CookieException ("Invalid cookie: value");
209 if (uri != null && cookie.Domain == "")
210 cookie.Domain = uri.Host;
212 if (cookie.Version == 0 && (cookie.Path == null || cookie.Path == "")) {
214 cookie.Path = uri.AbsolutePath;
220 if (cookie.Port == "" && uri != null && !uri.IsDefaultPort) {
221 cookie.Port = "\"" + uri.Port.ToString () + "\"";
225 public void Add (Uri uri, Cookie cookie)
228 throw new ArgumentNullException ("uri");
231 throw new ArgumentNullException ("cookie");
237 public void Add (Uri uri, CookieCollection cookies)
240 throw new ArgumentNullException ("uri");
243 throw new ArgumentNullException ("cookies");
245 foreach (Cookie c in cookies) {
251 public string GetCookieHeader (Uri uri)
254 throw new ArgumentNullException ("uri");
256 CookieCollection coll = GetCookies (uri);
260 StringBuilder result = new StringBuilder ();
261 foreach (Cookie cookie in coll) {
262 result.Append (cookie.ToString ());
263 result.Append ("; ");
266 if (result.Length > 0)
267 result.Length -= 2; // remove trailing semicolon and space
269 return result.ToString ();
272 static bool CheckDomain (string domain, string host)
274 if (domain == String.Empty)
277 int hlen = host.Length;
278 int dlen = domain.Length;
283 return (String.Compare (domain, host, true, CultureInfo.InvariantCulture) == 0);
285 if (domain [0] != '.') {
286 domain = "." + domain;
290 string subdomain = host.Substring (hlen - dlen);
291 return (String.Compare (subdomain, domain, true, CultureInfo.InvariantCulture) == 0);
294 public CookieCollection GetCookies (Uri uri)
297 throw new ArgumentNullException ("uri");
300 CookieCollection coll = new CookieCollection ();
304 foreach (Cookie cookie in cookies) {
305 string domain = cookie.Domain;
306 if (!CheckDomain (domain, uri.Host))
309 if (cookie.Port != "" && cookie.Ports != null && uri.Port != -1) {
310 if (Array.IndexOf (cookie.Ports, uri.Port) == -1)
314 string path = cookie.Path;
315 string uripath = uri.AbsolutePath;
316 if (path != "" && path != "/") {
317 if (uripath != path) {
318 if (!uripath.StartsWith (path))
321 if (path [path.Length - 1] != '/' && uripath.Length > path.Length &&
322 uripath [path.Length] != '/')
327 if (cookie.Secure && uri.Scheme != "https")
337 public void SetCookies (Uri uri, string cookieHeader)
340 throw new ArgumentNullException ("uri");
342 if (cookieHeader == null)
343 throw new ArgumentNullException ("cookieHeader");
345 ParseAndAddCookies (uri, cookieHeader);
348 // GetCookieValue, GetCookieName and ParseAndAddCookies copied from HttpRequest.cs
349 static string GetCookieValue (string str, int length, ref int i)
355 while (k < length && Char.IsWhiteSpace (str [k]))
359 while (k < length && str [k] != ';')
363 return str.Substring (begin, i - begin).Trim ();
366 static string GetCookieName (string str, int length, ref int i)
372 while (k < length && Char.IsWhiteSpace (str [k]))
376 while (k < length && str [k] != ';' && str [k] != '=')
380 return str.Substring (begin, k - begin).Trim ();
383 static string GetDir (string path)
385 if (path == null || path == "")
388 int last = path.LastIndexOf ('/');
392 return path.Substring (0, last + 1);
395 void ParseAndAddCookies (Uri uri, string header)
397 if (header.Length == 0)
400 string [] name_values = header.Trim ().Split (';');
401 int length = name_values.Length;
402 Cookie cookie = null;
404 CultureInfo inv = CultureInfo.InvariantCulture;
405 bool havePath = false;
406 bool haveDomain = false;
408 for (int i = 0; i < length; i++) {
410 string name_value = name_values [i].Trim ();
411 string name = GetCookieName (name_value, name_value.Length, ref pos);
412 if (name == null || name == "")
413 throw new CookieException ("Name is empty.");
415 string value = GetCookieValue (name_value, name_value.Length, ref pos);
416 if (cookie != null) {
417 if (!havePath && String.Compare (name, "$Path", true, inv) == 0 ||
418 String.Compare (name, "path", true, inv) == 0) {
424 if (!haveDomain && String.Compare (name, "$Domain", true, inv) == 0 ||
425 String.Compare (name, "domain", true, inv) == 0) {
426 cookie.Domain = value;
432 cookie.Path = GetDir (uri.AbsolutePath);
435 cookie.Domain = uri.Host;
442 cookie = new Cookie (name, value);
445 if (cookie != null) {
447 cookie.Path = GetDir (uri.AbsolutePath);
450 cookie.Domain = uri.Host;