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