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")]
43 public class CookieContainer
45 public const int DefaultCookieLengthLimit = 4096;
46 public const int DefaultCookieLimit = 300;
47 public const int DefaultPerDomainCookieLimit = 20;
50 int capacity = DefaultCookieLimit;
51 int perDomainCapacity = DefaultPerDomainCookieLimit;
52 int maxCookieSize = DefaultCookieLengthLimit;
53 CookieCollection cookies;
56 public CookieContainer ()
60 public CookieContainer (int capacity)
63 throw new ArgumentException ("Must be greater than zero", "capacity");
65 this.capacity = capacity;
68 public CookieContainer (int capacity, int perDomainCapacity, int maxCookieSize)
71 if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity))
72 throw new ArgumentException ("Invalid value", "perDomaniCapacity");
74 if (maxCookieSize <= 0)
75 throw new ArgumentException ("Must be greater than zero", "maxCookieSize");
77 this.perDomainCapacity = perDomainCapacity;
78 this.maxCookieSize = maxCookieSize;
88 get { return capacity; }
90 if (value < 0 || (value < perDomainCapacity && perDomainCapacity != Int32.MaxValue))
91 throw new ArgumentOutOfRangeException ("value");
93 if (value < maxCookieSize)
94 maxCookieSize = value;
100 public int MaxCookieSize {
101 get { return maxCookieSize; }
104 throw new ArgumentOutOfRangeException ("value");
105 maxCookieSize = value;
109 public int PerDomainCapacity {
110 get { return perDomainCapacity; }
112 if (value != Int32.MaxValue && (value <= 0 || value > capacity))
113 throw new ArgumentOutOfRangeException ("value");
115 perDomainCapacity = value;
119 public void Add (Cookie cookie)
122 throw new ArgumentNullException ("cookie");
124 if (cookie.Domain == "")
125 throw new ArgumentException ("Cookie domain not set.", "cookie");
127 if (cookie.Value.Length > maxCookieSize)
128 throw new CookieException ("value is larger than MaxCookieSize.");
133 void AddCookie (Cookie cookie)
136 cookies = new CookieCollection ();
138 if (count + 1 > capacity)
139 throw new CookieException ("Capacity exceeded");
141 cookies.Add (cookie);
142 count = cookies.Count;
147 // Only needs to be called from AddCookie (Cookie) and GetCookies (Uri)
148 void CheckExpiration ()
153 ArrayList removed = null;
154 for (int i = cookies.Count - 1; i >= 0; i--) {
155 Cookie cookie = cookies [i];
156 if (cookie.Expired) {
158 removed = new ArrayList ();
163 if (removed != null) {
164 // We went backwards above, so this works.
165 ArrayList list = cookies.List;
166 foreach (int n in removed) {
172 public void Add (CookieCollection cookies)
175 throw new ArgumentNullException ("cookies");
177 foreach (Cookie cookie in cookies)
181 void Cook (Uri uri, Cookie cookie)
183 if (cookie.Name == null || cookie.Name == "")
184 throw new CookieException ("Invalid cookie: name");
186 if (cookie.Value == null)
187 throw new CookieException ("Invalid cookie: value");
189 if (uri != null && cookie.Domain == "")
190 cookie.Domain = uri.Host;
192 if (cookie.Version == 0 && (cookie.Path == null || cookie.Path == "")) {
194 cookie.Path = uri.AbsolutePath;
200 if (cookie.Port == "" && uri != null && !uri.IsDefaultPort) {
201 cookie.Port = "\"" + uri.Port.ToString () + "\"";
205 public void Add (Uri uri, Cookie cookie)
208 throw new ArgumentNullException ("uri");
211 throw new ArgumentNullException ("cookie");
217 public void Add (Uri uri, CookieCollection cookies)
220 throw new ArgumentNullException ("uri");
223 throw new ArgumentNullException ("cookies");
225 foreach (Cookie c in cookies) {
231 public string GetCookieHeader (Uri uri)
234 throw new ArgumentNullException ("uri");
236 CookieCollection coll = GetCookies (uri);
240 StringBuilder result = new StringBuilder ();
241 foreach (Cookie cookie in coll) {
242 result.Append (cookie.ToString ());
246 if (result.Length > 0)
247 result.Length--; // remove trailing semicolon
249 return result.ToString ();
252 static bool CheckDomain (string domain, string host)
254 if (domain != "" && domain [0] != '.')
255 return (String.Compare (domain, host, true, CultureInfo.InvariantCulture) == 0);
257 int dot = host.IndexOf ('.');
259 return (String.Compare (host, domain, true, CultureInfo.InvariantCulture) == 0);
261 if (host.Length < domain.Length)
264 string subdomain = host.Substring (host.Length - domain.Length);
265 return (String.Compare (subdomain, domain, true, CultureInfo.InvariantCulture) == 0);
268 public CookieCollection GetCookies (Uri uri)
271 throw new ArgumentNullException ("uri");
274 CookieCollection coll = new CookieCollection ();
278 foreach (Cookie cookie in cookies) {
279 string domain = cookie.Domain;
280 string host = uri.Host;
281 if (!CheckDomain (domain, host))
284 if (cookie.Port != "" && cookie.Ports != null && uri.Port != -1) {
285 if (Array.IndexOf (cookie.Ports, uri.Port) == -1)
289 string path = cookie.Path;
290 string uripath = uri.AbsolutePath;
291 if (path != "" && path != "/") {
292 if (uripath != path) {
293 if (!uripath.StartsWith (path))
296 if (path [path.Length - 1] != '/' && uripath.Length > path.Length &&
297 uripath [path.Length] != '/')
302 if (cookie.Secure && uri.Scheme != "https")
312 public void SetCookies (Uri uri, string cookieHeader)
315 throw new ArgumentNullException ("uri");
317 if (cookieHeader == null)
318 throw new ArgumentNullException ("cookieHeader");
320 ParseAndAddCookies (uri, cookieHeader);
323 // GetCookieValue, GetCookieName and ParseAndAddCookies copied from HttpRequest.cs
324 static string GetCookieValue (string str, int length, ref int i)
330 while (k < length && Char.IsWhiteSpace (str [k]))
334 while (k < length && str [k] != ';')
338 return str.Substring (begin, i - begin).Trim ();
341 static string GetCookieName (string str, int length, ref int i)
347 while (k < length && Char.IsWhiteSpace (str [k]))
351 while (k < length && str [k] != ';' && str [k] != '=')
355 return str.Substring (begin, k - begin).Trim ();
358 static string GetDir (string path)
360 if (path == null || path == "")
363 int last = path.LastIndexOf ('/');
367 return path.Substring (0, last + 1);
370 void ParseAndAddCookies (Uri uri, string header)
372 if (header.Length == 0)
375 string [] name_values = header.Trim ().Split (';');
376 int length = name_values.Length;
377 Cookie cookie = null;
379 CultureInfo inv = CultureInfo.InvariantCulture;
380 bool havePath = false;
381 bool haveDomain = false;
383 for (int i = 0; i < length; i++) {
385 string name_value = name_values [i].Trim ();
386 string name = GetCookieName (name_value, name_value.Length, ref pos);
387 if (name == null || name == "")
388 throw new CookieException ("Name is empty.");
390 string value = GetCookieValue (name_value, name_value.Length, ref pos);
391 if (cookie != null) {
392 if (!havePath && String.Compare (name, "$Path", true, inv) == 0 ||
393 String.Compare (name, "path", true, inv) == 0) {
399 if (!haveDomain && String.Compare (name, "$Domain", true, inv) == 0 ||
400 String.Compare (name, "domain", true, inv) == 0) {
401 cookie.Domain = value;
407 cookie.Path = GetDir (uri.AbsolutePath);
410 cookie.Domain = uri.Host;
417 cookie = new Cookie (name, value);
420 if (cookie != null) {
422 cookie.Path = GetDir (uri.AbsolutePath);
425 cookie.Domain = uri.Host;