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 (dot == 0 && String.Compare ("." + host, domain, true, CultureInfo.InvariantCulture) == 0)
264 if (host.Length < domain.Length)
267 string subdomain = host.Substring (host.Length - domain.Length);
268 return (String.Compare (subdomain, domain, true, CultureInfo.InvariantCulture) == 0);
271 public CookieCollection GetCookies (Uri uri)
274 throw new ArgumentNullException ("uri");
277 CookieCollection coll = new CookieCollection ();
281 foreach (Cookie cookie in cookies) {
282 string domain = cookie.Domain;
283 string host = uri.Host;
284 if (!CheckDomain (domain, host))
287 if (cookie.Port != "" && cookie.Ports != null && uri.Port != -1) {
288 if (Array.IndexOf (cookie.Ports, uri.Port) == -1)
292 string path = cookie.Path;
293 string uripath = uri.AbsolutePath;
294 if (path != "" && path != "/") {
295 if (uripath != path) {
296 if (!uripath.StartsWith (path))
299 if (path [path.Length - 1] != '/' && uripath.Length > path.Length &&
300 uripath [path.Length] != '/')
305 if (cookie.Secure && uri.Scheme != "https")
315 public void SetCookies (Uri uri, string cookieHeader)
318 throw new ArgumentNullException ("uri");
320 if (cookieHeader == null)
321 throw new ArgumentNullException ("cookieHeader");
323 ParseAndAddCookies (uri, cookieHeader);
326 // GetCookieValue, GetCookieName and ParseAndAddCookies copied from HttpRequest.cs
327 static string GetCookieValue (string str, int length, ref int i)
333 while (k < length && Char.IsWhiteSpace (str [k]))
337 while (k < length && str [k] != ';')
341 return str.Substring (begin, i - begin).Trim ();
344 static string GetCookieName (string str, int length, ref int i)
350 while (k < length && Char.IsWhiteSpace (str [k]))
354 while (k < length && str [k] != ';' && str [k] != '=')
358 return str.Substring (begin, k - begin).Trim ();
361 static string GetDir (string path)
363 if (path == null || path == "")
366 int last = path.LastIndexOf ('/');
370 return path.Substring (0, last + 1);
373 void ParseAndAddCookies (Uri uri, string header)
375 if (header.Length == 0)
378 string [] name_values = header.Trim ().Split (';');
379 int length = name_values.Length;
380 Cookie cookie = null;
382 CultureInfo inv = CultureInfo.InvariantCulture;
383 bool havePath = false;
384 bool haveDomain = false;
386 for (int i = 0; i < length; i++) {
388 string name_value = name_values [i].Trim ();
389 string name = GetCookieName (name_value, name_value.Length, ref pos);
390 if (name == null || name == "")
391 throw new CookieException ("Name is empty.");
393 string value = GetCookieValue (name_value, name_value.Length, ref pos);
394 if (cookie != null) {
395 if (!havePath && String.Compare (name, "$Path", true, inv) == 0 ||
396 String.Compare (name, "path", true, inv) == 0) {
402 if (!haveDomain && String.Compare (name, "$Domain", true, inv) == 0 ||
403 String.Compare (name, "domain", true, inv) == 0) {
404 cookie.Domain = value;
410 cookie.Path = GetDir (uri.AbsolutePath);
413 cookie.Domain = uri.Host;
420 cookie = new Cookie (name, value);
423 if (cookie != null) {
425 cookie.Path = GetDir (uri.AbsolutePath);
428 cookie.Domain = uri.Host;