Exemplo n.º 1
0
    public (Stream request, Stream response) Start()
    {
        _request.StartAcceptingReads(_context);
        _response.StartAcceptingWrites();

        return(_upgradeableRequest, _upgradeableResponse);
    }
Exemplo n.º 2
0
        public async Task LogsWhenStartsReadingRequestBody()
        {
            using (var input = new TestInput())
            {
                var mockLogger = new Mock <IKestrelTrace>();
                input.Http1Connection.ServiceContext.Log  = mockLogger.Object;
                input.Http1Connection.ConnectionIdFeature = "ConnectionId";
                input.Http1Connection.TraceIdentifier     = "RequestId";

                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderContentLength = "2"
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                // Add some input and consume it to ensure PumpAsync is running
                input.Add("a");
                Assert.Equal(1, await stream.ReadAsync(new byte[1], 0, 1));

                mockLogger.Verify(logger => logger.RequestBodyStart("ConnectionId", "RequestId"));

                input.Fin();

                input.Http1Connection.RequestBodyPipe.Reader.Complete();
                await body.StopAsync();
            }
        }
Exemplo n.º 3
0
        public async Task ReadExitsGivenIncompleteChunkedExtension()
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderTransferEncoding = "chunked"
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                input.Add("5;\r\0");

                var buffer   = new byte[1024];
                var readTask = stream.ReadAsync(buffer, 0, buffer.Length);

                Assert.False(readTask.IsCompleted);

                input.Add("\r\r\r\nHello\r\n0\r\n\r\n");

                Assert.Equal(5, await readTask.DefaultTimeout());
                Assert.Equal(0, await stream.ReadAsync(buffer, 0, buffer.Length));

                await body.StopAsync();
            }
        }
Exemplo n.º 4
0
        public async Task CanReadFromChunkedEncoding()
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderTransferEncoding = "chunked"
                }, input.Http1Connection);
                var mockBodyControl = new Mock <IHttpBodyControlFeature>();
                mockBodyControl.Setup(m => m.AllowSynchronousIO).Returns(true);
                var stream = new HttpRequestStream(mockBodyControl.Object);
                stream.StartAcceptingReads(body);

                input.Add("5\r\nHello\r\n");

                var buffer = new byte[1024];

                var count = stream.Read(buffer, 0, buffer.Length);
                Assert.Equal(5, count);
                AssertASCII("Hello", new ArraySegment <byte>(buffer, 0, count));

                input.Add("0\r\n\r\n");

                count = stream.Read(buffer, 0, buffer.Length);
                Assert.Equal(0, count);

                await body.StopAsync();
            }
        }
Exemplo n.º 5
0
        public async Task CanReadAsyncFromChunkedEncoding()
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderTransferEncoding = "chunked"
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                input.Add("5\r\nHello\r\n");

                var buffer = new byte[1024];

                var count = await stream.ReadAsync(buffer, 0, buffer.Length);

                Assert.Equal(5, count);
                AssertASCII("Hello", new ArraySegment <byte>(buffer, 0, count));

                input.Add("0\r\n\r\n");

                count = await stream.ReadAsync(buffer, 0, buffer.Length);

                Assert.Equal(0, count);

                input.Http1Connection.RequestBodyPipe.Reader.Complete();
                await body.StopAsync();
            }
        }
Exemplo n.º 6
0
        public void NullDestinationCausesCopyToAsyncToThrowArgumentNullException()
        {
            var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());

            stream.StartAcceptingReads(null);
            Assert.Throws <ArgumentNullException>(() => { stream.CopyToAsync(null); });
        }
Exemplo n.º 7
0
        public void ZeroBufferSizeCausesCopyToAsyncToThrowArgumentException()
        {
            var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());

            stream.StartAcceptingReads(null);
            Assert.Throws <ArgumentException>(() => { stream.CopyToAsync(Mock.Of <Stream>(), 0); });
        }
Exemplo n.º 8
0
        public async Task UpgradeConnectionAcceptsContentLengthZero()
        {
            // https://tools.ietf.org/html/rfc7230#section-3.3.2
            // "A user agent SHOULD NOT send a Content-Length header field when the request message does not contain
            // a payload body and the method semantics do not anticipate such a body."
            //  ==> it can actually send that header
            var headerConnection = "Upgrade, Keep-Alive";

            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderConnection = headerConnection, ContentLength = 0
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                input.Add("Hello");

                var buffer = new byte[1024];
                Assert.Equal(5, await stream.ReadAsync(buffer, 0, buffer.Length));
                AssertASCII("Hello", new ArraySegment <byte>(buffer, 0, 5));

                input.Fin();

                await body.StopAsync();
            }
        }
Exemplo n.º 9
0
        public async Task CanReadAsyncFromContentLength(HttpVersion httpVersion)
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(httpVersion, new HttpRequestHeaders {
                    HeaderContentLength = "5"
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                input.Add("Hello");

                var buffer = new byte[1024];

                var count = await stream.ReadAsync(buffer, 0, buffer.Length);

                Assert.Equal(5, count);
                AssertASCII("Hello", new ArraySegment <byte>(buffer, 0, count));

                count = await stream.ReadAsync(buffer, 0, buffer.Length);

                Assert.Equal(0, count);

                await body.StopAsync();
            }
        }
Exemplo n.º 10
0
        public async Task SynchronousReadsThrowIfDisallowedByIHttpBodyControlFeature()
        {
            var allowSynchronousIO = false;
            var mockBodyControl    = new Mock <IHttpBodyControlFeature>();

            mockBodyControl.Setup(m => m.AllowSynchronousIO).Returns(() => allowSynchronousIO);
            var mockMessageBody = new Mock <MessageBody>((HttpProtocol)null);

            mockMessageBody.Setup(m => m.ReadAsync(It.IsAny <ArraySegment <byte> >(), CancellationToken.None)).ReturnsAsync(0);

            var stream = new HttpRequestStream(mockBodyControl.Object);

            stream.StartAcceptingReads(mockMessageBody.Object);

            Assert.Equal(0, await stream.ReadAsync(new byte[1], 0, 1));

            var ioEx = Assert.Throws <InvalidOperationException>(() => stream.Read(new byte[1], 0, 1));

            Assert.Equal("Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.", ioEx.Message);

            var ioEx2 = Assert.Throws <InvalidOperationException>(() => stream.CopyTo(Stream.Null));

            Assert.Equal("Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.", ioEx2.Message);

            allowSynchronousIO = true;
            Assert.Equal(0, stream.Read(new byte[1], 0, 1));
        }
Exemplo n.º 11
0
        public async Task LogsWhenStopsReadingRequestBody()
        {
            using (var input = new TestInput())
            {
                var logEvent   = new ManualResetEventSlim();
                var mockLogger = new Mock <IKestrelTrace>();
                mockLogger
                .Setup(logger => logger.RequestBodyDone("ConnectionId", "RequestId"))
                .Callback(() => logEvent.Set());
                input.Http1Connection.ServiceContext.Log  = mockLogger.Object;
                input.Http1Connection.ConnectionIdFeature = "ConnectionId";
                input.Http1Connection.TraceIdentifier     = "RequestId";

                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderContentLength = "2"
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                // Add some input and consume it to ensure PumpAsync is running
                input.Add("a");
                Assert.Equal(1, await stream.ReadAsync(new byte[1], 0, 1));

                input.Fin();

                Assert.True(logEvent.Wait(TestConstants.DefaultTimeout));

                await body.StopAsync();
            }
        }
Exemplo n.º 12
0
        public async Task CanHandleLargeBlocks()
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(HttpVersion.Http10, new HttpRequestHeaders {
                    HeaderContentLength = "8197"
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                // Input needs to be greater than 4032 bytes to allocate a block not backed by a slab.
                var largeInput = new string('a', 8192);

                input.Add(largeInput);
                // Add a smaller block to the end so that SocketInput attempts to return the large
                // block to the memory pool.
                input.Add("Hello");

                var ms = new MemoryStream();

                await stream.CopyToAsync(ms);

                var requestArray = ms.ToArray();
                Assert.Equal(8197, requestArray.Length);
                AssertASCII(largeInput + "Hello", new ArraySegment <byte>(requestArray, 0, requestArray.Length));

                await body.StopAsync();
            }
        }
Exemplo n.º 13
0
        public async Task CanReadFromRemainingData(HttpVersion httpVersion)
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(httpVersion, new HttpRequestHeaders {
                    HeaderConnection = "upgrade"
                }, input.Http1Connection);
                var mockBodyControl = new Mock <IHttpBodyControlFeature>();
                mockBodyControl.Setup(m => m.AllowSynchronousIO).Returns(true);
                var stream = new HttpRequestStream(mockBodyControl.Object);
                stream.StartAcceptingReads(body);

                input.Add("Hello");

                var buffer = new byte[1024];

                var count = stream.Read(buffer, 0, buffer.Length);
                Assert.Equal(5, count);
                AssertASCII("Hello", new ArraySegment <byte>(buffer, 0, count));

                input.Fin();

                await body.StopAsync();
            }
        }
Exemplo n.º 14
0
        public void StopAcceptingReadsCausesCopyToAsyncToThrowObjectDisposedException()
        {
            var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());

            stream.StartAcceptingReads(null);
            stream.StopAcceptingReads();
            Assert.Throws <ObjectDisposedException>(() => { stream.CopyToAsync(Mock.Of <Stream>()); });
        }
        public async Task AbortCausesCopyToAsyncToCancel()
        {
            var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());

            stream.StartAcceptingReads(null);
            stream.Abort();
            await Assert.ThrowsAsync <TaskCanceledException>(() => stream.CopyToAsync(Mock.Of <Stream>()));
        }
Exemplo n.º 16
0
        public void AbortCausesCopyToAsyncToCancel()
        {
            var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());

            stream.StartAcceptingReads(null);
            stream.Abort();
            var task = stream.CopyToAsync(Mock.Of <Stream>());

            Assert.True(task.IsCanceled);
        }
        public async Task AbortWithErrorCausesCopyToAsyncToCancel()
        {
            var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());

            stream.StartAcceptingReads(null);
            var error = new Exception();

            stream.Abort(error);
            var exception = await Assert.ThrowsAsync <Exception>(() => stream.CopyToAsync(Mock.Of <Stream>()));

            Assert.Same(error, exception);
        }
Exemplo n.º 18
0
        public void AbortWithErrorCausesCopyToAsyncToCancel()
        {
            var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());

            stream.StartAcceptingReads(null);
            var error = new Exception();

            stream.Abort(error);
            var task = stream.CopyToAsync(Mock.Of <Stream>());

            Assert.True(task.IsFaulted);
            Assert.Same(error, task.Exception.InnerException);
        }
Exemplo n.º 19
0
        public async Task ReadAsyncFromNoContentLengthReturnsZero(HttpVersion httpVersion)
        {
            using (var input = new TestInput())
            {
                var body   = Http1MessageBody.For(httpVersion, new HttpRequestHeaders(), input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                input.Add("Hello");

                var buffer = new byte[1024];
                Assert.Equal(0, await stream.ReadAsync(buffer, 0, buffer.Length));

                await body.StopAsync();
            }
        }
Exemplo n.º 20
0
        public (Stream request, Stream response) Start(MessageBody body)
        {
            _request.StartAcceptingReads(body);
            _emptyRequest.StartAcceptingReads(MessageBody.ZeroContentLengthClose);
            _response.StartAcceptingWrites();

            if (body.RequestUpgrade)
            {
                // until Upgrade() is called, context.Response.Body should use the normal output stream
                _upgradeableResponse.SetInnerStream(_response);
                // upgradeable requests should never have a request body
                return(_emptyRequest, _upgradeableResponse);
            }
            else
            {
                return(_request, _response);
            }
        }
Exemplo n.º 21
0
        public async Task ReadFromNoContentLengthReturnsZero(HttpVersion httpVersion)
        {
            using (var input = new TestInput())
            {
                var body            = Http1MessageBody.For(httpVersion, new HttpRequestHeaders(), input.Http1Connection);
                var mockBodyControl = new Mock <IHttpBodyControlFeature>();
                mockBodyControl.Setup(m => m.AllowSynchronousIO).Returns(true);
                var stream = new HttpRequestStream(mockBodyControl.Object);
                stream.StartAcceptingReads(body);

                input.Add("Hello");

                var buffer = new byte[1024];
                Assert.Equal(0, stream.Read(buffer, 0, buffer.Length));

                await body.StopAsync();
            }
        }
Exemplo n.º 22
0
        public async Task ConnectionUpgradeKeepAlive(string headerConnection)
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderConnection = headerConnection
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                input.Add("Hello");

                var buffer = new byte[1024];
                Assert.Equal(5, await stream.ReadAsync(buffer, 0, buffer.Length));
                AssertASCII("Hello", new ArraySegment <byte>(buffer, 0, 5));

                input.Fin();

                await body.StopAsync();
            }
        }
Exemplo n.º 23
0
        public async Task ReadThrowsGivenChunkPrefixGreaterThan8Bytes()
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderTransferEncoding = "chunked"
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                input.Add("012345678\r");

                var buffer = new byte[1024];
                var ex     = await Assert.ThrowsAsync <BadHttpRequestException>(async() =>
                                                                                await stream.ReadAsync(buffer, 0, buffer.Length));

                Assert.Equal(CoreStrings.BadRequest_BadChunkSizeData, ex.Message);

                await body.StopAsync();
            }
        }
Exemplo n.º 24
0
        public async Task PumpAsyncDoesNotReturnAfterCancelingInput()
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderContentLength = "2"
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                // Add some input and consume it to ensure PumpAsync is running
                input.Add("a");
                Assert.Equal(1, await stream.ReadAsync(new byte[1], 0, 1));

                input.Transport.Input.CancelPendingRead();

                // Add more input and verify is read
                input.Add("b");
                Assert.Equal(1, await stream.ReadAsync(new byte[1], 0, 1));

                await body.StopAsync();
            }
        }
Exemplo n.º 25
0
        public async Task StopAsyncPreventsFurtherDataConsumption()
        {
            using (var input = new TestInput())
            {
                var body = Http1MessageBody.For(HttpVersion.Http11, new HttpRequestHeaders {
                    HeaderContentLength = "2"
                }, input.Http1Connection);
                var stream = new HttpRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                // Add some input and consume it to ensure PumpAsync is running
                input.Add("a");
                Assert.Equal(1, await stream.ReadAsync(new byte[1], 0, 1));

                await body.StopAsync();

                // Add some more data. Checking for cancelation and exiting the loop
                // should take priority over reading this data.
                input.Add("b");

                // There shouldn't be any additional data available
                Assert.Equal(0, await stream.ReadAsync(new byte[1], 0, 1));
            }
        }
Exemplo n.º 26
0
 public void Start()
 {
     _request.StartAcceptingReads();
     _response.StartAcceptingWrites();
 }