void HandleHttpRequest(IChannelHandlerContext ctx, IFullHttpRequest req)
        {
            // Handle a bad request.
            if (!req.Result.IsSuccess)
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.BadRequest));
                return;
            }

            // Allow only GET methods.
            if (req.Method.ToString().ToUpper() != "GET")
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.Forbidden));
                return;
            }

            //Wesocket握手协议
            if (req.Uri == _path)
            {
                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);
                }
            }
        }
Beispiel #2
0
        void HandleHttpRequest(IChannelHandlerContext ctx, IFullHttpRequest req)
        {
            if (!req.Result.IsSuccess)
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.BadRequest));
                return;
            }
            if (req.Uri.Equals(WebsocketPath))
            {
                var wsFactory = new WebSocketServerHandshakerFactory(
                    GetWebSocketLocation(req), null, true, _webSocketConfig.MaxMessageLength);
                _handShaker = wsFactory.NewHandshaker(req);
                if (_handShaker == null)
                {
                    WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
                }
                else
                {
                    _handShaker.HandshakeAsync(ctx.Channel, req);
                }
                ConsoleHelper.ConDepServerWriteLine($"新的连接{ctx.Channel.Id}");
                return;
            }
            if (req.Uri.Equals("/favicon.ico"))
            {
                var res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound);
                SendHttpResponse(ctx, req, res);
                return;
            }
            var httpHandler = new HttpHandler();
            DefaultFullHttpResponse httpResponse = httpHandler.GetResponse(req);

            SendHttpResponse(ctx, req, httpResponse);
        }
Beispiel #3
0
        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;
            }

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

            _handshaker = wsFactory.NewHandshaker(req);
            if (this._handshaker == null)
            {
                WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
            }
            else
            {
                _logger.LogInformation($"New client to handshake:{ctx.Channel}");
                var appSession = new AppSession();
                appSession.Initialize(ctx.Channel, ctx.Channel.RemoteAddress);
                _appSessionContainer.Set(ctx.Channel.Id.ToString(), appSession);
                _handshaker.HandshakeAsync(ctx.Channel, req);
            }
        }
Beispiel #4
0
        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))
            {
                IByteBuffer content = Unpooled.WrappedBuffer(Encoding.ASCII.GetBytes(
                                                                 "<html><head><title>XMPP WebSocket Proxy</title></head>" + Environment.NewLine +
                                                                 "<body>" + Environment.NewLine +
                                                                 "<h1>XMPP WebSocket server</h1>" + Environment.NewLine +
                                                                 "<p>running at: " + GetWebSocketLocation(req) + "</p>" + Environment.NewLine +
                                                                 "</body>" + Environment.NewLine +
                                                                 "</html>"));

                var res = new DefaultFullHttpResponse(Http11, 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(Http11, NotFound);
                SendHttpResponse(ctx, req, res);
                return;
            }

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

            this.handshaker = wsFactory.NewHandshaker(req);
            if (this.handshaker == null)
            {
                WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
            }
            else
            {
                this.handshaker.HandshakeAsync(ctx.Channel, req);
            }
        }
        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();
                }
            }
        }
        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))
            {
                IByteBuffer content = WebSocketServerBenchmarkPage.GetContent(GetWebSocketLocation(req));
                var         res     = new DefaultFullHttpResponse(Http11, 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(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);
            }
        }
        private void HandleHttpRequest(IChannelHandlerContext context, IFullHttpRequest request)
        {
            // Handle a bad request.
            if (!request.Result.IsSuccess)
            {
                SendHttpResponse(context, request, new DefaultFullHttpResponse(Http11, BadRequest));
                return;
            }

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

            // Send the demo page and favicon.ico
            if ("/".Equals(request.Uri, StringComparison.OrdinalIgnoreCase))
            {
                var content  = WebSocketServerBenchmarkPage.GetContent(GetWebSocketLocation(request));
                var response = new DefaultFullHttpResponse(Http11, OK, content);

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

                SendHttpResponse(context, request, response);
                return;
            }
            if ("/favicon.ico".Equals(request.Uri, StringComparison.OrdinalIgnoreCase))
            {
                var res = new DefaultFullHttpResponse(Http11, NotFound);
                SendHttpResponse(context, request, res);
                return;
            }

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

            handshaker = wsFactory.NewHandshaker(request);
            if (handshaker.IsNull())
            {
                WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(context.Channel);
            }
            else
            {
                handshaker.HandshakeAsync(context.Channel, request);
            }
        }
        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);
            }
        }
 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;
     }
 }
Beispiel #10
0
        /// <summary>
        /// WebSocker握手
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="request"></param>
        private void WebSockerHandshake(IChannelHandlerContext ctx, IFullHttpRequest request)
        {
            //获取websocker路径
            bool   result   = request.Headers.TryGet(HttpHeaderNames.Host, out ICharSequence value);
            string location = value.ToString() + websocketPath;
            // Handshake 握手
            var wsFactory = new WebSocketServerHandshakerFactory(
                location, null, true, 5 * 1024 * 1024);

            this.handshaker = wsFactory.NewHandshaker(request);
            if (this.handshaker == null)
            {
                WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
            }
            else
            {
                this.handshaker.HandshakeAsync(ctx.Channel, request);
            }
        }
Beispiel #11
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);
        }
 protected override void ChannelRead0(IChannelHandlerContext ctx, object msg)
 {
     if (msg is IFullHttpRequest request)
     {
         // Handshake
         var wsFactory = new WebSocketServerHandshakerFactory(
             GetWebSocketLocation(request), null, true, 5 * 1024 * 1024);
         this.handshaker = wsFactory.NewHandshaker(request);
         if (this.handshaker == null)
         {
             WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
         }
         else
         {
             this.handshaker.HandshakeAsync(ctx.Channel, request);
         }
     }
     else if (msg is WebSocketFrame frame)
     {
         this.HandleWebSocketFrame(ctx, frame);
     }
 }
        protected override void ChannelRead0(IChannelHandlerContext ctx, WebSocketFrame frame)
        {
            WebSocketServerHandshaker handshaker = ctx.GetAttribute(wshsKey).Get();

            // Check for closing frame
            if (frame is CloseWebSocketFrame)
            {
                handshaker.CloseAsync(ctx.Channel, (CloseWebSocketFrame)frame.Retain());
                return;
            }

            if (frame is PingWebSocketFrame)
            {
                ctx.WriteAsync(new PongWebSocketFrame((IByteBuffer)frame.Content.Retain()));
                return;
            }

            if (frame is TextWebSocketFrame text)
            {
                var uri     = text.Text();
                var textmsg = messageFactory.Parse(uri);
                if (textmsg != null)
                {
                    ctx.FireChannelRead(textmsg);
                }
                return;
            }

            if (frame is BinaryWebSocketFrame)
            {
                var binarymsg = messageFactory.Parse(frame.Content);
                if (binarymsg != null)
                {
                    ctx.FireChannelRead(binarymsg);
                }
                return;
            }
        }
Beispiel #14
0
        void TestHttpResponseAndFrameInSameBuffer(bool codec)
        {
            string url = "ws://localhost:9999/ws";
            WebSocketClientHandshaker shaker = this.NewHandshaker(new Uri(url));
            var handshaker = new Handshaker(shaker);

            // use randomBytes helper from utils to check that it functions properly
            byte[] data = WebSocketUtil.RandomBytes(24);

            // Create a EmbeddedChannel which we will use to encode a BinaryWebsocketFrame to bytes and so use these
            // to test the actual handshaker.
            var factory = new WebSocketServerHandshakerFactory(url, null, false);
            IFullHttpRequest          request = shaker.NewHandshakeRequest();
            WebSocketServerHandshaker socketServerHandshaker = factory.NewHandshaker(request);

            request.Release();
            var websocketChannel = new EmbeddedChannel(socketServerHandshaker.NewWebSocketEncoder(),
                                                       socketServerHandshaker.NewWebsocketDecoder());

            Assert.True(websocketChannel.WriteOutbound(new BinaryWebSocketFrame(Unpooled.WrappedBuffer(data))));

            byte[] bytes = Encoding.ASCII.GetBytes("HTTP/1.1 101 Switching Protocols\r\nContent-Length: 0\r\n\r\n");

            CompositeByteBuffer compositeByteBuf = Unpooled.CompositeBuffer();

            compositeByteBuf.AddComponent(true, Unpooled.WrappedBuffer(bytes));
            for (; ;)
            {
                var frameBytes = websocketChannel.ReadOutbound <IByteBuffer>();
                if (frameBytes == null)
                {
                    break;
                }
                compositeByteBuf.AddComponent(true, frameBytes);
            }

            var ch = new EmbeddedChannel(new HttpObjectAggregator(int.MaxValue), new Handler(handshaker));

            if (codec)
            {
                ch.Pipeline.AddFirst(new HttpClientCodec());
            }
            else
            {
                ch.Pipeline.AddFirst(new HttpRequestEncoder(), new HttpResponseDecoder());
            }

            // We need to first write the request as HttpClientCodec will fail if we receive a response before a request
            // was written.
            shaker.HandshakeAsync(ch).Wait();
            for (; ;)
            {
                // Just consume the bytes, we are not interested in these.
                var buf = ch.ReadOutbound <IByteBuffer>();
                if (buf == null)
                {
                    break;
                }
                buf.Release();
            }
            Assert.True(ch.WriteInbound(compositeByteBuf));
            Assert.True(ch.Finish());

            var         frame  = ch.ReadInbound <BinaryWebSocketFrame>();
            IByteBuffer expect = Unpooled.WrappedBuffer(data);

            try
            {
                Assert.Equal(expect, frame.Content);
                Assert.True(frame.IsFinalFragment);
                Assert.Equal(0, frame.Rsv);
            }
            finally
            {
                expect.Release();
                frame.Release();
            }
        }