/*
 * Copyright (C) 2015 Tom Evans. All rights reserved.
 *
 * Licensed 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 org.jivesoftware.openfire.websocket;

import java.text.MessageFormat;

import org.eclipse.jetty.websocket.common.extensions.compress.PerMessageDeflateExtension;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.session.ClientSession;
import org.jivesoftware.openfire.session.LocalSession;
import org.jivesoftware.util.JiveGlobals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This Servlet enables XMPP over WebSocket (RFC 7395) for Openfire.
 * 
 * The Jetty WebSocketServlet serves as a base class and enables easy integration into the
 * BOSH (http-bind) web context. Each WebSocket request received at the "/ws/" URI will be
 * forwarded to this plugin/servlet, which will in turn create a new {@link XmppWebSocket}
 * for each new connection. 
 */
public class OpenfireWebSocketServlet extends WebSocketServlet {

    private static final long serialVersionUID = 7281841492829464605L;
    private static final Logger Log = LoggerFactory.getLogger(OpenfireWebSocketServlet.class);

    @Override
    public void destroy()
    {
        // terminate any active websocket sessions
        SessionManager sm = XMPPServer.getInstance().getSessionManager();
        for (ClientSession session : sm.getSessions()) {
            if (session instanceof LocalSession) {
                Object ws = ((LocalSession) session).getSessionData("ws");
                if (ws != null && (Boolean) ws) {
                    Log.debug( "Closing session as websocket servlet is being destroyed: {}", session );
                    session.close();
                }
            }
        }

        super.destroy();
    }

    @Override
    public void configure(WebSocketServletFactory factory)
    {
        if (XmppWebSocket.isCompressionEnabled()) {
            factory.getExtensionFactory().register("permessage-deflate", PerMessageDeflateExtension.class);
        }
        final int messageSize = JiveGlobals.getIntProperty("xmpp.parser.buffer.size", 1048576);
        factory.getPolicy().setMaxTextMessageBufferSize(messageSize * 5);
        factory.getPolicy().setMaxTextMessageSize(messageSize);
        factory.setCreator(new WebSocketCreator() {
            @Override
            public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp)
            {
                try {
                    for (String subprotocol : req.getSubProtocols())
                    {
                        if ("xmpp".equals(subprotocol))
                        {
                            resp.setAcceptedSubProtocol(subprotocol);
                            return new XmppWebSocket();
                        }
                    }
                } catch (Exception e) {
                    Log.warn(MessageFormat.format("Unable to load websocket factory: {0} ({1})", e.getClass().getName(), e.getMessage()));
                }
                Log.warn("Failed to create websocket for {}:{} make a request at {}", req.getRemoteAddress(), req.getRemotePort(), req.getRequestPath() );
                return null;
            }
        });
    }
}

@@ -674,26 +674,186 @@
 ava.
-text.MessageFormat
+io.IOException;%0Aimport java.text.MessageFormat;%0Aimport javax.servlet.ServletException;%0Aimport javax.servlet.http.HttpServletRequest;%0Aimport javax.servlet.http.HttpServletResponse
 ;%0A%0Ai
@@ -1264,16 +1264,71 @@
 actory;%0A
+import org.jivesoftware.openfire.http.HttpBindManager;%0A
 import o
@@ -2240,16 +2240,203 @@
 lass);%0A%0A
+    private HttpBindManager boshManager;%0A%0A    @Override%0A    public void init() throws ServletException %7B%0A        super.init();%0A        boshManager = HttpBindManager.getInstance();%0A    %7D%0A%0A
     @Ove
@@ -3040,32 +3040,1440 @@
 stroy();%0A    %7D%0A%0A
+    @Override%0A    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException%0A    %7B%0A        // add CORS headers for all HTTP responses (errors, etc.)%0A        if (boshManager.isCORSEnabled())%0A        %7B%0A            if (boshManager.isAllOriginsAllowed()) %7B%0A                // Set the Access-Control-Allow-Origin header to * to allow all Origin to do the CORS%0A                response.setHeader(%22Access-Control-Allow-Origin%22, HttpBindManager.HTTP_BIND_CORS_ALLOW_ORIGIN_DEFAULT);%0A            %7D else %7B%0A                // Get the Origin header from the request and check if it is in the allowed Origin Map.%0A                // If it is allowed write it back to the Access-Control-Allow-Origin header of the respond.%0A                final String origin = request.getHeader(%22Origin%22);%0A                if (boshManager.isThisOriginAllowed(origin)) %7B%0A                    response.setHeader(%22Access-Control-Allow-Origin%22, origin);%0A                %7D%0A            %7D%0A            response.setHeader(%22Access-Control-Allow-Methods%22, HttpBindManager.HTTP_BIND_CORS_ALLOW_METHODS_DEFAULT);%0A            response.setHeader(%22Access-Control-Allow-Headers%22, HttpBindManager.HTTP_BIND_CORS_ALLOW_HEADERS_DEFAULT);%0A            response.setHeader(%22Access-Control-Max-Age%22, HttpBindManager.HTTP_BIND_CORS_MAX_AGE_DEFAULT);%0A        %7D%0A        super.service(request, response);%0A    %7D%0A
     @Override%0A  

Add CORS support to web sockets