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.servlet;
20  
21  import java.io.FileNotFoundException;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.OutputStream;
25  import java.net.MalformedURLException;
26  import java.net.URL;
27  import java.nio.ByteBuffer;
28  import java.util.ArrayList;
29  import java.util.Enumeration;
30  import java.util.List;
31  import java.util.StringTokenizer;
32  
33  import javax.servlet.AsyncContext;
34  import javax.servlet.RequestDispatcher;
35  import javax.servlet.ServletContext;
36  import javax.servlet.ServletException;
37  import javax.servlet.UnavailableException;
38  import javax.servlet.http.HttpServlet;
39  import javax.servlet.http.HttpServletRequest;
40  import javax.servlet.http.HttpServletResponse;
41  
42  import org.eclipse.jetty.http.DateParser;
43  import org.eclipse.jetty.http.HttpContent;
44  import org.eclipse.jetty.http.HttpField;
45  import org.eclipse.jetty.http.HttpFields;
46  import org.eclipse.jetty.http.HttpHeader;
47  import org.eclipse.jetty.http.HttpMethod;
48  import org.eclipse.jetty.http.MimeTypes;
49  import org.eclipse.jetty.http.PathMap.MappedEntry;
50  import org.eclipse.jetty.http.PreEncodedHttpField;
51  import org.eclipse.jetty.http.ResourceHttpContent;
52  import org.eclipse.jetty.io.WriterOutputStream;
53  import org.eclipse.jetty.server.HttpOutput;
54  import org.eclipse.jetty.server.InclusiveByteRange;
55  import org.eclipse.jetty.server.Request;
56  import org.eclipse.jetty.server.ResourceCache;
57  import org.eclipse.jetty.server.Response;
58  import org.eclipse.jetty.server.handler.ContextHandler;
59  import org.eclipse.jetty.util.BufferUtil;
60  import org.eclipse.jetty.util.Callback;
61  import org.eclipse.jetty.util.IO;
62  import org.eclipse.jetty.util.MultiPartOutputStream;
63  import org.eclipse.jetty.util.QuotedStringTokenizer;
64  import org.eclipse.jetty.util.URIUtil;
65  import org.eclipse.jetty.util.log.Log;
66  import org.eclipse.jetty.util.log.Logger;
67  import org.eclipse.jetty.util.resource.Resource;
68  import org.eclipse.jetty.util.resource.ResourceCollection;
69  import org.eclipse.jetty.util.resource.ResourceFactory;
70  
71  
72  /** 
73   * The default servlet.
74   * <p>
75   * This servlet, normally mapped to /, provides the handling for static
76   * content, OPTION and TRACE methods for the context.
77   * The following initParameters are supported, these can be set either
78   * on the servlet itself or as ServletContext initParameters with a prefix
79   * of org.eclipse.jetty.servlet.Default. :
80   * <pre>
81   *  acceptRanges      If true, range requests and responses are
82   *                    supported
83   *
84   *  dirAllowed        If true, directory listings are returned if no
85   *                    welcome file is found. Else 403 Forbidden.
86   *
87   *  welcomeServlets   If true, attempt to dispatch to welcome files
88   *                    that are servlets, but only after no matching static
89   *                    resources could be found. If false, then a welcome
90   *                    file must exist on disk. If "exact", then exact
91   *                    servlet matches are supported without an existing file.
92   *                    Default is true.
93   *
94   *                    This must be false if you want directory listings,
95   *                    but have index.jsp in your welcome file list.
96   *
97   *  redirectWelcome   If true, welcome files are redirected rather than
98   *                    forwarded to.
99   *
100  *  gzip              If set to true, then static content will be served as
101  *                    gzip content encoded if a matching resource is
102  *                    found ending with ".gz"
103  *
104  *  resourceBase      Set to replace the context resource base
105  *
106  *  resourceCache     If set, this is a context attribute name, which the servlet
107  *                    will use to look for a shared ResourceCache instance.
108  *
109  *  relativeResourceBase
110  *                    Set with a pathname relative to the base of the
111  *                    servlet context root. Useful for only serving static content out
112  *                    of only specific subdirectories.
113  *
114  *  pathInfoOnly      If true, only the path info will be applied to the resourceBase
115  *
116  *  stylesheet	      Set with the location of an optional stylesheet that will be used
117  *                    to decorate the directory listing html.
118  *
119  *  etags             If True, weak etags will be generated and handled.
120  *
121  *  maxCacheSize      The maximum total size of the cache or 0 for no cache.
122  *  maxCachedFileSize The maximum size of a file to cache
123  *  maxCachedFiles    The maximum number of files to cache
124  *
125  *  useFileMappedBuffer
126  *                    If set to true, it will use mapped file buffer to serve static content
127  *                    when using NIO connector. Setting this value to false means that
128  *                    a direct buffer will be used instead of a mapped file buffer.
129  *                    This is set to false by default by this class, but may be overridden
130  *                    by eg webdefault.xml 
131  *
132  *  cacheControl      If set, all static content will have this value set as the cache-control
133  *                    header.
134  *                    
135  * otherGzipFileExtensions
136  *                    Other file extensions that signify that a file is gzip compressed. Eg ".svgz"
137  *
138  *
139  * </pre>
140  *
141  */
142 public class DefaultServlet extends HttpServlet implements ResourceFactory
143 {
144     private static final Logger LOG = Log.getLogger(DefaultServlet.class);
145 
146     private static final long serialVersionUID = 4930458713846881193L;
147     
148     private static final PreEncodedHttpField ACCEPT_RANGES = new PreEncodedHttpField(HttpHeader.ACCEPT_RANGES, "bytes");
149     
150     private ServletContext _servletContext;
151     private ContextHandler _contextHandler;
152 
153     private boolean _acceptRanges=true;
154     private boolean _dirAllowed=true;
155     private boolean _welcomeServlets=false;
156     private boolean _welcomeExactServlets=false;
157     private boolean _redirectWelcome=false;
158     private boolean _gzip=false;
159     private boolean _pathInfoOnly=false;
160     private boolean _etags=false;
161 
162     private Resource _resourceBase;
163     private ResourceCache _cache;
164 
165     private MimeTypes _mimeTypes;
166     private String[] _welcomes;
167     private Resource _stylesheet;
168     private boolean _useFileMappedBuffer=false;
169     private HttpField _cacheControl;
170     private String _relativeResourceBase;
171     private ServletHandler _servletHandler;
172     private ServletHolder _defaultHolder;
173     private List<String> _gzipEquivalentFileExtensions;
174 
175     /* ------------------------------------------------------------ */
176     @Override
177     public void init()
178     throws UnavailableException
179     {
180         _servletContext=getServletContext();
181         _contextHandler = initContextHandler(_servletContext);
182 
183         _mimeTypes = _contextHandler.getMimeTypes();
184 
185         _welcomes = _contextHandler.getWelcomeFiles();
186         if (_welcomes==null)
187             _welcomes=new String[] {"index.html","index.jsp"};
188 
189         _acceptRanges=getInitBoolean("acceptRanges",_acceptRanges);
190         _dirAllowed=getInitBoolean("dirAllowed",_dirAllowed);
191         _redirectWelcome=getInitBoolean("redirectWelcome",_redirectWelcome);
192         _gzip=getInitBoolean("gzip",_gzip);
193         _pathInfoOnly=getInitBoolean("pathInfoOnly",_pathInfoOnly);
194 
195         if ("exact".equals(getInitParameter("welcomeServlets")))
196         {
197             _welcomeExactServlets=true;
198             _welcomeServlets=false;
199         }
200         else
201             _welcomeServlets=getInitBoolean("welcomeServlets", _welcomeServlets);
202 
203         _useFileMappedBuffer=getInitBoolean("useFileMappedBuffer",_useFileMappedBuffer);
204 
205         _relativeResourceBase = getInitParameter("relativeResourceBase");
206 
207         String rb=getInitParameter("resourceBase");
208         if (rb!=null)
209         {
210             if (_relativeResourceBase!=null)
211                 throw new  UnavailableException("resourceBase & relativeResourceBase");
212             try{_resourceBase=_contextHandler.newResource(rb);}
213             catch (Exception e)
214             {
215                 LOG.warn(Log.EXCEPTION,e);
216                 throw new UnavailableException(e.toString());
217             }
218         }
219 
220         String css=getInitParameter("stylesheet");
221         try
222         {
223             if(css!=null)
224             {
225                 _stylesheet = Resource.newResource(css);
226                 if(!_stylesheet.exists())
227                 {
228                     LOG.warn("!" + css);
229                     _stylesheet = null;
230                 }
231             }
232             if(_stylesheet == null)
233             {
234                 _stylesheet = Resource.newResource(this.getClass().getResource("/jetty-dir.css"));
235             }
236         }
237         catch(Exception e)
238         {
239             LOG.warn(e.toString());
240             LOG.debug(e);
241         }
242 
243         String cc=getInitParameter("cacheControl");
244         if (cc!=null)
245             _cacheControl=new PreEncodedHttpField(HttpHeader.CACHE_CONTROL, cc);
246         
247         String resourceCache = getInitParameter("resourceCache");
248         int max_cache_size=getInitInt("maxCacheSize", -2);
249         int max_cached_file_size=getInitInt("maxCachedFileSize", -2);
250         int max_cached_files=getInitInt("maxCachedFiles", -2);
251         if (resourceCache!=null)
252         {
253             if (max_cache_size!=-1 || max_cached_file_size!= -2 || max_cached_files!=-2)
254                 LOG.debug("ignoring resource cache configuration, using resourceCache attribute");
255             if (_relativeResourceBase!=null || _resourceBase!=null)
256                 throw new UnavailableException("resourceCache specified with resource bases");
257             _cache=(ResourceCache)_servletContext.getAttribute(resourceCache);
258 
259             if (LOG.isDebugEnabled())
260                 LOG.debug("Cache {}={}",resourceCache,_cache);
261         }
262 
263         _etags = getInitBoolean("etags",_etags);
264         
265         try
266         {
267             if (_cache==null && (max_cached_files!=-2 || max_cache_size!=-2 || max_cached_file_size!=-2))
268             {
269                 _cache= new ResourceCache(null,this,_mimeTypes,_useFileMappedBuffer,_etags);
270 
271                 if (max_cache_size>=0)
272                     _cache.setMaxCacheSize(max_cache_size);
273                 if (max_cached_file_size>=-1)
274                     _cache.setMaxCachedFileSize(max_cached_file_size);
275                 if (max_cached_files>=-1)
276                     _cache.setMaxCachedFiles(max_cached_files);
277             }
278         }
279         catch (Exception e)
280         {
281             LOG.warn(Log.EXCEPTION,e);
282             throw new UnavailableException(e.toString());
283         }
284         
285        _gzipEquivalentFileExtensions = new ArrayList<String>();
286        String otherGzipExtensions = getInitParameter("otherGzipFileExtensions");
287        if (otherGzipExtensions != null)
288        {
289            //comma separated list
290            StringTokenizer tok = new StringTokenizer(otherGzipExtensions,",",false);
291            while (tok.hasMoreTokens())
292            {
293                String s = tok.nextToken().trim();
294                _gzipEquivalentFileExtensions.add((s.charAt(0)=='.'?s:"."+s));
295            }
296        }
297        else
298        {
299            //.svgz files are gzipped svg files and must be served with Content-Encoding:gzip
300            _gzipEquivalentFileExtensions.add(".svgz");   
301        }
302 
303        _servletHandler= _contextHandler.getChildHandlerByClass(ServletHandler.class);
304        for (ServletHolder h :_servletHandler.getServlets())
305            if (h.getServletInstance()==this)
306                _defaultHolder=h;
307 
308 
309        if (LOG.isDebugEnabled())
310            LOG.debug("resource base = "+_resourceBase);
311     }
312 
313     /**
314      * Compute the field _contextHandler.<br>
315      * In the case where the DefaultServlet is deployed on the HttpService it is likely that
316      * this method needs to be overwritten to unwrap the ServletContext facade until we reach
317      * the original jetty's ContextHandler.
318      * @param servletContext The servletContext of this servlet.
319      * @return the jetty's ContextHandler for this servletContext.
320      */
321     protected ContextHandler initContextHandler(ServletContext servletContext)
322     {
323         ContextHandler.Context scontext=ContextHandler.getCurrentContext();
324         if (scontext==null)
325         {
326             if (servletContext instanceof ContextHandler.Context)
327                 return ((ContextHandler.Context)servletContext).getContextHandler();
328             else
329                 throw new IllegalArgumentException("The servletContext " + servletContext + " " +
330                     servletContext.getClass().getName() + " is not " + ContextHandler.Context.class.getName());
331         }
332         else
333             return ContextHandler.getCurrentContext().getContextHandler();
334     }
335 
336     /* ------------------------------------------------------------ */
337     @Override
338     public String getInitParameter(String name)
339     {
340         String value=getServletContext().getInitParameter("org.eclipse.jetty.servlet.Default."+name);
341         if (value==null)
342             value=super.getInitParameter(name);
343         return value;
344     }
345 
346     /* ------------------------------------------------------------ */
347     private boolean getInitBoolean(String name, boolean dft)
348     {
349         String value=getInitParameter(name);
350         if (value==null || value.length()==0)
351             return dft;
352         return (value.startsWith("t")||
353                 value.startsWith("T")||
354                 value.startsWith("y")||
355                 value.startsWith("Y")||
356                 value.startsWith("1"));
357     }
358 
359     /* ------------------------------------------------------------ */
360     private int getInitInt(String name, int dft)
361     {
362         String value=getInitParameter(name);
363         if (value==null)
364             value=getInitParameter(name);
365         if (value!=null && value.length()>0)
366             return Integer.parseInt(value);
367         return dft;
368     }
369 
370     /* ------------------------------------------------------------ */
371     /** get Resource to serve.
372      * Map a path to a resource. The default implementation calls
373      * HttpContext.getResource but derived servlets may provide
374      * their own mapping.
375      * @param pathInContext The path to find a resource for.
376      * @return The resource to serve.
377      */
378     @Override
379     public Resource getResource(String pathInContext)
380     {
381         Resource r=null;
382         if (_relativeResourceBase!=null)
383             pathInContext=URIUtil.addPaths(_relativeResourceBase,pathInContext);
384 
385         try
386         {
387             if (_resourceBase!=null)
388             {
389                 r = _resourceBase.addPath(pathInContext);
390                 if (!_contextHandler.checkAlias(pathInContext,r))
391                     r=null;
392             }
393             else if (_servletContext instanceof ContextHandler.Context)
394             {
395                 r = _contextHandler.getResource(pathInContext);
396             }
397             else
398             {
399                 URL u = _servletContext.getResource(pathInContext);
400                 r = _contextHandler.newResource(u);
401             }
402 
403             if (LOG.isDebugEnabled())
404                 LOG.debug("Resource "+pathInContext+"="+r);
405         }
406         catch (IOException e)
407         {
408             LOG.ignore(e);
409         }
410 
411         if((r==null || !r.exists()) && pathInContext.endsWith("/jetty-dir.css"))
412             r=_stylesheet;
413 
414         return r;
415     }
416 
417     /* ------------------------------------------------------------ */
418     @Override
419     protected void doGet(HttpServletRequest request, HttpServletResponse response)
420     throws ServletException, IOException
421     {
422         String servletPath=null;
423         String pathInfo=null;
424         Enumeration<String> reqRanges = null;
425         Boolean included =request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI)!=null;
426         if (included!=null && included.booleanValue())
427         {
428             servletPath=(String)request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
429             pathInfo=(String)request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
430             if (servletPath==null)
431             {
432                 servletPath=request.getServletPath();
433                 pathInfo=request.getPathInfo();
434             }
435         }
436         else
437         {
438             included = Boolean.FALSE;
439             servletPath = _pathInfoOnly?"/":request.getServletPath();
440             pathInfo = request.getPathInfo();
441 
442             // Is this a Range request?
443             reqRanges = request.getHeaders(HttpHeader.RANGE.asString());
444             if (!hasDefinedRange(reqRanges))
445                 reqRanges = null;
446         }
447 
448         String pathInContext=URIUtil.addPaths(servletPath,pathInfo);
449         boolean endsWithSlash=(pathInfo==null?request.getServletPath():pathInfo).endsWith(URIUtil.SLASH);
450 
451 
452         // Find the resource and content
453         Resource resource=null;
454         HttpContent content=null;
455         try
456         {
457             // is gzip enabled?
458             String pathInContextGz=null;
459             boolean gzip=false;
460             if (!included.booleanValue() && _gzip && reqRanges==null && !endsWithSlash )
461             {
462                 // Look for a gzip resource
463                 pathInContextGz=pathInContext+".gz";
464                 if (_cache==null)
465                     resource=getResource(pathInContextGz);
466                 else
467                 {
468                     content=_cache.lookup(pathInContextGz);
469                     resource=(content==null)?null:content.getResource();
470                 }
471 
472                 // Does a gzip resource exist?
473                 if (resource!=null && resource.exists() && !resource.isDirectory())
474                 {
475                     // Tell caches that response may vary by accept-encoding
476                     response.addHeader(HttpHeader.VARY.asString(),HttpHeader.ACCEPT_ENCODING.asString());
477                     
478                     // Does the client accept gzip?
479                     String accept=request.getHeader(HttpHeader.ACCEPT_ENCODING.asString());
480                     if (accept!=null && accept.indexOf("gzip")>=0)
481                         gzip=true;
482                 }
483             }
484 
485             // find resource
486             if (!gzip)
487             {
488                 if (_cache==null)
489                     resource=getResource(pathInContext);
490                 else
491                 {
492                     content=_cache.lookup(pathInContext);
493                     resource=content==null?null:content.getResource();
494                 }
495             }
496 
497             if (LOG.isDebugEnabled())
498                 LOG.debug(String.format("uri=%s, resource=%s, content=%s",request.getRequestURI(),resource,content));
499 
500             // Handle resource
501             if (resource==null || !resource.exists())
502             {
503                 if (included)
504                     throw new FileNotFoundException("!" + pathInContext);
505                 response.sendError(HttpServletResponse.SC_NOT_FOUND);
506             }
507             else if (!resource.isDirectory())
508             {
509                 if (endsWithSlash && pathInContext.length()>1)
510                 {
511                     String q=request.getQueryString();
512                     pathInContext=pathInContext.substring(0,pathInContext.length()-1);
513                     if (q!=null&&q.length()!=0)
514                         pathInContext+="?"+q;
515                     response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(_servletContext.getContextPath(),pathInContext)));
516                 }
517                 else
518                 {
519                     // ensure we have content
520                     if (content==null)
521                         content=new ResourceHttpContent(resource,_mimeTypes.getMimeByExtension(resource.toString()),response.getBufferSize(),_etags);
522 
523                     if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
524                     {
525                         if (gzip || isGzippedContent(pathInContext))
526                         {
527                             response.setHeader(HttpHeader.CONTENT_ENCODING.asString(),"gzip");
528                             String mt=_servletContext.getMimeType(pathInContext);
529                             if (mt!=null)
530                                 response.setContentType(mt);
531                         }
532                         sendData(request,response,included.booleanValue(),resource,content,reqRanges);
533                     }
534                 }
535             }
536             else
537             {
538                 String welcome=null;
539 
540                 if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.eclipse.jetty.server.nullPathInfo")!=null))
541                 {
542                     StringBuffer buf=request.getRequestURL();
543                     synchronized(buf)
544                     {
545                         int param=buf.lastIndexOf(";");
546                         if (param<0)
547                             buf.append('/');
548                         else
549                             buf.insert(param,'/');
550                         String q=request.getQueryString();
551                         if (q!=null&&q.length()!=0)
552                         {
553                             buf.append('?');
554                             buf.append(q);
555                         }
556                         response.setContentLength(0);
557                         response.sendRedirect(response.encodeRedirectURL(buf.toString()));
558                     }
559                 }
560                 // else look for a welcome file
561                 else if (null!=(welcome=getWelcomeFile(pathInContext)))
562                 {
563                     if (LOG.isDebugEnabled())
564                         LOG.debug("welcome={}",welcome);
565                     if (_redirectWelcome)
566                     {
567                         // Redirect to the index
568                         response.setContentLength(0);
569                         String q=request.getQueryString();
570                         if (q!=null&&q.length()!=0)
571                             response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths( _servletContext.getContextPath(),welcome)+"?"+q));
572                         else
573                             response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths( _servletContext.getContextPath(),welcome)));
574                     }
575                     else
576                     {
577                         // Forward to the index
578                         RequestDispatcher dispatcher=request.getRequestDispatcher(welcome);
579                         if (dispatcher!=null)
580                         {
581                             if (included.booleanValue())
582                                 dispatcher.include(request,response);
583                             else
584                             {
585                                 request.setAttribute("org.eclipse.jetty.server.welcome",welcome);
586                                 dispatcher.forward(request,response);
587                             }
588                         }
589                     }
590                 }
591                 else
592                 {
593                     content=new ResourceHttpContent(resource,_mimeTypes.getMimeByExtension(resource.toString()),_etags);
594                     if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
595                         sendDirectory(request,response,resource,pathInContext);
596                 }
597             }
598         }
599         catch(IllegalArgumentException e)
600         {
601             LOG.warn(Log.EXCEPTION,e);
602             if(!response.isCommitted())
603                 response.sendError(500, e.getMessage());
604         }
605         finally
606         {
607             if (content!=null)
608                 content.release();
609             else if (resource!=null)
610                 resource.close();
611         }
612 
613     }
614 
615     protected boolean isGzippedContent(String path)
616     {
617         if (path == null) return false;
618       
619         for (String suffix:_gzipEquivalentFileExtensions)
620             if (path.endsWith(suffix))
621                 return true;
622         return false;
623     }
624 
625     /* ------------------------------------------------------------ */
626     private boolean hasDefinedRange(Enumeration<String> reqRanges)
627     {
628         return (reqRanges!=null && reqRanges.hasMoreElements());
629     }
630 
631     /* ------------------------------------------------------------ */
632     @Override
633     protected void doPost(HttpServletRequest request, HttpServletResponse response)
634     throws ServletException, IOException
635     {
636         doGet(request,response);
637     }
638 
639     /* ------------------------------------------------------------ */
640     /* (non-Javadoc)
641      * @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
642      */
643     @Override
644     protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
645     {
646         resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
647     }
648 
649     /* ------------------------------------------------------------ */
650     @Override
651     protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
652     throws ServletException, IOException
653     {
654         resp.setHeader("Allow", "GET,HEAD,POST,OPTIONS");
655     }
656 
657     /* ------------------------------------------------------------ */
658     /**
659      * Finds a matching welcome file for the supplied {@link Resource}. This will be the first entry in the list of
660      * configured {@link #_welcomes welcome files} that existing within the directory referenced by the <code>Resource</code>.
661      * If the resource is not a directory, or no matching file is found, then it may look for a valid servlet mapping.
662      * If there is none, then <code>null</code> is returned.
663      * The list of welcome files is read from the {@link ContextHandler} for this servlet, or
664      * <code>"index.jsp" , "index.html"</code> if that is <code>null</code>.
665      * @param resource
666      * @return The path of the matching welcome file in context or null.
667      * @throws IOException
668      * @throws MalformedURLException
669      */
670     private String getWelcomeFile(String pathInContext) throws MalformedURLException, IOException
671     {
672         if (_welcomes==null)
673             return null;
674 
675         String welcome_servlet=null;
676         for (int i=0;i<_welcomes.length;i++)
677         {
678             String welcome_in_context=URIUtil.addPaths(pathInContext,_welcomes[i]);
679             Resource welcome=getResource(welcome_in_context);
680             if (welcome!=null && welcome.exists())
681                 return _welcomes[i];
682 
683             if ((_welcomeServlets || _welcomeExactServlets) && welcome_servlet==null)
684             {
685                 MappedEntry<?> entry=_servletHandler.getHolderEntry(welcome_in_context);
686                 if (entry!=null && entry.getValue()!=_defaultHolder &&
687                         (_welcomeServlets || (_welcomeExactServlets && entry.getKey().equals(welcome_in_context))))
688                     welcome_servlet=welcome_in_context;
689 
690             }
691         }
692         return welcome_servlet;
693     }
694 
695     /* ------------------------------------------------------------ */
696     /* Check modification date headers.
697      */
698     protected boolean passConditionalHeaders(HttpServletRequest request,HttpServletResponse response, Resource resource, HttpContent content)
699     throws IOException
700     {
701         try
702         {
703             String ifm=null;
704             String ifnm=null;
705             String ifms=null;
706             long ifums=-1;
707             
708             if (request instanceof Request)
709             {
710                 HttpFields fields = ((Request)request).getHttpFields();
711                 for (int i=fields.size();i-->0;)
712                 {
713                     HttpField field=fields.getField(i);
714                     if (field.getHeader() != null)
715                     {
716                         switch (field.getHeader())
717                         {
718                             case IF_MATCH:
719                                 ifm=field.getValue();
720                                 break;
721                             case IF_NONE_MATCH:
722                                 ifnm=field.getValue();
723                                 break;
724                             case IF_MODIFIED_SINCE:
725                                 ifms=field.getValue();
726                                 break;
727                             case IF_UNMODIFIED_SINCE:
728                                 ifums=DateParser.parseDate(field.getValue());
729                                 break;
730                             default:
731                         }
732                     }
733                 }
734             }
735             else
736             {
737                 ifm=request.getHeader(HttpHeader.IF_MATCH.asString());
738                 ifnm=request.getHeader(HttpHeader.IF_NONE_MATCH.asString());
739                 ifms=request.getHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
740                 ifums=request.getDateHeader(HttpHeader.IF_UNMODIFIED_SINCE.asString());
741             }
742             
743             if (!HttpMethod.HEAD.is(request.getMethod()))
744             {
745                 if (_etags)
746                 {
747                     if (ifm!=null)
748                     {
749                         boolean match=false;
750                         if (content.getETagValue()!=null)
751                         {
752                             QuotedStringTokenizer quoted = new QuotedStringTokenizer(ifm,", ",false,true);
753                             while (!match && quoted.hasMoreTokens())
754                             {
755                                 String tag = quoted.nextToken();
756                                 if (content.getETagValue().equals(tag))
757                                     match=true;
758                             }
759                         }
760 
761                         if (!match)
762                         {
763                             response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
764                             return false;
765                         }
766                     }
767                     
768                     if (ifnm!=null && content.getETagValue()!=null)
769                     {
770                         // Look for Gzip'd version of etag
771                         if (content.getETagValue().equals(request.getAttribute("o.e.j.s.Gzip.ETag")))
772                         {
773                             response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
774                             response.setHeader(HttpHeader.ETAG.asString(),ifnm);
775                             return false;
776                         }
777                         
778                         // Handle special case of exact match.
779                         if (content.getETagValue().equals(ifnm))
780                         {
781                             response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
782                             response.setHeader(HttpHeader.ETAG.asString(),content.getETagValue());
783                             return false;
784                         }
785 
786                         // Handle list of tags
787                         QuotedStringTokenizer quoted = new QuotedStringTokenizer(ifnm,", ",false,true);
788                         while (quoted.hasMoreTokens())
789                         {
790                             String tag = quoted.nextToken();
791                             if (content.getETagValue().equals(tag))
792                             {
793                                 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
794                                 response.setHeader(HttpHeader.ETAG.asString(),content.getETagValue());
795                                 return false;
796                             }
797                         }
798                         
799                         // If etag requires content to be served, then do not check if-modified-since
800                         return true;
801                     }
802                 }
803                 
804                 // Handle if modified since
805                 if (ifms!=null)
806                 {
807                     //Get jetty's Response impl
808                     String mdlm=content.getLastModifiedValue();
809                     if (mdlm!=null && ifms.equals(mdlm))
810                     {
811                         response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
812                         if (_etags)
813                             response.setHeader(HttpHeader.ETAG.asString(),content.getETagValue());
814                         response.flushBuffer();
815                         return false;
816                     }
817 
818                     long ifmsl=request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
819                     if (ifmsl!=-1 && resource.lastModified()/1000 <= ifmsl/1000)
820                     { 
821                         response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
822                         if (_etags)
823                             response.setHeader(HttpHeader.ETAG.asString(),content.getETagValue());
824                         response.flushBuffer();
825                         return false;
826                     }
827                 }
828 
829                 // Parse the if[un]modified dates and compare to resource
830                 if (ifums!=-1 && resource.lastModified()/1000 > ifums/1000)
831                 {
832                     response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
833                     return false;
834                 }
835 
836             }
837         }
838         catch(IllegalArgumentException iae)
839         {
840             if(!response.isCommitted())
841                 response.sendError(400, iae.getMessage());
842             throw iae;
843         }
844         return true;
845     }
846 
847 
848     /* ------------------------------------------------------------------- */
849     protected void sendDirectory(HttpServletRequest request,
850             HttpServletResponse response,
851             Resource resource,
852             String pathInContext)
853     throws IOException
854     {
855         if (!_dirAllowed)
856         {
857             response.sendError(HttpServletResponse.SC_FORBIDDEN);
858             return;
859         }
860 
861         byte[] data=null;
862         String base = URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH);
863 
864         //If the DefaultServlet has a resource base set, use it
865         if (_resourceBase != null)
866         {
867             // handle ResourceCollection
868             if (_resourceBase instanceof ResourceCollection)
869                 resource=_resourceBase.addPath(pathInContext);
870         }
871         //Otherwise, try using the resource base of its enclosing context handler
872         else if (_contextHandler.getBaseResource() instanceof ResourceCollection)
873             resource=_contextHandler.getBaseResource().addPath(pathInContext);
874 
875         String dir = resource.getListHTML(base,pathInContext.length()>1);
876         if (dir==null)
877         {
878             response.sendError(HttpServletResponse.SC_FORBIDDEN,
879             "No directory");
880             return;
881         }
882 
883         data=dir.getBytes("utf-8");
884         response.setContentType("text/html;charset=utf-8");
885         response.setContentLength(data.length);
886         response.getOutputStream().write(data);
887     }
888 
889     /* ------------------------------------------------------------ */
890     protected void sendData(HttpServletRequest request,
891             HttpServletResponse response,
892             boolean include,
893             Resource resource,
894             HttpContent content,
895             Enumeration<String> reqRanges)
896     throws IOException
897     {
898         final long content_length = (content==null)?resource.length():content.getContentLengthValue();
899         
900         // Get the output stream (or writer)
901         OutputStream out =null;
902         boolean written;
903         try
904         {
905             out = response.getOutputStream();
906 
907             // has a filter already written to the response?
908             written = out instanceof HttpOutput
909                 ? ((HttpOutput)out).isWritten()
910                 : true;
911         }
912         catch(IllegalStateException e)
913         {
914             out = new WriterOutputStream(response.getWriter());
915             written=true; // there may be data in writer buffer, so assume written
916         }
917         
918         if (LOG.isDebugEnabled())
919             LOG.debug(String.format("sendData content=%s out=%s async=%b",content,out,request.isAsyncSupported()));
920 
921         if ( reqRanges == null || !reqRanges.hasMoreElements() || content_length<0)
922         {
923             //  if there were no ranges, send entire entity
924             if (include)
925             {
926                 // write without headers
927                 resource.writeTo(out,0,content_length);
928             }
929             // else if we can't do a bypass write because of wrapping
930             else if (content==null || written || !(out instanceof HttpOutput))
931             {
932                 // write normally
933                 putHeaders(response,content,written?-1:0);
934                 ByteBuffer buffer = (content==null)?null:content.getIndirectBuffer();
935                 if (buffer!=null)
936                     BufferUtil.writeTo(buffer,out);
937                 else
938                     resource.writeTo(out,0,content_length);
939             }
940             // else do a bypass write
941             else
942             {
943                 // write the headers
944                 putHeaders(response,content,0);
945 
946                 // write the content asynchronously if supported
947                 if (request.isAsyncSupported())
948                 {
949                     final AsyncContext context = request.startAsync();
950                     context.setTimeout(0);
951 
952                     ((HttpOutput)out).sendContent(content,new Callback()
953                     {
954                         @Override
955                         public void succeeded()
956                         {   
957                             context.complete();
958                         }
959 
960                         @Override
961                         public void failed(Throwable x)
962                         {
963                             if (x instanceof IOException)
964                                 LOG.debug(x);
965                             else
966                                 LOG.warn(x);
967                             context.complete();
968                         }
969                         
970                         @Override
971                         public String toString() 
972                         {
973                             return String.format("DefaultServlet@%x$CB", DefaultServlet.this.hashCode());
974                         }
975                     });
976                 }
977                 // otherwise write content blocking
978                 else
979                 {
980                     ((HttpOutput)out).sendContent(content);
981                 }
982             }
983         }
984         else
985         {
986             // Parse the satisfiable ranges
987             List<InclusiveByteRange> ranges =InclusiveByteRange.satisfiableRanges(reqRanges,content_length);
988 
989             //  if there are no satisfiable ranges, send 416 response
990             if (ranges==null || ranges.size()==0)
991             {
992                 putHeaders(response,content,0);
993                 response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
994                 response.setHeader(HttpHeader.CONTENT_RANGE.asString(),
995                         InclusiveByteRange.to416HeaderRangeString(content_length));
996                 resource.writeTo(out,0,content_length);
997                 return;
998             }
999 
1000             //  if there is only a single valid range (must be satisfiable
1001             //  since were here now), send that range with a 216 response
1002             if ( ranges.size()== 1)
1003             {
1004                 InclusiveByteRange singleSatisfiableRange = ranges.get(0);
1005                 long singleLength = singleSatisfiableRange.getSize(content_length);
1006                 putHeaders(response,content,singleLength);
1007                 response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
1008                 if (!response.containsHeader(HttpHeader.DATE.asString()))
1009                     response.addDateHeader(HttpHeader.DATE.asString(),System.currentTimeMillis());
1010                 response.setHeader(HttpHeader.CONTENT_RANGE.asString(),
1011                         singleSatisfiableRange.toHeaderRangeString(content_length));
1012                 resource.writeTo(out,singleSatisfiableRange.getFirst(content_length),singleLength);
1013                 return;
1014             }
1015 
1016             //  multiple non-overlapping valid ranges cause a multipart
1017             //  216 response which does not require an overall
1018             //  content-length header
1019             //
1020             putHeaders(response,content,-1);
1021             String mimetype=(content==null?null:content.getContentTypeValue());
1022             if (mimetype==null)
1023                 LOG.warn("Unknown mimetype for "+request.getRequestURI());
1024             MultiPartOutputStream multi = new MultiPartOutputStream(out);
1025             response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
1026             if (!response.containsHeader(HttpHeader.DATE.asString()))
1027                 response.addDateHeader(HttpHeader.DATE.asString(),System.currentTimeMillis());
1028 
1029             // If the request has a "Request-Range" header then we need to
1030             // send an old style multipart/x-byteranges Content-Type. This
1031             // keeps Netscape and acrobat happy. This is what Apache does.
1032             String ctp;
1033             if (request.getHeader(HttpHeader.REQUEST_RANGE.asString())!=null)
1034                 ctp = "multipart/x-byteranges; boundary=";
1035             else
1036                 ctp = "multipart/byteranges; boundary=";
1037             response.setContentType(ctp+multi.getBoundary());
1038 
1039             InputStream in=resource.getInputStream();
1040             long pos=0;
1041 
1042             // calculate the content-length
1043             int length=0;
1044             String[] header = new String[ranges.size()];
1045             for (int i=0;i<ranges.size();i++)
1046             {
1047                 InclusiveByteRange ibr = ranges.get(i);
1048                 header[i]=ibr.toHeaderRangeString(content_length);
1049                 length+=
1050                     ((i>0)?2:0)+
1051                     2+multi.getBoundary().length()+2+
1052                     (mimetype==null?0:HttpHeader.CONTENT_TYPE.asString().length()+2+mimetype.length())+2+
1053                     HttpHeader.CONTENT_RANGE.asString().length()+2+header[i].length()+2+
1054                     2+
1055                     (ibr.getLast(content_length)-ibr.getFirst(content_length))+1;
1056             }
1057             length+=2+2+multi.getBoundary().length()+2+2;
1058             response.setContentLength(length);
1059 
1060             for (int i=0;i<ranges.size();i++)
1061             {
1062                 InclusiveByteRange ibr =  ranges.get(i);
1063                 multi.startPart(mimetype,new String[]{HttpHeader.CONTENT_RANGE+": "+header[i]});
1064 
1065                 long start=ibr.getFirst(content_length);
1066                 long size=ibr.getSize(content_length);
1067                 if (in!=null)
1068                 {
1069                     // Handle non cached resource
1070                     if (start<pos)
1071                     {
1072                         in.close();
1073                         in=resource.getInputStream();
1074                         pos=0;
1075                     }
1076                     if (pos<start)
1077                     {
1078                         in.skip(start-pos);
1079                         pos=start;
1080                     }
1081                     
1082                     IO.copy(in,multi,size);
1083                     pos+=size;
1084                 }
1085                 else
1086                     // Handle cached resource
1087                     (resource).writeTo(multi,start,size);
1088             }
1089             if (in!=null)
1090                 in.close();
1091             multi.close();
1092         }
1093         return;
1094     }
1095 
1096     /* ------------------------------------------------------------ */
1097     protected void putHeaders(HttpServletResponse response,HttpContent content, long contentLength)
1098     {
1099         if (response instanceof Response)
1100         {
1101             Response r = (Response)response;
1102             r.putHeaders(content,contentLength,_etags);
1103             HttpFields f = r.getHttpFields();
1104             if (_acceptRanges)
1105                 f.put(ACCEPT_RANGES);
1106 
1107             if (_cacheControl!=null)
1108                 f.put(_cacheControl);
1109         }
1110         else
1111         {
1112             Response.putHeaders(response,content,contentLength,_etags);
1113             if (_acceptRanges)
1114                 response.setHeader(ACCEPT_RANGES.getName(),ACCEPT_RANGES.getValue());
1115 
1116             if (_cacheControl!=null)
1117                 response.setHeader(_cacheControl.getName(),_cacheControl.getValue());
1118         }
1119     }
1120 
1121     /* ------------------------------------------------------------ */
1122     /*
1123      * @see javax.servlet.Servlet#destroy()
1124      */
1125     @Override
1126     public void destroy()
1127     {
1128         if (_cache!=null)
1129             _cache.flushCache();
1130         super.destroy();
1131     }
1132 
1133 }