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));
        }
 /// <exception cref="Apache.Http.Auth.MalformedChallengeException"></exception>
 protected internal override void ParseChallenge(CharArrayBuffer buffer, int beginIndex
                                                 , int endIndex)
 {
     this.challenge = buffer.SubstringTrimmed(beginIndex, endIndex);
     if (this.challenge.Length == 0)
     {
         if (this.state == NTLMScheme.State.Uninitiated)
         {
             this.state = NTLMScheme.State.ChallengeReceived;
         }
         else
         {
             this.state = NTLMScheme.State.Failed;
         }
     }
     else
     {
         if (this.state.CompareTo(NTLMScheme.State.MsgType1Generated) < 0)
         {
             this.state = NTLMScheme.State.Failed;
             throw new MalformedChallengeException("Out of sequence NTLM response message");
         }
         else
         {
             if (this.state == NTLMScheme.State.MsgType1Generated)
             {
                 this.state = NTLMScheme.State.MsgType2Recevied;
             }
         }
     }
 }
        /// <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));
        }
Exemple #4
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);
        }
Exemple #6
0
 /// <summary>Creates an instance of this class.</summary>
 /// <remarks>Creates an instance of this class.</remarks>
 /// <param name="buffer">the session input buffer.</param>
 /// <param name="lineParser">the line parser.</param>
 /// <param name="requestFactory">
 /// the factory to use to create
 /// <see cref="Org.Apache.Http.IHttpRequest">Org.Apache.Http.IHttpRequest</see>
 /// s.
 /// </param>
 /// <param name="params">HTTP parameters.</param>		[System.ObsoleteAttribute(@"(4.3) useDefaultHttpRequestParser(Org.Apache.Http.IO.SessionInputBuffer, Org.Apache.Http.Message.LineParser, Org.Apache.Http.HttpRequestFactory, Org.Apache.Http.Config.MessageConstraints)")]
 public DefaultHttpRequestParser(SessionInputBuffer buffer, LineParser lineParser,
                                 HttpRequestFactory requestFactory, HttpParams @params) : base(buffer, lineParser
                                                                                               , @params)
 {
     this.requestFactory = Args.NotNull(requestFactory, "Request factory");
     this.lineBuf        = new CharArrayBuffer(128);
 }
Exemple #7
0
 /// <summary>Creates an instance of AbstractMessageWriter.</summary>
 /// <remarks>Creates an instance of AbstractMessageWriter.</remarks>
 /// <param name="buffer">the session output buffer.</param>
 /// <param name="formatter">
 /// the line formatter If <code>null</code>
 /// <see cref="Org.Apache.Http.Message.BasicLineFormatter.Instance">Org.Apache.Http.Message.BasicLineFormatter.Instance
 ///     </see>
 /// will be used.
 /// </param>
 /// <since>4.3</since>
 public AbstractMessageWriter(SessionOutputBuffer buffer, LineFormatter formatter)
     : base()
 {
     this.sessionBuffer = Args.NotNull(buffer, "Session input buffer");
     this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatter.Instance;
     this.lineBuf       = new CharArrayBuffer(128);
 }
Exemple #8
0
 private void ParseNextElement()
 {
     // loop while there are headers left to parse
     while (this.headerIt.HasNext() || this.cursor != null)
     {
         if (this.cursor == null || this.cursor.AtEnd())
         {
             // get next header value
             BufferHeaderValue();
         }
         // Anything buffered?
         if (this.cursor != null)
         {
             // loop while there is data in the buffer
             while (!this.cursor.AtEnd())
             {
                 HeaderElement e = this.parser.ParseHeaderElement(this.buffer, this.cursor);
                 if (!(e.GetName().Length == 0 && e.GetValue() == null))
                 {
                     // Found something
                     this.currentElement = e;
                     return;
                 }
             }
             // if at the end of the buffer
             if (this.cursor.AtEnd())
             {
                 // discard it
                 this.cursor = null;
                 this.buffer = null;
             }
         }
     }
 }
Exemple #9
0
        // non-javadoc, see interface HeaderValueFormatter
        public virtual CharArrayBuffer FormatParameters(CharArrayBuffer charBuffer, NameValuePair
                                                        [] nvps, bool quote)
        {
            Args.NotNull(nvps, "Header parameter array");
            int             len    = EstimateParametersLen(nvps);
            CharArrayBuffer buffer = charBuffer;

            if (buffer == null)
            {
                buffer = new CharArrayBuffer(len);
            }
            else
            {
                buffer.EnsureCapacity(len);
            }
            for (int i = 0; i < nvps.Length; i++)
            {
                if (i > 0)
                {
                    buffer.Append("; ");
                }
                FormatNameValuePair(buffer, nvps[i], quote);
            }
            return(buffer);
        }
Exemple #10
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>
 /// Writes characters from the specified char array followed by a line
 /// delimiter to this session buffer.
 /// </summary>
 /// <remarks>
 /// Writes characters from the specified char array followed by a line
 /// delimiter to this session buffer.
 /// <p>
 /// This method uses CR-LF as a line delimiter.
 /// </remarks>
 /// <param name="charbuffer">the buffer containing chars of the line.</param>
 /// <exception>
 /// IOException
 /// if an I/O error occurs.
 /// </exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void WriteLine(CharArrayBuffer charbuffer)
 {
     if (charbuffer == null)
     {
         return;
     }
     if (this.encoder == null)
     {
         int off       = 0;
         int remaining = charbuffer.Length();
         while (remaining > 0)
         {
             int chunk = this.buffer.Capacity() - this.buffer.Length();
             chunk = Math.Min(chunk, remaining);
             if (chunk > 0)
             {
                 this.buffer.Append(charbuffer, off, chunk);
             }
             if (this.buffer.IsFull())
             {
                 FlushBuffer();
             }
             off       += chunk;
             remaining -= chunk;
         }
     }
     else
     {
         CharBuffer cbuf = CharBuffer.Wrap(charbuffer.Buffer(), 0, charbuffer.Length());
         WriteEncoded(cbuf);
     }
     Write(Crlf);
 }
Exemple #12
0
        // non-javadoc, see interface HeaderValueFormatter
        public virtual CharArrayBuffer FormatHeaderElement(CharArrayBuffer charBuffer, HeaderElement
                                                           elem, bool quote)
        {
            Args.NotNull(elem, "Header element");
            int             len    = EstimateHeaderElementLen(elem);
            CharArrayBuffer buffer = charBuffer;

            if (buffer == null)
            {
                buffer = new CharArrayBuffer(len);
            }
            else
            {
                buffer.EnsureCapacity(len);
            }
            buffer.Append(elem.GetName());
            string value = elem.GetValue();

            if (value != null)
            {
                buffer.Append('=');
                DoFormatValue(buffer, value, quote);
            }
            int parcnt = elem.GetParameterCount();

            if (parcnt > 0)
            {
                for (int i = 0; i < parcnt; i++)
                {
                    buffer.Append("; ");
                    FormatNameValuePair(buffer, elem.GetParameter(i), quote);
                }
            }
            return(buffer);
        }
Exemple #13
0
        // non-javadoc, see interface HeaderValueFormatter
        public virtual CharArrayBuffer FormatElements(CharArrayBuffer charBuffer, HeaderElement
                                                      [] elems, bool quote)
        {
            Args.NotNull(elems, "Header element array");
            int             len    = EstimateElementsLen(elems);
            CharArrayBuffer buffer = charBuffer;

            if (buffer == null)
            {
                buffer = new CharArrayBuffer(len);
            }
            else
            {
                buffer.EnsureCapacity(len);
            }
            for (int i = 0; i < elems.Length; i++)
            {
                if (i > 0)
                {
                    buffer.Append(", ");
                }
                FormatHeaderElement(buffer, elems[i], quote);
            }
            return(buffer);
        }
Exemple #14
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('"');
            }
        }
Exemple #15
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));
        }
 /// <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()));
         }
     }
 }
Exemple #17
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);
        }
 /// <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("\"");
         }
     }
 }
Exemple #19
0
 /// <summary>Wraps session input stream and reads chunk coded input.</summary>
 /// <remarks>Wraps session input stream and reads chunk coded input.</remarks>
 /// <param name="in">The session input buffer</param>
 public ChunkedInputStream(SessionInputBuffer @in) : base()
 {
     this.@in    = Args.NotNull(@in, "Session input buffer");
     this.pos    = 0;
     this.buffer = new CharArrayBuffer(16);
     this.state  = ChunkLen;
 }
Exemple #20
0
 public DefaultHttpResponseParser(SessionInputBuffer buffer, LineParser parser, HttpResponseFactory
                                  responseFactory, HttpParams @params) : base(buffer, parser, @params)
 {
     Args.NotNull(responseFactory, "Response factory");
     this.responseFactory = responseFactory;
     this.lineBuf         = new CharArrayBuffer(128);
 }
Exemple #21
0
        // non-javadoc, see interface HeaderValueFormatter
        public virtual CharArrayBuffer FormatNameValuePair(CharArrayBuffer charBuffer, NameValuePair
                                                           nvp, bool quote)
        {
            Args.NotNull(nvp, "Name / value pair");
            int             len    = EstimateNameValuePairLen(nvp);
            CharArrayBuffer buffer = charBuffer;

            if (buffer == null)
            {
                buffer = new CharArrayBuffer(len);
            }
            else
            {
                buffer.EnsureCapacity(len);
            }
            buffer.Append(nvp.GetName());
            string value = nvp.GetValue();

            if (value != null)
            {
                buffer.Append('=');
                DoFormatValue(buffer, value, quote);
            }
            return(buffer);
        }
Exemple #22
0
 private void BufferHeaderValue()
 {
     this.cursor = null;
     this.buffer = null;
     while (this.headerIt.HasNext())
     {
         Header h = this.headerIt.NextHeader();
         if (h is FormattedHeader)
         {
             this.buffer = ((FormattedHeader)h).GetBuffer();
             this.cursor = new ParserCursor(0, this.buffer.Length());
             this.cursor.UpdatePos(((FormattedHeader)h).GetValuePos());
             break;
         }
         else
         {
             string value = h.GetValue();
             if (value != null)
             {
                 this.buffer = new CharArrayBuffer(value.Length);
                 this.buffer.Append(value);
                 this.cursor = new ParserCursor(0, this.buffer.Length());
                 break;
             }
         }
     }
 }
        /// <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));
                }
            }
        }
Exemple #24
0
 /// <summary>Creates new instance of DefaultHttpRequestParser.</summary>
 /// <remarks>Creates new instance of DefaultHttpRequestParser.</remarks>
 /// <param name="buffer">the session input buffer.</param>
 /// <param name="lineParser">
 /// the line parser. If <code>null</code>
 /// <see cref="Org.Apache.Http.Message.BasicLineParser.Instance">Org.Apache.Http.Message.BasicLineParser.Instance
 ///     </see>
 /// will be used.
 /// </param>
 /// <param name="requestFactory">
 /// the response factory. If <code>null</code>
 /// <see cref="Org.Apache.Http.Impl.DefaultHttpRequestFactory.Instance">Org.Apache.Http.Impl.DefaultHttpRequestFactory.Instance
 ///     </see>
 /// will be used.
 /// </param>
 /// <param name="constraints">
 /// the message constraints. If <code>null</code>
 /// <see cref="Org.Apache.Http.Config.MessageConstraints.Default">Org.Apache.Http.Config.MessageConstraints.Default
 ///     </see>
 /// will be used.
 /// </param>
 /// <since>4.3</since>
 public DefaultHttpRequestParser(SessionInputBuffer buffer, LineParser lineParser,
                                 HttpRequestFactory requestFactory, MessageConstraints constraints) : base(buffer
                                                                                                           , lineParser, constraints)
 {
     this.requestFactory = requestFactory != null ? requestFactory : DefaultHttpRequestFactory
                           .Instance;
     this.lineBuf = new CharArrayBuffer(128);
 }
        // non-javadoc, see interface LineParser
        /// <exception cref="Org.Apache.Http.ParseException"></exception>
        public virtual StatusLine ParseStatusLine(CharArrayBuffer buffer, ParserCursor cursor
                                                  )
        {
            Args.NotNull(buffer, "Char array buffer");
            Args.NotNull(cursor, "Parser cursor");
            int indexFrom = cursor.GetPos();
            int indexTo   = cursor.GetUpperBound();

            try
            {
                // handle the HTTP-Version
                ProtocolVersion ver = ParseProtocolVersion(buffer, cursor);
                // handle the Status-Code
                SkipWhitespace(buffer, cursor);
                int i     = cursor.GetPos();
                int blank = buffer.IndexOf(' ', i, indexTo);
                if (blank < 0)
                {
                    blank = indexTo;
                }
                int    statusCode;
                string s = buffer.SubstringTrimmed(i, blank);
                for (int j = 0; j < s.Length; j++)
                {
                    if (!char.IsDigit(s[j]))
                    {
                        throw new ParseException("Status line contains invalid status code: " + buffer.Substring
                                                     (indexFrom, indexTo));
                    }
                }
                try
                {
                    statusCode = System.Convert.ToInt32(s);
                }
                catch (FormatException)
                {
                    throw new ParseException("Status line contains invalid status code: " + buffer.Substring
                                                 (indexFrom, indexTo));
                }
                //handle the Reason-Phrase
                i = blank;
                string reasonPhrase;
                if (i < indexTo)
                {
                    reasonPhrase = buffer.SubstringTrimmed(i, indexTo);
                }
                else
                {
                    reasonPhrase = string.Empty;
                }
                return(CreateStatusLine(ver, statusCode, reasonPhrase));
            }
            catch (IndexOutOfRangeException)
            {
                throw new ParseException("Invalid status line: " + buffer.Substring(indexFrom, indexTo
                                                                                    ));
            }
        }
Exemple #26
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());
        }
        /// <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));
        }
        /// <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));
        }
        // non-javadoc, see interface LineFormatter
        public virtual CharArrayBuffer FormatRequestLine(CharArrayBuffer buffer, RequestLine
                                                         reqline)
        {
            Args.NotNull(reqline, "Request line");
            CharArrayBuffer result = InitBuffer(buffer);

            DoFormatRequestLine(result, reqline);
            return(result);
        }
        // non-javadoc, see interface LineFormatter
        public virtual CharArrayBuffer FormatStatusLine(CharArrayBuffer buffer, StatusLine
                                                        statline)
        {
            Args.NotNull(statline, "Status line");
            CharArrayBuffer result = InitBuffer(buffer);

            DoFormatStatusLine(result, statline);
            return(result);
        }
 internal static ReadOnlyCharArrayBuffer copy(CharArrayBuffer other, int markOfOther)
 {
     ReadOnlyCharArrayBuffer buf = new ReadOnlyCharArrayBuffer(other
             .capacity(), other.backingArray, other.offset);
     buf.limitJ = other.limit();
     buf.positionJ = other.position();
     buf.markJ = markOfOther;
     return buf;
 }