public void FilenameContainingSemicolon2()
        {
            const string Boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
            var          req      = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, "http://localhost");

            req.Headers.Add(HttpHeaderNames.ContentType, "multipart/form-data; boundary=" + Boundary);

            // Force to use memory-based data.
            var          inMemoryFactory = new DefaultHttpDataFactory(false);
            const string Data            = "asdf";
            const string Filename        = "tmp;0.txt";
            const string Body            = "--" + Boundary + "\r\n" +
                                           "Content-Disposition: form-data; name=\"file\"; filename=\"" + Filename + "\"\r\n" +
                                           "Content-Type: image/gif\r\n" +
                                           "\r\n" +
                                           Data + "\r\n" +
                                           "--" + Boundary + "--\r\n";

            req.Content.WriteBytes(Encoding.UTF8.GetBytes(Body));
            var decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
            List <IInterfaceHttpData> list = decoder.GetBodyHttpDatas();

            Assert.NotNull(list);
            Assert.False(list.Count == 0);

            IInterfaceHttpData part1 = list[0];

            Assert.IsAssignableFrom <IFileUpload>(part1);
            var fileUpload = (IFileUpload)part1;

            Assert.Equal("tmp 0.txt", fileUpload.FileName);
            decoder.Destroy();
        }
Example #2
0
        public void TestEncodeHttpsSchemeWhenSslHandlerExists()
        {
            var frames = new ConcurrentQueue <IHttp2StreamFrame>();
            var ch     = new EmbeddedChannel(new TestChannelOutboundHandlerAdapter(frames),
                                             new Http2StreamFrameToHttpObjectCodec(false));

            try
            {
                var req = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, "/hello/world");
                Assert.True(ch.WriteOutbound(req));

                ch.FinishAndReleaseAll();

                frames.TryDequeue(out var streamFrame);
                var headersFrame = (IHttp2HeadersFrame)streamFrame;
                var headers      = headersFrame.Headers;
                Assert.Equal("http", headers.Scheme);
                Assert.Equal("GET", headers.Method);
                Assert.Equal("/hello/world", headers.Path);
                Assert.True(headersFrame.IsEndStream);
                Assert.False(frames.TryDequeue(out _));
            }
            finally
            {
                ch.FinishAndReleaseAll();
            }
        }
Example #3
0
        public void TestEncodeEmptyFullRequestWithTrailers()
        {
            EmbeddedChannel  ch      = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
            IFullHttpRequest request = new DefaultFullHttpRequest(
                HttpVersion.Http11, HttpMethod.Put, "/hello/world");

            HttpHeaders trailers = request.TrailingHeaders;

            trailers.Set((AsciiString)"key", "value");
            Assert.True(ch.WriteOutbound(request));

            var           headersFrame = ch.ReadOutbound <IHttp2HeadersFrame>();
            IHttp2Headers headers      = headersFrame.Headers;

            Assert.Equal("http", headers.Scheme);
            Assert.Equal("PUT", headers.Method);
            Assert.Equal("/hello/world", headers.Path);
            Assert.False(headersFrame.IsEndStream);

            IHttp2HeadersFrame trailersFrame = ch.ReadOutbound <IHttp2HeadersFrame>();

            Assert.Equal("value", trailersFrame.Headers.Get((AsciiString)"key", null));
            Assert.True(trailersFrame.IsEndStream);

            Assert.Null(ch.ReadOutbound());
            Assert.False(ch.Finish());
        }
Example #4
0
        public void DecodesFinalResponseAfterSwitchingProtocols()
        {
            const string SwitchingProtocolsResponse = "HTTP/1.1 101 Switching Protocols\r\n" +
                                                      "Connection: Upgrade\r\n" +
                                                      "Upgrade: TLS/1.2, HTTP/1.1\r\n\r\n";

            var codec = new HttpClientCodec(4096, 8192, 8192, true);
            var ch    = new EmbeddedChannel(codec, new HttpObjectAggregator(1024));

            IHttpRequest request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, "http://localhost/");

            request.Headers.Set(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade);
            request.Headers.Set(HttpHeaderNames.Upgrade, "TLS/1.2");
            Assert.True(ch.WriteOutbound(request), "Channel outbound write failed.");

            Assert.True(
                ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(SwitchingProtocolsResponse))),
                "Channel inbound write failed.");
            var switchingProtocolsResponse = ch.ReadInbound <IFullHttpResponse>();

            Assert.NotNull(switchingProtocolsResponse);
            switchingProtocolsResponse.Release();

            Assert.True(
                ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(Response))),
                "Channel inbound write failed");
            var finalResponse = ch.ReadInbound <IFullHttpResponse>();

            Assert.NotNull(finalResponse);
            finalResponse.Release();
            Assert.True(ch.FinishAndReleaseAll(), "Channel finish failed");
        }
Example #5
0
        public void MultipleCookieEntriesAreCombined()
        {
            this.BootstrapEnv(2, 1, 0);
            IFullHttpRequest request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Get,
                                                                  "http://[email protected]:5555/example");
            HttpHeaders httpHeaders = request.Headers;

            httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 5);
            httpHeaders.Set(HttpHeaderNames.Host, "[email protected]:5555");
            httpHeaders.Set(HttpConversionUtil.ExtensionHeaderNames.Scheme, "http");
            httpHeaders.Set(HttpHeaderNames.Cookie, "a=b; c=d; e=f");
            var http2Headers = new DefaultHttp2Headers()
            {
                Method    = new AsciiString("GET"),
                Path      = new AsciiString("/example"),
                Authority = new AsciiString("www.example.org:5555"),
                Scheme    = new AsciiString("http")
            };

            http2Headers.Add(HttpHeaderNames.Cookie, new AsciiString("a=b"));
            http2Headers.Add(HttpHeaderNames.Cookie, new AsciiString("c=d"));
            http2Headers.Add(HttpHeaderNames.Cookie, new AsciiString("e=f"));

            var writePromise = this.NewPromise();

            this.VerifyHeadersOnly(http2Headers, writePromise, this.clientChannel.WriteAndFlushAsync(request, writePromise));
        }
Example #6
0
        public void KeepAlive(bool isKeepAliveResponseExpected, HttpVersion httpVersion, HttpResponseStatus responseStatus, string sendKeepAlive, int setSelfDefinedMessageLength, ICharSequence setResponseConnection)
        {
            var channel = new EmbeddedChannel(new HttpServerKeepAliveHandler());
            var request = new DefaultFullHttpRequest(httpVersion, HttpMethod.Get, "/v1/foo/bar");

            HttpUtil.SetKeepAlive(request, RequestKeepAlive.Equals(sendKeepAlive));
            var response = new DefaultFullHttpResponse(httpVersion, responseStatus);

            if (!CharUtil.IsNullOrEmpty(setResponseConnection))
            {
                response.Headers.Set(HttpHeaderNames.Connection, setResponseConnection);
            }
            SetupMessageLength(setSelfDefinedMessageLength, response);

            Assert.True(channel.WriteInbound(request));
            var requestForwarded = channel.ReadInbound <object>();

            Assert.Equal(request, requestForwarded);
            ReferenceCountUtil.Release(requestForwarded);
            channel.WriteAndFlushAsync(response).Wait(TimeSpan.FromSeconds(1));
            var writtenResponse = channel.ReadOutbound <IHttpResponse>();

            Assert.Equal(isKeepAliveResponseExpected, channel.Open);
            Assert.Equal(isKeepAliveResponseExpected, HttpUtil.IsKeepAlive(writtenResponse));
            ReferenceCountUtil.Release(writtenResponse);
            Assert.False(channel.FinishAndReleaseAll());
        }
        protected override object NewInitialMessage(IChannelHandlerContext ctx)
        {
            if (!TryParseEndpoint(DestinationAddress, out string hostnameString, out int port))
            {
                throw new NotSupportedException($"Endpoint {DestinationAddress} is not supported as http proxy destination");
            }

            string url        = hostnameString + ":" + port;
            string hostHeader = _ignoreDefaultPortsInConnectHostHeader && (port == 80 || port == 443) ? hostnameString : url;

            IFullHttpRequest req = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Connect, url, Unpooled.Empty, false);

            req.Headers.Set(HttpHeaderNames.Host, hostHeader);

            if (_authorization != null)
            {
                req.Headers.Set(HttpHeaderNames.ProxyAuthorization, _authorization);
            }

            if (_outboundHeaders != null)
            {
                req.Headers.Add(_outboundHeaders);
            }

            return(req);
        }
        public void SingleFileUploadNoName()
        {
            var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, "http://localhost");
            var encoder = new HttpPostRequestEncoder(request, true);

            FileStream fileStream = File.Open("./Multipart/file-01.txt", FileMode.Open, FileAccess.Read);

            this.files.Add(fileStream);
            encoder.AddBodyAttribute("foo", "bar");
            encoder.AddBodyFileUpload("quux", "", fileStream, "text/plain", false);

            string multipartDataBoundary = encoder.MultipartDataBoundary;
            string content = GetRequestBody(encoder);

            string expected = "--" + multipartDataBoundary + "\r\n" +
                              HttpHeaderNames.ContentDisposition + ": form-data; name=\"foo\"" + "\r\n" +
                              HttpHeaderNames.ContentLength + ": 3" + "\r\n" +
                              HttpHeaderNames.ContentType + ": text/plain; charset=utf-8" + "\r\n" +
                              "\r\n" +
                              "bar" +
                              "\r\n" +
                              "--" + multipartDataBoundary + "\r\n" +
                              HttpHeaderNames.ContentDisposition + ": form-data; name=\"quux\"\r\n" +
                              HttpHeaderNames.ContentLength + ": " + fileStream.Length + "\r\n" +
                              HttpHeaderNames.ContentType + ": text/plain" + "\r\n" +
                              HttpHeaderNames.ContentTransferEncoding + ": binary" + "\r\n" +
                              "\r\n" +
                              "File 01" + StringUtil.Newline +
                              "\r\n" +
                              "--" + multipartDataBoundary + "--" + "\r\n";

            Assert.Equal(expected, content);
        }
Example #9
0
        protected internal override IFullHttpRequest NewHandshakeRequest()
        {
            Uri wsUrl = Uri;

            // Get 16 bit nonce and base 64 encode it
            byte[] nonce = WebSocketUtil.RandomBytes(16);
            string key   = WebSocketUtil.Base64String(nonce);

            string acceptSeed = key + MagicGuid;

            byte[] sha1 = WebSocketUtil.Sha1(Encoding.ASCII.GetBytes(acceptSeed));
            _expectedChallengeResponseString = new AsciiString(WebSocketUtil.Base64String(sha1));

#if DEBUG
            if (Logger.DebugEnabled)
            {
                Logger.WebSocketVersion08ClientHandshakeKey(key, _expectedChallengeResponseString);
            }
#endif

            // Format request
            var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, UpgradeUrl(wsUrl),
                                                     Unpooled.Empty);
            HttpHeaders headers = request.Headers;

            if (CustomHeaders is object)
            {
                _ = headers.Add(CustomHeaders);
                if (!headers.Contains(HttpHeaderNames.Host))
                {
                    // Only add HOST header if customHeaders did not contain it.
                    //
                    // See https://github.com/netty/netty/issues/10101
                    _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
                }
            }
            else
            {
                _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
            }

            _ = headers.Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket)
                .Set(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade)
                .Set(HttpHeaderNames.SecWebsocketKey, key);

            if (!headers.Contains(HttpHeaderNames.SecWebsocketOrigin))
            {
                _ = headers.Set(HttpHeaderNames.SecWebsocketOrigin, WebsocketOriginValue(wsUrl));
            }

            string expectedSubprotocol = ExpectedSubprotocol;
            if (!string.IsNullOrEmpty(expectedSubprotocol))
            {
                _ = headers.Set(HttpHeaderNames.SecWebsocketProtocol, expectedSubprotocol);
            }

            _ = headers.Set(HttpHeaderNames.SecWebsocketVersion, Version.ToString());

            return(request);
        }
        static void ShouldThrowExceptionIfNotAllowed(HttpMethod method, FileStream fileStream)
        {
            fileStream.Position = 0; // Reset to the begining
            var request = new DefaultFullHttpRequest(HttpVersion.Http11, method, "http://localhost");

            var encoder = new HttpPostRequestEncoder(request, true);

            encoder.AddBodyAttribute("foo", "bar");
            encoder.AddBodyFileUpload("quux", fileStream, "text/plain", false);

            string multipartDataBoundary = encoder.MultipartDataBoundary;
            string content = GetRequestBody(encoder);

            string expected = "--" + multipartDataBoundary + "\r\n" +
                              HttpHeaderNames.ContentDisposition + ": form-data; name=\"foo\"" + "\r\n" +
                              HttpHeaderNames.ContentLength + ": 3" + "\r\n" +
                              HttpHeaderNames.ContentType + ": text/plain; charset=utf-8" + "\r\n" +
                              "\r\n" +
                              "bar" +
                              "\r\n" +
                              "--" + multipartDataBoundary + "\r\n" +
                              HttpHeaderNames.ContentDisposition + ": form-data; name=\"quux\"; filename=\"file-01.txt\"" + "\r\n" +
                              HttpHeaderNames.ContentLength + ": " + fileStream.Length + "\r\n" +
                              HttpHeaderNames.ContentType + ": text/plain" + "\r\n" +
                              HttpHeaderNames.ContentTransferEncoding + ": binary" + "\r\n" +
                              "\r\n" +
                              "File 01" + StringUtil.Newline +
                              "\r\n" +
                              "--" + multipartDataBoundary + "--" + "\r\n";

            Assert.Equal(expected, content);
        }
        public void DataIsMultipleOfChunkSize1()
        {
            var factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MinSize);
            var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, "http://localhost");
            var encoder = new HttpPostRequestEncoder(factory, request, true,
                                                     HttpConstants.DefaultEncoding, HttpPostRequestEncoder.EncoderMode.RFC1738);

            var first = new MemoryFileUpload("resources", "", "application/json", null, Encoding.UTF8, -1);

            first.MaxSize = -1;
            first.SetContent(new MemoryStream(new byte[7955]));
            encoder.AddBodyHttpData(first);

            var second = new MemoryFileUpload("resources2", "", "application/json", null, Encoding.UTF8, -1);

            second.MaxSize = -1;
            second.SetContent(new MemoryStream(new byte[7928]));
            encoder.AddBodyHttpData(second);

            Assert.NotNull(encoder.FinalizeRequest());

            CheckNextChunkSize(encoder, 8080);
            CheckNextChunkSize(encoder, 8055);

            IHttpContent httpContent = encoder.ReadChunk(default(IByteBufferAllocator));

            Assert.True(httpContent is ILastHttpContent, "Expected LastHttpContent is not received");
            httpContent.Release();

            Assert.True(encoder.IsEndOfInput, "Expected end of input is not receive");
        }
        public async Task PerformHandshakeWithoutOriginHeader()
        {
            EmbeddedChannel ch = new EmbeddedChannel(
                new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

            IFullHttpRequest req = new DefaultFullHttpRequest(
                Http11, HttpMethod.Get, "/chat", Unpooled.CopiedBuffer("^n:ds[4U", Encoding.ASCII));

            req.Headers.Set(HttpHeaderNames.Host, "server.example.com");
            req.Headers.Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket);
            req.Headers.Set(HttpHeaderNames.Connection, "Upgrade");
            req.Headers.Set(HttpHeaderNames.SecWebsocketKey1, "4 @1  46546xW%0l 1 5");
            req.Headers.Set(HttpHeaderNames.SecWebsocketProtocol, "chat, superchat");

            WebSocketServerHandshaker00 handshaker00 = new WebSocketServerHandshaker00(
                "ws://example.com/chat", "chat", int.MaxValue);

            try
            {
                await handshaker00.HandshakeAsync(ch, req);

                Assert.False(true, "Expecting WebSocketHandshakeException");
            }
            catch (WebSocketHandshakeException e)
            {
                Assert.Equal("Missing origin header, got only "
                             + "[host, upgrade, connection, sec-websocket-key1, sec-websocket-protocol]",
                             e.Message);
            }
            finally
            {
                req.Release();
            }
        }
        protected async Task DoRequestAsync(List <Uri> uris, int requestCount)
        {
            foreach (var uri in uris)
            {
                var sw    = Stopwatch.StartNew();
                var cts   = new CancellationTokenSource(TimeSpan.FromSeconds(2));
                var tasks = Enumerable.Range(0, requestCount).Select(async m =>
                {
                    IFullHttpResponse response = null;
                    try
                    {
                        var request = new DefaultFullHttpRequest(DNHttpVersion.Http11, DNHttpMethod.Get, uri.OriginalString);
                        response    = await _executor.ExecuteAsync(request, cts.Token).ConfigureAwait(false);

                        Assert.AreEqual(200, response.Status.Code);
                    }
                    catch { }
                    finally
                    {
                        response.SafeRelease();
                    }
                }).ToArray();

                await Task.WhenAll(tasks).ConfigureAwait(false);

                sw.Stop();

                Debug.WriteLine($"{uri.OriginalString}:{sw.Elapsed}");
            }
        }
        public static async Task DoRequest(Channel channel)
        {
            DefaultFullHttpRequest req = null;

            req = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Get, "/");
            req.Headers.Add(AsciiString.Cached("Host"), AsciiString.Cached("localhost"));
            req.Headers.Add(AsciiString.Cached("Connection"), AsciiString.Cached("Keep-Alive"));
            // Console.WriteLine("send get");
            channel.Busy = true;

            if (!upChannels.ContainsKey(channel.upstream))
            {
                upChannels.TryAdd(channel.upstream, channel);
            }
            Task.Run(async() =>
            {
                try
                {
                    await channel.upstream.WriteAndFlushAsync(req).ConfigureAwait(false);

                    // Console.WriteLine("send done");
                }
                catch (Exception ex)
                {
                    await channel.request.DisconnectAsync();
                    //Console.WriteLine("close connection");
                    Channel old = null;
                    upChannels.TryRemove(channel.upstream, out old);
                    Console.WriteLine(ex.Message);
                }
            });
        }
Example #15
0
        public void Http10()
        {
            var ch  = new EmbeddedChannel(new TestEncoder());
            var req = new DefaultFullHttpRequest(HttpVersion.Http10, HttpMethod.Get, "/");

            Assert.True(ch.WriteInbound(req));

            var res = new DefaultHttpResponse(HttpVersion.Http10, HttpResponseStatus.OK);

            res.Headers.Set(HttpHeaderNames.ContentLength, HttpHeaderValues.Zero);
            Assert.True(ch.WriteOutbound(res));
            Assert.True(ch.WriteOutbound(EmptyLastHttpContent.Default));
            Assert.True(ch.Finish());

            var request = ch.ReadInbound <IFullHttpRequest>();

            Assert.True(request.Release());
            var next = ch.ReadInbound();

            Assert.Null(next);

            var response = ch.ReadOutbound <IHttpResponse>();

            Assert.Same(res, response);

            var content = ch.ReadOutbound <ILastHttpContent>();

            Assert.Same(content, EmptyLastHttpContent.Default);
            content.Release();

            next = ch.ReadOutbound();
            Assert.Null(next);
        }
        public void MultipartRequestWithoutContentTypeBody()
        {
            const string Boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";

            var req = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, "http://localhost");

            req.Result = DecoderResult.Success;
            req.Headers.Add(HttpHeaderNames.ContentType, "multipart/form-data; boundary=" + Boundary);
            req.Headers.Add(HttpHeaderNames.TransferEncoding, HttpHeaderValues.Chunked);

            // Force to use memory-based data.
            var inMemoryFactory = new DefaultHttpDataFactory(false);

            var values = new[] { "", "\r", "\r\r", "\r\r\r" };

            foreach (string data in values)
            {
                string body =
                    "--" + Boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" +
                    "\r\n" +
                    data + "\r\n" +
                    "--" + Boundary + "--\r\n";

                req.Content.WriteBytes(Encoding.UTF8.GetBytes(body));
            }

            // Create decoder instance to test without any exception.
            var decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
            List <IInterfaceHttpData> list = decoder.GetBodyHttpDatas();

            Assert.NotNull(list);
            Assert.False(list.Count == 0);
            decoder.Destroy();
        }
        public virtual RequestHandle createConnection(Protocol protocol, LightstreamerRequest request, com.lightstreamer.client.transport.providers.HttpProvider_HttpRequestListener httpListener, IDictionary <string, string> extraHeaders, Proxy proxy, long tcpConnectTimeout, long tcpReadTimeout)
        {
            string address = request.TargetServer + "lightstreamer/" + request.RequestName + ".txt" + "?LS_protocol=" + Constants.TLCP_VERSION;
            Uri    uri;

            try
            {
                uri = new Uri(address);
            }
            catch (Exception e)
            {
                log.Fatal("Unexpectedly invalid URI: " + address, e);
                throw new System.ArgumentException(e.Message);
            }

            bool secure = isSSL(address);
            int  port   = uri.Port == -1 ? (secure ? 443 : 80) : uri.Port;

            IFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, uri.PathAndQuery);

            httpRequest.Headers.Set(HttpHeaderNames.Host, uri.Host);

            string cookies = CookieHelper.getCookieHeader(uri);

            log.Info("Requested cookies for uri " + uri + ": " + cookies);
            if (!string.ReferenceEquals(cookies, null) && cookies.Length > 0)
            {
                httpRequest.Headers.Set(HttpHeaderNames.Cookie, cookies);
            }

            httpRequest.Headers.Set(HttpHeaderNames.UserAgent, ua);
            httpRequest.Headers.Set(HttpHeaderNames.ContentType, "text/plain; charset=UTF-8");

            if (extraHeaders != null)
            {
                foreach (KeyValuePair <string, string> header in extraHeaders.SetOfKeyValuePairs())
                {
                    httpRequest.Headers.Set(new AsciiString(header.Key), header.Value);
                }
            }

            IByteBuffer bbuf = Unpooled.CopiedBuffer(request.getTransportAwareQueryString(null, true) + "\r\n", Encoding.UTF8);

            httpRequest.Headers.Set(HttpHeaderNames.ContentLength, bbuf.ReadableBytes);

            httpRequest.Content.Clear().WriteBytes(bbuf);

            string host4Netty = System.Net.Dns.GetHostAddresses(uri.Host)[0].ToString();

            log.Debug("cs ---- address: " + address + ", " + host4Netty);

            NettyFullAddress target = new NettyFullAddress(secure, host4Netty, port, uri.Host, proxy);

            NettyInterruptionHandler interruptionHandler = new NettyInterruptionHandler();

            bindAsync(uri, target, httpListener, httpRequest, interruptionHandler);

            return(interruptionHandler);
        }
            public IByteBufferHolder Replace(IByteBuffer newContent)
            {
                var duplicate = new DefaultFullHttpRequest(this.ProtocolVersion, this.Method, this.Uri, newContent);

                duplicate.Headers.Set(this.Headers);
                duplicate.TrailingHeaders.Set(this.TrailingHeaders);
                return(duplicate);
            }
Example #19
0
        static void RunUnsupportedExpectationTest(HttpVersion version, string expectations, bool expect)
        {
            var message = new DefaultFullHttpRequest(version, HttpMethod.Get, "/");

            if (expectations != null)
            {
                message.Headers.Set(new AsciiString("Expect"), expectations);
            }
            RunUnsupportedExpectationTest(message, expect);
        }
        public void ClientRequestStreamDependencyInHttpMessageFlow()
        {
            this.BootstrapEnv(1, 2, 1);
            string           text     = "hello world big time data!";
            IByteBuffer      content  = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text));
            string           text2    = "hello world big time data...number 2!!";
            IByteBuffer      content2 = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text2));
            IFullHttpRequest request  = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Put,
                                                                   "/some/path/resource", content, true);
            IFullHttpMessage request2 = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Put,
                                                                   "/some/path/resource2", content2, true);

            try
            {
                HttpHeaders httpHeaders = request.Headers;
                httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3);
                httpHeaders.SetInt(HttpHeaderNames.ContentLength, text.Length);
                httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16);
                HttpHeaders httpHeaders2 = request2.Headers;
                httpHeaders2.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 5);
                httpHeaders2.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamDependencyId, 3);
                httpHeaders2.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 123);
                httpHeaders2.SetInt(HttpHeaderNames.ContentLength, text2.Length);
                var http2Headers = new DefaultHttp2Headers()
                {
                    Method = new AsciiString("PUT"),
                    Path   = new AsciiString("/some/path/resource"),
                };
                var http2Headers2 = new DefaultHttp2Headers()
                {
                    Method = new AsciiString("PUT"),
                    Path   = new AsciiString("/some/path/resource2"),
                };
                Http2TestUtil.RunInChannel(this.clientChannel, () =>
                {
                    this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 3, http2Headers, 0, false, this.NewPromiseClient());
                    this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 5, http2Headers2, 3, 123, true, 0, false, this.NewPromiseClient());
                    this.clientChannel.Flush(); // Headers are queued in the flow controller and so flush them.
                    this.clientHandler.Encoder.WriteDataAsync(this.CtxClient(), 3, content.RetainedDuplicate(), 0, true, this.NewPromiseClient());
                    this.clientHandler.Encoder.WriteDataAsync(this.CtxClient(), 5, content2.RetainedDuplicate(), 0, true, this.NewPromiseClient());
                    this.clientChannel.Flush();
                });
                this.AwaitRequests();
                var httpObjectCaptor = new ArgumentCaptor <IFullHttpMessage>();
                this.serverListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => httpObjectCaptor.Capture((IFullHttpMessage)v))), Times.Exactly(2));
                this.capturedRequests = httpObjectCaptor.GetAllValues();
                Assert.Equal(request, (IFullHttpRequest)this.capturedRequests[0]);
                Assert.Equal(request2, this.capturedRequests[1]);
            }
            finally
            {
                request.Release();
                request2.Release();
            }
        }
Example #21
0
        public void AuthorizationQuertStringFailTest()
        {
            IServiceCollection serviceDescriptors = new ServiceCollection();

            serviceDescriptors.Configure <JT808Configuration>((options) => { });
            var options = serviceDescriptors.BuildServiceProvider().GetRequiredService <IOptionsMonitor <JT808Configuration> >();
            JT808AuthorizationDefault jT808AuthorizationDefault = new JT808AuthorizationDefault(options);
            var m = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, "/demo?token=12345");

            Assert.False(jT808AuthorizationDefault.Authorization(m, out var principal));
        }
Example #22
0
        static void Run100ContinueTest(HttpVersion version, string expectations, bool expect)
        {
            var message = new DefaultFullHttpRequest(version, HttpMethod.Get, "/");

            if (expectations != null)
            {
                message.Headers.Set(HttpHeaderNames.Expect, expectations);
            }

            Run100ContinueTest(message, expect);
        }
Example #23
0
        public void MultipartCodecWithCRasEndOfAttribute()
        {
            const string Boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";

            // Force to use memory-based data.
            var inMemoryFactory = new DefaultHttpDataFactory(false);

            const string Extradata = "aaaa";
            var          strings   = new string[5];

            for (int i = 0; i < 4; i++)
            {
                strings[i] = Extradata;
                for (int j = 0; j < i; j++)
                {
                    strings[i] += '\r';
                }
            }

            for (int i = 0; i < 4; i++)
            {
                var req = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, "http://localhost");
                req.Result = DecoderResult.Success;
                req.Headers.Add(HttpHeaderNames.ContentType, "multipart/form-data; boundary=" + Boundary);
                req.Headers.Add(HttpHeaderNames.TransferEncoding, HttpHeaderValues.Chunked);
                string body =
                    "--" + Boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"file" + i + "\"\r\n" +
                    "Content-Type: image/gif\r\n" +
                    "\r\n" +
                    strings[i] + "\r\n" +
                    "--" + Boundary + "--\r\n";

                req.Content.WriteBytes(Encoding.UTF8.GetBytes(body));
                // Create decoder instance to test.
                var decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
                List <IInterfaceHttpData> list = decoder.GetBodyHttpDatas();
                Assert.NotNull(list);
                Assert.False(list.Count == 0);

                // Check correctness: data size
                IInterfaceHttpData httpData = decoder.GetBodyHttpData($"file{i}");
                Assert.NotNull(httpData);
                var attribute = httpData as IAttribute;
                Assert.NotNull(attribute);

                byte[] data = attribute.GetBytes();
                Assert.NotNull(data);
                Assert.Equal(Encoding.UTF8.GetBytes(strings[i]).Length, data.Length);

                decoder.Destroy();
            }
        }
Example #24
0
        public void AuthorizationHeaderTest()
        {
            IServiceCollection serviceDescriptors = new ServiceCollection();

            serviceDescriptors.Configure <JT808Configuration>((options) => { });
            var options = serviceDescriptors.BuildServiceProvider().GetRequiredService <IOptionsMonitor <JT808Configuration> >();
            JT808AuthorizationDefault jT808AuthorizationDefault = new JT808AuthorizationDefault(options);
            var m = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, "/");

            m.Headers.Add((AsciiString)"token", "123456");
            Assert.True(jT808AuthorizationDefault.Authorization(m, out var principal));
        }
Example #25
0
        public void MultiFileUploadInMixedModeNoName()
        {
            var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, "http://localhost");
            var encoder = new HttpPostRequestEncoder(request, true);

            FileStream fileStream1 = File.Open("./Multipart/file-01.txt", FileMode.Open, FileAccess.Read);

            this.files.Add(fileStream1);
            FileStream fileStream2 = File.Open("./Multipart/file-02.txt", FileMode.Open, FileAccess.Read);

            this.files.Add(fileStream2);

            encoder.AddBodyAttribute("foo", "bar");
            encoder.AddBodyFileUpload("quux", "", fileStream1, "text/plain", false);
            encoder.AddBodyFileUpload("quux", "", fileStream2, "text/plain", false);

            // We have to query the value of these two fields before finalizing
            // the request, which unsets one of them.
            string multipartDataBoundary  = encoder.MultipartDataBoundary;
            string multipartMixedBoundary = encoder.MultipartMixedBoundary;
            string content = GetRequestBody(encoder);

            string expected = "--" + multipartDataBoundary + "\r\n" +
                              HttpHeaderNames.ContentDisposition + ": form-data; name=\"foo\"" + "\r\n" +
                              HttpHeaderNames.ContentLength + ": 3" + "\r\n" +
                              HttpHeaderNames.ContentType + ": text/plain; charset=utf-8" + "\r\n" +
                              "\r\n" +
                              "bar" + "\r\n" +
                              "--" + multipartDataBoundary + "\r\n" +
                              HttpHeaderNames.ContentDisposition + ": form-data; name=\"quux\"" + "\r\n" +
                              HttpHeaderNames.ContentType + ": multipart/mixed; boundary=" + multipartMixedBoundary + "\r\n" +
                              "\r\n" +
                              "--" + multipartMixedBoundary + "\r\n" +
                              HttpHeaderNames.ContentDisposition + ": attachment\r\n" +
                              HttpHeaderNames.ContentLength + ": " + fileStream1.Length + "\r\n" +
                              HttpHeaderNames.ContentType + ": text/plain" + "\r\n" +
                              HttpHeaderNames.ContentTransferEncoding + ": binary" + "\r\n" +
                              "\r\n" +
                              "File 01" + /*StringUtil.*/ Newline +
                              "\r\n" +
                              "--" + multipartMixedBoundary + "\r\n" +
                              HttpHeaderNames.ContentDisposition + ": attachment\r\n" +
                              HttpHeaderNames.ContentLength + ": " + fileStream2.Length + "\r\n" +
                              HttpHeaderNames.ContentType + ": text/plain" + "\r\n" +
                              HttpHeaderNames.ContentTransferEncoding + ": binary" + "\r\n" +
                              "\r\n" +
                              "File 02" + /*StringUtil.*/ Newline +
                              "\r\n" +
                              "--" + multipartMixedBoundary + "--" + "\r\n" +
                              "--" + multipartDataBoundary + "--" + "\r\n";

            Assert.Equal(expected, content);
        }
        public void TestDuplicateHandshakeResponseHeaders()
        {
            WebSocketServerHandshaker serverHandshaker = NewHandshaker("ws://example.com/chat",
                                                                       "chat", WebSocketDecoderConfig.Default);
            IFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, "/chat");

            request.Headers
            .Set(HttpHeaderNames.Host, "example.com")
            .Set(HttpHeaderNames.Origin, "example.com")
            .Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket)
            .Set(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade)
            .Set(HttpHeaderNames.SecWebsocketKey, "dGhlIHNhbXBsZSBub25jZQ==")
            .Set(HttpHeaderNames.SecWebsocketOrigin, "http://example.com")
            .Set(HttpHeaderNames.SecWebsocketProtocol, "chat, superchat")
            .Set(HttpHeaderNames.SecWebsocketVersion, WebSocketVersion().ToHttpHeaderValue());
            HttpHeaders customResponseHeaders = new DefaultHttpHeaders();

            // set duplicate required headers and one custom
            customResponseHeaders
            .Set(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade)
            .Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket)
            .Set(AsciiString.Of("custom"), AsciiString.Of("header"));

            if (WebSocketVersion() != Http.WebSockets.WebSocketVersion.V00)
            {
                customResponseHeaders.Set(HttpHeaderNames.SecWebsocketAccept, "12345");
            }

            IFullHttpResponse response = null;

            try
            {
                response = serverHandshaker.NewHandshakeResponse(request, customResponseHeaders);
                HttpHeaders responseHeaders = response.Headers;

                Assert.Equal(1, responseHeaders.GetAll(HttpHeaderNames.Connection).Count);
                Assert.Equal(1, responseHeaders.GetAll(HttpHeaderNames.Upgrade).Count);
                Assert.True(responseHeaders.ContainsValue(AsciiString.Of("custom"), AsciiString.Of("header"), true));
                if (WebSocketVersion() != Http.WebSockets.WebSocketVersion.V00)
                {
                    Assert.False(responseHeaders.ContainsValue(HttpHeaderNames.SecWebsocketAccept, AsciiString.Of("12345"), false));
                }
            }
            finally
            {
                request.Release();
                if (response != null)
                {
                    response.Release();
                }
            }
        }
        static void PerformOpeningHandshake0(bool subProtocol)
        {
            var ch = new EmbeddedChannel(
                new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

            var req = new DefaultFullHttpRequest(Http11, HttpMethod.Get, "/chat");

            req.Headers.Set(HttpHeaderNames.Host, "server.example.com");
            req.Headers.Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket);
            req.Headers.Set(HttpHeaderNames.Connection, "Upgrade");
            req.Headers.Set(HttpHeaderNames.SecWebsocketKey, "dGhlIHNhbXBsZSBub25jZQ==");
            req.Headers.Set(HttpHeaderNames.SecWebsocketOrigin, "http://example.com");
            req.Headers.Set(HttpHeaderNames.SecWebsocketProtocol, "chat, superchat");
            req.Headers.Set(HttpHeaderNames.SecWebsocketVersion, "13");

            WebSocketServerHandshaker13 handshaker;

            if (subProtocol)
            {
                handshaker = new WebSocketServerHandshaker13(
                    "ws://example.com/chat", "chat", false, int.MaxValue, false);
            }
            else
            {
                handshaker = new WebSocketServerHandshaker13(
                    "ws://example.com/chat", null, false, int.MaxValue, false);
            }

            Assert.True(handshaker.HandshakeAsync(ch, req).Wait(TimeSpan.FromSeconds(2)));

            var resBuf = ch.ReadOutbound <IByteBuffer>();

            var ch2 = new EmbeddedChannel(new HttpResponseDecoder());

            ch2.WriteInbound(resBuf);
            var res = ch2.ReadInbound <IHttpResponse>();

            Assert.True(res.Headers.TryGet(HttpHeaderNames.SecWebsocketAccept, out ICharSequence value));
            Assert.Equal("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", value.ToString());
            if (subProtocol)
            {
                Assert.True(res.Headers.TryGet(HttpHeaderNames.SecWebsocketProtocol, out value));
                Assert.Equal("chat", value.ToString());
            }
            else
            {
                Assert.False(res.Headers.TryGet(HttpHeaderNames.SecWebsocketProtocol, out value));
            }
            ReferenceCountUtil.Release(res);
            req.Release();
        }
        static void PerformOpeningHandshake0(bool subProtocol)
        {
            var ch = new EmbeddedChannel(
                new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

            var req = new DefaultFullHttpRequest(Http11, HttpMethod.Get, "/chat",
                                                 Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("^n:ds[4U")));

            req.Headers.Set(HttpHeaderNames.Host, "server.example.com");
            req.Headers.Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket);
            req.Headers.Set(HttpHeaderNames.Connection, "Upgrade");
            req.Headers.Set(HttpHeaderNames.Origin, "http://example.com");
            req.Headers.Set(HttpHeaderNames.SecWebsocketKey1, "4 @1  46546xW%0l 1 5");
            req.Headers.Set(HttpHeaderNames.SecWebsocketKey2, "12998 5 Y3 1  .P00");
            req.Headers.Set(HttpHeaderNames.SecWebsocketProtocol, "chat, superchat");

            WebSocketServerHandshaker00 handshaker;

            if (subProtocol)
            {
                handshaker = new WebSocketServerHandshaker00("ws://example.com/chat", "chat", int.MaxValue);
            }
            else
            {
                handshaker = new WebSocketServerHandshaker00("ws://example.com/chat", null, int.MaxValue);
            }
            Assert.True(handshaker.HandshakeAsync(ch, req).Wait(TimeSpan.FromSeconds(2)));

            var ch2 = new EmbeddedChannel(new HttpResponseDecoder());

            ch2.WriteInbound(ch.ReadOutbound <IByteBuffer>());
            var res = ch2.ReadInbound <IHttpResponse>();

            Assert.True(res.Headers.TryGet(HttpHeaderNames.SecWebsocketLocation, out ICharSequence value));
            Assert.Equal("ws://example.com/chat", value.ToString());

            if (subProtocol)
            {
                Assert.True(res.Headers.TryGet(HttpHeaderNames.SecWebsocketProtocol, out value));
                Assert.Equal("chat", value.ToString());
            }
            else
            {
                Assert.False(res.Headers.TryGet(HttpHeaderNames.SecWebsocketProtocol, out value));
            }
            var content = ch2.ReadInbound <ILastHttpContent>();

            Assert.Equal("8jKS'y:G*Co,Wxa-", content.Content.ToString(Encoding.ASCII));
            content.Release();
            req.Release();
        }
Example #29
0
        private static void NotLeakWhenWrapIllegalArgumentException(IByteBuffer buf)
        {
            buf.WriteCharSequence((AsciiString)"a=b&foo=%22bar%22&==", Encoding.ASCII);
            IFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, "/", buf);

            try
            {
                new HttpPostStandardRequestDecoder(request);
            }
            finally
            {
                Assert.True(request.Release());
            }
        }
Example #30
0
        private static void TestUpgrade(Http2ConnectionHandler handler, IChannelHandler multiplexer)
        {
            IFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Options, "*");

            request.Headers.Set(HttpHeaderNames.Host, "netty.io");
            request.Headers.Set(HttpHeaderNames.Connection, "Upgrade, HTTP2-Settings");
            request.Headers.Set(HttpHeaderNames.Upgrade, "h2c");
            request.Headers.Set((AsciiString)"HTTP2-Settings", "AAMAAABkAAQAAP__");

            var                     parent  = new Mock <IServerChannel>();
            EmbeddedChannel         channel = new EmbeddedChannel(parent.Object, DefaultChannelId.NewInstance(), false, true, new ChannelHandlerAdapter());
            IChannelHandlerContext  ctx     = channel.Pipeline.FirstContext();
            Http2ServerUpgradeCodec codec;

            if (multiplexer == null)
            {
                codec = new Http2ServerUpgradeCodec(handler);
            }
            else
            {
                codec = new Http2ServerUpgradeCodec((Http2FrameCodec)handler, multiplexer);
            }
            Assert.True(codec.PrepareUpgradeResponse(ctx, request, new DefaultHttpHeaders()));
            codec.UpgradeTo(ctx, request);
            // Flush the channel to ensure we write out all buffered data
            channel.Flush();

            channel.WriteInbound(Http2CodecUtil.ConnectionPrefaceBuf());
            Http2FrameInboundWriter writer = new Http2FrameInboundWriter(channel);

            writer.WriteInboundSettings(new Http2Settings());
            writer.WriteInboundRstStream(Http2CodecUtil.HttpUpgradeStreamId, Http2Error.Cancel);

            Assert.Same(handler, channel.Pipeline.Remove <Http2ConnectionHandler>());
            Assert.Null(channel.Pipeline.Get <Http2ConnectionHandler>());
            Assert.True(channel.Finish());

            // Check that the preface was send (a.k.a the settings frame)
            var settingsBuffer = channel.ReadOutbound <IByteBuffer>();

            Assert.NotNull(settingsBuffer);
            settingsBuffer.Release();

            var buf = channel.ReadOutbound <IByteBuffer>();

            Assert.NotNull(buf);
            buf.Release();

            Assert.Null(channel.ReadOutbound());
        }