001/*
002 * Copyright 2002-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.remoting.httpinvoker;
018
019import java.io.FilterOutputStream;
020import java.io.IOException;
021import java.io.InputStream;
022import java.io.ObjectInputStream;
023import java.io.ObjectOutputStream;
024import java.io.OutputStream;
025import javax.servlet.ServletException;
026import javax.servlet.http.HttpServletRequest;
027import javax.servlet.http.HttpServletResponse;
028
029import org.springframework.remoting.rmi.RemoteInvocationSerializingExporter;
030import org.springframework.remoting.support.RemoteInvocation;
031import org.springframework.remoting.support.RemoteInvocationResult;
032import org.springframework.web.HttpRequestHandler;
033import org.springframework.web.util.NestedServletException;
034
035/**
036 * Servlet-API-based HTTP request handler that exports the specified service bean
037 * as HTTP invoker service endpoint, accessible via an HTTP invoker proxy.
038 *
039 * <p><b>Note:</b> Spring also provides an alternative version of this exporter,
040 * for Sun's JRE 1.6 HTTP server: {@link SimpleHttpInvokerServiceExporter}.
041 *
042 * <p>Deserializes remote invocation objects and serializes remote invocation
043 * result objects. Uses Java serialization just like RMI, but provides the
044 * same ease of setup as Caucho's HTTP-based Hessian and Burlap protocols.
045 *
046 * <p><b>HTTP invoker is the recommended protocol for Java-to-Java remoting.</b>
047 * It is more powerful and more extensible than Hessian and Burlap, at the
048 * expense of being tied to Java. Nevertheless, it is as easy to set up as
049 * Hessian and Burlap, which is its main advantage compared to RMI.
050 *
051 * <p><b>WARNING: Be aware of vulnerabilities due to unsafe Java deserialization:
052 * Manipulated input streams could lead to unwanted code execution on the server
053 * during the deserialization step. As a consequence, do not expose HTTP invoker
054 * endpoints to untrusted clients but rather just between your own services.</b>
055 * In general, we strongly recommend any other message format (e.g. JSON) instead.
056 *
057 * @author Juergen Hoeller
058 * @since 1.1
059 * @see HttpInvokerClientInterceptor
060 * @see HttpInvokerProxyFactoryBean
061 * @see org.springframework.remoting.rmi.RmiServiceExporter
062 * @see org.springframework.remoting.caucho.HessianServiceExporter
063 * @see org.springframework.remoting.caucho.BurlapServiceExporter
064 */
065public class HttpInvokerServiceExporter extends RemoteInvocationSerializingExporter implements HttpRequestHandler {
066
067        /**
068         * Reads a remote invocation from the request, executes it,
069         * and writes the remote invocation result to the response.
070         * @see #readRemoteInvocation(HttpServletRequest)
071         * @see #invokeAndCreateResult(org.springframework.remoting.support.RemoteInvocation, Object)
072         * @see #writeRemoteInvocationResult(HttpServletRequest, HttpServletResponse, RemoteInvocationResult)
073         */
074        @Override
075        public void handleRequest(HttpServletRequest request, HttpServletResponse response)
076                        throws ServletException, IOException {
077
078                try {
079                        RemoteInvocation invocation = readRemoteInvocation(request);
080                        RemoteInvocationResult result = invokeAndCreateResult(invocation, getProxy());
081                        writeRemoteInvocationResult(request, response, result);
082                }
083                catch (ClassNotFoundException ex) {
084                        throw new NestedServletException("Class not found during deserialization", ex);
085                }
086        }
087
088        /**
089         * Read a RemoteInvocation from the given HTTP request.
090         * <p>Delegates to {@link #readRemoteInvocation(HttpServletRequest, InputStream)} with
091         * the {@link HttpServletRequest#getInputStream() servlet request's input stream}.
092         * @param request current HTTP request
093         * @return the RemoteInvocation object
094         * @throws IOException in case of I/O failure
095         * @throws ClassNotFoundException if thrown by deserialization
096         */
097        protected RemoteInvocation readRemoteInvocation(HttpServletRequest request)
098                        throws IOException, ClassNotFoundException {
099
100                return readRemoteInvocation(request, request.getInputStream());
101        }
102
103        /**
104         * Deserialize a RemoteInvocation object from the given InputStream.
105         * <p>Gives {@link #decorateInputStream} a chance to decorate the stream
106         * first (for example, for custom encryption or compression). Creates a
107         * {@link org.springframework.remoting.rmi.CodebaseAwareObjectInputStream}
108         * and calls {@link #doReadRemoteInvocation} to actually read the object.
109         * <p>Can be overridden for custom serialization of the invocation.
110         * @param request current HTTP request
111         * @param is the InputStream to read from
112         * @return the RemoteInvocation object
113         * @throws IOException in case of I/O failure
114         * @throws ClassNotFoundException if thrown during deserialization
115         */
116        protected RemoteInvocation readRemoteInvocation(HttpServletRequest request, InputStream is)
117                        throws IOException, ClassNotFoundException {
118
119                ObjectInputStream ois = createObjectInputStream(decorateInputStream(request, is));
120                try {
121                        return doReadRemoteInvocation(ois);
122                }
123                finally {
124                        ois.close();
125                }
126        }
127
128        /**
129         * Return the InputStream to use for reading remote invocations,
130         * potentially decorating the given original InputStream.
131         * <p>The default implementation returns the given stream as-is.
132         * Can be overridden, for example, for custom encryption or compression.
133         * @param request current HTTP request
134         * @param is the original InputStream
135         * @return the potentially decorated InputStream
136         * @throws IOException in case of I/O failure
137         */
138        protected InputStream decorateInputStream(HttpServletRequest request, InputStream is) throws IOException {
139                return is;
140        }
141
142        /**
143         * Write the given RemoteInvocationResult to the given HTTP response.
144         * @param request current HTTP request
145         * @param response current HTTP response
146         * @param result the RemoteInvocationResult object
147         * @throws IOException in case of I/O failure
148         */
149        protected void writeRemoteInvocationResult(
150                        HttpServletRequest request, HttpServletResponse response, RemoteInvocationResult result)
151                        throws IOException {
152
153                response.setContentType(getContentType());
154                writeRemoteInvocationResult(request, response, result, response.getOutputStream());
155        }
156
157        /**
158         * Serialize the given RemoteInvocation to the given OutputStream.
159         * <p>The default implementation gives {@link #decorateOutputStream} a chance
160         * to decorate the stream first (for example, for custom encryption or compression).
161         * Creates an {@link java.io.ObjectOutputStream} for the final stream and calls
162         * {@link #doWriteRemoteInvocationResult} to actually write the object.
163         * <p>Can be overridden for custom serialization of the invocation.
164         * @param request current HTTP request
165         * @param response current HTTP response
166         * @param result the RemoteInvocationResult object
167         * @param os the OutputStream to write to
168         * @throws IOException in case of I/O failure
169         * @see #decorateOutputStream
170         * @see #doWriteRemoteInvocationResult
171         */
172        protected void writeRemoteInvocationResult(
173                        HttpServletRequest request, HttpServletResponse response, RemoteInvocationResult result, OutputStream os)
174                        throws IOException {
175
176                ObjectOutputStream oos =
177                                createObjectOutputStream(new FlushGuardedOutputStream(decorateOutputStream(request, response, os)));
178                try {
179                        doWriteRemoteInvocationResult(result, oos);
180                }
181                finally {
182                        oos.close();
183                }
184        }
185
186        /**
187         * Return the OutputStream to use for writing remote invocation results,
188         * potentially decorating the given original OutputStream.
189         * <p>The default implementation returns the given stream as-is.
190         * Can be overridden, for example, for custom encryption or compression.
191         * @param request current HTTP request
192         * @param response current HTTP response
193         * @param os the original OutputStream
194         * @return the potentially decorated OutputStream
195         * @throws IOException in case of I/O failure
196         */
197        protected OutputStream decorateOutputStream(
198                        HttpServletRequest request, HttpServletResponse response, OutputStream os) throws IOException {
199
200                return os;
201        }
202
203
204        /**
205         * Decorate an {@code OutputStream} to guard against {@code flush()} calls,
206         * which are turned into no-ops.
207         * <p>Because {@link ObjectOutputStream#close()} will in fact flush/drain
208         * the underlying stream twice, this {@link FilterOutputStream} will
209         * guard against individual flush calls. Multiple flush calls can lead
210         * to performance issues, since writes aren't gathered as they should be.
211         * @see <a href="https://jira.spring.io/browse/SPR-14040">SPR-14040</a>
212         */
213        private static class FlushGuardedOutputStream extends FilterOutputStream {
214
215                public FlushGuardedOutputStream(OutputStream out) {
216                        super(out);
217                }
218
219                @Override
220                public void flush() throws IOException {
221                        // Do nothing on flush
222                }
223        }
224
225}