View Javadoc
1   /*
2    * Copyright 2012 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.ChannelHandlerAdapter;
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.channel.ChannelPipeline;
23  import io.netty.handler.codec.http.DefaultFullHttpResponse;
24  import io.netty.handler.codec.http.FullHttpRequest;
25  import io.netty.handler.codec.http.HttpHeaderNames;
26  import io.netty.handler.codec.http.HttpHeaderUtil;
27  import io.netty.handler.codec.http.HttpRequest;
28  import io.netty.handler.codec.http.HttpResponse;
29  import io.netty.handler.ssl.SslHandler;
30  
31  import static io.netty.handler.codec.http.HttpMethod.*;
32  import static io.netty.handler.codec.http.HttpResponseStatus.*;
33  import static io.netty.handler.codec.http.HttpVersion.*;
34  
35  /**
36   * Handles the HTTP handshake (the HTTP Upgrade request) for {@link WebSocketServerProtocolHandler}.
37   */
38  class WebSocketServerProtocolHandshakeHandler extends ChannelHandlerAdapter {
39  
40      private final String websocketPath;
41      private final String subprotocols;
42      private final boolean allowExtensions;
43      private final int maxFramePayloadSize;
44      private final boolean allowMaskMismatch;
45  
46      WebSocketServerProtocolHandshakeHandler(String websocketPath, String subprotocols,
47              boolean allowExtensions, int maxFrameSize, boolean allowMaskMismatch) {
48          this.websocketPath = websocketPath;
49          this.subprotocols = subprotocols;
50          this.allowExtensions = allowExtensions;
51          maxFramePayloadSize = maxFrameSize;
52          this.allowMaskMismatch = allowMaskMismatch;
53      }
54  
55      @Override
56      public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
57          FullHttpRequest req = (FullHttpRequest) msg;
58          try {
59              if (req.method() != GET) {
60                  sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
61                  return;
62              }
63  
64              final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
65                      getWebSocketLocation(ctx.pipeline(), req, websocketPath), subprotocols,
66                              allowExtensions, maxFramePayloadSize, allowMaskMismatch);
67              final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
68              if (handshaker == null) {
69                  WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
70              } else {
71                  final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
72                  handshakeFuture.addListener(new ChannelFutureListener() {
73                      @Override
74                      public void operationComplete(ChannelFuture future) throws Exception {
75                          if (!future.isSuccess()) {
76                              ctx.fireExceptionCaught(future.cause());
77                          } else {
78                              ctx.fireUserEventTriggered(
79                                      WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
80                          }
81                      }
82                  });
83                  WebSocketServerProtocolHandler.setHandshaker(ctx, handshaker);
84                  ctx.pipeline().replace(this, "WS403Responder",
85                          WebSocketServerProtocolHandler.forbiddenHttpRequestResponder());
86              }
87          } finally {
88              req.release();
89          }
90      }
91  
92      private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
93          ChannelFuture f = ctx.channel().writeAndFlush(res);
94          if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) {
95              f.addListener(ChannelFutureListener.CLOSE);
96          }
97      }
98  
99      private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
100         String protocol = "ws";
101         if (cp.get(SslHandler.class) != null) {
102             // SSL in use so use Secure WebSockets
103             protocol = "wss";
104         }
105         return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
106     }
107 
108 }