001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.transport.http;
018
019import java.io.*;
020import java.util.HashMap;
021import java.util.concurrent.ConcurrentHashMap;
022import java.util.concurrent.ConcurrentMap;
023import java.util.concurrent.LinkedBlockingQueue;
024import java.util.concurrent.TimeUnit;
025import java.util.zip.GZIPInputStream;
026import javax.jms.JMSException;
027import javax.servlet.ServletException;
028import javax.servlet.http.HttpServlet;
029import javax.servlet.http.HttpServletRequest;
030import javax.servlet.http.HttpServletResponse;
031
032import org.apache.activemq.Service;
033import org.apache.activemq.command.Command;
034import org.apache.activemq.command.ConnectionInfo;
035import org.apache.activemq.command.WireFormatInfo;
036import org.apache.activemq.transport.Transport;
037import org.apache.activemq.transport.TransportAcceptListener;
038import org.apache.activemq.transport.util.TextWireFormat;
039import org.apache.activemq.transport.xstream.XStreamWireFormat;
040import org.apache.activemq.util.IOExceptionSupport;
041import org.apache.activemq.util.ServiceListener;
042import org.slf4j.Logger;
043import org.slf4j.LoggerFactory;
044
045/**
046 * A servlet which handles server side HTTP transport, delegating to the
047 * ActiveMQ broker. This servlet is designed for being embedded inside an
048 * ActiveMQ Broker using an embedded Jetty or Tomcat instance.
049 */
050public class HttpTunnelServlet extends HttpServlet {
051    private static final long serialVersionUID = -3826714430767484333L;
052    private static final Logger LOG = LoggerFactory.getLogger(HttpTunnelServlet.class);
053
054    private TransportAcceptListener listener;
055    private HttpTransportFactory transportFactory;
056    private TextWireFormat wireFormat;
057    private ConcurrentMap<String, BlockingQueueTransport> clients = new ConcurrentHashMap<String, BlockingQueueTransport>();
058    private final long requestTimeout = 30000L;
059    private HashMap<String, Object> transportOptions;
060    private HashMap<String, Object> wireFormatOptions;
061
062    @SuppressWarnings("unchecked")
063    @Override
064    public void init() throws ServletException {
065        super.init();
066        listener = (TransportAcceptListener)getServletContext().getAttribute("acceptListener");
067        if (listener == null) {
068            throw new ServletException("No such attribute 'acceptListener' available in the ServletContext");
069        }
070        transportFactory = (HttpTransportFactory)getServletContext().getAttribute("transportFactory");
071        if (transportFactory == null) {
072            throw new ServletException("No such attribute 'transportFactory' available in the ServletContext");
073        }
074        transportOptions = (HashMap<String, Object>)getServletContext().getAttribute("transportOptions");
075        wireFormatOptions = (HashMap<String, Object>)getServletContext().getAttribute("wireFormatOptions");
076        wireFormat = (TextWireFormat)getServletContext().getAttribute("wireFormat");
077        if (wireFormat == null) {
078            wireFormat = createWireFormat();
079        }
080    }
081
082    @Override
083    protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
084        response.addHeader("Accepts-Encoding", "gzip");
085        super.doOptions(request, response);
086    }
087
088    @Override
089    protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
090        createTransportChannel(request, response);
091    }
092
093    @Override
094    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
095        // lets return the next response
096        Command packet = null;
097        int count = 0;
098        try {
099            BlockingQueueTransport transportChannel = getTransportChannel(request, response);
100            if (transportChannel == null) {
101                return;
102            }
103
104            packet = (Command)transportChannel.getQueue().poll(requestTimeout, TimeUnit.MILLISECONDS);
105
106            DataOutputStream stream = new DataOutputStream(response.getOutputStream());
107            wireFormat.marshal(packet, stream);
108            count++;
109        } catch (InterruptedException ignore) {
110        }
111
112        if (count == 0) {
113            response.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT);
114        }
115    }
116
117    @Override
118    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
119
120        if (wireFormatOptions.get("maxFrameSize") != null && request.getContentLength() > Integer.parseInt(wireFormatOptions.get("maxFrameSize").toString())) {
121            response.setStatus(405);
122            response.setContentType("plain/text");
123            PrintWriter writer = response.getWriter();
124            writer.println("maxFrameSize exceeded");
125            writer.flush();
126            writer.close();
127            return;
128        }
129
130        InputStream stream = request.getInputStream();
131        String contentType = request.getContentType();
132        if (contentType != null && contentType.equals("application/x-gzip")) {
133            stream = new GZIPInputStream(stream);
134        }
135
136        // Read the command directly from the reader, assuming UTF8 encoding
137        Command command = (Command) wireFormat.unmarshalText(new InputStreamReader(stream, "UTF-8"));
138
139        if (command instanceof WireFormatInfo) {
140            WireFormatInfo info = (WireFormatInfo) command;
141            if (!canProcessWireFormatVersion(info.getVersion())) {
142                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot process wire format of version: "
143                        + info.getVersion());
144            }
145
146        } else {
147
148            BlockingQueueTransport transport = getTransportChannel(request, response);
149            if (transport == null) {
150                return;
151            }
152
153            if (command instanceof ConnectionInfo) {
154                ((ConnectionInfo) command).setTransportContext(request.getAttribute("javax.servlet.request.X509Certificate"));
155            }
156            transport.doConsume(command);
157        }
158    }
159
160    private boolean canProcessWireFormatVersion(int version) {
161        return true;
162    }
163
164    protected BlockingQueueTransport getTransportChannel(HttpServletRequest request, HttpServletResponse response) throws IOException {
165        String clientID = request.getHeader("clientID");
166        if (clientID == null) {
167            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No clientID header specified");
168            LOG.warn("No clientID header specified");
169            return null;
170        }
171        BlockingQueueTransport answer = clients.get(clientID);
172        if (answer == null) {
173            LOG.warn("The clientID header specified is invalid. Client sesion has not yet been established for it: " + clientID);
174            return null;
175        }
176        return answer;
177    }
178
179    protected BlockingQueueTransport createTransportChannel(HttpServletRequest request, HttpServletResponse response) throws IOException {
180        final String clientID = request.getHeader("clientID");
181
182        if (clientID == null) {
183            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No clientID header specified");
184            LOG.warn("No clientID header specified");
185            return null;
186        }
187
188        // Optimistically create the client's transport; this transport may be thrown away if the client has already registered.
189        BlockingQueueTransport answer = createTransportChannel();
190
191        // Record the client's transport and ensure that it has not already registered; this is thread-safe and only allows one
192        // thread to register the client
193        if (clients.putIfAbsent(clientID, answer) != null) {
194            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "A session for the given clientID has already been established");
195            LOG.warn("A session for clientID '" + clientID + "' has already been established");
196            return null;
197        }
198
199        // Ensure that the client's transport is cleaned up when no longer
200        // needed.
201        answer.addServiceListener(new ServiceListener() {
202            public void started(Service service) {
203                // Nothing to do.
204            }
205
206            public void stopped(Service service) {
207                clients.remove(clientID);
208            }
209        });
210
211        // Configure the transport with any additional properties or filters.  Although the returned transport is not explicitly
212        // persisted, if it is a filter (e.g., InactivityMonitor) it will be linked to the client's transport as a TransportListener
213        // and not GC'd until the client's transport is disposed.
214        Transport transport = answer;
215        try {
216            // Preserve the transportOptions for future use by making a copy before applying (they are removed when applied).
217            HashMap<String, Object> options = new HashMap<String, Object>(transportOptions);
218            transport = transportFactory.serverConfigure(answer, null, options);
219        } catch (Exception e) {
220            throw IOExceptionSupport.create(e);
221        }
222
223        // Wait for the transport to be connected or disposed.
224        listener.onAccept(transport);
225        while (!transport.isConnected() && !transport.isDisposed()) {
226            try {
227                Thread.sleep(100);
228            } catch (InterruptedException ignore) {
229            }
230        }
231
232        // Ensure that the transport was not prematurely disposed.
233        if (transport.isDisposed()) {
234            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The session for the given clientID was prematurely disposed");
235            LOG.warn("The session for clientID '" + clientID + "' was prematurely disposed");
236            return null;
237        }
238
239        return answer;
240    }
241
242    protected BlockingQueueTransport createTransportChannel() {
243       return new BlockingQueueTransport(new LinkedBlockingQueue<Object>());
244    }
245
246    protected TextWireFormat createWireFormat() {
247        return new XStreamWireFormat();
248    }
249}