예제 #1
0
        public static Header Authenticate(Credentials credentials, string charset, bool proxy
                                          )
        {
            Args.NotNull(credentials, "Credentials");
            Args.NotNull(charset, "charset");
            StringBuilder tmp = new StringBuilder();

            tmp.Append(credentials.GetUserPrincipal().GetName());
            tmp.Append(":");
            tmp.Append((credentials.GetPassword() == null) ? "null" : credentials.GetPassword
                           ());
            byte[] base64password = Base64.EncodeBase64(EncodingUtils.GetBytes(tmp.ToString()
                                                                               , charset), false);
            CharArrayBuffer buffer = new CharArrayBuffer(32);

            if (proxy)
            {
                buffer.Append(AUTH.ProxyAuthResp);
            }
            else
            {
                buffer.Append(AUTH.WwwAuthResp);
            }
            buffer.Append(": Basic ");
            buffer.Append(base64password, 0, base64password.Length);
            return(new BufferedHeader(buffer));
        }
예제 #2
0
        /// <summary>Actually formats the value of a name-value pair.</summary>
        /// <remarks>
        /// Actually formats the value of a name-value pair.
        /// This does not include a leading = character.
        /// Called from
        /// <see cref="FormatNameValuePair(Org.Apache.Http.NameValuePair, bool, HeaderValueFormatter)
        ///     ">formatNameValuePair</see>
        /// .
        /// </remarks>
        /// <param name="buffer">the buffer to append to, never <code>null</code></param>
        /// <param name="value">the value to append, never <code>null</code></param>
        /// <param name="quote">
        /// <code>true</code> to always format with quotes,
        /// <code>false</code> to use quotes only when necessary
        /// </param>
        protected internal virtual void DoFormatValue(CharArrayBuffer buffer, string value
                                                      , bool quote)
        {
            bool quoteFlag = quote;

            if (!quoteFlag)
            {
                for (int i = 0; (i < value.Length) && !quoteFlag; i++)
                {
                    quoteFlag = IsSeparator(value[i]);
                }
            }
            if (quoteFlag)
            {
                buffer.Append('"');
            }
            for (int i_1 = 0; i_1 < value.Length; i_1++)
            {
                char ch = value[i_1];
                if (IsUnsafe(ch))
                {
                    buffer.Append('\\');
                }
                buffer.Append(ch);
            }
            if (quoteFlag)
            {
                buffer.Append('"');
            }
        }
예제 #3
0
 /// <summary>Gets a header representing all of the header values with the given name.
 ///     </summary>
 /// <remarks>
 /// Gets a header representing all of the header values with the given name.
 /// If more that one header with the given name exists the values will be
 /// combined with a "," as per RFC 2616.
 /// <p>Header name comparison is case insensitive.
 /// </remarks>
 /// <param name="name">the name of the header(s) to get</param>
 /// <returns>
 /// a header with a condensed value or <code>null</code> if no
 /// headers by the given name are present
 /// </returns>
 public virtual Header GetCondensedHeader(string name)
 {
     Header[] hdrs = GetHeaders(name);
     if (hdrs.Length == 0)
     {
         return(null);
     }
     else
     {
         if (hdrs.Length == 1)
         {
             return(hdrs[0]);
         }
         else
         {
             CharArrayBuffer valueBuffer = new CharArrayBuffer(128);
             valueBuffer.Append(hdrs[0].GetValue());
             for (int i = 1; i < hdrs.Length; i++)
             {
                 valueBuffer.Append(", ");
                 valueBuffer.Append(hdrs[i].GetValue());
             }
             return(new BasicHeader(name.ToLower(Sharpen.Extensions.GetEnglishCulture()), valueBuffer
                                    .ToString()));
         }
     }
 }
예제 #4
0
        private IList <Header> DoFormatOneHeader(IList <Apache.Http.Cookie.Cookie> cookies)
        {
            int version = int.MaxValue;

            // Pick the lowest common denominator
            foreach (Apache.Http.Cookie.Cookie cookie in cookies)
            {
                if (cookie.GetVersion() < version)
                {
                    version = cookie.GetVersion();
                }
            }
            CharArrayBuffer buffer = new CharArrayBuffer(40 * cookies.Count);

            buffer.Append(SM.Cookie);
            buffer.Append(": ");
            buffer.Append("$Version=");
            buffer.Append(Sharpen.Extensions.ToString(version));
            foreach (Apache.Http.Cookie.Cookie cooky in cookies)
            {
                buffer.Append("; ");
                Apache.Http.Cookie.Cookie cookie_1 = cooky;
                FormatCookieAsVer(buffer, cookie_1, version);
            }
            IList <Header> headers = new AList <Header>(1);

            headers.AddItem(new BufferedHeader(buffer));
            return(headers);
        }
예제 #5
0
 /// <summary>Adds valid Port attribute value, e.g.</summary>
 /// <remarks>Adds valid Port attribute value, e.g. "8000,8001,8002"</remarks>
 protected internal override void FormatCookieAsVer(CharArrayBuffer buffer, Apache.Http.Cookie.Cookie
                                                    cookie, int version)
 {
     base.FormatCookieAsVer(buffer, cookie, version);
     // format port attribute
     if (cookie is ClientCookie)
     {
         // Test if the port attribute as set by the origin server is not blank
         string s = ((ClientCookie)cookie).GetAttribute(ClientCookie.PortAttr);
         if (s != null)
         {
             buffer.Append("; $Port");
             buffer.Append("=\"");
             if (s.Trim().Length > 0)
             {
                 int[] ports = cookie.GetPorts();
                 if (ports != null)
                 {
                     int len = ports.Length;
                     for (int i = 0; i < len; i++)
                     {
                         if (i > 0)
                         {
                             buffer.Append(",");
                         }
                         buffer.Append(Sharpen.Extensions.ToString(ports[i]));
                     }
                 }
             }
             buffer.Append("\"");
         }
     }
 }
예제 #6
0
        /// <summary>
        /// Produces basic authorization header for the given set of
        /// <see cref="Apache.Http.Auth.Credentials">Apache.Http.Auth.Credentials</see>
        /// .
        /// </summary>
        /// <param name="credentials">The set of credentials to be used for authentication</param>
        /// <param name="request">The request being authenticated</param>
        /// <exception cref="Apache.Http.Auth.InvalidCredentialsException">
        /// if authentication
        /// credentials are not valid or not applicable for this authentication scheme
        /// </exception>
        /// <exception cref="Apache.Http.Auth.AuthenticationException">
        /// if authorization string cannot
        /// be generated due to an authentication failure
        /// </exception>
        /// <returns>a basic authorization string</returns>
        public override Header Authenticate(Credentials credentials, IHttpRequest request
                                            , HttpContext context)
        {
            Args.NotNull(credentials, "Credentials");
            Args.NotNull(request, "HTTP request");
            StringBuilder tmp = new StringBuilder();

            tmp.Append(credentials.GetUserPrincipal().GetName());
            tmp.Append(":");
            tmp.Append((credentials.GetPassword() == null) ? "null" : credentials.GetPassword
                           ());
            byte[] base64password = base64codec.Encode(EncodingUtils.GetBytes(tmp.ToString(),
                                                                              GetCredentialsCharset(request)));
            CharArrayBuffer buffer = new CharArrayBuffer(32);

            if (IsProxy())
            {
                buffer.Append(AUTH.ProxyAuthResp);
            }
            else
            {
                buffer.Append(AUTH.WwwAuthResp);
            }
            buffer.Append(": Basic ");
            buffer.Append(base64password, 0, base64password.Length);
            return(new BufferedHeader(buffer));
        }
예제 #7
0
        /// <exception cref="Apache.Http.Auth.AuthenticationException"></exception>
        public override Header Authenticate(Credentials credentials, IHttpRequest request
                                            )
        {
            NTCredentials ntcredentials = null;

            try
            {
                ntcredentials = (NTCredentials)credentials;
            }
            catch (InvalidCastException)
            {
                throw new InvalidCredentialsException("Credentials cannot be used for NTLM authentication: "
                                                      + credentials.GetType().FullName);
            }
            string response = null;

            if (this.state == NTLMScheme.State.Failed)
            {
                throw new AuthenticationException("NTLM authentication failed");
            }
            else
            {
                if (this.state == NTLMScheme.State.ChallengeReceived)
                {
                    response = this.engine.GenerateType1Msg(ntcredentials.GetDomain(), ntcredentials.
                                                            GetWorkstation());
                    this.state = NTLMScheme.State.MsgType1Generated;
                }
                else
                {
                    if (this.state == NTLMScheme.State.MsgType2Recevied)
                    {
                        response = this.engine.GenerateType3Msg(ntcredentials.GetUserName(), ntcredentials
                                                                .GetPassword(), ntcredentials.GetDomain(), ntcredentials.GetWorkstation(), this.
                                                                challenge);
                        this.state = NTLMScheme.State.MsgType3Generated;
                    }
                    else
                    {
                        throw new AuthenticationException("Unexpected state: " + this.state);
                    }
                }
            }
            CharArrayBuffer buffer = new CharArrayBuffer(32);

            if (IsProxy())
            {
                buffer.Append(AUTH.ProxyAuthResp);
            }
            else
            {
                buffer.Append(AUTH.WwwAuthResp);
            }
            buffer.Append(": NTLM ");
            buffer.Append(response);
            return(new BufferedHeader(buffer));
        }
예제 #8
0
        public override Header GetVersionHeader()
        {
            CharArrayBuffer buffer = new CharArrayBuffer(40);

            buffer.Append(SM.Cookie2);
            buffer.Append(": ");
            buffer.Append("$Version=");
            buffer.Append(Sharpen.Extensions.ToString(GetVersion()));
            return(new BufferedHeader(buffer));
        }
예제 #9
0
        /// <summary>Parses the Set-Cookie value into an array of <tt>Cookie</tt>s.</summary>
        /// <remarks>
        /// Parses the Set-Cookie value into an array of <tt>Cookie</tt>s.
        /// <p>Syntax of the Set-Cookie HTTP Response Header:</p>
        /// <p>This is the format a CGI script would use to add to
        /// the HTTP headers a new piece of data which is to be stored by
        /// the client for later retrieval.</p>
        /// <PRE>
        /// Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
        /// </PRE>
        /// <p>Please note that the Netscape draft specification does not fully conform to the HTTP
        /// header format. Comma character if present in <code>Set-Cookie</code> will not be treated
        /// as a header element separator</p>
        /// </remarks>
        /// <seealso><a href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">
        /// *  The Cookie Spec.</a></seealso>
        /// <param name="header">the <tt>Set-Cookie</tt> received from the server</param>
        /// <returns>an array of <tt>Cookie</tt>s parsed from the Set-Cookie value</returns>
        /// <exception cref="Apache.Http.Cookie.MalformedCookieException">if an exception occurs during parsing
        ///     </exception>
        public override IList <Apache.Http.Cookie.Cookie> Parse(Header header, CookieOrigin
                                                                origin)
        {
            Args.NotNull(header, "Header");
            Args.NotNull(origin, "Cookie origin");
            if (!Sharpen.Runtime.EqualsIgnoreCase(header.GetName(), SM.SetCookie))
            {
                throw new MalformedCookieException("Unrecognized cookie header '" + header.ToString
                                                       () + "'");
            }
            NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.Default;
            CharArrayBuffer           buffer;
            ParserCursor cursor;

            if (header is FormattedHeader)
            {
                buffer = ((FormattedHeader)header).GetBuffer();
                cursor = new ParserCursor(((FormattedHeader)header).GetValuePos(), buffer.Length(
                                              ));
            }
            else
            {
                string s = header.GetValue();
                if (s == null)
                {
                    throw new MalformedCookieException("Header value is null");
                }
                buffer = new CharArrayBuffer(s.Length);
                buffer.Append(s);
                cursor = new ParserCursor(0, buffer.Length());
            }
            return(Parse(new HeaderElement[] { parser.ParseHeader(buffer, cursor) }, origin));
        }
예제 #10
0
        /// <summary>
        /// Returns a list of
        /// <see cref="Apache.Http.NameValuePair">NameValuePairs</see>
        /// as parsed from the given string using the given character
        /// encoding.
        /// </summary>
        /// <param name="s">text to parse.</param>
        /// <param name="charset">Encoding to use when decoding the parameters.</param>
        /// <param name="parameterSeparator">
        /// The characters used to separate parameters, by convention,
        /// <code>'&'</code>
        /// and
        /// <code>';'</code>
        /// .
        /// </param>
        /// <returns>
        /// a list of
        /// <see cref="Apache.Http.NameValuePair">Apache.Http.NameValuePair</see>
        /// as built from the URI's query portion.
        /// </returns>
        /// <since>4.3</since>
        public static IList <NameValuePair> Parse(string s, Encoding charset, params char[]
                                                  parameterSeparator)
        {
            if (s == null)
            {
                return(Sharpen.Collections.EmptyList());
            }
            BasicHeaderValueParser parser = BasicHeaderValueParser.Instance;
            CharArrayBuffer        buffer = new CharArrayBuffer(s.Length);

            buffer.Append(s);
            ParserCursor          cursor = new ParserCursor(0, buffer.Length());
            IList <NameValuePair> list   = new AList <NameValuePair>();

            while (!cursor.AtEnd())
            {
                NameValuePair nvp = parser.ParseNameValuePair(buffer, cursor, parameterSeparator);
                if (nvp.GetName().Length > 0)
                {
                    list.AddItem(new BasicNameValuePair(DecodeFormFields(nvp.GetName(), charset), DecodeFormFields
                                                            (nvp.GetValue(), charset)));
                }
            }
            return(list);
        }
        /// <summary>
        /// Reads a complete line of characters up to a line delimiter from this
        /// session buffer.
        /// </summary>
        /// <remarks>
        /// Reads a complete line of characters up to a line delimiter from this
        /// session buffer. The line delimiter itself is discarded. If no char is
        /// available because the end of the stream has been reached,
        /// <code>null</code> is returned. This method blocks until input data is
        /// available, end of file is detected, or an exception is thrown.
        /// <p>
        /// This method treats a lone LF as a valid line delimiters in addition
        /// to CR-LF required by the HTTP specification.
        /// </remarks>
        /// <returns>HTTP line as a string</returns>
        /// <exception>
        /// IOException
        /// if an I/O error occurs.
        /// </exception>
        /// <exception cref="System.IO.IOException"></exception>
        private int LineFromLineBuffer(CharArrayBuffer charbuffer)
        {
            // discard LF if found
            int len = this.linebuffer.Length();

            if (len > 0)
            {
                if (this.linebuffer.ByteAt(len - 1) == HTTP.Lf)
                {
                    len--;
                }
                // discard CR if found
                if (len > 0)
                {
                    if (this.linebuffer.ByteAt(len - 1) == HTTP.Cr)
                    {
                        len--;
                    }
                }
            }
            if (this.decoder == null)
            {
                charbuffer.Append(this.linebuffer, 0, len);
            }
            else
            {
                ByteBuffer bbuf = ByteBuffer.Wrap(this.linebuffer.Buffer(), 0, len);
                len = AppendDecoded(charbuffer, bbuf);
            }
            this.linebuffer.Clear();
            return(len);
        }
        /// <summary>Actually formats a request line.</summary>
        /// <remarks>
        /// Actually formats a request line.
        /// Called from
        /// <see cref="FormatRequestLine(Org.Apache.Http.RequestLine, LineFormatter)">FormatRequestLine(Org.Apache.Http.RequestLine, LineFormatter)
        ///     </see>
        /// .
        /// </remarks>
        /// <param name="buffer">
        /// the empty buffer into which to format,
        /// never <code>null</code>
        /// </param>
        /// <param name="reqline">the request line to format, never <code>null</code></param>
        protected internal virtual void DoFormatRequestLine(CharArrayBuffer buffer, RequestLine
                                                            reqline)
        {
            string method = reqline.GetMethod();
            string uri    = reqline.GetUri();
            // room for "GET /index.html HTTP/1.1"
            int len = method.Length + 1 + uri.Length + 1 + EstimateProtocolVersionLen(reqline
                                                                                      .GetProtocolVersion());

            buffer.EnsureCapacity(len);
            buffer.Append(method);
            buffer.Append(' ');
            buffer.Append(uri);
            buffer.Append(' ');
            AppendProtocolVersion(buffer, reqline.GetProtocolVersion());
        }
예제 #13
0
        /// <exception cref="Apache.Http.Cookie.MalformedCookieException"></exception>
        public virtual IList <Apache.Http.Cookie.Cookie> Parse(Header header, CookieOrigin
                                                               origin)
        {
            Args.NotNull(header, "Header");
            Args.NotNull(origin, "Cookie origin");
            HeaderElement[] helems    = header.GetElements();
            bool            versioned = false;
            bool            netscape  = false;

            foreach (HeaderElement helem in helems)
            {
                if (helem.GetParameterByName("version") != null)
                {
                    versioned = true;
                }
                if (helem.GetParameterByName("expires") != null)
                {
                    netscape = true;
                }
            }
            if (netscape || !versioned)
            {
                // Need to parse the header again, because Netscape style cookies do not correctly
                // support multiple header elements (comma cannot be treated as an element separator)
                NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.Default;
                CharArrayBuffer           buffer;
                ParserCursor cursor;
                if (header is FormattedHeader)
                {
                    buffer = ((FormattedHeader)header).GetBuffer();
                    cursor = new ParserCursor(((FormattedHeader)header).GetValuePos(), buffer.Length(
                                                  ));
                }
                else
                {
                    string s = header.GetValue();
                    if (s == null)
                    {
                        throw new MalformedCookieException("Header value is null");
                    }
                    buffer = new CharArrayBuffer(s.Length);
                    buffer.Append(s);
                    cursor = new ParserCursor(0, buffer.Length());
                }
                helems = new HeaderElement[] { parser.ParseHeader(buffer, cursor) };
                return(GetCompat().Parse(helems, origin));
            }
            else
            {
                if (SM.SetCookie2.Equals(header.GetName()))
                {
                    return(GetStrict().Parse(helems, origin));
                }
                else
                {
                    return(GetObsoleteStrict().Parse(helems, origin));
                }
            }
        }
예제 #14
0
        /// <summary>Processes the given challenge token.</summary>
        /// <remarks>
        /// Processes the given challenge token. Some authentication schemes
        /// may involve multiple challenge-response exchanges. Such schemes must be able
        /// to maintain the state information when dealing with sequential challenges
        /// </remarks>
        /// <param name="header">the challenge header</param>
        /// <exception cref="Apache.Http.Auth.MalformedChallengeException">
        /// is thrown if the authentication challenge
        /// is malformed
        /// </exception>
        public virtual void ProcessChallenge(Header header)
        {
            Args.NotNull(header, "Header");
            string authheader = header.GetName();

            if (Sharpen.Runtime.EqualsIgnoreCase(authheader, AUTH.WwwAuth))
            {
                this.challengeState = ChallengeState.Target;
            }
            else
            {
                if (Sharpen.Runtime.EqualsIgnoreCase(authheader, AUTH.ProxyAuth))
                {
                    this.challengeState = ChallengeState.Proxy;
                }
                else
                {
                    throw new MalformedChallengeException("Unexpected header name: " + authheader);
                }
            }
            CharArrayBuffer buffer;
            int             pos;

            if (header is FormattedHeader)
            {
                buffer = ((FormattedHeader)header).GetBuffer();
                pos    = ((FormattedHeader)header).GetValuePos();
            }
            else
            {
                string s = header.GetValue();
                if (s == null)
                {
                    throw new MalformedChallengeException("Header value is null");
                }
                buffer = new CharArrayBuffer(s.Length);
                buffer.Append(s);
                pos = 0;
            }
            while (pos < buffer.Length() && HTTP.IsWhitespace(buffer.CharAt(pos)))
            {
                pos++;
            }
            int beginIndex = pos;

            while (pos < buffer.Length() && !HTTP.IsWhitespace(buffer.CharAt(pos)))
            {
                pos++;
            }
            int    endIndex = pos;
            string s_1      = buffer.Substring(beginIndex, endIndex);

            if (!Sharpen.Runtime.EqualsIgnoreCase(s_1, GetSchemeName()))
            {
                throw new MalformedChallengeException("Invalid scheme identifier: " + s_1);
            }
            ParseChallenge(buffer, pos, buffer.Length());
        }
예제 #15
0
        private IList <Header> DoFormatManyHeaders(IList <Apache.Http.Cookie.Cookie> cookies
                                                   )
        {
            IList <Header> headers = new AList <Header>(cookies.Count);

            foreach (Apache.Http.Cookie.Cookie cookie in cookies)
            {
                int             version = cookie.GetVersion();
                CharArrayBuffer buffer  = new CharArrayBuffer(40);
                buffer.Append("Cookie: ");
                buffer.Append("$Version=");
                buffer.Append(Sharpen.Extensions.ToString(version));
                buffer.Append("; ");
                FormatCookieAsVer(buffer, cookie, version);
                headers.AddItem(new BufferedHeader(buffer));
            }
            return(headers);
        }
예제 #16
0
        /// <exception cref="Org.Apache.Http.ParseException"></exception>
        public static Header ParseHeader(string value, LineParser parser)
        {
            Args.NotNull(value, "Value");
            CharArrayBuffer buffer = new CharArrayBuffer(value.Length);

            buffer.Append(value);
            return((parser != null ? parser : Org.Apache.Http.Message.BasicLineParser.Instance
                    ).ParseHeader(buffer));
        }
        // formatHeader
        /// <summary>Actually formats a header.</summary>
        /// <remarks>
        /// Actually formats a header.
        /// Called from
        /// <see cref="FormatHeader(Org.Apache.Http.Header, LineFormatter)">FormatHeader(Org.Apache.Http.Header, LineFormatter)
        ///     </see>
        /// .
        /// </remarks>
        /// <param name="buffer">
        /// the empty buffer into which to format,
        /// never <code>null</code>
        /// </param>
        /// <param name="header">the header to format, never <code>null</code></param>
        protected internal virtual void DoFormatHeader(CharArrayBuffer buffer, Header header
                                                       )
        {
            string name  = header.GetName();
            string value = header.GetValue();
            int    len   = name.Length + 2;

            if (value != null)
            {
                len += value.Length;
            }
            buffer.EnsureCapacity(len);
            buffer.Append(name);
            buffer.Append(": ");
            if (value != null)
            {
                buffer.Append(value);
            }
        }
예제 #18
0
        /// <exception cref="Org.Apache.Http.ParseException"></exception>
        public static StatusLine ParseStatusLine(string value, LineParser parser)
        {
            Args.NotNull(value, "Value");
            CharArrayBuffer buffer = new CharArrayBuffer(value.Length);

            buffer.Append(value);
            ParserCursor cursor = new ParserCursor(0, value.Length);

            return((parser != null ? parser : Org.Apache.Http.Message.BasicLineParser.Instance
                    ).ParseStatusLine(buffer, cursor));
        }
예제 #19
0
        /// <summary>
        /// Generates textual representation of this content type which can be used as the value
        /// of a <code>Content-Type</code> header.
        /// </summary>
        /// <remarks>
        /// Generates textual representation of this content type which can be used as the value
        /// of a <code>Content-Type</code> header.
        /// </remarks>
        public override string ToString()
        {
            CharArrayBuffer buf = new CharArrayBuffer(64);

            buf.Append(this.mimeType);
            if (this.@params != null)
            {
                buf.Append("; ");
                BasicHeaderValueFormatter.Instance.FormatParameters(buf, this.@params, false);
            }
            else
            {
                if (this.charset != null)
                {
                    buf.Append("; charset=");
                    buf.Append(this.charset.Name());
                }
            }
            return(buf.ToString());
        }
예제 #20
0
        /// <summary>Parses elements with the given parser.</summary>
        /// <remarks>Parses elements with the given parser.</remarks>
        /// <param name="value">the header value to parse</param>
        /// <param name="parser">the parser to use, or <code>null</code> for default</param>
        /// <returns>array holding the header elements, never <code>null</code></returns>
        /// <exception cref="Org.Apache.Http.ParseException"></exception>
        public static HeaderElement[] ParseElements(string value, HeaderValueParser parser
                                                    )
        {
            Args.NotNull(value, "Value");
            CharArrayBuffer buffer = new CharArrayBuffer(value.Length);

            buffer.Append(value);
            ParserCursor cursor = new ParserCursor(0, value.Length);

            return((parser != null ? parser : Org.Apache.Http.Message.BasicHeaderValueParser.
                    Instance).ParseElements(buffer, cursor));
        }
예제 #21
0
        public override IList <Header> FormatCookies(IList <Apache.Http.Cookie.Cookie> cookies
                                                     )
        {
            Args.NotEmpty(cookies, "List of cookies");
            CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.Count);

            buffer.Append(SM.Cookie);
            buffer.Append(": ");
            for (int i = 0; i < cookies.Count; i++)
            {
                Apache.Http.Cookie.Cookie cookie = cookies[i];
                if (i > 0)
                {
                    buffer.Append("; ");
                }
                buffer.Append(cookie.GetName());
                string s = cookie.GetValue();
                if (s != null)
                {
                    buffer.Append("=");
                    buffer.Append(s);
                }
            }
            IList <Header> headers = new AList <Header>(1);

            headers.AddItem(new BufferedHeader(buffer));
            return(headers);
        }
        /// <summary>Actually formats a status line.</summary>
        /// <remarks>
        /// Actually formats a status line.
        /// Called from
        /// <see cref="FormatStatusLine(Org.Apache.Http.StatusLine, LineFormatter)">FormatStatusLine(Org.Apache.Http.StatusLine, LineFormatter)
        ///     </see>
        /// .
        /// </remarks>
        /// <param name="buffer">
        /// the empty buffer into which to format,
        /// never <code>null</code>
        /// </param>
        /// <param name="statline">the status line to format, never <code>null</code></param>
        protected internal virtual void DoFormatStatusLine(CharArrayBuffer buffer, StatusLine
                                                           statline)
        {
            int len = EstimateProtocolVersionLen(statline.GetProtocolVersion()) + 1 + 3 + 1;
            // room for "HTTP/1.1 200 "
            string reason = statline.GetReasonPhrase();

            if (reason != null)
            {
                len += reason.Length;
            }
            buffer.EnsureCapacity(len);
            AppendProtocolVersion(buffer, statline.GetProtocolVersion());
            buffer.Append(' ');
            buffer.Append(Sharpen.Extensions.ToString(statline.GetStatusCode()));
            buffer.Append(' ');
            // keep whitespace even if reason phrase is empty
            if (reason != null)
            {
                buffer.Append(reason);
            }
        }
예제 #23
0
 /// <summary>
 /// Return a string suitable for sending in a <tt>"Cookie"</tt> header
 /// as defined in RFC 2109 for backward compatibility with cookie version 0
 /// </summary>
 /// <param name="buffer">The char array buffer to use for output</param>
 /// <param name="cookie">
 /// The
 /// <see cref="Apache.Http.Cookie.Cookie">Apache.Http.Cookie.Cookie</see>
 /// to be formatted as string
 /// </param>
 /// <param name="version">The version to use.</param>
 protected internal virtual void FormatCookieAsVer(CharArrayBuffer buffer, Apache.Http.Cookie.Cookie
                                                   cookie, int version)
 {
     FormatParamAsVer(buffer, cookie.GetName(), cookie.GetValue(), version);
     if (cookie.GetPath() != null)
     {
         if (cookie is ClientCookie && ((ClientCookie)cookie).ContainsAttribute(ClientCookie
                                                                                .PathAttr))
         {
             buffer.Append("; ");
             FormatParamAsVer(buffer, "$Path", cookie.GetPath(), version);
         }
     }
     if (cookie.GetDomain() != null)
     {
         if (cookie is ClientCookie && ((ClientCookie)cookie).ContainsAttribute(ClientCookie
                                                                                .DomainAttr))
         {
             buffer.Append("; ");
             FormatParamAsVer(buffer, "$Domain", cookie.GetDomain(), version);
         }
     }
 }
        /// <exception cref="System.IO.IOException"></exception>
        private int HandleDecodingResult(CoderResult result, CharArrayBuffer charbuffer,
                                         ByteBuffer bbuf)
        {
            if (result.IsError())
            {
                result.ThrowException();
            }
            this.cbuf.Flip();
            int len = this.cbuf.Remaining();

            while (this.cbuf.HasRemaining())
            {
                charbuffer.Append(this.cbuf.Get());
            }
            this.cbuf.Compact();
            return(len);
        }
예제 #25
0
        /// <summary>Parses textual representation of <code>Content-Type</code> value.</summary>
        /// <remarks>Parses textual representation of <code>Content-Type</code> value.</remarks>
        /// <param name="s">text</param>
        /// <returns>content type</returns>
        /// <exception cref="Org.Apache.Http.ParseException">
        /// if the given text does not represent a valid
        /// <code>Content-Type</code> value.
        /// </exception>
        /// <exception cref="Sharpen.UnsupportedCharsetException">
        /// Thrown when the named charset is not available in
        /// this instance of the Java virtual machine
        /// </exception>
        public static Org.Apache.Http.Entity.ContentType Parse(string s)
        {
            Args.NotNull(s, "Content type");
            CharArrayBuffer buf = new CharArrayBuffer(s.Length);

            buf.Append(s);
            ParserCursor cursor = new ParserCursor(0, s.Length);

            HeaderElement[] elements = BasicHeaderValueParser.Instance.ParseElements(buf, cursor
                                                                                     );
            if (elements.Length > 0)
            {
                return(Create(elements[0]));
            }
            else
            {
                throw new ParseException("Invalid content type: " + s);
            }
        }
        /// <exception cref="Apache.Http.Auth.MalformedChallengeException"></exception>
        public virtual IDictionary <string, Header> GetChallenges(HttpHost authhost, HttpResponse
                                                                  response, HttpContext context)
        {
            Args.NotNull(response, "HTTP response");
            Header[] headers = response.GetHeaders(this.headerName);
            IDictionary <string, Header> map = new Dictionary <string, Header>(headers.Length);

            foreach (Header header in headers)
            {
                CharArrayBuffer buffer;
                int             pos;
                if (header is FormattedHeader)
                {
                    buffer = ((FormattedHeader)header).GetBuffer();
                    pos    = ((FormattedHeader)header).GetValuePos();
                }
                else
                {
                    string s = header.GetValue();
                    if (s == null)
                    {
                        throw new MalformedChallengeException("Header value is null");
                    }
                    buffer = new CharArrayBuffer(s.Length);
                    buffer.Append(s);
                    pos = 0;
                }
                while (pos < buffer.Length() && HTTP.IsWhitespace(buffer.CharAt(pos)))
                {
                    pos++;
                }
                int beginIndex = pos;
                while (pos < buffer.Length() && !HTTP.IsWhitespace(buffer.CharAt(pos)))
                {
                    pos++;
                }
                int    endIndex = pos;
                string s_1      = buffer.Substring(beginIndex, endIndex);
                map.Put(s_1.ToLower(CultureInfo.InvariantCulture), header);
            }
            return(map);
        }
        /// <exception cref="System.IO.IOException"></exception>
        private int LineFromReadBuffer(CharArrayBuffer charbuffer, int position)
        {
            int pos = position;
            int off = this.bufferpos;
            int len;

            this.bufferpos = pos + 1;
            if (pos > off && this.buffer[pos - 1] == HTTP.Cr)
            {
                // skip CR if found
                pos--;
            }
            len = pos - off;
            if (this.decoder == null)
            {
                charbuffer.Append(this.buffer, off, len);
            }
            else
            {
                ByteBuffer bbuf = ByteBuffer.Wrap(this.buffer, off, len);
                len = AppendDecoded(charbuffer, bbuf);
            }
            return(len);
        }
예제 #28
0
 /// <summary>
 /// Return a name/value string suitable for sending in a <tt>"Cookie"</tt>
 /// header as defined in RFC 2109 for backward compatibility with cookie
 /// version 0
 /// </summary>
 /// <param name="buffer">The char array buffer to use for output</param>
 /// <param name="name">The cookie name</param>
 /// <param name="value">The cookie value</param>
 /// <param name="version">The cookie version</param>
 protected internal virtual void FormatParamAsVer(CharArrayBuffer buffer, string name
                                                  , string value, int version)
 {
     buffer.Append(name);
     buffer.Append("=");
     if (value != null)
     {
         if (version > 0)
         {
             buffer.Append('\"');
             buffer.Append(value);
             buffer.Append('\"');
         }
         else
         {
             buffer.Append(value);
         }
     }
 }
예제 #29
0
		public override IList<Header> FormatCookies(IList<Apache.Http.Cookie.Cookie> cookies
			)
		{
			Args.NotEmpty(cookies, "List of cookies");
			CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.Count);
			buffer.Append(SM.Cookie);
			buffer.Append(": ");
			for (int i = 0; i < cookies.Count; i++)
			{
				Apache.Http.Cookie.Cookie cookie = cookies[i];
				if (i > 0)
				{
					buffer.Append("; ");
				}
				string cookieName = cookie.GetName();
				string cookieValue = cookie.GetValue();
				if (cookie.GetVersion() > 0 && !IsQuoteEnclosed(cookieValue))
				{
					BasicHeaderValueFormatter.Instance.FormatHeaderElement(buffer, new BasicHeaderElement
						(cookieName, cookieValue), false);
				}
				else
				{
					// Netscape style cookies do not support quoted values
					buffer.Append(cookieName);
					buffer.Append("=");
					if (cookieValue != null)
					{
						buffer.Append(cookieValue);
					}
				}
			}
			IList<Header> headers = new AList<Header>(1);
			headers.AddItem(new BufferedHeader(buffer));
			return headers;
		}
예제 #30
0
        /// <exception cref="Apache.Http.Auth.AuthenticationException"></exception>
        public override Header Authenticate(Credentials credentials, IHttpRequest request
                                            , HttpContext context)
        {
            Args.NotNull(request, "HTTP request");
            switch (state)
            {
            case GGSSchemeBase.State.Uninitiated:
            {
                throw new AuthenticationException(GetSchemeName() + " authentication has not been initiated"
                                                  );
            }

            case GGSSchemeBase.State.Failed:
            {
                throw new AuthenticationException(GetSchemeName() + " authentication has failed");
            }

            case GGSSchemeBase.State.ChallengeReceived:
            {
                try
                {
                    HttpRoute route = (HttpRoute)context.GetAttribute(HttpClientContext.HttpRoute);
                    if (route == null)
                    {
                        throw new AuthenticationException("Connection route is not available");
                    }
                    HttpHost host;
                    if (IsProxy())
                    {
                        host = route.GetProxyHost();
                        if (host == null)
                        {
                            host = route.GetTargetHost();
                        }
                    }
                    else
                    {
                        host = route.GetTargetHost();
                    }
                    string authServer;
                    if (!this.stripPort && host.GetPort() > 0)
                    {
                        authServer = host.ToHostString();
                    }
                    else
                    {
                        authServer = host.GetHostName();
                    }
                    if (log.IsDebugEnabled())
                    {
                        log.Debug("init " + authServer);
                    }
                    token = GenerateToken(token, authServer);
                    state = GGSSchemeBase.State.TokenGenerated;
                }
                catch (GSSException gsse)
                {
                    state = GGSSchemeBase.State.Failed;
                    if (gsse.GetMajor() == GSSException.DefectiveCredential || gsse.GetMajor() == GSSException
                        .CredentialsExpired)
                    {
                        throw new InvalidCredentialsException(gsse.Message, gsse);
                    }
                    if (gsse.GetMajor() == GSSException.NoCred)
                    {
                        throw new InvalidCredentialsException(gsse.Message, gsse);
                    }
                    if (gsse.GetMajor() == GSSException.DefectiveToken || gsse.GetMajor() == GSSException
                        .DuplicateToken || gsse.GetMajor() == GSSException.OldToken)
                    {
                        throw new AuthenticationException(gsse.Message, gsse);
                    }
                    // other error
                    throw new AuthenticationException(gsse.Message);
                }
                goto case GGSSchemeBase.State.TokenGenerated;
            }

            case GGSSchemeBase.State.TokenGenerated:
            {
                string tokenstr = Sharpen.Runtime.GetStringForBytes(base64codec.Encode(token));
                if (log.IsDebugEnabled())
                {
                    log.Debug("Sending response '" + tokenstr + "' back to the auth server");
                }
                CharArrayBuffer buffer = new CharArrayBuffer(32);
                if (IsProxy())
                {
                    buffer.Append(AUTH.ProxyAuthResp);
                }
                else
                {
                    buffer.Append(AUTH.WwwAuthResp);
                }
                buffer.Append(": Negotiate ");
                buffer.Append(tokenstr);
                return(new BufferedHeader(buffer));
            }

            default:
            {
                throw new InvalidOperationException("Illegal state: " + state);
            }
            }
        }