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.server.handler;
20  
21  import java.io.IOException;
22  import java.io.OutputStream;
23  import java.net.MalformedURLException;
24  import java.nio.ByteBuffer;
25  import java.nio.channels.ReadableByteChannel;
26  
27  import javax.servlet.AsyncContext;
28  import javax.servlet.RequestDispatcher;
29  import javax.servlet.ServletException;
30  import javax.servlet.http.HttpServletRequest;
31  import javax.servlet.http.HttpServletResponse;
32  
33  import org.eclipse.jetty.http.HttpFields;
34  import org.eclipse.jetty.http.HttpHeader;
35  import org.eclipse.jetty.http.HttpMethod;
36  import org.eclipse.jetty.http.HttpStatus;
37  import org.eclipse.jetty.http.MimeTypes;
38  import org.eclipse.jetty.io.WriterOutputStream;
39  import org.eclipse.jetty.server.HttpOutput;
40  import org.eclipse.jetty.server.Request;
41  import org.eclipse.jetty.server.Response;
42  import org.eclipse.jetty.server.handler.ContextHandler.Context;
43  import org.eclipse.jetty.util.BufferUtil;
44  import org.eclipse.jetty.util.Callback;
45  import org.eclipse.jetty.util.URIUtil;
46  import org.eclipse.jetty.util.log.Log;
47  import org.eclipse.jetty.util.log.Logger;
48  import org.eclipse.jetty.util.resource.PathResource;
49  import org.eclipse.jetty.util.resource.Resource;
50  
51  
52  /* ------------------------------------------------------------ */
53  /** Resource Handler.
54   *
55   * This handle will serve static content and handle If-Modified-Since headers.
56   * No caching is done.
57   * Requests for resources that do not exist are let pass (Eg no 404's).
58   *
59   *
60   * @org.apache.xbean.XBean
61   */
62  public class ResourceHandler extends HandlerWrapper
63  {
64      private static final Logger LOG = Log.getLogger(ResourceHandler.class);
65  
66      ContextHandler _context;
67      Resource _baseResource;
68      Resource _defaultStylesheet;
69      Resource _stylesheet;
70      String[] _welcomeFiles={"index.html"};
71      MimeTypes _mimeTypes = new MimeTypes();
72      String _cacheControl;
73      boolean _directory;
74      boolean _etags;
75      int _minMemoryMappedContentLength=1024;
76      int _minAsyncContentLength=0;
77  
78      /* ------------------------------------------------------------ */
79      public ResourceHandler()
80      {
81  
82      }
83  
84      /* ------------------------------------------------------------ */
85      public MimeTypes getMimeTypes()
86      {
87          return _mimeTypes;
88      }
89  
90      /* ------------------------------------------------------------ */
91      public void setMimeTypes(MimeTypes mimeTypes)
92      {
93          _mimeTypes = mimeTypes;
94      }
95  
96      /* ------------------------------------------------------------ */
97      /** Get the directory option.
98       * @return true if directories are listed.
99       */
100     public boolean isDirectoriesListed()
101     {
102         return _directory;
103     }
104 
105     /* ------------------------------------------------------------ */
106     /** Set the directory.
107      * @param directory true if directories are listed.
108      */
109     public void setDirectoriesListed(boolean directory)
110     {
111         _directory = directory;
112     }
113 
114     /* ------------------------------------------------------------ */
115     /** Get minimum memory mapped file content length.
116      * @return the minimum size in bytes of a file resource that will
117      * be served using a memory mapped buffer, or -1 (default) for no memory mapped
118      * buffers.
119      */
120     public int getMinMemoryMappedContentLength()
121     {
122         return _minMemoryMappedContentLength;
123     }
124 
125     /* ------------------------------------------------------------ */
126     /** Set minimum memory mapped file content length.
127      * @param minMemoryMappedFileSize the minimum size in bytes of a file resource that will
128      * be served using a memory mapped buffer, or -1 for no memory mapped
129      * buffers.
130      */
131     public void setMinMemoryMappedContentLength(int minMemoryMappedFileSize)
132     {
133         _minMemoryMappedContentLength = minMemoryMappedFileSize;
134     }
135 
136     /* ------------------------------------------------------------ */
137     /** Get the minimum content length for async handling.
138      * @return The minimum size in bytes of the content before asynchronous 
139      * handling is used, or -1 for no async handling or 0 (default) for using
140      * {@link HttpServletResponse#getBufferSize()} as the minimum length.
141      */
142     public int getMinAsyncContentLength()
143     {
144         return _minAsyncContentLength;
145     }
146 
147     /* ------------------------------------------------------------ */
148     /** Set the minimum content length for async handling.
149      * @param minAsyncContentLength The minimum size in bytes of the content before asynchronous 
150      * handling is used, or -1 for no async handling or 0 for using
151      * {@link HttpServletResponse#getBufferSize()} as the minimum length.
152      */
153     public void setMinAsyncContentLength(int minAsyncContentLength)
154     {
155         _minAsyncContentLength = minAsyncContentLength;
156     }
157 
158     /* ------------------------------------------------------------ */
159     /**
160      * @return True if ETag processing is done
161      */
162     public boolean isEtags()
163     {
164         return _etags;
165     }
166 
167     /* ------------------------------------------------------------ */
168     /**
169      * @param etags True if ETag processing is done
170      */
171     public void setEtags(boolean etags)
172     {
173         _etags = etags;
174     }
175 
176     /* ------------------------------------------------------------ */
177     @Override
178     public void doStart()
179     throws Exception
180     {
181         Context scontext = ContextHandler.getCurrentContext();
182         _context = (scontext==null?null:scontext.getContextHandler());
183 
184         super.doStart();
185     }
186 
187     /* ------------------------------------------------------------ */
188     /**
189      * @return Returns the resourceBase.
190      */
191     public Resource getBaseResource()
192     {
193         if (_baseResource==null)
194             return null;
195         return _baseResource;
196     }
197 
198     /* ------------------------------------------------------------ */
199     /**
200      * @return Returns the base resource as a string.
201      */
202     public String getResourceBase()
203     {
204         if (_baseResource==null)
205             return null;
206         return _baseResource.toString();
207     }
208 
209 
210     /* ------------------------------------------------------------ */
211     /**
212      * @param base The resourceBase to set.
213      */
214     public void setBaseResource(Resource base)
215     {
216         _baseResource=base;
217     }
218 
219     /* ------------------------------------------------------------ */
220     /**
221      * @param resourceBase The base resource as a string.
222      */
223     public void setResourceBase(String resourceBase)
224     {
225         try
226         {
227             setBaseResource(Resource.newResource(resourceBase));
228         }
229         catch (Exception e)
230         {
231             LOG.warn(e.toString());
232             LOG.debug(e);
233             throw new IllegalArgumentException(resourceBase);
234         }
235     }
236 
237     /* ------------------------------------------------------------ */
238     /**
239      * @return Returns the stylesheet as a Resource.
240      */
241     public Resource getStylesheet()
242     {
243         if(_stylesheet != null)
244         {
245             return _stylesheet;
246         }
247         else
248         {
249             if(_defaultStylesheet == null)
250             {
251                 _defaultStylesheet =  Resource.newResource(this.getClass().getResource("/jetty-dir.css"));
252             }
253             return _defaultStylesheet;
254         }
255     }
256 
257     /* ------------------------------------------------------------ */
258     /**
259      * @param stylesheet The location of the stylesheet to be used as a String.
260      */
261     public void setStylesheet(String stylesheet)
262     {
263         try
264         {
265             _stylesheet = Resource.newResource(stylesheet);
266             if(!_stylesheet.exists())
267             {
268                 LOG.warn("unable to find custom stylesheet: " + stylesheet);
269                 _stylesheet = null;
270             }
271         }
272         catch(Exception e)
273         {
274             LOG.warn(e.toString());
275             LOG.debug(e);
276             throw new IllegalArgumentException(stylesheet);
277         }
278     }
279 
280     /* ------------------------------------------------------------ */
281     /**
282      * @return the cacheControl header to set on all static content.
283      */
284     public String getCacheControl()
285     {
286         return _cacheControl;
287     }
288 
289     /* ------------------------------------------------------------ */
290     /**
291      * @param cacheControl the cacheControl header to set on all static content.
292      */
293     public void setCacheControl(String cacheControl)
294     {
295         _cacheControl=cacheControl;
296     }
297 
298     /* ------------------------------------------------------------ */
299     /*
300      */
301     public Resource getResource(String path) throws MalformedURLException
302     {
303         if (path==null || !path.startsWith("/"))
304             throw new MalformedURLException(path);
305 
306         if (LOG.isDebugEnabled())
307             LOG.debug("{} getResource({})",_context==null?_baseResource:_context,_baseResource,path);
308         
309         Resource base = _baseResource;
310         if (base==null)
311         {
312             if (_context==null)
313                 return null;
314             return _context.getResource(path);
315         }
316 
317         try
318         {
319             path=URIUtil.canonicalPath(path);
320             Resource r = base.addPath(path);
321             if (r!=null && r.isAlias() && (_context==null || !_context.checkAlias(path, r)))
322             {
323                 if (LOG.isDebugEnabled())
324                     LOG.debug("resource={} alias={}",r,r.getAlias());
325                 return null;
326             }
327             return r;
328         }
329         catch(Exception e)
330         {
331             LOG.ignore(e);
332         }
333 
334         return null;
335     }
336 
337     /* ------------------------------------------------------------ */
338     protected Resource getResource(HttpServletRequest request) throws MalformedURLException
339     {
340         String servletPath;
341         String pathInfo;
342         Boolean included = request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null;
343         if (included != null && included.booleanValue())
344         {
345             servletPath = (String)request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
346             pathInfo = (String)request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
347 
348             if (servletPath == null && pathInfo == null)
349             {
350                 servletPath = request.getServletPath();
351                 pathInfo = request.getPathInfo();
352             }
353         }
354         else
355         {
356             servletPath = request.getServletPath();
357             pathInfo = request.getPathInfo();
358         }
359 
360         String pathInContext=URIUtil.addPaths(servletPath,pathInfo);
361         return getResource(pathInContext);
362     }
363 
364 
365     /* ------------------------------------------------------------ */
366     public String[] getWelcomeFiles()
367     {
368         return _welcomeFiles;
369     }
370 
371     /* ------------------------------------------------------------ */
372     public void setWelcomeFiles(String[] welcomeFiles)
373     {
374         _welcomeFiles=welcomeFiles;
375     }
376 
377     /* ------------------------------------------------------------ */
378     protected Resource getWelcome(Resource directory) throws MalformedURLException, IOException
379     {
380         for (int i=0;i<_welcomeFiles.length;i++)
381         {
382             Resource welcome=directory.addPath(_welcomeFiles[i]);
383             if (welcome.exists() && !welcome.isDirectory())
384                 return welcome;
385         }
386 
387         return null;
388     }
389 
390     /* ------------------------------------------------------------ */
391     /*
392      * @see org.eclipse.jetty.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
393      */
394     @Override
395     public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
396     {
397         if (baseRequest.isHandled())
398             return;
399 
400         boolean skipContentBody = false;
401 
402         if(!HttpMethod.GET.is(request.getMethod()))
403         {
404             if(!HttpMethod.HEAD.is(request.getMethod()))
405             {
406                 //try another handler
407                 super.handle(target, baseRequest, request, response);
408                 return;
409             }
410             skipContentBody = true;
411         }
412 
413         Resource resource = getResource(request);
414         
415         if (LOG.isDebugEnabled())
416         { 
417             if (resource==null)
418                 LOG.debug("resource=null");
419             else
420                 LOG.debug("resource={} alias={} exists={}",resource,resource.getAlias(),resource.exists());
421         }
422         
423         
424         // If resource is not found
425         if (resource==null || !resource.exists())
426         {
427             // inject the jetty-dir.css file if it matches
428             if (target.endsWith("/jetty-dir.css"))
429             {
430                 resource = getStylesheet();
431                 if (resource==null)
432                     return;
433                 response.setContentType("text/css");
434             }
435             else
436             {
437                 //no resource - try other handlers
438                 super.handle(target, baseRequest, request, response);
439                 return;
440             }
441         }
442 
443         // We are going to serve something
444         baseRequest.setHandled(true);
445 
446         // handle directories
447         if (resource.isDirectory())
448         {
449             String pathInfo = request.getPathInfo();
450             boolean endsWithSlash=(pathInfo==null?request.getServletPath():pathInfo).endsWith(URIUtil.SLASH);
451             if (!endsWithSlash)
452             {
453                 response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH)));
454                 return;
455             }
456 
457             Resource welcome=getWelcome(resource);
458             if (welcome!=null && welcome.exists())
459                 resource=welcome;
460             else
461             {
462                 doDirectory(request,response,resource);
463                 baseRequest.setHandled(true);
464                 return;
465             }
466         }
467 
468         // Handle ETAGS
469         long last_modified=resource.lastModified();
470         String etag=null;
471         if (_etags)
472         {
473             // simple handling of only a single etag
474             String ifnm = request.getHeader(HttpHeader.IF_NONE_MATCH.asString());
475             etag=resource.getWeakETag();
476             if (ifnm!=null && resource!=null && ifnm.equals(etag))
477             {
478                 response.setStatus(HttpStatus.NOT_MODIFIED_304);
479                 baseRequest.getResponse().getHttpFields().put(HttpHeader.ETAG,etag);
480                 return;
481             }
482         }
483         
484         // Handle if modified since 
485         if (last_modified>0)
486         {
487             long if_modified=request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
488             if (if_modified>0 && last_modified/1000<=if_modified/1000)
489             {
490                 response.setStatus(HttpStatus.NOT_MODIFIED_304);
491                 return;
492             }
493         }
494 
495         // set the headers
496         String mime=_mimeTypes.getMimeByExtension(resource.toString());
497         if (mime==null)
498             mime=_mimeTypes.getMimeByExtension(request.getPathInfo());
499         doResponseHeaders(response,resource,mime);
500         if (_etags)
501             baseRequest.getResponse().getHttpFields().put(HttpHeader.ETAG,etag);
502         
503         if(skipContentBody)
504             return;
505         
506         
507         // Send the content
508         OutputStream out =null;
509         try {out = response.getOutputStream();}
510         catch(IllegalStateException e) {out = new WriterOutputStream(response.getWriter());}
511 
512         // Has the output been wrapped
513         if (!(out instanceof HttpOutput))
514             // Write content via wrapped output
515             resource.writeTo(out,0,resource.length());
516         else
517         {
518             // select async by size
519             int min_async_size=_minAsyncContentLength==0?response.getBufferSize():_minAsyncContentLength;
520             
521             if (request.isAsyncSupported() && 
522                 min_async_size>0 &&
523                 resource.length()>=min_async_size)
524             {
525                 final AsyncContext async = request.startAsync();
526                 async.setTimeout(0);
527                 Callback callback = new Callback()
528                 {
529                     @Override
530                     public void succeeded()
531                     {
532                         async.complete();
533                     }
534 
535                     @Override
536                     public void failed(Throwable x)
537                     {
538                         LOG.warn(x.toString());
539                         LOG.debug(x);
540                         async.complete();
541                     }   
542                 };
543 
544                 // Can we use a memory mapped file?
545                 if (_minMemoryMappedContentLength>0 && 
546                     resource.length()>_minMemoryMappedContentLength &&
547                     resource.length()<Integer.MAX_VALUE &&
548                     resource instanceof PathResource)
549                 {
550                     ByteBuffer buffer = BufferUtil.toMappedBuffer(resource.getFile());
551                     ((HttpOutput)out).sendContent(buffer,callback);
552                 }
553                 else  // Do a blocking write of a channel (if available) or input stream
554                 {
555                     // Close of the channel/inputstream is done by the async sendContent
556                     ReadableByteChannel channel= resource.getReadableByteChannel();
557                     if (channel!=null)
558                         ((HttpOutput)out).sendContent(channel,callback);
559                     else
560                         ((HttpOutput)out).sendContent(resource.getInputStream(),callback);
561                 }
562             }
563             else
564             {
565                 // Can we use a memory mapped file?
566                 if (_minMemoryMappedContentLength>0 && 
567                     resource.length()>_minMemoryMappedContentLength &&
568                     resource instanceof PathResource)
569                 {
570                     ByteBuffer buffer = BufferUtil.toMappedBuffer(resource.getFile());
571                     ((HttpOutput)out).sendContent(buffer);
572                 }
573                 else  // Do a blocking write of a channel (if available) or input stream
574                 {
575                     ReadableByteChannel channel= resource.getReadableByteChannel();
576                     if (channel!=null)
577                         ((HttpOutput)out).sendContent(channel);
578                     else
579                         ((HttpOutput)out).sendContent(resource.getInputStream());
580                 }
581             }
582         }
583     }
584 
585     /* ------------------------------------------------------------ */
586     protected void doDirectory(HttpServletRequest request,HttpServletResponse response, Resource resource)
587         throws IOException
588     {
589         if (_directory)
590         {
591             String listing = resource.getListHTML(request.getRequestURI(),request.getPathInfo().lastIndexOf("/") > 0);
592             response.setContentType("text/html;charset=utf-8");
593             response.getWriter().println(listing);
594         }
595         else
596             response.sendError(HttpStatus.FORBIDDEN_403);
597     }
598 
599     /* ------------------------------------------------------------ */
600     /** Set the response headers.
601      * This method is called to set the response headers such as content type and content length.
602      * May be extended to add additional headers.
603      * @param response the http response
604      * @param resource the resource
605      * @param mimeType the mime type
606      */
607     protected void doResponseHeaders(HttpServletResponse response, Resource resource, String mimeType)
608     {
609         if (mimeType!=null)
610             response.setContentType(mimeType);
611 
612         long length=resource.length();
613 
614         if (response instanceof Response)
615         {
616             HttpFields fields = ((Response)response).getHttpFields();
617 
618             if (length>0)
619                 ((Response)response).setLongContentLength(length);
620 
621             if (_cacheControl!=null)
622                 fields.put(HttpHeader.CACHE_CONTROL,_cacheControl);
623         }
624         else
625         {
626             if (length>Integer.MAX_VALUE)
627                 response.setHeader(HttpHeader.CONTENT_LENGTH.asString(),Long.toString(length));
628             else if (length>0)
629                 response.setContentLength((int)length);
630 
631             if (_cacheControl!=null)
632                 response.setHeader(HttpHeader.CACHE_CONTROL.asString(),_cacheControl);
633         }
634     }
635 }