View Javadoc
1   /*
2    * Copyright 2019 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.http.websocketx;
17  
18  import io.netty.channel.ChannelFuture;
19  import io.netty.channel.ChannelFutureListener;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.channel.ChannelInboundHandlerAdapter;
22  import io.netty.channel.ChannelPipeline;
23  import io.netty.channel.ChannelPromise;
24  import io.netty.handler.codec.http.DefaultFullHttpResponse;
25  import io.netty.handler.codec.http.FullHttpRequest;
26  import io.netty.handler.codec.http.HttpHeaderNames;
27  import io.netty.handler.codec.http.HttpRequest;
28  import io.netty.handler.codec.http.HttpResponse;
29  import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.ServerHandshakeStateEvent;
30  import io.netty.handler.ssl.SslHandler;
31  import io.netty.util.concurrent.Future;
32  import io.netty.util.concurrent.FutureListener;
33  
34  import java.util.concurrent.TimeUnit;
35  
36  import static io.netty.handler.codec.http.HttpMethod.*;
37  import static io.netty.handler.codec.http.HttpResponseStatus.*;
38  import static io.netty.handler.codec.http.HttpUtil.*;
39  import static io.netty.handler.codec.http.HttpVersion.*;
40  import static io.netty.util.internal.ObjectUtil.*;
41  
42  /**
43   * Handles the HTTP handshake (the HTTP Upgrade request) for {@link WebSocketServerProtocolHandler}.
44   */
45  class WebSocketServerProtocolHandshakeHandler extends ChannelInboundHandlerAdapter {
46  
47      private final WebSocketServerProtocolConfig serverConfig;
48      private ChannelHandlerContext ctx;
49      private ChannelPromise handshakePromise;
50  
51      WebSocketServerProtocolHandshakeHandler(WebSocketServerProtocolConfig serverConfig) {
52          this.serverConfig = checkNotNull(serverConfig, "serverConfig");
53      }
54  
55      @Override
56      public void handlerAdded(ChannelHandlerContext ctx) {
57          this.ctx = ctx;
58          handshakePromise = ctx.newPromise();
59      }
60  
61      @Override
62      public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
63          final FullHttpRequest req = (FullHttpRequest) msg;
64          if (isNotWebSocketPath(req)) {
65              ctx.fireChannelRead(msg);
66              return;
67          }
68  
69          try {
70              if (!GET.equals(req.method())) {
71                  sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN, ctx.alloc().buffer(0)));
72                  return;
73              }
74  
75              final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
76                      getWebSocketLocation(ctx.pipeline(), req, serverConfig.websocketPath()),
77                      serverConfig.subprotocols(), serverConfig.decoderConfig());
78              final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
79              final ChannelPromise localHandshakePromise = handshakePromise;
80              if (handshaker == null) {
81                  WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
82              } else {
83                  // Ensure we set the handshaker and replace this handler before we
84                  // trigger the actual handshake. Otherwise we may receive websocket bytes in this handler
85                  // before we had a chance to replace it.
86                  //
87                  // See https://github.com/netty/netty/issues/9471.
88                  WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
89                  ctx.pipeline().remove(this);
90  
91                  final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
92                  handshakeFuture.addListener(new ChannelFutureListener() {
93                      @Override
94                      public void operationComplete(ChannelFuture future) {
95                          if (!future.isSuccess()) {
96                              localHandshakePromise.tryFailure(future.cause());
97                              ctx.fireExceptionCaught(future.cause());
98                          } else {
99                              localHandshakePromise.trySuccess();
100                             // Kept for compatibility
101                             ctx.fireUserEventTriggered(
102                                     WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
103                             ctx.fireUserEventTriggered(
104                                     new WebSocketServerProtocolHandler.HandshakeComplete(
105                                             req.uri(), req.headers(), handshaker.selectedSubprotocol()));
106                         }
107                     }
108                 });
109                 applyHandshakeTimeout();
110             }
111         } finally {
112             req.release();
113         }
114     }
115 
116     private boolean isNotWebSocketPath(FullHttpRequest req) {
117         String websocketPath = serverConfig.websocketPath();
118         return serverConfig.checkStartsWith() ? !req.uri().startsWith(websocketPath) : !req.uri().equals(websocketPath);
119     }
120 
121     private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
122         ChannelFuture f = ctx.channel().writeAndFlush(res);
123         if (!isKeepAlive(req) || res.status().code() != 200) {
124             f.addListener(ChannelFutureListener.CLOSE);
125         }
126     }
127 
128     private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
129         String protocol = "ws";
130         if (cp.get(SslHandler.class) != null) {
131             // SSL in use so use Secure WebSockets
132             protocol = "wss";
133         }
134         String host = req.headers().get(HttpHeaderNames.HOST);
135         return protocol + "://" + host + path;
136     }
137 
138     private void applyHandshakeTimeout() {
139         final ChannelPromise localHandshakePromise = handshakePromise;
140         final long handshakeTimeoutMillis = serverConfig.handshakeTimeoutMillis();
141         if (handshakeTimeoutMillis <= 0 || localHandshakePromise.isDone()) {
142             return;
143         }
144 
145         final Future<?> timeoutFuture = ctx.executor().schedule(new Runnable() {
146             @Override
147             public void run() {
148                 if (!localHandshakePromise.isDone() &&
149                         localHandshakePromise.tryFailure(new WebSocketHandshakeException("handshake timed out"))) {
150                     ctx.flush()
151                        .fireUserEventTriggered(ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT)
152                        .close();
153                 }
154             }
155         }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
156 
157         // Cancel the handshake timeout when handshake is finished.
158         localHandshakePromise.addListener(new FutureListener<Void>() {
159             @Override
160             public void operationComplete(Future<Void> f) {
161                 timeoutFuture.cancel(false);
162             }
163         });
164     }
165 }