Refactored Cookie.cs

This commit is contained in:
sta 2014-03-20 20:57:05 +09:00
parent dcb96a4073
commit bdd3a493ed

View File

@ -1,36 +1,44 @@
// #region License
// Cookie.cs /*
// Copied from System.Net.Cookie.cs * Cookie.cs
// *
// Authors: * This code is derived from System.Net.Cookie.cs of Mono
// Lawrence Pit (loz@cable.a2000.nl) * (http://www.mono-project.com).
// Gonzalo Paniagua Javier (gonzalo@ximian.com) *
// Daniel Nauck (dna@mono-project.de) * The MIT License
// Sebastien Pouliot (sebastien@ximian.com) *
// sta (sta.blockhead@gmail.com) * Copyright (c) 2004,2009 Novell, Inc. (http://www.novell.com)
// * Copyright (c) 2012-2014 sta.blockhead
// Copyright (c) 2004,2009 Novell, Inc (http://www.novell.com) *
// Copyright (c) 2012-2013 sta.blockhead (sta.blockhead@gmail.com) * Permission is hereby granted, free of charge, to any person obtaining a copy
// * of this software and associated documentation files (the "Software"), to deal
// Permission is hereby granted, free of charge, to any person obtaining * in the Software without restriction, including without limitation the rights
// a copy of this software and associated documentation files (the * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// "Software"), to deal in the Software without restriction, including * copies of the Software, and to permit persons to whom the Software is
// without limitation the rights to use, copy, modify, merge, publish, * furnished to do so, subject to the following conditions:
// distribute, sublicense, and/or sell copies of the Software, and to *
// permit persons to whom the Software is furnished to do so, subject to * The above copyright notice and this permission notice shall be included in
// the following conditions: * all copies or substantial portions of the Software.
// *
// The above copyright notice and this permission notice shall be * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// included in all copies or substantial portions of the Software. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * THE SOFTWARE.
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION */
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION #endregion
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// #region Authors
/*
* Authors:
* - Lawrence Pit <loz@cable.a2000.nl>
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
* - Daniel Nauck <dna@mono-project.de>
* - Sebastien Pouliot <sebastien@ximian.com>
*/
#endregion
using System; using System;
using System.Text; using System.Text;
@ -40,14 +48,14 @@ using System.Collections;
namespace WebSocketSharp.Net namespace WebSocketSharp.Net
{ {
/// <summary> /// <summary>
/// Provides a set of properties and methods used to manage an HTTP Cookie. /// Provides a set of methods and properties used to manage an HTTP Cookie.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
/// The Cookie class supports the following cookie formats: /// The Cookie class supports the following cookie formats:
/// <see href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">Netscape specification</see>, /// <see href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">Netscape specification</see>,
/// <see href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</see> and /// <see href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</see>, and
/// <see href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</see>. /// <see href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</see>
/// </para> /// </para>
/// <para> /// <para>
/// The Cookie class cannot be inherited. /// The Cookie class cannot be inherited.
@ -56,29 +64,29 @@ namespace WebSocketSharp.Net
[Serializable] [Serializable]
public sealed class Cookie public sealed class Cookie
{ {
#region Static Private Fields #region Private Static Fields
static char [] reservedCharsForName = new char [] {' ', '=', ';', ',', '\n', '\r', '\t'}; private static char [] _reservedCharsForName = { ' ', '=', ';', ',', '\n', '\r', '\t' };
static char [] reservedCharsForValue = new char [] {';', ','}; private static char [] _reservedCharsForValue = { ';', ',' };
#endregion #endregion
#region Private Fields #region Private Fields
string comment; private string _comment;
Uri commentUri; private Uri _commentUri;
bool discard; private bool _discard;
string domain; private string _domain;
DateTime expires; private DateTime _expires;
bool httpOnly; private bool _httpOnly;
string name; private string _name;
string path; private string _path;
string port; private string _port;
int [] ports; private int [] _ports;
bool secure; private bool _secure;
DateTime timestamp; private DateTime _timestamp;
string val; private string _value;
int version; private int _version;
#endregion #endregion
@ -89,31 +97,31 @@ namespace WebSocketSharp.Net
/// </summary> /// </summary>
public Cookie () public Cookie ()
{ {
comment = String.Empty; _comment = String.Empty;
domain = String.Empty; _domain = String.Empty;
expires = DateTime.MinValue; _expires = DateTime.MinValue;
name = String.Empty; _name = String.Empty;
path = String.Empty; _path = String.Empty;
port = String.Empty; _port = String.Empty;
ports = new int [] {}; _ports = new int [0];
timestamp = DateTime.Now; _timestamp = DateTime.Now;
val = String.Empty; _value = String.Empty;
version = 0; _version = 0;
} }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="Cookie"/> class /// Initializes a new instance of the <see cref="Cookie"/> class with the specified
/// with the specified <paramref name="name"/> and <paramref name="value"/>. /// <paramref name="name"/> and <paramref name="value"/>.
/// </summary> /// </summary>
/// <param name="name"> /// <param name="name">
/// A <see cref="string"/> that contains the Name of the cookie. /// A <see cref="string"/> that represents the Name of the cookie.
/// </param> /// </param>
/// <param name="value"> /// <param name="value">
/// A <see cref="string"/> that contains the Value of the cookie. /// A <see cref="string"/> that represents the Value of the cookie.
/// </param> /// </param>
/// <exception cref="CookieException"> /// <exception cref="CookieException">
/// <para> /// <para>
/// <paramref name="name"/> is <see langword="null"/> or <see cref="String.Empty"/>. /// <paramref name="name"/> is <see langword="null"/> or empty.
/// </para> /// </para>
/// <para> /// <para>
/// - or - /// - or -
@ -143,21 +151,21 @@ namespace WebSocketSharp.Net
} }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="Cookie"/> class /// Initializes a new instance of the <see cref="Cookie"/> class with the specified
/// with the specified <paramref name="name"/>, <paramref name="value"/> and <paramref name="path"/>. /// <paramref name="name"/>, <paramref name="value"/>, and <paramref name="path"/>.
/// </summary> /// </summary>
/// <param name="name"> /// <param name="name">
/// A <see cref="string"/> that contains the Name of the cookie. /// A <see cref="string"/> that represents the Name of the cookie.
/// </param> /// </param>
/// <param name="value"> /// <param name="value">
/// A <see cref="string"/> that contains the Value of the cookie. /// A <see cref="string"/> that represents the Value of the cookie.
/// </param> /// </param>
/// <param name="path"> /// <param name="path">
/// A <see cref="string"/> that contains the value of the Path attribute of the cookie. /// A <see cref="string"/> that represents the value of the Path attribute of the cookie.
/// </param> /// </param>
/// <exception cref="CookieException"> /// <exception cref="CookieException">
/// <para> /// <para>
/// <paramref name="name"/> is <see langword="null"/> or <see cref="String.Empty"/>. /// <paramref name="name"/> is <see langword="null"/> or empty.
/// </para> /// </para>
/// <para> /// <para>
/// - or - /// - or -
@ -186,25 +194,25 @@ namespace WebSocketSharp.Net
} }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="Cookie"/> class /// Initializes a new instance of the <see cref="Cookie"/> class with the specified
/// with the specified <paramref name="name"/>, <paramref name="value"/>, /// <paramref name="name"/>, <paramref name="value"/>, <paramref name="path"/>, and
/// <paramref name="path"/> and <paramref name="domain"/>. /// <paramref name="domain"/>.
/// </summary> /// </summary>
/// <param name="name"> /// <param name="name">
/// A <see cref="string"/> that contains the Name of the cookie. /// A <see cref="string"/> that represents the Name of the cookie.
/// </param> /// </param>
/// <param name="value"> /// <param name="value">
/// A <see cref="string"/> that contains the Value of the cookie. /// A <see cref="string"/> that represents the Value of the cookie.
/// </param> /// </param>
/// <param name="path"> /// <param name="path">
/// A <see cref="string"/> that contains the value of the Path attribute of the cookie. /// A <see cref="string"/> that represents the value of the Path attribute of the cookie.
/// </param> /// </param>
/// <param name="domain"> /// <param name="domain">
/// A <see cref="string"/> that contains the value of the Domain attribute of the cookie. /// A <see cref="string"/> that represents the value of the Domain attribute of the cookie.
/// </param> /// </param>
/// <exception cref="CookieException"> /// <exception cref="CookieException">
/// <para> /// <para>
/// <paramref name="name"/> is <see langword="null"/> or <see cref="String.Empty"/>. /// <paramref name="name"/> is <see langword="null"/> or empty.
/// </para> /// </para>
/// <para> /// <para>
/// - or - /// - or -
@ -236,26 +244,30 @@ namespace WebSocketSharp.Net
#region Internal Properties #region Internal Properties
internal bool ExactDomain { get; set; } internal bool ExactDomain {
get; set;
}
internal int MaxAge { internal int MaxAge {
get { get {
if (expires == DateTime.MinValue || Expired) if (_expires == DateTime.MinValue)
return 0; return 0;
var tmp = expires.Kind == DateTimeKind.Local var expires = _expires.Kind != DateTimeKind.Local
? expires ? _expires.ToLocalTime ()
: expires.ToLocalTime (); : _expires;
var span = tmp - DateTime.Now; var span = expires - DateTime.Now;
return span <= TimeSpan.Zero return span > TimeSpan.Zero
? 0 ? (int) span.TotalSeconds
: (int) span.TotalSeconds; : 0;
} }
} }
internal int [] Ports { internal int [] Ports {
get { return ports; } get {
return _ports;
}
} }
#endregion #endregion
@ -266,23 +278,33 @@ namespace WebSocketSharp.Net
/// Gets or sets the value of the Comment attribute of the cookie. /// Gets or sets the value of the Comment attribute of the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="string"/> that contains a comment to document intended use of the cookie. /// A <see cref="string"/> that represents the comment to document intended use of the cookie.
/// </value> /// </value>
public string Comment { public string Comment {
get { return comment; } get {
set { comment = value ?? String.Empty; } return _comment;
}
set {
_comment = value ?? String.Empty;
}
} }
/// <summary> /// <summary>
/// Gets or sets the value of the CommentURL attribute of the cookie. /// Gets or sets the value of the CommentURL attribute of the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="Uri"/> that contains a URI that provides the comment /// A <see cref="Uri"/> that represents the URI that provides the comment to document intended
/// to document intended use of the cookie. /// use of the cookie.
/// </value> /// </value>
public Uri CommentUri { public Uri CommentUri {
get { return commentUri; } get {
set { commentUri = value; } return _commentUri;
}
set {
_commentUri = value;
}
} }
/// <summary> /// <summary>
@ -291,27 +313,36 @@ namespace WebSocketSharp.Net
/// </summary> /// </summary>
/// <value> /// <value>
/// <c>true</c> if the client discards the cookie unconditionally when the client terminates; /// <c>true</c> if the client discards the cookie unconditionally when the client terminates;
/// otherwise, <c>false</c>. The default is <c>false</c>. /// otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value> /// </value>
public bool Discard { public bool Discard {
get { return discard; } get {
set { discard = value; } return _discard;
}
set {
_discard = value;
}
} }
/// <summary> /// <summary>
/// Gets or sets the value of the Domain attribute of the cookie. /// Gets or sets the value of the Domain attribute of the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="string"/> that contains a URI for which the cookie is valid. /// A <see cref="string"/> that represents the URI for which the cookie is valid.
/// </value> /// </value>
public string Domain { public string Domain {
get { return domain; } get {
return _domain;
}
set { set {
if (value.IsNullOrEmpty ()) { if (value.IsNullOrEmpty ()) {
domain = String.Empty; _domain = String.Empty;
ExactDomain = true; ExactDomain = true;
} else { }
domain = value; else {
_domain = value;
ExactDomain = value [0] != '.'; ExactDomain = value [0] != '.';
} }
} }
@ -321,17 +352,16 @@ namespace WebSocketSharp.Net
/// Gets or sets a value indicating whether the cookie has expired. /// Gets or sets a value indicating whether the cookie has expired.
/// </summary> /// </summary>
/// <value> /// <value>
/// <c>true</c> if the cookie has expired; otherwise, <c>false</c>. The default is <c>false</c>. /// <c>true</c> if the cookie has expired; otherwise, <c>false</c>.
/// The default value is <c>false</c>.
/// </value> /// </value>
public bool Expired { public bool Expired {
get { get {
return expires <= DateTime.Now && return _expires != DateTime.MinValue && _expires <= DateTime.Now;
expires != DateTime.MinValue;
} }
set { set {
expires = value _expires = value ? DateTime.Now : DateTime.MinValue;
? DateTime.Now
: DateTime.MinValue;
} }
} }
@ -339,34 +369,45 @@ namespace WebSocketSharp.Net
/// Gets or sets the value of the Expires attribute of the cookie. /// Gets or sets the value of the Expires attribute of the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="DateTime"/> that contains the date and time at which the cookie expires. /// A <see cref="DateTime"/> that represents the date and time at which the cookie expires.
/// The default is <see cref="DateTime.MinValue"/>. /// The default value is <see cref="DateTime.MinValue"/>.
/// </value> /// </value>
public DateTime Expires { public DateTime Expires {
get { return expires; } get {
set { expires = value; } return _expires;
}
set {
_expires = value;
}
} }
/// <summary> /// <summary>
/// Gets or sets a value indicating non-HTTP APIs can access the cookie. /// Gets or sets a value indicating whether non-HTTP APIs can access the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// <c>true</c> if non-HTTP APIs can not access the cookie; otherwise, <c>false</c>. /// <c>true</c> if non-HTTP APIs cannot access the cookie; otherwise, <c>false</c>.
/// The default value is <c>false</c>.
/// </value> /// </value>
public bool HttpOnly { public bool HttpOnly {
get { return httpOnly; } get {
set { httpOnly = value; } return _httpOnly;
}
set {
_httpOnly = value;
}
} }
/// <summary> /// <summary>
/// Gets or sets the Name of the cookie. /// Gets or sets the Name of the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="string"/> that contains the Name of the cookie. /// A <see cref="string"/> that represents the Name of the cookie.
/// </value> /// </value>
/// <exception cref="CookieException"> /// <exception cref="CookieException">
/// <para> /// <para>
/// The value specified for a set operation is <see langword="null"/> or <see cref="String.Empty"/>. /// The value specified for a set operation is <see langword="null"/> or empty.
/// </para> /// </para>
/// <para> /// <para>
/// - or - /// - or -
@ -376,13 +417,16 @@ namespace WebSocketSharp.Net
/// </para> /// </para>
/// </exception> /// </exception>
public string Name { public string Name {
get { return name; } get {
return _name;
}
set { set {
string msg; string msg;
if (!CanSetName (value, out msg)) if (!canSetName (value, out msg))
throw new CookieException (msg); throw new CookieException (msg);
name = value; _name = value;
} }
} }
@ -390,42 +434,52 @@ namespace WebSocketSharp.Net
/// Gets or sets the value of the Path attribute of the cookie. /// Gets or sets the value of the Path attribute of the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="string"/> that contains a subset of URI on the origin server /// A <see cref="string"/> that represents the subset of URI on the origin server
/// to which the cookie applies. /// to which the cookie applies.
/// </value> /// </value>
public string Path { public string Path {
get { return path; } get {
set { path = value ?? String.Empty; } return _path;
}
set {
_path = value ?? String.Empty;
}
} }
/// <summary> /// <summary>
/// Gets or sets the value of the Port attribute of the cookie. /// Gets or sets the value of the Port attribute of the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="string"/> that contains a list of the TCP ports to which the cookie applies. /// A <see cref="string"/> that represents the list of TCP ports to which the cookie applies.
/// </value> /// </value>
/// <exception cref="CookieException"> /// <exception cref="CookieException">
/// The value specified for a set operation is not enclosed in double quotes or could not be parsed. /// The value specified for a set operation isn't enclosed in double quotes or
/// couldn't be parsed.
/// </exception> /// </exception>
public string Port { public string Port {
get { return port; } get {
return _port;
}
set { set {
if (value.IsNullOrEmpty ()) { if (value.IsNullOrEmpty ()) {
port = String.Empty; _port = String.Empty;
ports = new int [] {}; _ports = new int [0];
return; return;
} }
if (!value.IsEnclosedIn ('"')) if (!value.IsEnclosedIn ('"'))
throw new CookieException (String.Format ( throw new CookieException (
"The 'Port={0}' attribute of the cookie is invalid. The value must be enclosed in double quotes.", value)); "The value of Port attribute must be enclosed in double quotes.");
string error; string error;
if (!TryCreatePorts (value, out ports, out error)) if (!tryCreatePorts (value, out _ports, out error))
throw new CookieException (String.Format ( throw new CookieException (
"The 'Port={0}' attribute of the cookie is invalid. Invalid value: {1}", value, error)); String.Format ("The value of Port attribute contains an invalid value: {0}", error));
port = value; _port = value;
} }
} }
@ -438,28 +492,35 @@ namespace WebSocketSharp.Net
/// </remarks> /// </remarks>
/// <value> /// <value>
/// <c>true</c> if the security level of the cookie is secure; otherwise, <c>false</c>. /// <c>true</c> if the security level of the cookie is secure; otherwise, <c>false</c>.
/// The default is <c>false</c>. /// The default value is <c>false</c>.
/// </value> /// </value>
public bool Secure { public bool Secure {
get { return secure; } get {
set { secure = value; } return _secure;
}
set {
_secure = value;
}
} }
/// <summary> /// <summary>
/// Gets the time when the cookie was issued. /// Gets the time when the cookie was issued.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="DateTime"/> that contains the time when the cookie was issued. /// A <see cref="DateTime"/> that represents the time when the cookie was issued.
/// </value> /// </value>
public DateTime TimeStamp { public DateTime TimeStamp {
get { return timestamp; } get {
return _timestamp;
}
} }
/// <summary> /// <summary>
/// Gets or sets the Value of the cookie. /// Gets or sets the Value of the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="string"/> that contains the Value of the cookie. /// A <see cref="string"/> that represents the Value of the cookie.
/// </value> /// </value>
/// <exception cref="CookieException"> /// <exception cref="CookieException">
/// <para> /// <para>
@ -474,13 +535,16 @@ namespace WebSocketSharp.Net
/// </para> /// </para>
/// </exception> /// </exception>
public string Value { public string Value {
get { return val; } get {
return _value;
}
set { set {
string msg; string msg;
if (!CanSetValue (value, out msg)) if (!canSetValue (value, out msg))
throw new CookieException (msg); throw new CookieException (msg);
val = value.Length == 0 ? "\"\"" : value; _value = value.Length > 0 ? value : "\"\"";
} }
} }
@ -488,19 +552,22 @@ namespace WebSocketSharp.Net
/// Gets or sets the value of the Version attribute of the cookie. /// Gets or sets the value of the Version attribute of the cookie.
/// </summary> /// </summary>
/// <value> /// <value>
/// An <see cref="int"/> that contains the version of the HTTP state management /// An <see cref="int"/> that represents the version of the HTTP state management
/// to which the cookie conforms. /// to which the cookie conforms.
/// </value> /// </value>
/// <exception cref="ArgumentOutOfRangeException"> /// <exception cref="ArgumentOutOfRangeException">
/// The value specified for a set operation is not allowed. The value must be 0 or 1. /// The value specified for a set operation isn't 0 or 1.
/// </exception> /// </exception>
public int Version { public int Version {
get { return version; } get {
return _version;
}
set { set {
if (value < 0 || value > 1) if (value < 0 || value > 1)
throw new ArgumentOutOfRangeException ("value", "Must be 0 or 1."); throw new ArgumentOutOfRangeException ("value", "Must be 0 or 1.");
else
version = value; _version = value;
} }
} }
@ -508,14 +575,14 @@ namespace WebSocketSharp.Net
#region Private Methods #region Private Methods
static bool CanSetName (string name, out string message) private static bool canSetName (string name, out string message)
{ {
if (name.IsNullOrEmpty ()) { if (name.IsNullOrEmpty ()) {
message = "Name must not be null or empty."; message = "Name must not be null or empty.";
return false; return false;
} }
if (name [0] == '$' || name.Contains (reservedCharsForName)) { if (name [0] == '$' || name.Contains (_reservedCharsForName)) {
message = "Name contains an invalid character."; message = "Name contains an invalid character.";
return false; return false;
} }
@ -524,106 +591,115 @@ namespace WebSocketSharp.Net
return true; return true;
} }
static bool CanSetValue (string value, out string message) private static bool canSetValue (string value, out string message)
{ {
if (value == null) { if (value == null) {
message = "Value must not be null."; message = "Value must not be null.";
return false; return false;
} }
if (value.Contains (reservedCharsForValue)) { if (value.Contains (_reservedCharsForValue) && !value.IsEnclosedIn ('"')) {
if (!value.IsEnclosedIn ('"')) {
message = "Value contains an invalid character."; message = "Value contains an invalid character.";
return false; return false;
} }
}
message = String.Empty; message = String.Empty;
return true; return true;
} }
static int Hash (int i, int j, int k, int l, int m) private static int hash (int i, int j, int k, int l, int m)
{ {
return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25) ^ (m << 20 | m >> 12); return i ^
(j << 13 | j >> 19) ^
(k << 26 | k >> 6) ^
(l << 7 | l >> 25) ^
(m << 20 | m >> 12);
} }
string ToResponseStringVersion0 () private string toResponseStringVersion0 ()
{ {
var result = new StringBuilder (64); var result = new StringBuilder (64);
result.AppendFormat ("{0}={1}", name, val); result.AppendFormat ("{0}={1}", _name, _value);
if (expires != DateTime.MinValue)
result.AppendFormat ("; Expires={0}",
expires.ToUniversalTime ().ToString ("ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'",
CultureInfo.CreateSpecificCulture("en-US")));
if (!path.IsNullOrEmpty ()) if (_expires != DateTime.MinValue)
result.AppendFormat ("; Path={0}", path); result.AppendFormat (
"; Expires={0}",
_expires.ToUniversalTime ().ToString (
"ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'",
CultureInfo.CreateSpecificCulture ("en-US")));
if (!domain.IsNullOrEmpty ()) if (!_path.IsNullOrEmpty ())
result.AppendFormat ("; Domain={0}", domain); result.AppendFormat ("; Path={0}", _path);
if (secure) if (!_domain.IsNullOrEmpty ())
result.AppendFormat ("; Domain={0}", _domain);
if (_secure)
result.Append ("; Secure"); result.Append ("; Secure");
if (httpOnly) if (_httpOnly)
result.Append ("; HttpOnly"); result.Append ("; HttpOnly");
return result.ToString (); return result.ToString ();
} }
string ToResponseStringVersion1 () private string toResponseStringVersion1 ()
{ {
var result = new StringBuilder (64); var result = new StringBuilder (64);
result.AppendFormat ("{0}={1}; Version={2}", name, val, version); result.AppendFormat ("{0}={1}; Version={2}", _name, _value, _version);
if (expires != DateTime.MinValue)
if (_expires != DateTime.MinValue)
result.AppendFormat ("; Max-Age={0}", MaxAge); result.AppendFormat ("; Max-Age={0}", MaxAge);
if (!path.IsNullOrEmpty ()) if (!_path.IsNullOrEmpty ())
result.AppendFormat ("; Path={0}", path); result.AppendFormat ("; Path={0}", _path);
if (!domain.IsNullOrEmpty ()) if (!_domain.IsNullOrEmpty ())
result.AppendFormat ("; Domain={0}", domain); result.AppendFormat ("; Domain={0}", _domain);
if (!port.IsNullOrEmpty ()) if (!_port.IsNullOrEmpty ()) {
if (port == "\"\"") if (_port == "\"\"")
result.Append ("; Port"); result.Append ("; Port");
else else
result.AppendFormat ("; Port={0}", port); result.AppendFormat ("; Port={0}", _port);
}
if (!comment.IsNullOrEmpty ()) if (!_comment.IsNullOrEmpty ())
result.AppendFormat ("; Comment={0}", comment.UrlEncode ()); result.AppendFormat ("; Comment={0}", _comment.UrlEncode ());
if (commentUri != null) if (_commentUri != null)
result.AppendFormat ("; CommentURL={0}", commentUri.OriginalString.Quote ()); result.AppendFormat ("; CommentURL={0}", _commentUri.OriginalString.Quote ());
if (discard) if (_discard)
result.Append ("; Discard"); result.Append ("; Discard");
if (secure) if (_secure)
result.Append ("; Secure"); result.Append ("; Secure");
return result.ToString (); return result.ToString ();
} }
static bool TryCreatePorts (string value, out int [] result, out string parseError) private static bool tryCreatePorts (string value, out int [] result, out string parseError)
{ {
var values = value.Trim ('"').Split (','); var ports = value.Trim ('"').Split (',');
var tmp = new int [values.Length]; var tmp = new int [ports.Length];
for (int i = 0; i < values.Length; i++) { for (int i = 0; i < ports.Length; i++) {
tmp [i] = int.MinValue; tmp [i] = int.MinValue;
var v = values [i].Trim (); var port = ports [i].Trim ();
if (v.Length == 0) if (port.Length == 0)
continue; continue;
if (!int.TryParse (v, out tmp [i])) { if (!int.TryParse (port, out tmp [i])) {
result = new int [] {}; result = new int [0];
parseError = v; parseError = port;
return false; return false;
} }
} }
result = tmp; result = tmp;
parseError = String.Empty; parseError = String.Empty;
return true; return true;
} }
@ -634,30 +710,32 @@ namespace WebSocketSharp.Net
// From client to server // From client to server
internal string ToRequestString (Uri uri) internal string ToRequestString (Uri uri)
{ {
if (name.Length == 0) if (_name.Length == 0)
return String.Empty; return String.Empty;
if (version == 0) if (_version == 0)
return String.Format ("{0}={1}", name, val); return String.Format ("{0}={1}", _name, _value);
var result = new StringBuilder (64); var result = new StringBuilder (64);
result.AppendFormat ("$Version={0}; {1}={2}", version, name, val); result.AppendFormat ("$Version={0}; {1}={2}", _version, _name, _value);
if (!path.IsNullOrEmpty ())
result.AppendFormat ("; $Path={0}", path); if (!_path.IsNullOrEmpty ())
result.AppendFormat ("; $Path={0}", _path);
else if (uri != null) else if (uri != null)
result.AppendFormat ("; $Path={0}", uri.GetAbsolutePath ()); result.AppendFormat ("; $Path={0}", uri.GetAbsolutePath ());
else else
result.Append ("; $Path=/"); result.Append ("; $Path=/");
bool append_domain = uri == null || uri.Host != domain; bool appendDomain = uri == null || uri.Host != _domain;
if (append_domain && !domain.IsNullOrEmpty ()) if (appendDomain && !_domain.IsNullOrEmpty ())
result.AppendFormat ("; $Domain={0}", domain); result.AppendFormat ("; $Domain={0}", _domain);
if (!port.IsNullOrEmpty ()) if (!_port.IsNullOrEmpty ()) {
if (port == "\"\"") if (_port == "\"\"")
result.Append ("; $Port"); result.Append ("; $Port");
else else
result.AppendFormat ("; $Port={0}", port); result.AppendFormat ("; $Port={0}", _port);
}
return result.ToString (); return result.ToString ();
} }
@ -665,11 +743,9 @@ namespace WebSocketSharp.Net
// From server to client // From server to client
internal string ToResponseString () internal string ToResponseString ()
{ {
return name.Length == 0 return _name.Length > 0
? String.Empty ? (_version == 0 ? toResponseStringVersion0 () : toResponseStringVersion1 ())
: version == 0 : String.Empty;
? ToResponseStringVersion0 ()
: ToResponseStringVersion1 ();
} }
#endregion #endregion
@ -677,47 +753,49 @@ namespace WebSocketSharp.Net
#region Public Methods #region Public Methods
/// <summary> /// <summary>
/// Determines whether the specified <see cref="Object"/> is equal to the current <see cref="Cookie"/>. /// Determines whether the specified <see cref="Object"/> is equal to the current
/// <see cref="Cookie"/>.
/// </summary> /// </summary>
/// <param name="comparand"> /// <param name="comparand">
/// An <see cref="Object"/> to compare with the current <see cref="Cookie"/>. /// An <see cref="Object"/> to compare with the current <see cref="Cookie"/>.
/// </param> /// </param>
/// <returns> /// <returns>
/// <c>true</c> if the specified <see cref="Object"/> is equal to the current <see cref="Cookie"/>; /// <c>true</c> if <paramref name="comparand"/> is equal to the current <see cref="Cookie"/>;
/// otherwise, <c>false</c>. /// otherwise, <c>false</c>.
/// </returns> /// </returns>
public override bool Equals (Object comparand) public override bool Equals (Object comparand)
{ {
var cookie = comparand as Cookie; var cookie = comparand as Cookie;
return cookie != null && return cookie != null &&
name.Equals (cookie.Name, StringComparison.InvariantCultureIgnoreCase) && _name.Equals (cookie.Name, StringComparison.InvariantCultureIgnoreCase) &&
val.Equals (cookie.Value, StringComparison.InvariantCulture) && _value.Equals (cookie.Value, StringComparison.InvariantCulture) &&
path.Equals (cookie.Path, StringComparison.InvariantCulture) && _path.Equals (cookie.Path, StringComparison.InvariantCulture) &&
domain.Equals (cookie.Domain, StringComparison.InvariantCultureIgnoreCase) && _domain.Equals (cookie.Domain, StringComparison.InvariantCultureIgnoreCase) &&
version == cookie.Version; _version == cookie.Version;
} }
/// <summary> /// <summary>
/// Serves as a hash function for a <see cref="Cookie"/> object. /// Serves as a hash function for a <see cref="Cookie"/> object.
/// </summary> /// </summary>
/// <returns> /// <returns>
/// An <see cref="int"/> that contains a hash code for this instance. /// An <see cref="int"/> that represents the hash code for the current <see cref="Cookie"/>.
/// </returns> /// </returns>
public override int GetHashCode () public override int GetHashCode ()
{ {
return Hash ( return hash (
StringComparer.InvariantCultureIgnoreCase.GetHashCode (name), StringComparer.InvariantCultureIgnoreCase.GetHashCode (_name),
val.GetHashCode (), _value.GetHashCode (),
path.GetHashCode (), _path.GetHashCode (),
StringComparer.InvariantCultureIgnoreCase.GetHashCode (domain), StringComparer.InvariantCultureIgnoreCase.GetHashCode (_domain),
version); _version);
} }
/// <summary> /// <summary>
/// Returns a <see cref="string"/> that represents the current <see cref="Cookie"/>. /// Returns a <see cref="string"/> that represents the current <see cref="Cookie"/>.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// This method returns a <see cref="string"/> to use to send an HTTP Cookie to an origin server. /// This method returns a <see cref="string"/> to use to send an HTTP Cookie to
/// an origin server.
/// </remarks> /// </remarks>
/// <returns> /// <returns>
/// A <see cref="string"/> that represents the current <see cref="Cookie"/>. /// A <see cref="string"/> that represents the current <see cref="Cookie"/>.
@ -725,8 +803,8 @@ namespace WebSocketSharp.Net
public override string ToString () public override string ToString ()
{ {
// i.e., only used for clients // i.e., only used for clients
// see para 4.2.2 of RFC 2109 and para 3.3.4 of RFC 2965 // See para 4.2.2 of RFC 2109 and para 3.3.4 of RFC 2965
// see also bug #316017 // See also bug #316017
return ToRequestString (null); return ToRequestString (null);
} }