Exemplo n.º 1
0
        public async Task ReadNextPair_ReturnsNullOnEmptyStream(bool bufferRequest)
        {
            var body = MakeStream(bufferRequest, "");

            var reader = new FormReader(body);

            Assert.Null(await ReadPair(reader));
        }
Exemplo n.º 2
0
        public async Task ReadSmallFormAsyncStream()
        {
            var bytes  = Encoding.UTF8.GetBytes("foo=bar&baz=boo");
            var stream = new MemoryStream(bytes);

            for (var i = 0; i < 1000; i++)
            {
                var formReader = new FormReader(stream);
                await formReader.ReadFormAsync();

                stream.Position = 0;
            }
        }
Exemplo n.º 3
0
        public async Task ReadNextPair_ReadsAllPairs(bool bufferRequest)
        {
            var body = MakeStream(bufferRequest, "foo=&baz=2");

            var reader = new FormReader(body);

            var pair = (KeyValuePair <string, string>) await ReadPair(reader);

            Assert.Equal("foo", pair.Key);
            Assert.Equal("", pair.Value);

            pair = (KeyValuePair <string, string>) await ReadPair(reader);

            Assert.Equal("baz", pair.Key);
            Assert.Equal("2", pair.Value);

            Assert.Null(await ReadPair(reader));
        }
Exemplo n.º 4
0
 protected override async Task <KeyValuePair <string, string>?> ReadPair(FormReader reader)
 {
     return(await reader.ReadNextPairAsync());
 }
Exemplo n.º 5
0
 protected override async Task <Dictionary <string, StringValues> > ReadFormAsync(FormReader reader)
 {
     return(await reader.ReadFormAsync());
 }
Exemplo n.º 6
0
 protected virtual Task <KeyValuePair <string, string>?> ReadPair(FormReader reader)
 {
     return(Task.FromResult(reader.ReadNextPair()));
 }
Exemplo n.º 7
0
 protected virtual Task <Dictionary <string, StringValues> > ReadFormAsync(FormReader reader)
 {
     return(Task.FromResult(reader.ReadForm()));
 }
Exemplo n.º 8
0
        private async Task<IFormCollection> InnerReadFormAsync(CancellationToken cancellationToken)
        {
            if (!HasFormContentType)
            {
                throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType);
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (_options.BufferBody)
            {
                _request.EnableRewind(_options.MemoryBufferThreshold, _options.BufferBodyLengthLimit);
            }

            FormCollection formFields = null;
            FormFileCollection files = null;

            // Some of these code paths use StreamReader which does not support cancellation tokens.
            using (cancellationToken.Register((state) => ((HttpContext)state).Abort(), _request.HttpContext))
            {
                var contentType = ContentType;
                // Check the content-type
                if (HasApplicationFormContentType(contentType))
                {
                    var encoding = FilterEncoding(contentType.Encoding);
                    using (var formReader = new FormReader(_request.Body, encoding)
                    {
                        ValueCountLimit = _options.ValueCountLimit,
                        KeyLengthLimit = _options.KeyLengthLimit,
                        ValueLengthLimit = _options.ValueLengthLimit,
                    })
                    {
                        formFields = new FormCollection(await formReader.ReadFormAsync(cancellationToken));
                    }
                }
                else if (HasMultipartFormContentType(contentType))
                {
                    var formAccumulator = new KeyValueAccumulator();

                    var boundary = GetBoundary(contentType, _options.MultipartBoundaryLengthLimit);
                    var multipartReader = new MultipartReader(boundary, _request.Body)
                    {
                        HeadersCountLimit = _options.MultipartHeadersCountLimit,
                        HeadersLengthLimit = _options.MultipartHeadersLengthLimit,
                        BodyLengthLimit = _options.MultipartBodyLengthLimit,
                    };
                    var section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    while (section != null)
                    {
                        ContentDispositionHeaderValue contentDisposition;
                        ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
                        if (HasFileContentDisposition(contentDisposition))
                        {
                            // Enable buffering for the file if not already done for the full body
                            section.EnableRewind(_request.HttpContext.Response.RegisterForDispose,
                                _options.MemoryBufferThreshold, _options.MultipartBodyLengthLimit);
                            // Find the end
                            await section.Body.DrainAsync(cancellationToken);

                            var name = HeaderUtilities.RemoveQuotes(contentDisposition.Name) ?? string.Empty;
                            var fileName = HeaderUtilities.RemoveQuotes(contentDisposition.FileName) ?? string.Empty;

                            FormFile file;
                            if (section.BaseStreamOffset.HasValue)
                            {
                                // Relative reference to buffered request body
                                file = new FormFile(_request.Body, section.BaseStreamOffset.Value, section.Body.Length, name, fileName);
                            }
                            else
                            {
                                // Individually buffered file body
                                file = new FormFile(section.Body, 0, section.Body.Length, name, fileName);
                            }
                            file.Headers = new HeaderDictionary(section.Headers);

                            if (files == null)
                            {
                                files = new FormFileCollection();
                            }
                            if (files.Count >= _options.ValueCountLimit)
                            {
                                throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
                            }
                            files.Add(file);
                        }
                        else if (HasFormDataContentDisposition(contentDisposition))
                        {
                            // Content-Disposition: form-data; name="key"
                            //
                            // value

                            // Do not limit the key name length here because the mulipart headers length limit is already in effect.
                            var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            MediaTypeHeaderValue mediaType;
                            MediaTypeHeaderValue.TryParse(section.ContentType, out mediaType);
                            var encoding = FilterEncoding(mediaType?.Encoding);
                            using (var reader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                            {
                                // The value length limit is enforced by MultipartBodyLengthLimit
                                var value = await reader.ReadToEndAsync();
                                formAccumulator.Append(key, value);
                                if (formAccumulator.ValueCount > _options.ValueCountLimit)
                                {
                                    throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded.");
                                }
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + section.ContentDisposition);
                        }

                        section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    }

                    if (formAccumulator.HasValues)
                    {
                        formFields = new FormCollection(formAccumulator.GetResults(), files);
                    }
                }
            }

            // Rewind so later readers don't have to.
            if (_request.Body.CanSeek)
            {
                _request.Body.Seek(0, SeekOrigin.Begin);
            }

            if (formFields != null)
            {
                Form = formFields;
            }
            else if (files != null)
            {
                Form = new FormCollection(null, files);
            }
            else
            {
                Form = FormCollection.Empty;
            }

            return Form;
        }