예제 #1
0
        /// <summary>
        /// Sets an HTTP <paramref name="cookie"/> to send with
        /// the WebSocket handshake request to the server.
        /// </summary>
        /// <param name="cookie">
        /// A <see cref="Cookie"/> that represents a cookie to send.
        /// </param>
        public void SetCookie(Cookie cookie)
        {
            string msg;
              if (!checkIfAvailable (true, false, true, false, false, true, out msg)) {
            _logger.Error (msg);
            error ("An error has occurred in setting a cookie.", null);

            return;
              }

              if (cookie == null) {
            _logger.Error ("'cookie' is null.");
            error ("An error has occurred in setting a cookie.", null);

            return;
              }

              lock (_forState) {
            if (!checkIfAvailable (true, false, false, true, out msg)) {
              _logger.Error (msg);
              error ("An error has occurred in setting a cookie.", null);

              return;
            }

            lock (_cookies.SyncRoot)
              _cookies.SetOrRemove (cookie);
              }
        }
예제 #2
0
    /// <summary>
    /// Sets an HTTP <paramref name="cookie"/> to send with
    /// the WebSocket connection request to the server.
    /// </summary>
    /// <param name="cookie">
    /// A <see cref="Cookie"/> that represents the cookie to send.
    /// </param>
    public void SetCookie (Cookie cookie)
    {
      lock (_forConn) {
        var msg = checkIfAvailable (true, false, true, false, false, true) ??
                  (cookie == null ? "'cookie' is null." : null);

        if (msg != null) {
          _logger.Error (msg);
          error ("An error has occurred in setting the cookie.", null);

          return;
        }

        lock (_cookies.SyncRoot)
          _cookies.SetOrRemove (cookie);
      }
    }
예제 #3
0
        internal void AddHeader(string header)
        {
            int colon = header.IndexOf(':');

            if (colon == -1 || colon == 0)
            {
                context.ErrorMessage = "Bad Request";
                context.ErrorStatus  = 400;
                return;
            }

            string name  = header.Substring(0, colon).Trim();
            string val   = header.Substring(colon + 1).Trim();
            string lower = name.ToLower(CultureInfo.InvariantCulture);

            headers.SetInternal(name, val);
            switch (lower)
            {
            case "accept-language":
                user_languages = val.Split(',');                          // yes, only split with a ','
                break;

            case "accept":
                accept_types = val.Split(',');                          // yes, only split with a ','
                break;

            case "content-length":
                try {
                    //TODO: max. content_length?
                    content_length = Int64.Parse(val.Trim());
                    if (content_length < 0)
                    {
                        context.ErrorMessage = "Invalid Content-Length.";
                    }
                    cl_set = true;
                } catch {
                    context.ErrorMessage = "Invalid Content-Length.";
                }

                break;

            case "referer":
                try {
                    referrer = new Uri(val);
                } catch {
                    referrer = new Uri("http://someone.is.screwing.with.the.headers.com/");
                }
                break;

            case "cookie":
                if (cookies == null)
                {
                    cookies = new CookieCollection();
                }

                string[] cookieStrings = val.Split(new char[] { ',', ';' });
                Cookie   current       = null;
                int      version       = 0;
                foreach (string cookieString in cookieStrings)
                {
                    string str = cookieString.Trim();
                    if (str.Length == 0)
                    {
                        continue;
                    }
                    if (str.StartsWith("$Version"))
                    {
                        version = Int32.Parse(Unquote(str.Substring(str.IndexOf('=') + 1)));
                    }
                    else if (str.StartsWith("$Path"))
                    {
                        if (current != null)
                        {
                            current.Path = str.Substring(str.IndexOf('=') + 1).Trim();
                        }
                    }
                    else if (str.StartsWith("$Domain"))
                    {
                        if (current != null)
                        {
                            current.Domain = str.Substring(str.IndexOf('=') + 1).Trim();
                        }
                    }
                    else if (str.StartsWith("$Port"))
                    {
                        if (current != null)
                        {
                            current.Port = str.Substring(str.IndexOf('=') + 1).Trim();
                        }
                    }
                    else
                    {
                        if (current != null)
                        {
                            cookies.Add(current);
                        }
                        current = new Cookie();
                        int idx = str.IndexOf('=');
                        if (idx > 0)
                        {
                            current.Name  = str.Substring(0, idx).Trim();
                            current.Value = str.Substring(idx + 1).Trim();
                        }
                        else
                        {
                            current.Name  = str.Trim();
                            current.Value = String.Empty;
                        }
                        current.Version = version;
                    }
                }
                if (current != null)
                {
                    cookies.Add(current);
                }
                break;
            }
        }
예제 #4
0
    internal void SetOrRemove (Cookie cookie)
    {
      var pos = searchCookie (cookie);
      if (pos == -1) {
        if (!cookie.Expired)
          _list.Add (cookie);

        return;
      }

      if (!cookie.Expired) {
        _list[pos] = cookie;
        return;
      }

      _list.RemoveAt (pos);
    }
예제 #5
0
    /// <summary>
    /// Copies the elements of the collection to the specified array of <see cref="Cookie"/>,
    /// starting at the specified <paramref name="index"/> in the <paramref name="array"/>.
    /// </summary>
    /// <param name="array">
    /// An array of <see cref="Cookie"/> that represents the destination of the elements
    /// copied from the collection.
    /// </param>
    /// <param name="index">
    /// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/>
    /// at which copying begins.
    /// </param>
    /// <exception cref="ArgumentNullException">
    /// <paramref name="array"/> is <see langword="null"/>.
    /// </exception>
    /// <exception cref="ArgumentOutOfRangeException">
    /// <paramref name="index"/> is less than zero.
    /// </exception>
    /// <exception cref="ArgumentException">
    /// The number of elements in the collection is greater than the available space from
    /// <paramref name="index"/> to the end of the destination <paramref name="array"/>.
    /// </exception>
    public void CopyTo (Cookie[] array, int index)
    {
      if (array == null)
        throw new ArgumentNullException ("array");

      if (index < 0)
        throw new ArgumentOutOfRangeException ("index", "Less than zero.");

      if (array.Length - index < _list.Count)
        throw new ArgumentException (
          "The number of elements in this collection is greater than the available space of the destination array.");

      _list.CopyTo (array, index);
    }
예제 #6
0
 private static int compareCookieWithinSorted (Cookie x, Cookie y)
 {
   var ret = 0;
   return (ret = x.Version - y.Version) != 0
          ? ret
          : (ret = x.Name.CompareTo (y.Name)) != 0
            ? ret
            : y.Path.Length - x.Path.Length;
 }
예제 #7
0
    private static CookieCollection parseResponse (string value)
    {
      var cookies = new CookieCollection ();

      Cookie cookie = null;
      var pairs = splitCookieHeaderValue (value);
      for (var i = 0; i < pairs.Length; i++) {
        var pair = pairs[i].Trim ();
        if (pair.Length == 0)
          continue;

        if (pair.StartsWith ("version", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Version = Int32.Parse (pair.GetValue ('=', true));
        }
        else if (pair.StartsWith ("expires", StringComparison.InvariantCultureIgnoreCase)) {
          var buff = new StringBuilder (pair.GetValue ('='), 32);
          if (i < pairs.Length - 1)
            buff.AppendFormat (", {0}", pairs[++i].Trim ());

          DateTime expires;
          if (!DateTime.TryParseExact (
            buff.ToString (),
            new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
            CultureInfo.CreateSpecificCulture ("en-US"),
            DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
            out expires))
            expires = DateTime.Now;

          if (cookie != null && cookie.Expires == DateTime.MinValue)
            cookie.Expires = expires.ToLocalTime ();
        }
        else if (pair.StartsWith ("max-age", StringComparison.InvariantCultureIgnoreCase)) {
          var max = Int32.Parse (pair.GetValue ('=', true));
          var expires = DateTime.Now.AddSeconds ((double) max);
          if (cookie != null)
            cookie.Expires = expires;
        }
        else if (pair.StartsWith ("path", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Path = pair.GetValue ('=');
        }
        else if (pair.StartsWith ("domain", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Domain = pair.GetValue ('=');
        }
        else if (pair.StartsWith ("port", StringComparison.InvariantCultureIgnoreCase)) {
          var port = pair.Equals ("port", StringComparison.InvariantCultureIgnoreCase)
                     ? "\"\""
                     : pair.GetValue ('=');

          if (cookie != null)
            cookie.Port = port;
        }
        else if (pair.StartsWith ("comment", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Comment = pair.GetValue ('=').UrlDecode ();
        }
        else if (pair.StartsWith ("commenturl", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.CommentUri = pair.GetValue ('=', true).ToUri ();
        }
        else if (pair.StartsWith ("discard", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Discard = true;
        }
        else if (pair.StartsWith ("secure", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Secure = true;
        }
        else if (pair.StartsWith ("httponly", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.HttpOnly = true;
        }
        else {
          if (cookie != null)
            cookies.Add (cookie);

          string name;
          string val = String.Empty;

          var pos = pair.IndexOf ('=');
          if (pos == -1) {
            name = pair;
          }
          else if (pos == pair.Length - 1) {
            name = pair.Substring (0, pos).TrimEnd (' ');
          }
          else {
            name = pair.Substring (0, pos).TrimEnd (' ');
            val = pair.Substring (pos + 1).TrimStart (' ');
          }

          cookie = new Cookie (name, val);
        }
      }

      if (cookie != null)
        cookies.Add (cookie);

      return cookies;
    }
예제 #8
0
        static CookieCollection ParseRequest(string value)
        {
            var cookies = new CookieCollection();

            Cookie cookie  = null;
            int    version = 0;

            string [] pairs = Split(value).ToArray();
            for (int i = 0; i < pairs.Length; i++)
            {
                string pair = pairs [i].Trim();
                if (pair.Length == 0)
                {
                    continue;
                }

                if (pair.StartsWith("$version", StringComparison.InvariantCultureIgnoreCase))
                {
                    version = Int32.Parse(pair.GetValueInternal("=").Trim('"'));
                }
                else if (pair.StartsWith("$path", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Path = pair.GetValueInternal("=");
                    }
                }
                else if (pair.StartsWith("$domain", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Domain = pair.GetValueInternal("=");
                    }
                }
                else if (pair.StartsWith("$port", StringComparison.InvariantCultureIgnoreCase))
                {
                    var port = pair.Equals("$port", StringComparison.InvariantCultureIgnoreCase)
                                                 ? "\"\""
                                                 : pair.GetValueInternal("=");

                    if (cookie != null)
                    {
                        cookie.Port = port;
                    }
                }
                else
                {
                    if (cookie != null)
                    {
                        cookies.Add(cookie);
                    }

                    string name;
                    string val = String.Empty;
                    int    pos = pair.IndexOf('=');
                    if (pos == -1)
                    {
                        name = pair;
                    }
                    else if (pos == pair.Length - 1)
                    {
                        name = pair.Substring(0, pos).TrimEnd(' ');
                    }
                    else
                    {
                        name = pair.Substring(0, pos).TrimEnd(' ');
                        val  = pair.Substring(pos + 1).TrimStart(' ');
                    }

                    cookie = new Cookie(name, val);
                    if (version != 0)
                    {
                        cookie.Version = version;
                    }
                }
            }

            if (cookie != null)
            {
                cookies.Add(cookie);
            }

            return(cookies);
        }
예제 #9
0
        static CookieCollection ParseResponse(string value)
        {
            var cookies = new CookieCollection();

            Cookie cookie = null;

            string [] pairs = Split(value).ToArray();
            for (int i = 0; i < pairs.Length; i++)
            {
                string pair = pairs [i].Trim();
                if (pair.Length == 0)
                {
                    continue;
                }

                if (pair.StartsWith("version", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Version = Int32.Parse(pair.GetValueInternal("=").Trim('"'));
                    }
                }
                else if (pair.StartsWith("expires", StringComparison.InvariantCultureIgnoreCase))
                {
                    var buffer = new StringBuilder(pair.GetValueInternal("="), 32);
                    if (i < pairs.Length - 1)
                    {
                        buffer.AppendFormat(", {0}", pairs [++i].Trim());
                    }

                    DateTime expires;
                    if (!DateTime.TryParseExact(buffer.ToString(),
                                                new string [] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
                                                CultureInfo.CreateSpecificCulture("en-US"),
                                                DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
                                                out expires))
                    {
                        expires = DateTime.Now;
                    }

                    if (cookie != null && cookie.Expires == DateTime.MinValue)
                    {
                        cookie.Expires = expires.ToLocalTime();
                    }
                }
                else if (pair.StartsWith("max-age", StringComparison.InvariantCultureIgnoreCase))
                {
                    int max     = Int32.Parse(pair.GetValueInternal("=").Trim('"'));
                    var expires = DateTime.Now.AddSeconds((double)max);
                    if (cookie != null)
                    {
                        cookie.Expires = expires;
                    }
                }
                else if (pair.StartsWith("path", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Path = pair.GetValueInternal("=");
                    }
                }
                else if (pair.StartsWith("domain", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Domain = pair.GetValueInternal("=");
                    }
                }
                else if (pair.StartsWith("port", StringComparison.InvariantCultureIgnoreCase))
                {
                    var port = pair.Equals("port", StringComparison.InvariantCultureIgnoreCase)
                                                 ? "\"\""
                                                 : pair.GetValueInternal("=");

                    if (cookie != null)
                    {
                        cookie.Port = port;
                    }
                }
                else if (pair.StartsWith("comment", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Comment = pair.GetValueInternal("=").UrlDecode();
                    }
                }
                else if (pair.StartsWith("commenturl", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.CommentUri = pair.GetValueInternal("=").Trim('"').ToUri();
                    }
                }
                else if (pair.StartsWith("discard", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Discard = true;
                    }
                }
                else if (pair.StartsWith("secure", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Secure = true;
                    }
                }
                else if (pair.StartsWith("httponly", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.HttpOnly = true;
                    }
                }
                else
                {
                    if (cookie != null)
                    {
                        cookies.Add(cookie);
                    }

                    string name;
                    string val = String.Empty;
                    int    pos = pair.IndexOf('=');
                    if (pos == -1)
                    {
                        name = pair;
                    }
                    else if (pos == pair.Length - 1)
                    {
                        name = pair.Substring(0, pos).TrimEnd(' ');
                    }
                    else
                    {
                        name = pair.Substring(0, pos).TrimEnd(' ');
                        val  = pair.Substring(pos + 1).TrimStart(' ');
                    }

                    cookie = new Cookie(name, val);
                }
            }

            if (cookie != null)
            {
                cookies.Add(cookie);
            }

            return(cookies);
        }
예제 #10
0
 /// <summary>
 /// Appends the specified cookie to the cookies sent with the response.
 /// </summary>
 /// <param name="cookie">
 /// A <see cref="Cookie"/> to append.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="cookie"/> is <see langword="null"/>.
 /// </exception>
 public void AppendCookie (Cookie cookie)
 {
   Cookies.Add (cookie);
 }
예제 #11
0
        internal void SendHeaders(bool closing, MemoryStream stream)
        {
            if (this._contentType != null)
            {
                if (this._contentEncoding != null && this._contentType.IndexOf("charset=", StringComparison.Ordinal) == -1)
                {
                    string webName = this._contentEncoding.WebName;
                    this._headers.SetInternal("Content-Type", this._contentType + "; charset=" + webName, true);
                }
                else
                {
                    this._headers.SetInternal("Content-Type", this._contentType, true);
                }
            }
            if (this._headers["Server"] == null)
            {
                this._headers.SetInternal("Server", "websocket-sharp/1.0", true);
            }
            CultureInfo invariantCulture = CultureInfo.InvariantCulture;

            if (this._headers["Date"] == null)
            {
                this._headers.SetInternal("Date", DateTime.UtcNow.ToString("r", invariantCulture), true);
            }
            if (!this._chunked)
            {
                if (!this._contentLengthSet && closing)
                {
                    this._contentLengthSet = true;
                    this._contentLength    = 0L;
                }
                if (this._contentLengthSet)
                {
                    this._headers.SetInternal("Content-Length", this._contentLength.ToString(invariantCulture), true);
                }
            }
            Version protocolVersion = this._context.Request.ProtocolVersion;

            if (!this._contentLengthSet && !this._chunked && protocolVersion >= HttpVersion.Version11)
            {
                this._chunked = true;
            }
            bool flag = this._statusCode == 400 || this._statusCode == 408 || this._statusCode == 411 || this._statusCode == 413 || this._statusCode == 414 || this._statusCode == 500 || this._statusCode == 503;

            if (!flag)
            {
                flag = !this._context.Request.KeepAlive;
            }
            if (!this._keepAlive || flag)
            {
                this._headers.SetInternal("Connection", "close", true);
                flag = true;
            }
            if (this._chunked)
            {
                this._headers.SetInternal("Transfer-Encoding", "chunked", true);
            }
            int reuses = this._context.Connection.Reuses;

            if (reuses >= 100)
            {
                this._forceCloseChunked = true;
                if (!flag)
                {
                    this._headers.SetInternal("Connection", "close", true);
                    flag = true;
                }
            }
            if (!flag)
            {
                this._headers.SetInternal("Keep-Alive", string.Format("timeout=15,max={0}", 100 - reuses), true);
                if (this._context.Request.ProtocolVersion <= HttpVersion.Version10)
                {
                    this._headers.SetInternal("Connection", "keep-alive", true);
                }
            }
            if (this._location != null)
            {
                this._headers.SetInternal("Location", this._location, true);
            }
            if (this._cookies != null)
            {
                IEnumerator enumerator = this._cookies.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        object obj    = enumerator.Current;
                        Cookie cookie = (Cookie)obj;
                        this._headers.SetInternal("Set-Cookie", cookie.ToResponseString(), true);
                    }
                }
                finally
                {
                    IDisposable disposable;
                    if ((disposable = (enumerator as IDisposable)) != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            Encoding     encoding     = this._contentEncoding ?? Encoding.Default;
            StreamWriter streamWriter = new StreamWriter(stream, encoding, 256);

            streamWriter.Write("HTTP/{0} {1} {2}\r\n", this._version, this._statusCode, this._statusDescription);
            string value = this._headers.ToStringMultiValue(true);

            streamWriter.Write(value);
            streamWriter.Flush();
            int num = (encoding.CodePage != 65001) ? encoding.GetPreamble().Length : 3;

            if (this._outputStream == null)
            {
                this._outputStream = this._context.Connection.GetResponseStream();
            }
            stream.Position  = (long)num;
            this.HeadersSent = true;
        }
예제 #12
0
        private static CookieCollection parseRequest(string value)
        {
            var cookies = new CookieCollection();

            Cookie cookie = null;
            var    ver    = 0;
            var    pairs  = splitCookieHeaderValue(value);

            for (var i = 0; i < pairs.Length; i++)
            {
                var pair = pairs[i].Trim();
                if (pair.Length == 0)
                {
                    continue;
                }

                if (pair.StartsWith("$version", StringComparison.InvariantCultureIgnoreCase))
                {
                    ver = Int32.Parse(pair.GetValue('=', true));
                }
                else if (pair.StartsWith("$path", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Path = pair.GetValue('=');
                    }
                }
                else if (pair.StartsWith("$domain", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Domain = pair.GetValue('=');
                    }
                }
                else if (pair.StartsWith("$port", StringComparison.InvariantCultureIgnoreCase))
                {
                    var port = pair.Equals("$port", StringComparison.InvariantCultureIgnoreCase)
                               ? "\"\""
                               : pair.GetValue('=');

                    if (cookie != null)
                    {
                        cookie.Port = port;
                    }
                }
                else
                {
                    if (cookie != null)
                    {
                        cookies.Add(cookie);
                    }

                    string name;
                    string val = String.Empty;

                    var pos = pair.IndexOf('=');
                    if (pos == -1)
                    {
                        name = pair;
                    }
                    else if (pos == pair.Length - 1)
                    {
                        name = pair.Substring(0, pos).TrimEnd(' ');
                    }
                    else
                    {
                        name = pair.Substring(0, pos).TrimEnd(' ');
                        val  = pair.Substring(pos + 1).TrimStart(' ');
                    }

                    cookie = new Cookie(name, val);
                    if (ver != 0)
                    {
                        cookie.Version = ver;
                    }
                }
            }

            if (cookie != null)
            {
                cookies.Add(cookie);
            }

            return(cookies);
        }
예제 #13
0
 private static int compareCookieWithinSort(Cookie x, Cookie y)
 {
     return((x.Name.Length + x.Value.Length) - (y.Name.Length + y.Value.Length));
 }
예제 #14
0
        public override bool Equals(object comparand)
        {
            Cookie cookie = comparand as Cookie;

            return(cookie != null && _name.Equals(cookie.Name, StringComparison.InvariantCultureIgnoreCase) && _value.Equals(cookie.Value, StringComparison.InvariantCulture) && _path.Equals(cookie.Path, StringComparison.InvariantCulture) && _domain.Equals(cookie.Domain, StringComparison.InvariantCultureIgnoreCase) && _version == cookie.Version);
        }
예제 #15
0
        /// <summary>
        /// Sets a <see cref="Cookie"/> used in the WebSocket opening handshake.
        /// </summary>
        /// <param name="cookie">
        /// A <see cref="Cookie"/> that contains an HTTP Cookie to set.
        /// </param>
        public void SetCookie(Cookie cookie)
        {
            if (isOpened(true))
            return;

              if (cookie == null)
              {
            onError("'cookie' must not be null.");
            return;
              }

              lock (_cookies.SyncRoot)
              {
            _cookies.SetOrRemove(cookie);
              }
        }
 /// <summary>
 /// Appends the specified <paramref name="cookie"/> to the cookies sent with the response.
 /// </summary>
 /// <param name="cookie">
 /// A <see cref="Cookie"/> to append.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="cookie"/> is <see langword="null"/>.
 /// </exception>
 public void AppendCookie (Cookie cookie)
 {
   Cookies.Add (cookie);
 }
예제 #17
0
 private static int compareCookieWithinSort (Cookie x, Cookie y)
 {
   return (x.Name.Length + x.Value.Length) - (y.Name.Length + y.Value.Length);
 }
예제 #18
0
        /// <summary>
        /// Sets a <see cref="Cookie"/> used in the WebSocket opening handshake.
        /// </summary>
        /// <param name="cookie">
        /// A <see cref="Cookie"/> that contains an HTTP Cookie to set.
        /// </param>
        public void SetCookie(Cookie cookie)
        {
            var msg = _readyState == WsState.OPEN
              ? "The WebSocket connection has been established already."
              : cookie.IsNull()
                ? "'cookie' must not be null."
                : String.Empty;

              if (!msg.IsEmpty())
              {
            onError(msg);
            return;
              }

              lock (_cookies.SyncRoot)
              {
            _cookies.SetOrRemove(cookie);
              }
        }
예제 #19
0
    private static CookieCollection parseRequest (string value)
    {
      var cookies = new CookieCollection ();

      Cookie cookie = null;
      var ver = 0;
      var pairs = splitCookieHeaderValue (value);
      for (var i = 0; i < pairs.Length; i++) {
        var pair = pairs[i].Trim ();
        if (pair.Length == 0)
          continue;

        if (pair.StartsWith ("$version", StringComparison.InvariantCultureIgnoreCase)) {
          ver = Int32.Parse (pair.GetValue ('=', true));
        }
        else if (pair.StartsWith ("$path", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Path = pair.GetValue ('=');
        }
        else if (pair.StartsWith ("$domain", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Domain = pair.GetValue ('=');
        }
        else if (pair.StartsWith ("$port", StringComparison.InvariantCultureIgnoreCase)) {
          var port = pair.Equals ("$port", StringComparison.InvariantCultureIgnoreCase)
                     ? "\"\""
                     : pair.GetValue ('=');

          if (cookie != null)
            cookie.Port = port;
        }
        else {
          if (cookie != null)
            cookies.Add (cookie);

          string name;
          string val = String.Empty;

          var pos = pair.IndexOf ('=');
          if (pos == -1) {
            name = pair;
          }
          else if (pos == pair.Length - 1) {
            name = pair.Substring (0, pos).TrimEnd (' ');
          }
          else {
            name = pair.Substring (0, pos).TrimEnd (' ');
            val = pair.Substring (pos + 1).TrimStart (' ');
          }

          cookie = new Cookie (name, val);
          if (ver != 0)
            cookie.Version = ver;
        }
      }

      if (cookie != null)
        cookies.Add (cookie);

      return cookies;
    }
 /// <summary>
 /// Appends the specified <paramref name="cookie"/> to the cookies sent with the response.
 /// </summary>
 /// <param name="cookie">
 /// A <see cref="Cookie"/> to append.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="cookie"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// The response has already been sent.
 /// </exception>
 /// <exception cref="ObjectDisposedException">
 /// This object is closed.
 /// </exception>
 public void AppendCookie(Cookie cookie)
 {
     checkDisposedOrHeadersSent ();
       Cookies.Add (cookie);
 }
예제 #21
0
    private int searchCookie (Cookie cookie)
    {
      var name = cookie.Name;
      var path = cookie.Path;
      var domain = cookie.Domain;
      var ver = cookie.Version;

      for (var i = _list.Count - 1; i >= 0; i--) {
        var c = _list[i];
        if (c.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase) &&
            c.Path.Equals (path, StringComparison.InvariantCulture) &&
            c.Domain.Equals (domain, StringComparison.InvariantCultureIgnoreCase) &&
            c.Version == ver)
          return i;
      }

      return -1;
    }
        /// <summary>
        /// Adds or updates a <paramref name="cookie"/> in the cookies sent with the response.
        /// </summary>
        /// <param name="cookie">
        /// A <see cref="Cookie"/> to set.
        /// </param>
        /// <exception cref="ArgumentException">
        /// <paramref name="cookie"/> already exists in the cookies and couldn't be replaced.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="cookie"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The response has already been sent.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// This object is closed.
        /// </exception>
        public void SetCookie(Cookie cookie)
        {
            checkDisposedOrHeadersSent ();
              if (cookie == null)
            throw new ArgumentNullException ("cookie");

              if (!canAddOrUpdate (cookie))
            throw new ArgumentException ("Cannot be replaced.", "cookie");

              Cookies.Add (cookie);
        }
예제 #23
0
    /// <summary>
    /// Adds the specified <paramref name="cookie"/> to the collection.
    /// </summary>
    /// <param name="cookie">
    /// A <see cref="Cookie"/> to add.
    /// </param>
    /// <exception cref="ArgumentNullException">
    /// <paramref name="cookie"/> is <see langword="null"/>.
    /// </exception>
    public void Add (Cookie cookie) 
    {
      if (cookie == null)
        throw new ArgumentNullException ("cookie");

      var pos = searchCookie (cookie);
      if (pos == -1) {
        _list.Add (cookie);
        return;
      }

      _list[pos] = cookie;
    }
        private bool canAddOrUpdate(Cookie cookie)
        {
            if (_cookies == null || _cookies.Count == 0)
            return true;

              var found = findCookie (cookie).ToList ();
              if (found.Count == 0)
            return true;

              var ver = cookie.Version;
              foreach (var c in found)
            if (c.Version == ver)
              return true;

              return false;
        }
예제 #25
0
        /// <summary>
        /// Sets an HTTP <paramref name="cookie"/> to send with the WebSocket connection request
        /// to the server.
        /// </summary>
        /// <param name="cookie">
        /// A <see cref="Cookie"/> that represents the cookie to send.
        /// </param>
        public void SetCookie(Cookie cookie)
        {
            lock (_forConn) {
            var msg = checkIfAvailable ("SetCookie", false, false) ??
                  (cookie == null ? "'cookie' must not be null." : null);

            if (msg != null) {
              _logger.Error (msg);
              error (msg);

              return;
            }

            lock (_cookies.SyncRoot) {
              _cookies.SetOrRemove (cookie);
            }
              }
        }
 private IEnumerable<Cookie> findCookie(Cookie cookie)
 {
     var name = cookie.Name;
       var domain = cookie.Domain;
       var path = cookie.Path;
       if (_cookies != null)
     foreach (Cookie c in _cookies)
       if (c.Name.Equals (name, StringComparison.OrdinalIgnoreCase) &&
       c.Domain.Equals (domain, StringComparison.OrdinalIgnoreCase) &&
       c.Path.Equals (path, StringComparison.Ordinal))
     yield return c;
 }
예제 #27
0
        /// <summary>
        /// Sets a <see cref="Cookie"/> used in the WebSocket opening handshake.
        /// </summary>
        /// <param name="cookie">
        /// A <see cref="Cookie"/> that contains an HTTP Cookie to set.
        /// </param>
        public void SetCookie(Cookie cookie)
        {
            var msg = IsOpened
              ? "A WebSocket connection has already been established."
              : cookie == null
                ? "'cookie' must not be null."
                : null;

              if (msg != null)
              {
            _logger.Error (msg);
            error (msg);

            return;
              }

              lock (_cookies.SyncRoot)
              {
            _cookies.SetOrRemove (cookie);
              }
        }
예제 #28
0
    /// <summary>
    /// Sets a <see cref="Cookie"/> used in the WebSocket connection request.
    /// </summary>
    /// <param name="cookie">
    /// A <see cref="Cookie"/> that represents an HTTP Cookie to set.
    /// </param>
    public void SetCookie (Cookie cookie)
    {
      lock (_forConnect) {
        var msg = !_client
                ? "SetCookie isn't available as a server."
                : IsOpened
                  ? "A WebSocket connection has already been established."
                  : cookie == null
                    ? "'cookie' must not be null."
                    : null;

        if (msg != null) {
          _logger.Error (msg);
          error (msg);

          return;
        }

        lock (_cookies.SyncRoot) {
          _cookies.SetOrRemove (cookie);
        }
      }
    }