Example #1
0
        public void ParsesRequestLine(
            string requestLine,
            string expectedMethod,
            string expectedRawTarget,
            string expectedRawPath,
// This warns that theory methods should use all of their parameters,
// but this method is using a shared data collection with Http1ConnectionTests.TakeStartLineSetsHttpProtocolProperties and others.
#pragma warning disable xUnit1026
            string expectedDecodedPath,
            string expectedQueryString,
#pragma warning restore xUnit1026
            string expectedVersion)
        {
            var parser         = CreateParser(Mock.Of <IKestrelTrace>());
            var buffer         = ReadableBuffer.Create(Encoding.ASCII.GetBytes(requestLine));
            var requestHandler = new RequestHandler();

            Assert.True(parser.ParseRequestLine(requestHandler, buffer, out var consumed, out var examined));

            Assert.Equal(requestHandler.Method, expectedMethod);
            Assert.Equal(requestHandler.Version, expectedVersion);
            Assert.Equal(requestHandler.RawTarget, expectedRawTarget);
            Assert.Equal(requestHandler.RawPath, expectedRawPath);
            Assert.Equal(requestHandler.Version, expectedVersion);
            Assert.Equal(buffer.End, consumed);
            Assert.Equal(buffer.End, examined);
        }
Example #2
0
        public void InvalidMultiFramePayloads(byte[] payload1, byte[] payload2)
        {
            var validator = new Utf8Validator();

            Assert.True(validator.ValidateUtf8Frame(ReadableBuffer.Create(payload1), fin: false));
            Assert.False(validator.ValidateUtf8Frame(ReadableBuffer.Create(payload2), fin: true));
        }
 public ReadableBuffer GetHeaderRaw(string key)
 {
     if (_headers.TryGetValue(key, out HeaderValue value))
     {
         return(ReadableBuffer.Create(value.Raw));
     }
     return(default);
Example #4
0
            public override ReadableBuffer CreateWithContent(byte[] data)
            {
                var startSegment = new byte[data.Length + 20];

                System.Array.Copy(data, 0, startSegment, 10, data.Length);
                return(ReadableBuffer.Create(startSegment, 10, data.Length));
            }
Example #5
0
        public void ReadableBufferMove_DoesNotAlowNegative()
        {
            var data   = new byte[20];
            var buffer = ReadableBuffer.Create(data);

            Assert.Throws <ArgumentOutOfRangeException>(() => buffer.Move(buffer.Start, -1));
        }
        public void Setup()
        {
            var liveaspnetRequestBytes = Encoding.UTF8.GetBytes(liveaspnetRequest);
            var pipelinedRequests      = string.Concat(Enumerable.Repeat(plaintextRequest, 16));

            _plainTextPipelinedBuffer = ReadableBuffer.Create(Encoding.UTF8.GetBytes(pipelinedRequests));
            _plainTextBuffer          = ReadableBuffer.Create(Encoding.UTF8.GetBytes(plaintextRequest));
            _liveAspNetBuffer         = ReadableBuffer.Create(liveaspnetRequestBytes);

            // Split the liveaspnetRequest across 3 byte[]
            var remaining         = liveaspnetRequestBytes.Length;
            var consumed          = 0;
            var liveAspNetBuffers = new List <byte[]>();
            var chunk             = remaining / 3;

            while (remaining > 0)
            {
                var bytes = new byte[Math.Min(chunk, remaining)];
                Buffer.BlockCopy(liveaspnetRequestBytes, consumed, bytes, 0, bytes.Length);
                consumed  += bytes.Length;
                remaining -= bytes.Length;

                liveAspNetBuffers.Add(bytes);
            }

            _liveAspNetMultiBuffer = BufferUtilities.CreateBuffer(liveAspNetBuffers.ToArray());
        }
Example #7
0
 public void ReadableBufferDoesNotAllowSlicingOutOfRange(Action <ReadableBuffer> fail)
 {
     // we want big buffer so cursor.Seek succeeds but is out of range of readable buffer
     var data   = new byte[150];
     var buffer = ReadableBuffer.Create(data).Slice(0, 50);
     var ex     = Assert.Throws <InvalidOperationException>(() => fail(buffer));
 }
        public void CanUseOwnedBufferBasedReadableBuffers()
        {
            var data   = Encoding.ASCII.GetBytes("***abc|def|ghijk****"); // note sthe padding here - verifying that it is omitted correctly
            var buffer = ReadableBuffer.Create(data, 3, data.Length - 7);

            Assert.Equal(13, buffer.Length);
            var split = buffer.Split((byte)'|');

            Assert.Equal(3, split.Count());
            using (var iter = split.GetEnumerator())
            {
                Assert.True(iter.MoveNext());
                var current = iter.Current;
                Assert.Equal("abc", current.GetAsciiString());

                Assert.True(iter.MoveNext());
                current = iter.Current;
                Assert.Equal("def", current.GetAsciiString());

                Assert.True(iter.MoveNext());
                current = iter.Current;
                Assert.Equal("ghijk", current.GetAsciiString());

                Assert.False(iter.MoveNext());
            }
        }
Example #9
0
 /// <summary>
 /// Creates a new <see cref="WebSocketFrame"/> containing the same information, but with all buffers
 /// copied to new heap memory.
 /// </summary>
 /// <returns></returns>
 public WebSocketFrame Copy()
 {
     return(new WebSocketFrame(
                endOfMessage: EndOfMessage,
                opcode: Opcode,
                payload: ReadableBuffer.Create(Payload.ToArray())));
 }
        public void Create_WorksWithOwnedMemory()
        {
            var memory         = new OwnedArray <byte>(new byte[] { 1, 2, 3, 4, 5 });
            var readableBuffer = ReadableBuffer.Create(memory, 2, 3);

            Assert.Equal(new byte[] { 3, 4, 5 }, readableBuffer.ToArray());
        }
Example #11
0
            public async Task ValidSingleFramePayloads(byte[] payload, string decoded)
            {
                using (var pair = WebSocketPair.Create())
                {
                    var timeoutToken = TestUtil.CreateTimeoutToken();
                    using (timeoutToken.Register(() => pair.Dispose()))
                    {
                        var server = pair.ServerSocket.ExecuteAndCaptureFramesAsync();
                        var client = pair.ClientSocket.ExecuteAndCaptureFramesAsync();

                        var frame = new WebSocketFrame(
                            endOfMessage: true,
                            opcode: WebSocketOpcode.Text,
                            payload: ReadableBuffer.Create(payload));
                        await pair.ClientSocket.SendAsync(frame).OrTimeout();

                        await pair.ClientSocket.CloseAsync(WebSocketCloseStatus.NormalClosure).OrTimeout();

                        var serverSummary = await server.OrTimeout();

                        await pair.ServerSocket.CloseAsync(WebSocketCloseStatus.NormalClosure).OrTimeout();

                        var clientSummary = await client.OrTimeout();

                        Assert.Equal(0, clientSummary.Received.Count);

                        Assert.Equal(1, serverSummary.Received.Count);
                        Assert.True(serverSummary.Received[0].EndOfMessage);
                        Assert.Equal(WebSocketOpcode.Text, serverSummary.Received[0].Opcode);
                        Assert.Equal(decoded, Encoding.UTF8.GetString(serverSummary.Received[0].Payload.ToArray()));
                    }
                }
            }
Example #12
0
        public void PeekReturnsByteWithoutMoving()
        {
            var reader = new ReadableBufferReader(ReadableBuffer.Create(new byte[] { 1, 2 }, 0, 2));

            Assert.Equal(1, reader.Peek());
            Assert.Equal(1, reader.Peek());
        }
Example #13
0
        public void WorkesWithEmptyBuffer()
        {
            var reader = new ReadableBufferReader(ReadableBuffer.Create(new byte[] { 0 }, 0, 0));

            Assert.Equal(-1, reader.Peek());
            Assert.Equal(-1, reader.Take());
        }
Example #14
0
    static bool RequestLineRb()
    {
        ReadableBuffer buffer   = ReadableBuffer.Create(s_plaintextTechEmpowerRequestBytes);
        var            parser   = new HttpParser();
        var            request  = new Request();
        ReadCursor     consumed = default;
        ReadCursor     read;
        bool           success = true;

        foreach (var iteration in Benchmark.Iterations)
        {
            using (iteration.StartMeasurement())
            {
                for (int i = 0; i < Benchmark.InnerIterationCount; i++)
                {
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                    success = success && parser.ParseRequestLine(request, buffer, out consumed, out read);
                }
            }
        }

        return(success);
    }
Example #15
0
            public async Task TerminatesConnectionOnUnsolicitedContinuationFrame()
            {
                // Arrange
                using (var pair = WebSocketPair.Create(
                           serverOptions: new WebSocketOptions().WithAllFramesPassedThrough(),
                           clientOptions: new WebSocketOptions().WithAllFramesPassedThrough()))
                {
                    var payload = Encoding.UTF8.GetBytes("hello");

                    var client = pair.ClientSocket.ExecuteAndCaptureFramesAsync();
                    var server = pair.ServerSocket.ExecuteAndCaptureFramesAsync();

                    // Act
                    await pair.ClientSocket.SendAsync(new WebSocketFrame(
                                                          endOfMessage : true,
                                                          opcode : WebSocketOpcode.Text,
                                                          payload : ReadableBuffer.Create(payload)));

                    await pair.ClientSocket.SendAsync(new WebSocketFrame(
                                                          endOfMessage : true,
                                                          opcode : WebSocketOpcode.Continuation,
                                                          payload : ReadableBuffer.Create(payload)));

                    // Server should terminate
                    var clientSummary = await client.OrTimeout();

                    Assert.Equal(WebSocketCloseStatus.ProtocolError, clientSummary.CloseResult.Status);
                    Assert.Equal("Continuation Frame was received when expecting a new message", clientSummary.CloseResult.Description);

                    await server.OrTimeout();
                }
            }
Example #16
0
        public void ReadableBufferMove_ChecksBounds()
        {
            var data      = new byte[20];
            var buffer    = ReadableBuffer.Create(data);
            var subbuffer = buffer.Slice(0, 10);

            Assert.Throws <InvalidOperationException>(() => subbuffer.Move(buffer.Start, 11));
        }
Example #17
0
        public void ReadableBufferMove_MovesReadCursor()
        {
            var data   = new byte[10];
            var buffer = ReadableBuffer.Create(data);
            var cursor = buffer.Move(buffer.Start, 5);

            Assert.Equal(buffer.Slice(5).Start, cursor);
        }
Example #18
0
        public void PeekReturnsMinuOneByteInTheEnd()
        {
            var reader = new ReadableBufferReader(ReadableBuffer.Create(new byte[] { 1, 2 }, 0, 2));

            Assert.Equal(1, reader.Take());
            Assert.Equal(2, reader.Take());
            Assert.Equal(-1, reader.Peek());
        }
Example #19
0
        public void TakeReturnsByteAndMoves()
        {
            var reader = new ReadableBufferReader(ReadableBuffer.Create(new byte[] { 1, 2 }, 0, 2));

            Assert.Equal(1, reader.Take());
            Assert.Equal(2, reader.Take());
            Assert.Equal(-1, reader.Take());
        }
        public void ParseRequestLineReturnsFalseWhenGivenIncompleteRequestLines(string requestLine)
        {
            var parser         = CreateParser(Mock.Of <IKestrelTrace>());
            var buffer         = ReadableBuffer.Create(Encoding.ASCII.GetBytes(requestLine));
            var requestHandler = new RequestHandler();

            Assert.False(parser.ParseRequestLine(requestHandler, buffer, out var consumed, out var examined));
        }
Example #21
0
        public void SkipSingleBufferSkipsBytes()
        {
            var reader = new ReadableBufferReader(ReadableBuffer.Create(new byte[] { 1, 2, 3, 4, 5 }, 0, 5));

            reader.Skip(2);
            Assert.Equal(3, reader.Peek());
            reader.Skip(2);
            Assert.Equal(5, reader.Peek());
        }
        public void SkipToEndThenPeekReturnsMinusOne()
        {
            var reader = new ReadableBufferReader(ReadableBuffer.Create(new byte[] { 1, 2, 3, 4, 5 }, 0, 5));

            reader.Skip(5);
            Assert.True(reader.End);
            Assert.Equal(-1, reader.Peek());
            Assert.True(reader.Cursor.IsEnd);
        }
        public void CursorIsCorrectAtEnd()
        {
            var reader = new ReadableBufferReader(ReadableBuffer.Create(new byte[] { 1, 2 }, 0, 2));

            reader.Take();
            reader.Take();
            Assert.True(reader.End);
            Assert.True(reader.Cursor.IsEnd);
        }
Example #24
0
        public void SlicingBufferReturnsCorrectCursor()
        {
            var buffer = ReadableBuffer.Create(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 0, 10);
            var sliced = buffer.Slice(2);

            var reader = new ReadableBufferReader(sliced);

            Assert.Equal(sliced.Start, reader.Cursor);
            Assert.Equal(2, reader.Peek());
        }
Example #25
0
        public void ParseSSEMessageFailureCases(string encodedMessage, string expectedExceptionMessage)
        {
            var buffer         = Encoding.UTF8.GetBytes(encodedMessage);
            var readableBuffer = ReadableBuffer.Create(buffer);
            var parser         = new ServerSentEventsMessageParser();

            var ex = Assert.Throws <FormatException>(() => { parser.ParseMessage(readableBuffer, out var consumed, out var examined, out var message); });

            Assert.Equal(expectedExceptionMessage, ex.Message);
        }
Example #26
0
        public void ParseSSEMessageIncompleteParseResult(string encodedMessage)
        {
            var buffer         = Encoding.UTF8.GetBytes(encodedMessage);
            var readableBuffer = ReadableBuffer.Create(buffer);
            var parser         = new ServerSentEventsMessageParser();

            var parseResult = parser.ParseMessage(readableBuffer, out var consumed, out var examined, out var message);

            Assert.Equal(ServerSentEventsMessageParser.ParseResult.Incomplete, parseResult);
        }
Example #27
0
            public Task ReservedOpcodes(byte opcode)
            {
                var payload = Encoding.UTF8.GetBytes("hello");
                var frame   = new WebSocketFrame(
                    endOfMessage: true,
                    opcode: (WebSocketOpcode)opcode,
                    payload: ReadableBuffer.Create(payload));

                return(SendFrameAndExpectClose(frame, WebSocketCloseStatus.ProtocolError, $"Received frame using reserved opcode: 0x{opcode:X}"));
            }
Example #28
0
        public void ValidSingleFramePayloads(byte[] payload, string decoded)
        {
            var validator = new Utf8Validator();

            Assert.True(validator.ValidateUtf8Frame(ReadableBuffer.Create(payload), fin: true));

            // Not really part of the test, but it ensures that the "decoded" string matches the "payload",
            // so that the "decoded" string can be used as a human-readable explanation of the string in question
            Assert.Equal(decoded, Encoding.UTF8.GetString(payload));
        }
        public void ParseRequestLineDoesNotConsumeIncompleteRequestLine(string requestLine)
        {
            var parser         = CreateParser(Mock.Of <IKestrelTrace>());
            var buffer         = ReadableBuffer.Create(Encoding.ASCII.GetBytes(requestLine));
            var requestHandler = new RequestHandler();

            Assert.False(parser.ParseRequestLine(requestHandler, buffer, out var consumed, out var examined));

            Assert.Equal(buffer.Start, consumed);
            Assert.Equal(buffer.End, examined);
        }
Example #30
0
        public void ValidMultiFramePayloads(byte[] payload1, byte[] payload2, string decoded)
        {
            var validator = new Utf8Validator();

            Assert.True(validator.ValidateUtf8Frame(ReadableBuffer.Create(payload1), fin: false));
            Assert.True(validator.ValidateUtf8Frame(ReadableBuffer.Create(payload2), fin: true));

            // Not really part of the test, but it ensures that the "decoded" string matches the "payload",
            // so that the "decoded" string can be used as a human-readable explanation of the string in question
            Assert.Equal(decoded, Encoding.UTF8.GetString(Enumerable.Concat(payload1, payload2).ToArray()));
        }