コード例 #1
0
ファイル: HttpUtilTest.cs プロジェクト: dora-BYR/Fenix
        public void Is100Continue()
        {
            // test all possible cases of 100-continue
            foreach (string continueCase in AllPossibleCasesOfContinue())
            {
                Run100ContinueTest(HttpVersion.Http11, "100-" + continueCase, true);
            }
            Run100ContinueTest(HttpVersion.Http11, null, false);
            Run100ContinueTest(HttpVersion.Http11, "chocolate=yummy", false);
            Run100ContinueTest(HttpVersion.Http10, "100-continue", false);

            var message = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            message.Headers.Set(HttpHeaderNames.Expect, "100-continue");
            Run100ContinueTest(message, false);
        }
コード例 #2
0
#pragma warning disable xUnit1026 // Theory methods should use all of their parameters
        public void ConnectionCloseHeaderHandledCorrectly(bool isKeepAliveResponseExpected, HttpVersion httpVersion, HttpResponseStatus responseStatus, string sendKeepAlive, int setSelfDefinedMessageLength, ICharSequence setResponseConnection)
#pragma warning restore xUnit1026 // Theory methods should use all of their parameters
        {
            var channel  = new EmbeddedChannel(new HttpServerKeepAliveHandler());
            var response = new DefaultFullHttpResponse(httpVersion, responseStatus);

            response.Headers.Set(HttpHeaderNames.Connection, HttpHeaderValues.Close);
            SetupMessageLength(setSelfDefinedMessageLength, response);

            channel.WriteAndFlushAsync(response).Wait(TimeSpan.FromSeconds(1));
            var writtenResponse = channel.ReadOutbound <IHttpResponse>();

            Assert.False(channel.Open);
            ReferenceCountUtil.Release(writtenResponse);
            Assert.False(channel.FinishAndReleaseAll());
        }
コード例 #3
0
ファイル: HttpUtilTest.cs プロジェクト: dora-BYR/Fenix
        public void ContainsUnsupportedExpectation()
        {
            // test all possible cases of 100-continue
            foreach (string continueCase in AllPossibleCasesOfContinue())
            {
                RunUnsupportedExpectationTest(HttpVersion.Http11, "100-" + continueCase, false);
            }
            RunUnsupportedExpectationTest(HttpVersion.Http11, null, false);
            RunUnsupportedExpectationTest(HttpVersion.Http11, "chocolate=yummy", true);
            RunUnsupportedExpectationTest(HttpVersion.Http10, "100-continue", false);

            var message = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            message.Headers.Set(new AsciiString("Expect"), "100-continue");
            RunUnsupportedExpectationTest(message, false);
        }
コード例 #4
0
 public override void ExceptionCaught(IChannelHandlerContext ctx, Exception cause)
 {
     if (cause is WebSocketHandshakeException)
     {
         var response = new DefaultFullHttpResponse(Http11, HttpResponseStatus.BadRequest,
                                                    Unpooled.WrappedBuffer(Encoding.ASCII.GetBytes(cause.Message)));
         ctx.Channel.WriteAndFlushAsync(response)
         .ContinueWith((t, c) => ((IChannelHandlerContext)c).CloseAsync(),
                       ctx, TaskContinuationOptions.ExecuteSynchronously);
     }
     else
     {
         ctx.FireExceptionCaught(cause);
         ctx.CloseAsync();
     }
 }
コード例 #5
0
        protected override IFullHttpResponse NewHandshakeResponse(IFullHttpRequest req, HttpHeaders headers)
        {
            var res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.SwitchingProtocols);

            if (headers != null)
            {
                res.Headers.Add(headers);
            }

            if (!req.Headers.TryGet(HttpHeaderNames.SecWebsocketKey, out ICharSequence key) ||
                key == null)
            {
                throw new WebSocketHandshakeException("not a WebSocket request: missing key");
            }
            string acceptSeed = key + Websocket07AcceptGuid;

            byte[] sha1   = WebSocketUtil.Sha1(Encoding.ASCII.GetBytes(acceptSeed));
            string accept = WebSocketUtil.Base64String(sha1);

            if (Logger.DebugEnabled)
            {
                Logger.Debug("WebSocket version 07 server handshake key: {}, response: {}.", key, accept);
            }

            res.Headers.Add(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket);
            res.Headers.Add(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade);
            res.Headers.Add(HttpHeaderNames.SecWebsocketAccept, accept);


            if (req.Headers.TryGet(HttpHeaderNames.SecWebsocketProtocol, out ICharSequence subprotocols) &&
                subprotocols != null)
            {
                string selectedSubprotocol = this.SelectSubprotocol(subprotocols.ToString());
                if (selectedSubprotocol == null)
                {
                    if (Logger.DebugEnabled)
                    {
                        Logger.Debug("Requested subprotocol(s) not supported: {}", subprotocols);
                    }
                }
                else
                {
                    res.Headers.Add(HttpHeaderNames.SecWebsocketProtocol, selectedSubprotocol);
                }
            }
            return(res);
        }
コード例 #6
0
        public void FullContentWithContentLength()
        {
            var ch = new EmbeddedChannel(new HttpContentCompressor());

            ch.WriteInbound(NewRequest());

            var fullRes = new DefaultFullHttpResponse(
                HttpVersion.Http11,
                HttpResponseStatus.OK,
                Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("Hello, World")));

            fullRes.Headers.Set(HttpHeaderNames.ContentLength, fullRes.Content.ReadableBytes);
            ch.WriteOutbound(fullRes);

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

            Assert.NotNull(res);
            Assert.False(res is IHttpContent, $"{res.GetType()}");

            Assert.False(res.Headers.TryGet(HttpHeaderNames.TransferEncoding, out _));
            Assert.Equal("gzip", res.Headers.Get(HttpHeaderNames.ContentEncoding, null).ToString());

            long contentLengthHeaderValue = HttpUtil.GetContentLength(res);
            long observedLength           = 0;

            var c = ch.ReadOutbound <IHttpContent>();

            observedLength += c.Content.ReadableBytes;
            Assert.Equal($"1f8b08000000000000{Platform}f248cdc9c9d75108cf2fca4901000000ffff", ByteBufferUtil.HexDump(c.Content));
            c.Release();

            c = ch.ReadOutbound <IHttpContent>();
            observedLength += c.Content.ReadableBytes;
            Assert.Equal("0300c6865b260c000000", ByteBufferUtil.HexDump(c.Content));
            c.Release();

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

            Assert.Equal(0, last.Content.ReadableBytes);
            last.Release();

            var next = ch.ReadOutbound();

            Assert.Null(next);
            Assert.Equal(contentLengthHeaderValue, observedLength);
        }
コード例 #7
0
        private void HandleHttpRequest(IChannelHandlerContext ctx, IFullHttpRequest req)
        {
            // Handle a bad request.
            if (!req.Result.IsSuccess)
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, BadRequest));
                return;
            }

            // Allow only GET methods.
            if (!Equals(req.Method, HttpMethod.Get))
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, Forbidden));
                return;
            }

            // Send the demo page and favicon.ico
            if ("/".Equals(req.Uri))
            {
                var res = new DefaultFullHttpResponse(Http11, NotFound);
                SendHttpResponse(ctx, req, res);
                return;
            }

            if ("/favicon.ico".Equals(req.Uri))
            {
                var res = new DefaultFullHttpResponse(Http11, NotFound);
                SendHttpResponse(ctx, req, res);
                return;
            }

            // Handshake
            var wsFactory = new WebSocketServerHandshakerFactory(
                GetWebSocketLocation(req), null, true, 5 * 1024 * 1024);

            this._handshaker = wsFactory.NewHandshaker(req);
            if (this._handshaker == null)
            {
                WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
            }
            else
            {
                this._handshaker.HandshakeAsync(ctx.Channel, req);
            }
        }
コード例 #8
0
 void HandleHttpRequest(IChannelHandlerContext ctx, IFullHttpRequest req)
 {
     // Handle a bad request.
     if (!req.Result.IsSuccess)
     {
         SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, BadRequest));
         return;
     }
     if ("/favicon.ico".Equals(req.Uri))
     {
         var res = new DefaultFullHttpResponse(Http11, NotFound);
         SendHttpResponse(ctx, req, res);
         return;
     }
     if (iJT1078Authorization.Authorization(req, out var principal))
     {
         if (req.Uri.StartsWith(WebsocketPath))
         {
             // Handshake
             var wsFactory = new WebSocketServerHandshakerFactory(GetWebSocketLocation(req), null, true, 5 * 1024 * 1024);
             this.handshaker = wsFactory.NewHandshaker(req);
             if (this.handshaker == null)
             {
                 WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
             }
             else
             {
                 this.handshaker.HandshakeAsync(ctx.Channel, req);
                 jT1078HttpSessionManager.TryAdd(principal.Identity.Name, ctx.Channel);
                 httpMiddleware?.Next(ctx, req, principal);
             }
         }
         else
         {
             jT1078HttpSessionManager.TryAdd(principal.Identity.Name, ctx.Channel);
             httpMiddleware?.Next(ctx, req, principal);
         }
     }
     else
     {
         SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, Unauthorized));
         return;
     }
 }
コード例 #9
0
        protected override void ChannelRead0(IChannelHandlerContext ctx, IHttpRequest req)
        {
            if (HttpUtil.Is100ContinueExpected(req))
            {
                ctx.WriteAsync(new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.Continue, Unpooled.Empty));
            }

            IByteBuffer content = ctx.Allocator.Buffer();

            content.WriteBytes(Response.Duplicate());

            IFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, content);

            response.Headers.Set(HttpHeaderNames.ContentType, "text/html; charset=UTF-8");
            response.Headers.SetInt(HttpHeaderNames.ContentLength, response.Content.ReadableBytes);

            ctx.WriteAsync(response)
            .ContinueWith(t => ctx.CloseAsync(), TaskContinuationOptions.ExecuteSynchronously);
        }
コード例 #10
0
ファイル: OldHttpHandler.cs プロジェクト: sunshyon/NettyFrame
        /// <summary>
        /// 基础返回
        /// </summary>
        /// <param name="status">状态吗</param>
        /// <param name="body"></param>
        /// <param name="headers"></param>
        private IFullHttpResponse GetHttpResponse(HttpResponseStatus status, byte[] body, Dictionary <AsciiString, object> headers)
        {
            DefaultFullHttpResponse result;

            if (body != null && body.Length > 0)
            {
                IByteBuffer bodyBuffer = Unpooled.WrappedBuffer(body);
                result = new DefaultFullHttpResponse(HttpVersion.Http11, status, bodyBuffer);
            }
            else
            {
                result = new DefaultFullHttpResponse(HttpVersion.Http11, status);
            }
            foreach ((AsciiString key, object value) in headers)
            {
                result.Headers.Set(key, value);
            }
            return(result);
        }
コード例 #11
0
        void HandleHttpRequest(IChannelHandlerContext ctx, IFullHttpRequest req)
        {
            if (!req.Result.IsSuccess)
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.BadRequest));
                return;
            }
            if (!Equals(req.Method, HttpMethod.Get))
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.Forbidden));
                return;
            }
            if ("/api".Equals(req.Uri))
            {
                IByteBuffer content = WebSocketServerBenchmarkPage.GetContent(GetWebSocketLocation(req));
                var         res     = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, content);

                res.Headers.Set(HttpHeaderNames.ContentType, "text/html; charset=UTF-8");
                HttpUtil.SetContentLength(res, content.ReadableBytes);

                SendHttpResponse(ctx, req, res);
                return;
            }
            if ("/favicon.ico".Equals(req.Uri))
            {
                var res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound);
                SendHttpResponse(ctx, req, res);
                return;
            }
            // Handshake
            var wsFactory = new WebSocketServerHandshakerFactory(
                GetWebSocketLocation(req), null, true, 5 * 1024 * 1024);

            _handShaker = wsFactory.NewHandshaker(req);
            if (_handShaker == null)
            {
                WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
            }
            else
            {
                _handShaker.HandshakeAsync(ctx.Channel, req);
            }
        }
コード例 #12
0
        void HandlePreflight(IChannelHandlerContext ctx, IHttpRequest req)
        {
            var response = new DefaultFullHttpResponse(req.ProtocolVersion, HttpResponseStatus.OK, true, true);

            if (this.SetOrigin(response))
            {
                this.SetAllowMethods(response);
                this.SetAllowHeaders(response);
                this.SetAllowCredentials(response);
                this.SetMaxAge(response);
                this.SetPreflightHeaders(response);
            }
            if (!response.Headers.Contains(HttpHeaderNames.ContentLength))
            {
                response.Headers.Set(HttpHeaderNames.ContentLength, HttpHeaderValues.Zero);
            }

            Release(req);
            Respond(ctx, req, response);
        }
コード例 #13
0
        void Process(IChannelHandlerContext context, IHttpRequest request)
        {
            string uri = request.Uri;

            switch (uri)
            {
            case "/plaintext":
                this.WriteResponse(context, PlaintextContentBuffer.Duplicate(), TypePlain, PlaintextClheaderValue, HttpUtil.IsKeepAlive(request));
                break;

            case "/json":
                byte[] json = Encoding.UTF8.GetBytes(NewMessage().ToJsonFormat());
                this.WriteResponse(context, Unpooled.WrappedBuffer(json), TypeJson, JsonClheaderValue, HttpUtil.IsKeepAlive(request));
                break;

            default:
                var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false);
                context.WriteAsync(response).CloseOnComplete(context.Channel);
                break;
            }
        }
コード例 #14
0
        void WriteResponse(IChannelHandlerContext context, IByteBuffer buffer, ICharSequence contentType, ICharSequence contentLength, bool keepAlive)
        {
            // Build the response object.
            var         response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, buffer, false);
            HttpHeaders headers  = response.Headers;

            headers.Set(ContentTypeEntity, contentType);
            //headers.Set(ServerEntity, ServerName);
            //headers.Set(DateEntity, this.date);
            headers.Set(ContentLengthEntity, contentLength);

            if (keepAlive)
            {
                response.Headers.Set(HttpHeaderNames.Connection, KeepAlive);
                context.WriteAsync(response);
            }
            else
            {
                context.WriteAsync(response).CloseOnComplete(context.Channel);
            }
        }
コード例 #15
0
        private void HandleHttpRequest(IChannelHandlerContext ctx, IFullHttpRequest req)
        {
            // Handle a bad request.
            if (!req.Result.IsSuccess)
            {
                Extention.SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, BadRequest));
                return;
            }

            // Allow only GET methods.
            if (!Equals(req.Method, HttpMethod.Get))
            {
                Extention.SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, Forbidden));
                return;
            }

            if ("/favicon.ico".Equals(req.Uri))
            {
                var res = new DefaultFullHttpResponse(Http11, NotFound);
                Extention.SendHttpResponse(ctx, req, res);
                return;
            }

            // Handshake
            var wsFactory = new WebSocketServerHandshakerFactory(Extention.GetWebSocketLocation(req, _server._path, _server._useSsl), null, true, 5 * 1024 * 1024);

            handshaker = wsFactory.NewHandshaker(req);

            if (handshaker == null)
            {
                WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
            }
            else
            {
                handshaker.HandshakeAsync(ctx.Channel, req);
            }

            _server.connectionDict.TryGetValue(ctx.Channel.Id.AsShortText(), out WebSocketConnection conn);
            _server._event.OnConnectionConnectAction?.Invoke(conn);
        }
コード例 #16
0
        public void TestUpgradeEmptyFullResponseWithTrailers()
        {
            EmbeddedChannel ch       = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(true));
            var             response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);
            HttpHeaders     trailers = response.TrailingHeaders;

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

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

            Assert.Equal("200", headersFrame.Headers.Status.ToString());
            Assert.False(headersFrame.IsEndStream);

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

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

            Assert.Null(ch.ReadOutbound <object>());
            Assert.False(ch.Finish());
        }
コード例 #17
0
        private void Process(IChannelHandlerContext context, IHttpRequest request)
        {
            string uri = request.Uri;

            switch (uri)
            {
            case "/json":
                var json = Encoding.UTF8.GetBytes(_newMessage().ToJsonFormat());
                WriteResponse(context, Unpooled.WrappedBuffer(json), _typeJson, _jsonClheaderValue);
                break;

            case "/404":
                var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false);
                context.WriteAndFlushAsync(response);
                context.CloseAsync();
                break;

            default:
                WriteResponse(context, _plaintextContentBuffer.Duplicate(), _typePlain, _plaintextClheaderValue);
                break;
            }
        }
コード例 #18
0
        protected override void Encode(IChannelHandlerContext ctx, IResponseMessage msg, List <object> output)
        {
            var buf      = msg.ToBodyBuffer();
            var status   = HttpResponseStatus.ValueOf(Convert.ToInt32(msg.Headers.Get(Constants.ResponseStatusCode)));
            var response = new DefaultFullHttpResponse(HttpVersion.Http11, status, buf, false);

            HttpHeaders headers = response.Headers;

            headers.Set(HttpHeaderNames.Server, AsciiString.Cached(Options.Name));
            headers.Set(HttpHeaderNames.Date, this.date);
            headers.Set(HttpHeaderNames.ContentLength, AsciiString.Cached($"{msg.Headers.Get(Constants.Headers.ContentLength)}"));

            if (Convert.ToInt32(msg.Headers.Get(Constants.Headers.ContractId)) == (int)ContractType.HandShake)
            {
                headers.Set(HttpHeaderNames.ContentType, AsciiString.Cached("text/plain"));
            }
            else
            {
                headers.Set(HttpHeaderNames.ContentType, AsciiString.Cached(msg.Headers.Get(Constants.Headers.ContentType)));
            }
            output.Add(response);
        }
コード例 #19
0
        public void Status100Continue()
        {
            IFullHttpRequest request = NewRequest();

            HttpUtil.Set100ContinueExpected(request, true);

            var ch = new EmbeddedChannel(new HttpContentCompressor());

            ch.WriteInbound(request);

            var continueResponse = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.Continue, Unpooled.Empty);

            ch.WriteOutbound(continueResponse);

            IFullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, Unpooled.Empty);

            res.TrailingHeaders.Set((AsciiString)"X-Test", (AsciiString)"Netty");
            ch.WriteOutbound(res);

            res = ch.ReadOutbound <IFullHttpResponse>();
            Assert.NotNull(res);
            Assert.Same(continueResponse, res);
            res.Release();

            res = ch.ReadOutbound <IFullHttpResponse>();
            Assert.NotNull(res);
            Assert.False(res.Headers.TryGet(HttpHeaderNames.TransferEncoding, out _));

            // Content encoding shouldn't be modified.
            Assert.False(res.Headers.TryGet(HttpHeaderNames.ContentEncoding, out _));
            Assert.Equal(0, res.Content.ReadableBytes);
            Assert.Equal("", res.Content.ToString(Encoding.ASCII));
            Assert.Equal("Netty", res.TrailingHeaders.Get((AsciiString)"X-Test", null));

            var last = ch.ReadOutbound <object>();

            Assert.Null(last);
        }
コード例 #20
0
        void Process(IChannelHandlerContext ctx, IFullHttpRequest request)
        {
            var    ctssc = ctx.Channel as CustHttpSocketChannel;
            string ClientId;
            string uri           = request.Uri;
            var    appkey        = getAppKeyFromUri(request.Uri);
            var    clientchannel = obtainClientChannel(ctx, appkey) as CustHttpSocketChannel;

            if (clientchannel == null)
            {
                var response = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false);
                ctx.WriteAndFlushAsync(response);
                ctx.CloseAsync();
                return;
            }

            int pos = request.Uri.IndexOf("/" + appkey);
            var tmp = request.Uri.Substring(pos + appkey.Length + 1);

            DefaultFullHttpRequest forwardrequest = new DefaultFullHttpRequest(request.ProtocolVersion, request.Method,
                                                                               tmp, request.Content);
            var bytecount = request.Content.ReadableBytes + request.Method.ToString().Length + tmp.Length + request.ProtocolVersion.ToString().Length;

            foreach (var obj in request.Headers)
            {
                bytecount = bytecount + obj.Key.Count + 3 + obj.Value.Count;
                forwardrequest.Headers.Set(obj.Key, obj.Value);
            }

            if (!clientchannel.ChannelMata.tags.ContainsKey("readStart"))
            {
                clientchannel.ChannelMata.tags.AddOrUpdate("readStart", DateTime.Now, (key, value) => value);
            }

            (clientchannel as CustHttpSocketChannel).outMapPort.addRecvBytes(bytecount);

            clientchannel.WriteAndFlushAsync(forwardrequest);
        }
コード例 #21
0
        public void Identity()
        {
            var ch = new EmbeddedChannel(new HttpContentCompressor());

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

            var res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK,
                                                  Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("Hello, World")));
            int len = res.Content.ReadableBytes;

            res.Headers.Set(HttpHeaderNames.ContentLength, len);
            res.Headers.Set(HttpHeaderNames.ContentEncoding, HttpHeaderValues.Identity);
            Assert.True(ch.WriteOutbound(res));

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

            Assert.Equal(len.ToString(), response.Headers.Get(HttpHeaderNames.ContentLength, null).ToString());
            Assert.Equal(HttpHeaderValues.Identity.ToString(), response.Headers.Get(HttpHeaderNames.ContentEncoding, null).ToString());
            Assert.Equal("Hello, World", response.Content.ToString(Encoding.ASCII));
            response.Release();

            Assert.True(ch.FinishAndReleaseAll());
        }
コード例 #22
0
            protected override bool HandleProxyProtocol(IChannelHandlerContext ctx, object msg)
            {
                var req = (IFullHttpRequest)msg;
                IFullHttpResponse res;

                if (!_server.Authenticate(ctx, req))
                {
                    res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.Unauthorized);
                    res.Headers.Set(HttpHeaderNames.ContentLength, 0);
                }
                else
                {
                    res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);
                    var uri          = req.Uri;
                    var lastColonPos = uri.LastIndexOf(':');
                    Assert.True(lastColonPos > 0);
                    IntermediaryDestination = new DnsEndPoint(uri.Substring(0, lastColonPos),
                                                              int.Parse(uri.Substring(lastColonPos + 1)));
                }

                ctx.WriteAsync(res);
                ctx.Pipeline.Get <HttpServerCodec>().RemoveOutboundHandler();
                return(true);
            }
コード例 #23
0
        public void EmptyFullContent()
        {
            var ch = new EmbeddedChannel(new TestEncoder());

            ch.WriteInbound(new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, "/"));

            IFullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, Unpooled.Empty);

            ch.WriteOutbound(res);

            res = ch.ReadOutbound <IFullHttpResponse>();
            Assert.NotNull(res);
            Assert.False(res.Headers.TryGet(HttpHeaderNames.TransferEncoding, out _));

            // Content encoding shouldn't be modified.
            Assert.False(res.Headers.TryGet(HttpHeaderNames.ContentEncoding, out _));
            Assert.Equal(0, res.Content.ReadableBytes);
            Assert.Equal("", res.Content.ToString(Encoding.ASCII));
            res.Release();

            var next = ch.ReadOutbound <object>();

            Assert.Null(next);
        }
コード例 #24
0
 public static async Task OnEnd(IChannelHandlerContext ctx, object message)
 {
     try
     {
         Channel channel = null;
         bool    success = upChannels.TryGetValue(ctx.Channel, out channel);
         if (success)
         {
             var         oldContext = channel;
             var         response   = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.OK, Unpooled.Empty, false);
             HttpHeaders headers    = response.Headers;
             headers.Set(ContentTypeEntity, TypePlain);
             headers.Set(ServerEntity, ServerName);
             int StaticPlaintextLen = 0;
             headers.Set(ContentLengthEntity, AsciiString.Cached($"{StaticPlaintextLen}"));
             oldContext.request.WriteAndFlushAsync(message as IFullHttpResponse).ConfigureAwait(false);
             freeChannels.Enqueue(channel);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message + ex.StackTrace);
     }
 }
コード例 #25
0
        internal static DefaultFullHttpResponse ExceptionCaught(Exception cause)
        {
            Exception e = cause is Exception ? (Exception)cause : new Exception(cause);

            if (Log.IsTraceEnabled())
            {
                Log.Trace("GOT EXCEPITION", e);
            }
            //Convert exception
            if (e is ParamException)
            {
                ParamException paramexception = (ParamException)e;
                e = new ArgumentException("Invalid value for webhdfs parameter \"" + paramexception
                                          .GetParameterName() + "\": " + e.InnerException.Message, e);
            }
            else
            {
                if (e is ContainerException || e is SecurityException)
                {
                    e = ToCause(e);
                }
                else
                {
                    if (e is RemoteException)
                    {
                        e = ((RemoteException)e).UnwrapRemoteException();
                    }
                }
            }
            //Map response status
            HttpResponseStatus s;

            if (e is SecurityException)
            {
                s = HttpResponseStatus.Forbidden;
            }
            else
            {
                if (e is AuthorizationException)
                {
                    s = HttpResponseStatus.Forbidden;
                }
                else
                {
                    if (e is FileNotFoundException)
                    {
                        s = HttpResponseStatus.NotFound;
                    }
                    else
                    {
                        if (e is IOException)
                        {
                            s = HttpResponseStatus.Forbidden;
                        }
                        else
                        {
                            if (e is NotSupportedException)
                            {
                                s = HttpResponseStatus.BadRequest;
                            }
                            else
                            {
                                if (e is ArgumentException)
                                {
                                    s = HttpResponseStatus.BadRequest;
                                }
                                else
                                {
                                    Log.Warn("INTERNAL_SERVER_ERROR", e);
                                    s = HttpResponseStatus.InternalServerError;
                                }
                            }
                        }
                    }
                }
            }
            byte[] js = Sharpen.Runtime.GetBytesForString(JsonUtil.ToJsonString(e), Charsets.
                                                          Utf8);
            DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.Http11, s,
                                                                       Unpooled.WrappedBuffer(js));

            resp.Headers().Set(HttpHeaders.Names.ContentType, WebHdfsHandler.ApplicationJsonUtf8
                               );
            resp.Headers().Set(HttpHeaders.Names.ContentLength, js.Length);
            return(resp);
        }
コード例 #26
0
        protected override void ChannelRead0(IChannelHandlerContext context, IFullHttpRequest request)
        {
            var res = new DefaultFullHttpResponse(request.ProtocolVersion, NotFound, context.Allocator.Buffer(0));

            SendHttpResponse(context, request, res);
        }
コード例 #27
0
        public void ServerRequestPushPromise()
        {
            this.BootstrapEnv(1, 1, 1);
            string           text     = "hello world big time data!";
            IByteBuffer      content  = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text));
            string           text2    = "hello world smaller data?";
            IByteBuffer      content2 = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text2));
            IFullHttpMessage response = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.OK,
                                                                    content, true);
            IFullHttpMessage response2 = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.Created,
                                                                     content2, true);
            IFullHttpMessage request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Get, "/push/test",
                                                                  true);

            try
            {
                HttpHeaders httpHeaders = response.Headers;
                httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3);
                httpHeaders.SetInt(HttpHeaderNames.ContentLength, text.Length);
                httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16);
                HttpHeaders httpHeaders2 = response2.Headers;
                httpHeaders2.Set(HttpConversionUtil.ExtensionHeaderNames.Scheme, "https");
                httpHeaders2.Set(HttpHeaderNames.Host, "example.org");
                httpHeaders2.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 5);
                httpHeaders2.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamDependencyId, 3);
                httpHeaders2.SetInt(HttpHeaderNames.ContentLength, text2.Length);

                httpHeaders = request.Headers;
                httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3);
                httpHeaders.SetInt(HttpHeaderNames.ContentLength, 0);
                httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16);
                var http2Headers3 = new DefaultHttp2Headers()
                {
                    Method = new AsciiString("GET"),
                    Path   = new AsciiString("/push/test"),
                };
                Http2TestUtil.RunInChannel(this.clientChannel, () =>
                {
                    this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 3, http2Headers3, 0, true, this.NewPromiseClient());
                    this.clientChannel.Flush();
                });
                this.AwaitRequests();
                var requestCaptor = new ArgumentCaptor <IFullHttpMessage>();
                this.serverListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => requestCaptor.Capture((IFullHttpMessage)v))));
                this.capturedRequests = requestCaptor.GetAllValues();
                Assert.Equal(request, (IFullHttpRequest)this.capturedRequests[0]);

                IHttp2Headers http2Headers = new DefaultHttp2Headers()
                {
                    Status = new AsciiString("200")
                };
                // The PUSH_PROMISE frame includes a header block that contains a
                // complete set of request header fields that the server attributes to
                // the request.
                // https://tools.ietf.org/html/rfc7540#section-8.2.1
                // Therefore, we should consider the case where there is no Http response status.
                IHttp2Headers http2Headers2 = new DefaultHttp2Headers()
                {
                    Scheme    = new AsciiString("https"),
                    Authority = new AsciiString("example.org")
                };
                Http2TestUtil.RunInChannel(this.serverConnectedChannel, () =>
                {
                    this.serverHandler.Encoder.WriteHeadersAsync(this.CtxServer(), 3, http2Headers, 0, false, this.NewPromiseServer());
                    this.serverHandler.Encoder.WritePushPromiseAsync(this.CtxServer(), 3, 2, http2Headers2, 0, this.NewPromiseServer());
                    this.serverHandler.Encoder.WriteDataAsync(this.CtxServer(), 3, content.RetainedDuplicate(), 0, true, this.NewPromiseServer());
                    this.serverHandler.Encoder.WriteDataAsync(this.CtxServer(), 5, content2.RetainedDuplicate(), 0, true, this.NewPromiseServer());
                    this.serverConnectedChannel.Flush();
                });
                this.AwaitResponses();
                var responseCaptor = new ArgumentCaptor <IFullHttpMessage>();
                this.clientListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => responseCaptor.Capture((IFullHttpMessage)v))));
                this.capturedResponses = responseCaptor.GetAllValues();
                Assert.Equal(response, this.capturedResponses[0]);
            }
            finally
            {
                request.Release();
                response.Release();
                response2.Release();
            }
        }
コード例 #28
0
        public void ServerResponseHeaderInformational()
        {
            this.BootstrapEnv(1, 2, 1, 2, 1);
            IFullHttpMessage request     = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Put, "/info/test", true);
            HttpHeaders      httpHeaders = request.Headers;

            httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3);
            httpHeaders.Set(HttpHeaderNames.Expect, HttpHeaderValues.Continue);
            httpHeaders.SetInt(HttpHeaderNames.ContentLength, 0);
            httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16);

            IHttp2Headers http2Headers = new DefaultHttp2Headers()
            {
                Method = new AsciiString("PUT"),
                Path   = new AsciiString("/info/test")
            };

            http2Headers.Set(new AsciiString(HttpHeaderNames.Expect.ToString()), new AsciiString(HttpHeaderValues.Continue.ToString()));
            IFullHttpMessage response  = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.Continue);
            string           text      = "a big payload";
            IByteBuffer      payload   = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text));
            IFullHttpMessage request2  = (IFullHttpMessage)request.Replace(payload);
            IFullHttpMessage response2 = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.OK);

            try
            {
                Http2TestUtil.RunInChannel(this.clientChannel, () =>
                {
                    this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 3, http2Headers, 0, false, this.NewPromiseClient());
                    this.clientChannel.Flush();
                });

                this.AwaitRequests();
                httpHeaders = response.Headers;
                httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3);
                httpHeaders.SetInt(HttpHeaderNames.ContentLength, 0);
                IHttp2Headers http2HeadersResponse = new DefaultHttp2Headers()
                {
                    Status = new AsciiString("100")
                };
                Http2TestUtil.RunInChannel(this.serverConnectedChannel, () =>
                {
                    this.serverHandler.Encoder.WriteHeadersAsync(this.CtxServer(), 3, http2HeadersResponse, 0, false, this.NewPromiseServer());
                    this.serverConnectedChannel.Flush();
                });

                this.AwaitResponses();
                httpHeaders = request2.Headers;
                httpHeaders.SetInt(HttpHeaderNames.ContentLength, text.Length);
                httpHeaders.Remove(HttpHeaderNames.Expect);
                Http2TestUtil.RunInChannel(this.clientChannel, () =>
                {
                    this.clientHandler.Encoder.WriteDataAsync(this.CtxClient(), 3, payload.RetainedDuplicate(), 0, true, this.NewPromiseClient());
                    this.clientChannel.Flush();
                });

                this.AwaitRequests2();
                httpHeaders = response2.Headers;
                httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3);
                httpHeaders.SetInt(HttpHeaderNames.ContentLength, 0);
                httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16);

                IHttp2Headers http2HeadersResponse2 = new DefaultHttp2Headers()
                {
                    Status = new AsciiString("200")
                };
                Http2TestUtil.RunInChannel(this.serverConnectedChannel, () =>
                {
                    this.serverHandler.Encoder.WriteHeadersAsync(this.CtxServer(), 3, http2HeadersResponse2, 0, true, this.NewPromiseServer());
                    this.serverConnectedChannel.Flush();
                });

                this.AwaitResponses2();
                var requestCaptor = new ArgumentCaptor <IFullHttpMessage>();
                this.serverListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => requestCaptor.Capture((IFullHttpMessage)v))), Times.Exactly(2));
                this.capturedRequests = requestCaptor.GetAllValues();
                Assert.Equal(2, this.capturedRequests.Count);
                // We do not expect to have this header in the captured request so remove it now.
                Assert.NotNull(request.Headers.Remove((AsciiString)"x-http2-stream-weight"));

                Assert.Equal(request, (IFullHttpRequest)this.capturedRequests[0]);
                Assert.Equal(request2, this.capturedRequests[1]);

                var responseCaptor = new ArgumentCaptor <IFullHttpMessage>();
                this.clientListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => responseCaptor.Capture((IFullHttpMessage)v))), Times.Exactly(2));
                this.capturedResponses = responseCaptor.GetAllValues();
                Assert.Equal(2, this.capturedResponses.Count);
                Assert.Equal(response, this.capturedResponses[0]);
                Assert.Equal(response2, this.capturedResponses[1]);
            }
            finally
            {
                request.Release();
                request2.Release();
                response.Release();
                response2.Release();
            }
        }
コード例 #29
0
        protected override IFullHttpResponse NewHandshakeResponse(IFullHttpRequest req, HttpHeaders headers)
        {
            // Serve the WebSocket handshake request.
            if (!req.Headers.ContainsValue(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade, true) ||
                !req.Headers.TryGet(HttpHeaderNames.Upgrade, out ICharSequence value) ||
                !HttpHeaderValues.Websocket.ContentEqualsIgnoreCase(value))
            {
                throw new WebSocketHandshakeException("not a WebSocket handshake request: missing upgrade");
            }

            // Hixie 75 does not contain these headers while Hixie 76 does
            bool isHixie76 = req.Headers.Contains(HttpHeaderNames.SecWebsocketKey1) &&
                             req.Headers.Contains(HttpHeaderNames.SecWebsocketKey2);

            // Create the WebSocket handshake response.
            var res = new DefaultFullHttpResponse(HttpVersion.Http11,
                                                  new HttpResponseStatus(101, new AsciiString(isHixie76 ? "WebSocket Protocol Handshake" : "Web Socket Protocol Handshake")));

            if (headers != null)
            {
                res.Headers.Add(headers);
            }

            res.Headers.Add(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket);
            res.Headers.Add(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade);

            // Fill in the headers and contents depending on handshake getMethod.
            if (isHixie76)
            {
                // New handshake getMethod with a challenge:
                value = req.Headers.Get(HttpHeaderNames.Origin, null);
                Debug.Assert(value != null);
                res.Headers.Add(HttpHeaderNames.SecWebsocketOrigin, value);
                res.Headers.Add(HttpHeaderNames.SecWebsocketLocation, this.Uri);

                if (req.Headers.TryGet(HttpHeaderNames.SecWebsocketProtocol, out ICharSequence subprotocols))
                {
                    string selectedSubprotocol = this.SelectSubprotocol(subprotocols.ToString());
                    if (selectedSubprotocol == null)
                    {
                        if (Logger.DebugEnabled)
                        {
                            Logger.Debug("Requested subprotocol(s) not supported: {}", subprotocols);
                        }
                    }
                    else
                    {
                        res.Headers.Add(HttpHeaderNames.SecWebsocketProtocol, selectedSubprotocol);
                    }
                }

                // Calculate the answer of the challenge.
                value = req.Headers.Get(HttpHeaderNames.SecWebsocketKey1, null);
                Debug.Assert(value != null, $"{HttpHeaderNames.SecWebsocketKey1} must exist");
                string key1 = value.ToString();
                value = req.Headers.Get(HttpHeaderNames.SecWebsocketKey2, null);
                Debug.Assert(value != null, $"{HttpHeaderNames.SecWebsocketKey2} must exist");
                string key2 = value.ToString();
                int    a    = (int)(long.Parse(BeginningDigit.Replace(key1, "")) /
                                    BeginningSpace.Replace(key1, "").Length);
                int b = (int)(long.Parse(BeginningDigit.Replace(key2, "")) /
                              BeginningSpace.Replace(key2, "").Length);
                long        c     = req.Content.ReadLong();
                IByteBuffer input = Unpooled.Buffer(16);
                input.WriteInt(a);
                input.WriteInt(b);
                input.WriteLong(c);
                res.Content.WriteBytes(WebSocketUtil.Md5(input.Array));
            }
            else
            {
                // Old Hixie 75 handshake getMethod with no challenge:
                value = req.Headers.Get(HttpHeaderNames.Origin, null);
                Debug.Assert(value != null);
                res.Headers.Add(HttpHeaderNames.WebsocketOrigin, value);
                res.Headers.Add(HttpHeaderNames.WebsocketLocation, this.Uri);

                if (req.Headers.TryGet(HttpHeaderNames.WebsocketProtocol, out ICharSequence protocol))
                {
                    res.Headers.Add(HttpHeaderNames.WebsocketProtocol, this.SelectSubprotocol(protocol.ToString()));
                }
            }

            return(res);
        }
コード例 #30
0
        /// <summary>
        /// <para>
        /// Handle the web socket handshake for the web socket specification <a href=
        /// "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00">HyBi version 0</a> and lower. This standard
        /// is really a rehash of <a href="http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76" >hixie-76</a> and
        /// <a href="http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75" >hixie-75</a>.
        /// </para>
        ///
        /// <para>
        /// Browser request to the server:
        /// </para>
        ///
        /// <![CDATA[
        /// GET /demo HTTP/1.1
        /// Upgrade: WebSocket
        /// Connection: Upgrade
        /// Host: example.com
        /// Origin: http://example.com
        /// Sec-WebSocket-Protocol: chat, sample
        /// Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5
        /// Sec-WebSocket-Key2: 12998 5 Y3 1  .P00
        ///
        /// ^n:ds[4U
        /// ]]>
        ///
        /// <para>
        /// Server response:
        /// </para>
        ///
        /// <![CDATA[
        /// HTTP/1.1 101 WebSocket Protocol Handshake
        /// Upgrade: WebSocket
        /// Connection: Upgrade
        /// Sec-WebSocket-Origin: http://example.com
        /// Sec-WebSocket-Location: ws://example.com/demo
        /// Sec-WebSocket-Protocol: sample
        ///
        /// 8jKS'y:G*Co,Wxa-
        /// ]]>
        /// </summary>
        /// <param name="req"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        protected override IFullHttpResponse NewHandshakeResponse(IFullHttpRequest req, HttpHeaders headers)
        {
            // Serve the WebSocket handshake request.
            if (!req.Headers.ContainsValue(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade, true) ||
                !req.Headers.TryGet(HttpHeaderNames.Upgrade, out ICharSequence value) ||
                !HttpHeaderValues.Websocket.ContentEqualsIgnoreCase(value))
            {
                ThrowHelper.ThrowWebSocketHandshakeException_MissingUpgrade();
            }

            // Hixie 75 does not contain these headers while Hixie 76 does
            bool isHixie76 = req.Headers.Contains(HttpHeaderNames.SecWebsocketKey1) &&
                             req.Headers.Contains(HttpHeaderNames.SecWebsocketKey2);

            var origin = req.Headers.Get(HttpHeaderNames.Origin, null);

            //throw before allocating FullHttpResponse
            if (origin is null && !isHixie76)
            {
                ThrowHelper.ThrowWebSocketHandshakeException_Missing_origin_header(req);
            }

            // Create the WebSocket handshake response.
            var res = new DefaultFullHttpResponse(HttpVersion.Http11, new HttpResponseStatus(101,
                                                                                             new AsciiString(isHixie76 ? "WebSocket Protocol Handshake" : "Web Socket Protocol Handshake")),
                                                  req.Content.Allocator.Buffer(0));

            if (headers is object)
            {
                _ = res.Headers.Add(headers);
            }

            _ = res.Headers.Add(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket);
            _ = res.Headers.Add(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade);

            // Fill in the headers and contents depending on handshake getMethod.
            if (isHixie76)
            {
                // New handshake getMethod with a challenge:
                _ = res.Headers.Add(HttpHeaderNames.SecWebsocketOrigin, origin);
                _ = res.Headers.Add(HttpHeaderNames.SecWebsocketLocation, this.Uri);

                if (req.Headers.TryGet(HttpHeaderNames.SecWebsocketProtocol, out ICharSequence subprotocols))
                {
                    string selectedSubprotocol = this.SelectSubprotocol(subprotocols.ToString());
                    if (selectedSubprotocol is null)
                    {
                        if (Logger.DebugEnabled)
                        {
                            Logger.RequestedSubprotocolNotSupported(subprotocols);
                        }
                    }
                    else
                    {
                        _ = res.Headers.Add(HttpHeaderNames.SecWebsocketProtocol, selectedSubprotocol);
                    }
                }

                // Calculate the answer of the challenge.
                value = req.Headers.Get(HttpHeaderNames.SecWebsocketKey1, null);
                Debug.Assert(value is object, $"{HttpHeaderNames.SecWebsocketKey1} must exist");
                string key1 = value.ToString();
                value = req.Headers.Get(HttpHeaderNames.SecWebsocketKey2, null);
                Debug.Assert(value is object, $"{HttpHeaderNames.SecWebsocketKey2} must exist");
                string key2 = value.ToString();
                int    a    = (int)(long.Parse(BeginningDigit.Replace(key1, "")) /
                                    BeginningSpace.Replace(key1, "").Length);
                int b = (int)(long.Parse(BeginningDigit.Replace(key2, "")) /
                              BeginningSpace.Replace(key2, "").Length);
                long        c     = req.Content.ReadLong();
                IByteBuffer input = Unpooled.WrappedBuffer(new byte[16]).SetIndex(0, 0);
                _ = input.WriteInt(a);
                _ = input.WriteInt(b);
                _ = input.WriteLong(c);
                _ = res.Content.WriteBytes(WebSocketUtil.Md5(input.Array));
            }
            else
            {
                // Old Hixie 75 handshake getMethod with no challenge:
                _ = res.Headers.Add(HttpHeaderNames.WebsocketOrigin, origin);
                _ = res.Headers.Add(HttpHeaderNames.WebsocketLocation, this.Uri);

                if (req.Headers.TryGet(HttpHeaderNames.WebsocketProtocol, out ICharSequence protocol))
                {
                    _ = res.Headers.Add(HttpHeaderNames.WebsocketProtocol, this.SelectSubprotocol(protocol.ToString()));
                }
            }

            return(res);
        }