Beispiel #1
0
        private void CheckValidParsedValue(string input, int startIndex,
                                           NameValueWithParametersHeaderValue expectedResult, int expectedIndex)
        {
            HttpHeaderParser parser = GenericHeaderParser.MultipleValueNameValueWithParametersParser;
            object           result = null;

            Assert.True(parser.TryParseValue(input, null, ref startIndex, out result),
                        string.Format("TryParse returned false. Input: '{0}', Index: {1}", input, startIndex));
            Assert.Equal(expectedIndex, startIndex);
            Assert.Equal(result, expectedResult);
        }
Beispiel #2
0
        private void CheckValidParsedValue(string input, int startIndex, RangeConditionHeaderValue expectedResult,
                                           int expectedIndex)
        {
            HttpHeaderParser parser = GenericHeaderParser.RangeConditionParser;
            object           result = null;

            Assert.True(parser.TryParseValue(input, null, ref startIndex, out result),
                        string.Format("TryParse returned false. Input: '{0}'", input));
            Assert.Equal(expectedIndex, startIndex);
            Assert.Equal(expectedResult, result);
        }
        private void CheckValidParsedValue(string input, int startIndex, string expectedResult,
                                           int expectedIndex)
        {
            HttpHeaderParser parser = GenericHeaderParser.MailAddressParser;
            object           result = null;

            Assert.True(parser.TryParseValue(input, null, ref startIndex, out result),
                        string.Format("TryParse returned false: {0}", input));
            Assert.Equal(expectedIndex, startIndex);
            Assert.Equal(expectedResult, result);
        }
Beispiel #4
0
        public void Properties_ReadValues_MatchExpectation()
        {
            HttpHeaderParser parser = GenericHeaderParser.MultipleValueNameValueWithParametersParser;

            Assert.True(parser.SupportsMultipleValues);
            Assert.Null(parser.Comparer);

            parser = GenericHeaderParser.SingleValueNameValueWithParametersParser;
            Assert.False(parser.SupportsMultipleValues);
            Assert.Null(parser.Comparer);
        }
Beispiel #5
0
        private void CheckInvalidParsedValue(string input, int startIndex)
        {
            HttpHeaderParser parser = GenericHeaderParser.MultipleValueNameValueWithParametersParser;
            object           result = null;
            int newIndex            = startIndex;

            Assert.False(parser.TryParseValue(input, null, ref newIndex, out result),
                         string.Format("TryParse returned true. Input: '{0}', Index: {1}", input, startIndex));
            Assert.Null(result);
            Assert.Equal(startIndex, newIndex);
        }
Beispiel #6
0
        private void CheckInvalidParsedValue(string input, int startIndex)
        {
            HttpHeaderParser parser = GenericHeaderParser.ContentRangeParser;
            object           result = null;
            int newIndex            = startIndex;

            Assert.False(parser.TryParseValue(input, null, ref newIndex, out result),
                         string.Format("TryParse returned true. Input: '{0}'", input));
            Assert.Equal(null, result);
            Assert.Equal(startIndex, newIndex);
        }
        private void CheckInvalidParsedValue(string input, int startIndex)
        {
            HttpHeaderParser parser = GenericHeaderParser.MultipleValueStringWithQualityParser;
            object           result = null;
            int newIndex            = startIndex;

            Assert.False(parser.TryParseValue(input, null, ref newIndex, out result),
                         string.Format("TryParse returned true: {0}", input));
            Assert.Equal(null, result);
            Assert.Equal(startIndex, newIndex);
        }
        public void Parse_ValidValue_ReturnsNameValueWithParametersHeaderValue()
        {
            // This test verifies that Parse() correctly calls TryParse().
            HttpHeaderParser parser = GenericHeaderParser.MultipleValueNameValueWithParametersParser;
            int index = 2;

            NameValueWithParametersHeaderValue expected = new NameValueWithParametersHeaderValue("custom");

            expected.Parameters.Add(new NameValueHeaderValue("name", "value"));
            Assert.True(expected.Equals(parser.ParseValue("   custom ; name = value ", null, ref index)));
            Assert.Equal(25, index);
        }
        public void Parse()
        {
            var buffer = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\nSERVER: LOCALHOST\r\n\r\n");
            var slice  = new BufferSlice(buffer, 0, buffer.Length);
            var reader = new SliceStream(slice);


            var parser = new HttpHeaderParser();

            parser.HeaderParsed += (sender, args) => Console.WriteLine(args.Name + ": " + args.Value);
            parser.Parse(reader);
        }
 public override Response ParseNetworkResponse(NetworkResponse response)
 {
     Java.Lang.String parsed;
     try
     {
         parsed = new Java.Lang.String(response.Data, HttpHeaderParser.ParseCharset(response.Headers));
     }
     catch (Java.IO.UnsupportedEncodingException)
     {
         parsed = new Java.Lang.String(response.Data);
     }
     return(Response.Success(parsed.ToString(), HttpHeaderParser.ParseCacheHeaders(response)));
 }
        private Response DoParse(NetworkResponse response)
        {
            byte[] data = response.Data;
            BitmapFactory.Options decodeOption = new BitmapFactory.Options();
            Bitmap bitmap = null;

            if (mMaxWidth == 0 && mMaxHeight == 0)
            {
                decodeOption.InPreferredConfig = mDecodeConfig;
                bitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length, decodeOption);
            }
            else
            {
                decodeOption.InJustDecodeBounds = true;
                BitmapFactory.DecodeByteArray(data, 0, data.Length, decodeOption);
                int actualWidth  = decodeOption.OutWidth;
                int actualHeight = decodeOption.OutHeight;

                int desiredWidth  = GetResizedDimension(mMaxWidth, mMaxHeight, actualWidth, actualHeight, mScaleType);
                int desiredHeight = GetResizedDimension(mMaxHeight, mMaxWidth, actualHeight, actualWidth, mScaleType);

                decodeOption.InJustDecodeBounds = false;
                decodeOption.InSampleSize       = FindBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
                Bitmap tempBitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length, decodeOption);

                if (tempBitmap != null && (tempBitmap.Width > desiredWidth || tempBitmap.Height > desiredHeight))
                {
                    bitmap = Bitmap.CreateScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
                    tempBitmap.Recycle();
                }
                else
                {
                    bitmap = tempBitmap;
                }
            }

            if (bitmap == null)
            {
                return(Response.Error(new ParseError(response)));
            }
            else
            {
                return(Response.Success(bitmap, HttpHeaderParser.ParseCacheHeaders(response)));
            }
        }
        public void ParseAuthorizationAllowsQuotedValues()
        {
            var headerValues = new Dictionary <string, string>
            {
                { "key", "value" },
                { "other", "otherValue" },
                { "more-stuff", "omg-value" }
            };

            var headerValue = $"Digest { String.Join(", ", headerValues.Select(pair => $@"{ pair.Key }=""{ pair.Value }""")) }";
            var parser      = new HttpHeaderParser();
            var result      = parser.ParseAuthorization(headerValue);

            result.ContainsKey(HttpHeaderParser.DefaultAuthorizationHeaderName).Should().BeTrue("because the header name should have been used");

            foreach (var pair in headerValues)
            {
                result.ContainsKey(pair.Key).Should().BeTrue("because {0} was one of the header values", pair.Key);
                result[pair.Key].Should().Be(pair.Value, "because the value for {0} should have been populated", pair.Key);
            }
        }
        private void CheckInvalidParsedValue(string input, int startIndex, bool supportMultipleValues)
        {
            HttpHeaderParser parser = null;

            if (supportMultipleValues)
            {
                parser = GenericHeaderParser.MultipleValueAuthenticationParser;
            }
            else
            {
                parser = GenericHeaderParser.SingleValueAuthenticationParser;
            }

            object result   = null;
            int    newIndex = startIndex;

            Assert.False(parser.TryParseValue(input, null, ref newIndex, out result),
                         string.Format("TryParse returned true. Input: '{0}'", input));
            Assert.Null(result);
            Assert.Equal(startIndex, newIndex);
        }
        private void CheckValidParsedValue(string input, int startIndex, AuthenticationHeaderValue expectedResult,
                                           int expectedIndex, bool supportMultipleValues)
        {
            HttpHeaderParser parser = null;

            if (supportMultipleValues)
            {
                parser = GenericHeaderParser.MultipleValueAuthenticationParser;
            }
            else
            {
                parser = GenericHeaderParser.SingleValueAuthenticationParser;
            }

            object result = null;

            Assert.True(parser.TryParseValue(input, null, ref startIndex, out result),
                        string.Format("TryParse returned false. Input: '{0}'", input));
            Assert.Equal(expectedIndex, startIndex);
            Assert.Equal(result, expectedResult);
        }
        public void ParseAuthorizationSupportsValueDelimiters(string delimiter)
        {
            var headerValues = new Dictionary <string, string>
            {
                { "key", "value" },
                { "other", @"""otherValue""" },
                { "more-stuff", @"""omg-value" },
                { "yetanother", @"omg-value""" },
            };

            var headerValue = $"Digest { String.Join(delimiter, headerValues.Select(pair => $@"{ pair.Key }={ pair.Value }")) }";
            var parser      = new HttpHeaderParser();
            var result      = parser.ParseAuthorization(headerValue);

            result.ContainsKey(HttpHeaderParser.DefaultAuthorizationHeaderName).Should().BeTrue("because the header name should have been used");

            foreach (var pair in headerValues)
            {
                result.ContainsKey(pair.Key).Should().BeTrue("because {0} was one of the header values", pair.Key);
                result[pair.Key].Should().Be(pair.Value.Replace(@"""", String.Empty), "because the value for {0} should have been populated", pair.Key);
            }
        }
        private void CheckInvalidParsedValue(string input, int startIndex, bool supportsMultipleValues)
        {
            HttpHeaderParser parser = null;

            if (supportsMultipleValues)
            {
                parser = GenericHeaderParser.MultipleValueEntityTagParser;
            }
            else
            {
                parser = GenericHeaderParser.SingleValueEntityTagParser;
            }

            object result   = null;
            int    newIndex = startIndex;

            Assert.False(parser.TryParseValue(input, null, ref newIndex, out result),
                         string.Format("TryParse returned true. Input: '{0}', AllowMultipleValues/Any: {1}", input,
                                       supportsMultipleValues));
            Assert.Equal(null, result);
            Assert.Equal(startIndex, newIndex);
        }
        private void CheckValidParsedValue(string input, int startIndex, EntityTagHeaderValue expectedResult,
                                           int expectedIndex, bool supportsMultipleValues)
        {
            HttpHeaderParser parser = null;

            if (supportsMultipleValues)
            {
                parser = GenericHeaderParser.MultipleValueEntityTagParser;
            }
            else
            {
                parser = GenericHeaderParser.SingleValueEntityTagParser;
            }

            object result = null;

            Assert.True(parser.TryParseValue(input, null, ref startIndex, out result),
                        string.Format("TryParse returned false. Input: '{0}', AllowMultipleValues/Any: {1}", input,
                                      supportsMultipleValues));
            Assert.Equal(expectedIndex, startIndex);
            Assert.Equal(result, expectedResult);
        }
Beispiel #18
0
        public void TestValidResponse()
        {
            var header = "HTTP/1.1 200 OK\r\n" +
                         "Date: Mon, 27 Jul 2009 12:28:53 GMT\r\n" +
                         "Server: Apache\r\n" +
                         "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\r\n" +
                         "ETag: \"34aa387-d-1568eb00\"\r\n" +
                         "Accept-Ranges: bytes\r\n" +
                         "Content-Length: 0\r\n" +
                         "Vary: Accept-Encoding\r\n" +
                         "Content-Type: text/plain\r\n\r\n";

            var parser = new HttpHeaderParser();
            var stream = new ByteArray(ASCIIEncoding.ASCII.GetBytes(header));

            parser.Parse(stream, true);
            Assert.Equal("Mon, 27 Jul 2009 12:28:53 GMT", parser.GetHeader("Date"));
            Assert.Equal("Apache", parser.GetHeader("Server"));
            Assert.Equal("\"34aa387-d-1568eb00\"", parser.GetHeader("ETag"));

            var data = parser.Create(stream, EmptyData.Instance);
        }
Beispiel #19
0
        // adapted from Header serialization code in Http2Connection.cs
        private static Memory <byte> HPackEncode(HttpHeaders headers)
        {
            var buffer = new ArrayBuffer(4);

            FillAvailableSpaceWithOnes(buffer);

            foreach (KeyValuePair <HeaderDescriptor, string[]> header in headers.GetHeaderDescriptorsAndValues())
            {
                KnownHeader knownHeader = header.Key.KnownHeader;
                if (knownHeader != null)
                {
                    // For all other known headers, send them via their pre-encoded name and the associated value.
                    WriteBytes(knownHeader.Http2EncodedName);
                    string separator = null;
                    if (header.Value.Length > 1)
                    {
                        HttpHeaderParser parser = header.Key.Parser;
                        if (parser != null && parser.SupportsMultipleValues)
                        {
                            separator = parser.Separator;
                        }
                        else
                        {
                            separator = HttpHeaderParser.DefaultSeparator;
                        }
                    }

                    WriteLiteralHeaderValues(header.Value, separator);
                }
                else
                {
                    // The header is not known: fall back to just encoding the header name and value(s).
                    WriteLiteralHeader(header.Key.Name, header.Value);
                }
            }

            return(buffer.ActiveMemory);

            void WriteBytes(ReadOnlySpan <byte> bytes)
            {
                if (bytes.Length > buffer.AvailableLength)
                {
                    buffer.EnsureAvailableSpace(bytes.Length);
                    FillAvailableSpaceWithOnes(buffer);
                }

                bytes.CopyTo(buffer.AvailableSpan);
                buffer.Commit(bytes.Length);
            }

            void WriteLiteralHeaderValues(string[] values, string separator)
            {
                int bytesWritten;

                while (!HPackEncoder.EncodeStringLiterals(values, separator, buffer.AvailableSpan, out bytesWritten))
                {
                    buffer.EnsureAvailableSpace(buffer.AvailableLength + 1);
                    FillAvailableSpaceWithOnes(buffer);
                }

                buffer.Commit(bytesWritten);
            }

            void WriteLiteralHeader(string name, string[] values)
            {
                int bytesWritten;

                while (!HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingNewName(name, values, HttpHeaderParser.DefaultSeparator, buffer.AvailableSpan, out bytesWritten))
                {
                    buffer.EnsureAvailableSpace(buffer.AvailableLength + 1);
                    FillAvailableSpaceWithOnes(buffer);
                }

                buffer.Commit(bytesWritten);
            }

            // force issues related to buffer not being zeroed out
            void FillAvailableSpaceWithOnes(ArrayBuffer buffer) => buffer.AvailableSpan.Fill(0xff);
        }
Beispiel #20
0
        // adapted from Header serialization code in Http2Connection.cs
        private static Memory <byte> HPackEncode(HttpHeaders headers, Encoding?valueEncoding)
        {
            var buffer = new ArrayBuffer(4);

            FillAvailableSpaceWithOnes(buffer);
            string[] headerValues = Array.Empty <string>();

            foreach (HeaderEntry header in headers.GetEntries())
            {
                int headerValuesCount = HttpHeaders.GetStoreValuesIntoStringArray(header.Key, header.Value, ref headerValues);
                Assert.InRange(headerValuesCount, 0, int.MaxValue);
                ReadOnlySpan <string> headerValuesSpan = headerValues.AsSpan(0, headerValuesCount);

                KnownHeader knownHeader = header.Key.KnownHeader;
                if (knownHeader != null)
                {
                    // For all other known headers, send them via their pre-encoded name and the associated value.
                    WriteBytes(knownHeader.Http2EncodedName);
                    string separator = null;
                    if (headerValuesSpan.Length > 1)
                    {
                        HttpHeaderParser parser = header.Key.Parser;
                        if (parser != null && parser.SupportsMultipleValues)
                        {
                            separator = parser.Separator;
                        }
                        else
                        {
                            separator = HttpHeaderParser.DefaultSeparator;
                        }
                    }

                    WriteLiteralHeaderValues(headerValuesSpan, separator);
                }
                else
                {
                    // The header is not known: fall back to just encoding the header name and value(s).
                    WriteLiteralHeader(header.Key.Name, headerValuesSpan);
                }
            }

            return(buffer.ActiveMemory);

            void WriteBytes(ReadOnlySpan <byte> bytes)
            {
                if (bytes.Length > buffer.AvailableLength)
                {
                    buffer.EnsureAvailableSpace(bytes.Length);
                    FillAvailableSpaceWithOnes(buffer);
                }

                bytes.CopyTo(buffer.AvailableSpan);
                buffer.Commit(bytes.Length);
            }

            void WriteLiteralHeaderValues(ReadOnlySpan <string> values, string separator)
            {
                int bytesWritten;

                while (!HPackEncoder.EncodeStringLiterals(values, separator, valueEncoding, buffer.AvailableSpan, out bytesWritten))
                {
                    buffer.EnsureAvailableSpace(buffer.AvailableLength + 1);
                    FillAvailableSpaceWithOnes(buffer);
                }

                buffer.Commit(bytesWritten);
            }

            void WriteLiteralHeader(string name, ReadOnlySpan <string> values)
            {
                int bytesWritten;

                while (!HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingNewName(name, values, HttpHeaderParser.DefaultSeparator, valueEncoding, buffer.AvailableSpan, out bytesWritten))
                {
                    buffer.EnsureAvailableSpace(buffer.AvailableLength + 1);
                    FillAvailableSpaceWithOnes(buffer);
                }

                buffer.Commit(bytesWritten);
            }

            // force issues related to buffer not being zeroed out
            void FillAvailableSpaceWithOnes(ArrayBuffer buffer) => buffer.AvailableSpan.Fill(0xff);
        }
Beispiel #21
0
        public void TestParseStartLine(string line, bool isRequest)
        {
            var builder = HttpHeaderParser.ParseStartLine(line + "\r\n");

            Assert.Equal(isRequest, builder.IsRequest);
        }