/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.handler.codec.http.websocketx;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.ssl.SslHandler;

import static io.netty.handler.codec.http.HttpHeaders.*;
import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;

/**
 * Handles the HTTP handshake (the HTTP Upgrade request) for {@link WebSocketServerProtocolHandler}.
 */
class WebSocketServerProtocolHandshakeHandler extends ChannelHandlerAdapter {

    private final String websocketPath;
    private final String subprotocols;
    private final boolean allowExtensions;

    public WebSocketServerProtocolHandshakeHandler(String websocketPath, String subprotocols,
            boolean allowExtensions) {
        this.websocketPath = websocketPath;
        this.subprotocols = subprotocols;
        this.allowExtensions = allowExtensions;
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest req = (FullHttpRequest) msg;
        if (req.getMethod() != GET) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
            return;
        }

        final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                getWebSocketLocation(ctx.pipeline(), req, websocketPath), subprotocols, allowExtensions);
        final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
            handshakeFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    } else {
                        ctx.fireUserEventTriggered(
                                WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
                    }
                }
            });
            WebSocketServerProtocolHandler.setHandshaker(ctx, handshaker);
            ctx.pipeline().replace(this, "WS403Responder",
                    WebSocketServerProtocolHandler.forbiddenHttpRequestResponder());
        }
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!isKeepAlive(req) || res.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
        String protocol = "ws";
        if (cp.get(SslHandler.class) != null) {
            // SSL in use so use Secure WebSockets
            protocol = "wss";
        }
        return protocol + "://" + req.headers().get(HttpHeaders.Names.HOST) + path;
    }

}

@@ -1746,23 +1746,16 @@
 s;%0A%0A    
-public 
 WebSocke
@@ -2168,16 +2168,34 @@
 t) msg;%0A
+        try %7B%0A    
         
@@ -2220,24 +2220,28 @@
 ) != GET) %7B%0A
+    
             
@@ -2326,24 +2326,28 @@
             
+    
 return;%0A    
@@ -2354,19 +2354,26 @@
     
-%7D%0A%0A
+    %7D%0A%0A   
         
 fina
@@ -2360,32 +2360,33 @@
   %7D%0A%0A           
+ 
 final WebSocketS
@@ -2458,16 +2458,20 @@
 actory(%0A
+    
         
@@ -2568,32 +2568,36 @@
 sions);%0A        
+ 
+   
 final WebSocketS
@@ -2659,24 +2659,28 @@
 q);%0A        
+  
+  
 if (handshak
@@ -2685,32 +2685,36 @@
 aker == null) %7B%0A
+    
             WebS
@@ -2789,32 +2789,36 @@
 nel());%0A        
+    
 %7D else %7B%0A       
@@ -2818,24 +2818,28 @@
             
+ 
+   
 final Channe
@@ -2918,16 +2918,20 @@
         
+    
 handshak
@@ -2976,24 +2976,28 @@
 istener() %7B%0A
+    
             
@@ -3022,24 +3022,28 @@
             
+    
 public void 
@@ -3117,24 +3117,28 @@
             
+    
 if (!future.
@@ -3168,32 +3168,36 @@
                 
+   
+ 
 ctx.fireExceptio
@@ -3233,32 +3233,36 @@
                 
+    
 %7D else %7B%0A       
@@ -3270,32 +3270,36 @@
                 
+ 
+   
 ctx.fireUserEven
@@ -3334,32 +3334,36 @@
                 
+  
+  
 WebSocketServerP
@@ -3436,34 +3436,42 @@
                 
-%7D%0A
+    %7D%0A    
                 
@@ -3488,12 +3488,20 @@
     
+ 
+   
 %7D);%0A
+    
     
@@ -3571,16 +3571,20 @@
 haker);%0A
+    
         
@@ -3646,32 +3646,36 @@
                 
+    
 WebSocketServerP
@@ -3719,24 +3719,85 @@
 sponder());%0A
+            %7D%0A        %7D finally %7B%0A            req.release();%0A
         %7D%0A  

Fix a leak in WebSocketServerProtocolHandshakeHandler