View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.proxy;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.net.URI;
24  import java.nio.ByteBuffer;
25  import java.util.concurrent.TimeUnit;
26  import javax.servlet.AsyncContext;
27  import javax.servlet.ServletConfig;
28  import javax.servlet.ServletContext;
29  import javax.servlet.ServletException;
30  import javax.servlet.UnavailableException;
31  import javax.servlet.http.HttpServletRequest;
32  import javax.servlet.http.HttpServletResponse;
33  
34  import org.eclipse.jetty.client.HttpClient;
35  import org.eclipse.jetty.client.api.ContentProvider;
36  import org.eclipse.jetty.client.api.Request;
37  import org.eclipse.jetty.client.api.Response;
38  import org.eclipse.jetty.client.api.Result;
39  import org.eclipse.jetty.client.util.InputStreamContentProvider;
40  import org.eclipse.jetty.http.HttpVersion;
41  import org.eclipse.jetty.util.Callback;
42  
43  /**
44   * Asynchronous ProxyServlet.
45   * <p/>
46   * Forwards requests to another server either as a standard web reverse proxy
47   * (as defined by RFC2616) or as a transparent reverse proxy.
48   * <p/>
49   * To facilitate JMX monitoring, the {@link HttpClient} instance is set as context attribute,
50   * prefixed with the servlet's name and exposed by the mechanism provided by
51   * {@link ServletContext#setAttribute(String, Object)}.
52   * <p/>
53   * The following init parameters may be used to configure the servlet:
54   * <ul>
55   * <li>hostHeader - forces the host header to a particular value</li>
56   * <li>viaHost - the name to use in the Via header: Via: http/1.1 &lt;viaHost&gt;</li>
57   * <li>whiteList - comma-separated list of allowed proxy hosts</li>
58   * <li>blackList - comma-separated list of forbidden proxy hosts</li>
59   * </ul>
60   * <p/>
61   * In addition, see {@link #createHttpClient()} for init parameters used to configure
62   * the {@link HttpClient} instance.
63   *
64   * @see ConnectHandler
65   */
66  public class ProxyServlet extends AbstractProxyServlet
67  {
68      @Override
69      protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
70      {
71          final int requestId = getRequestId(request);
72  
73          URI rewrittenURI = rewriteURI(request);
74  
75          if (_log.isDebugEnabled())
76          {
77              StringBuffer uri = request.getRequestURL();
78              if (request.getQueryString() != null)
79                  uri.append("?").append(request.getQueryString());
80              if (_log.isDebugEnabled())
81                  _log.debug("{} rewriting: {} -> {}", requestId, uri, rewrittenURI);
82          }
83  
84          if (rewrittenURI == null)
85          {
86              onRewriteFailed(request, response);
87              return;
88          }
89  
90          final Request proxyRequest = getHttpClient().newRequest(rewrittenURI)
91                  .method(request.getMethod())
92                  .version(HttpVersion.fromString(request.getProtocol()));
93  
94          copyHeaders(request, proxyRequest);
95  
96          addProxyHeaders(request, proxyRequest);
97  
98          final AsyncContext asyncContext = request.startAsync();
99          // We do not timeout the continuation, but the proxy request
100         asyncContext.setTimeout(0);
101         proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);
102 
103         if (hasContent(request))
104             proxyRequest.content(proxyRequestContent(proxyRequest, request));
105 
106         customizeProxyRequest(proxyRequest, request);
107 
108         sendProxyRequest(request, response, proxyRequest);
109     }
110 
111     protected ContentProvider proxyRequestContent(final Request proxyRequest, final HttpServletRequest request) throws IOException
112     {
113         return new ProxyInputStreamContentProvider(proxyRequest, request, request.getInputStream());
114     }
115 
116     protected Response.Listener newProxyResponseListener(HttpServletRequest request, HttpServletResponse response)
117     {
118         return new ProxyResponseListener(request, response);
119     }
120 
121     protected void onClientRequestFailure(Request proxyRequest, HttpServletRequest request, Throwable failure)
122     {
123         if (_log.isDebugEnabled())
124             _log.debug(getRequestId(request) + " client request failure", failure);
125         proxyRequest.abort(failure);
126     }
127 
128     /**
129      * @deprecated use {@link #onProxyRewriteFailed(HttpServletRequest, HttpServletResponse)}
130      */
131     @Deprecated
132     protected void onRewriteFailed(HttpServletRequest request, HttpServletResponse response) throws IOException
133     {
134         onProxyRewriteFailed(request, response);
135     }
136 
137     /**
138      * @deprecated use {@link #onServerResponseHeaders(HttpServletRequest, HttpServletResponse, Response)}
139      */
140     @Deprecated
141     protected void onResponseHeaders(HttpServletRequest request, HttpServletResponse response, Response proxyResponse)
142     {
143         onServerResponseHeaders(request, response, proxyResponse);
144     }
145 
146     // TODO: remove in Jetty 9.3, only here for backward compatibility.
147     @Override
148     protected String filterServerResponseHeader(HttpServletRequest clientRequest, Response serverResponse, String headerName, String headerValue)
149     {
150         return filterResponseHeader(clientRequest, headerName, headerValue);
151     }
152 
153     protected void onResponseContent(HttpServletRequest request, HttpServletResponse response, Response proxyResponse, byte[] buffer, int offset, int length, Callback callback)
154     {
155         try
156         {
157             if (_log.isDebugEnabled())
158                 _log.debug("{} proxying content to downstream: {} bytes", getRequestId(request), length);
159             response.getOutputStream().write(buffer, offset, length);
160             callback.succeeded();
161         }
162         catch (Throwable x)
163         {
164             callback.failed(x);
165         }
166     }
167 
168     /**
169      * @deprecated Use {@link #onProxyResponseSuccess(HttpServletRequest, HttpServletResponse, Response)}
170      */
171     @Deprecated
172     protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse)
173     {
174         onProxyResponseSuccess(request, response, proxyResponse);
175     }
176 
177     /**
178      * @deprecated Use {@link #onProxyResponseFailure(HttpServletRequest, HttpServletResponse, Response, Throwable)}
179      */
180     @Deprecated
181     protected void onResponseFailure(HttpServletRequest request, HttpServletResponse response, Response proxyResponse, Throwable failure)
182     {
183         onProxyResponseFailure(request, response, proxyResponse, failure);
184     }
185 
186     /**
187      * @deprecated use {@link #rewriteTarget(HttpServletRequest)}
188      */
189     @Deprecated
190     protected URI rewriteURI(HttpServletRequest request)
191     {
192         String newTarget = rewriteTarget(request);
193         return newTarget == null ? null : URI.create(newTarget);
194     }
195 
196     /**
197      * @deprecated use {@link #sendProxyRequest(HttpServletRequest, HttpServletResponse, Request)}
198      */
199     @Deprecated
200     protected void customizeProxyRequest(Request proxyRequest, HttpServletRequest request)
201     {
202     }
203 
204     /**
205      * Extension point for remote server response header filtering.
206      * The default implementation returns the header value as is.
207      * If null is returned, this header won't be forwarded back to the client.
208      *
209      * @param headerName the header name
210      * @param headerValue the header value
211      * @param request the request to proxy
212      * @return filteredHeaderValue the new header value
213      */
214     protected String filterResponseHeader(HttpServletRequest request, String headerName, String headerValue)
215     {
216         return headerValue;
217     }
218 
219     /**
220      * This convenience extension to {@link ProxyServlet} configures the servlet as a transparent proxy.
221      * This servlet is configured with the following init parameters:
222      * <ul>
223      * <li>proxyTo - a mandatory URI like http://host:80/context to which the request is proxied.</li>
224      * <li>prefix - an optional URI prefix that is stripped from the start of the forwarded URI.</li>
225      * </ul>
226      * <p/>
227      * For example, if a request is received at "/foo/bar", the 'proxyTo' parameter is "http://host:80/context"
228      * and the 'prefix' parameter is "/foo", then the request would be proxied to "http://host:80/context/bar".
229      */
230     public static class Transparent extends ProxyServlet
231     {
232         private final TransparentDelegate delegate = new TransparentDelegate(this);
233 
234         @Override
235         public void init(ServletConfig config) throws ServletException
236         {
237             super.init(config);
238             delegate.init(config);
239         }
240 
241         @Override
242         protected URI rewriteURI(HttpServletRequest request)
243         {
244             return delegate.rewriteURI(request);
245         }
246     }
247 
248     protected static class TransparentDelegate
249     {
250         private final ProxyServlet proxyServlet;
251         private String _proxyTo;
252         private String _prefix;
253 
254         protected TransparentDelegate(ProxyServlet proxyServlet)
255         {
256             this.proxyServlet = proxyServlet;
257         }
258 
259         protected void init(ServletConfig config) throws ServletException
260         {
261             _proxyTo = config.getInitParameter("proxyTo");
262             if (_proxyTo == null)
263                 throw new UnavailableException("Init parameter 'proxyTo' is required.");
264 
265             String prefix = config.getInitParameter("prefix");
266             if (prefix != null)
267             {
268                 if (!prefix.startsWith("/"))
269                     throw new UnavailableException("Init parameter 'prefix' must start with a '/'.");
270                 _prefix = prefix;
271             }
272 
273             // Adjust prefix value to account for context path
274             String contextPath = config.getServletContext().getContextPath();
275             _prefix = _prefix == null ? contextPath : (contextPath + _prefix);
276 
277             if (proxyServlet._log.isDebugEnabled())
278                 proxyServlet._log.debug(config.getServletName() + " @ " + _prefix + " to " + _proxyTo);
279         }
280 
281         protected URI rewriteURI(HttpServletRequest request)
282         {
283             String path = request.getRequestURI();
284             if (!path.startsWith(_prefix))
285                 return null;
286 
287             StringBuilder uri = new StringBuilder(_proxyTo);
288             if (_proxyTo.endsWith("/"))
289                 uri.setLength(uri.length() - 1);
290             String rest = path.substring(_prefix.length());
291             if (!rest.startsWith("/"))
292                 uri.append("/");
293             uri.append(rest);
294             String query = request.getQueryString();
295             if (query != null)
296                 uri.append("?").append(query);
297             URI rewrittenURI = URI.create(uri.toString()).normalize();
298 
299             if (!proxyServlet.validateDestination(rewrittenURI.getHost(), rewrittenURI.getPort()))
300                 return null;
301 
302             return rewrittenURI;
303         }
304     }
305 
306     protected class ProxyResponseListener extends Response.Listener.Adapter
307     {
308         private final HttpServletRequest request;
309         private final HttpServletResponse response;
310 
311         protected ProxyResponseListener(HttpServletRequest request, HttpServletResponse response)
312         {
313             this.request = request;
314             this.response = response;
315         }
316 
317         @Override
318         public void onBegin(Response proxyResponse)
319         {
320             response.setStatus(proxyResponse.getStatus());
321         }
322 
323         @Override
324         public void onHeaders(Response proxyResponse)
325         {
326             onResponseHeaders(request, response, proxyResponse);
327         }
328 
329         @Override
330         public void onContent(final Response proxyResponse, ByteBuffer content, final Callback callback)
331         {
332             byte[] buffer;
333             int offset;
334             int length = content.remaining();
335             if (content.hasArray())
336             {
337                 buffer = content.array();
338                 offset = content.arrayOffset();
339             }
340             else
341             {
342                 buffer = new byte[length];
343                 content.get(buffer);
344                 offset = 0;
345             }
346 
347             onResponseContent(request, response, proxyResponse, buffer, offset, length, new Callback()
348             {
349                 @Override
350                 public void succeeded()
351                 {
352                     callback.succeeded();
353                 }
354 
355                 @Override
356                 public void failed(Throwable x)
357                 {
358                     callback.failed(x);
359                     proxyResponse.abort(x);
360                 }
361             });
362         }
363 
364         @Override
365         public void onComplete(Result result)
366         {
367             if (result.isSucceeded())
368                 onResponseSuccess(request, response, result.getResponse());
369             else
370                 onResponseFailure(request, response, result.getResponse(), result.getFailure());
371             if (_log.isDebugEnabled())
372                 _log.debug("{} proxying complete", getRequestId(request));
373         }
374     }
375 
376     protected class ProxyInputStreamContentProvider extends InputStreamContentProvider
377     {
378         private final Request proxyRequest;
379         private final HttpServletRequest request;
380 
381         protected ProxyInputStreamContentProvider(Request proxyRequest, HttpServletRequest request, InputStream input)
382         {
383             super(input);
384             this.proxyRequest = proxyRequest;
385             this.request = request;
386         }
387 
388         @Override
389         public long getLength()
390         {
391             return request.getContentLength();
392         }
393 
394         @Override
395         protected ByteBuffer onRead(byte[] buffer, int offset, int length)
396         {
397             if (_log.isDebugEnabled())
398                 _log.debug("{} proxying content to upstream: {} bytes", getRequestId(request), length);
399             return onRequestContent(proxyRequest, request, buffer, offset, length);
400         }
401 
402         protected ByteBuffer onRequestContent(Request proxyRequest, final HttpServletRequest request, byte[] buffer, int offset, int length)
403         {
404             return super.onRead(buffer, offset, length);
405         }
406 
407         @Override
408         protected void onReadFailure(Throwable failure)
409         {
410             onClientRequestFailure(proxyRequest, request, failure);
411         }
412     }
413 }