View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.http;
19  
20  import java.io.FileNotFoundException;
21  import java.io.IOException;
22  import java.io.InterruptedIOException;
23  import java.io.PrintStream;
24  import java.net.BindException;
25  import java.net.InetSocketAddress;
26  import java.net.URI;
27  import java.net.URISyntaxException;
28  import java.net.URL;
29  import java.util.ArrayList;
30  import java.util.Collections;
31  import java.util.Enumeration;
32  import java.util.HashMap;
33  import java.util.List;
34  import java.util.Map;
35  
36  import javax.servlet.Filter;
37  import javax.servlet.FilterChain;
38  import javax.servlet.FilterConfig;
39  import javax.servlet.ServletContext;
40  import javax.servlet.ServletException;
41  import javax.servlet.ServletRequest;
42  import javax.servlet.ServletResponse;
43  import javax.servlet.http.HttpServlet;
44  import javax.servlet.http.HttpServletRequest;
45  import javax.servlet.http.HttpServletRequestWrapper;
46  import javax.servlet.http.HttpServletResponse;
47  
48  import org.apache.commons.logging.Log;
49  import org.apache.commons.logging.LogFactory;
50  import org.apache.hadoop.HadoopIllegalArgumentException;
51  import org.apache.hadoop.hbase.classification.InterfaceAudience;
52  import org.apache.hadoop.hbase.classification.InterfaceStability;
53  import org.apache.hadoop.conf.Configuration;
54  import org.apache.hadoop.fs.CommonConfigurationKeys;
55  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
56  import org.apache.hadoop.hbase.http.conf.ConfServlet;
57  import org.apache.hadoop.hbase.http.jmx.JMXJsonServlet;
58  import org.apache.hadoop.hbase.http.log.LogLevel;
59  import org.apache.hadoop.hbase.util.Threads;
60  import org.apache.hadoop.hbase.util.ReflectionUtils;
61  import org.apache.hadoop.metrics.MetricsServlet;
62  import org.apache.hadoop.security.SecurityUtil;
63  import org.apache.hadoop.security.UserGroupInformation;
64  import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
65  import org.apache.hadoop.security.authorize.AccessControlList;
66  import org.apache.hadoop.util.Shell;
67  import org.mortbay.io.Buffer;
68  import org.mortbay.jetty.Connector;
69  import org.mortbay.jetty.Handler;
70  import org.mortbay.jetty.MimeTypes;
71  import org.mortbay.jetty.RequestLog;
72  import org.mortbay.jetty.Server;
73  import org.mortbay.jetty.handler.ContextHandler;
74  import org.mortbay.jetty.handler.ContextHandlerCollection;
75  import org.mortbay.jetty.handler.HandlerCollection;
76  import org.mortbay.jetty.handler.RequestLogHandler;
77  import org.mortbay.jetty.nio.SelectChannelConnector;
78  import org.mortbay.jetty.security.SslSocketConnector;
79  import org.mortbay.jetty.servlet.Context;
80  import org.mortbay.jetty.servlet.DefaultServlet;
81  import org.mortbay.jetty.servlet.FilterHolder;
82  import org.mortbay.jetty.servlet.FilterMapping;
83  import org.mortbay.jetty.servlet.ServletHandler;
84  import org.mortbay.jetty.servlet.ServletHolder;
85  import org.mortbay.jetty.webapp.WebAppContext;
86  import org.mortbay.thread.QueuedThreadPool;
87  import org.mortbay.util.MultiException;
88  
89  import com.google.common.base.Preconditions;
90  import com.google.common.collect.Lists;
91  import com.sun.jersey.spi.container.servlet.ServletContainer;
92  
93  /**
94   * Create a Jetty embedded server to answer http requests. The primary goal
95   * is to serve up status information for the server.
96   * There are three contexts:
97   *   "/logs/" -> points to the log directory
98   *   "/static/" -> points to common static files (src/webapps/static)
99   *   "/" -> the jsp server code from (src/webapps/<name>)
100  */
101 @InterfaceAudience.Private
102 @InterfaceStability.Evolving
103 public class HttpServer implements FilterContainer {
104   private static final Log LOG = LogFactory.getLog(HttpServer.class);
105 
106   static final String FILTER_INITIALIZERS_PROPERTY
107       = "hbase.http.filter.initializers";
108   static final String HTTP_MAX_THREADS = "hbase.http.max.threads";
109 
110   // The ServletContext attribute where the daemon Configuration
111   // gets stored.
112   public static final String CONF_CONTEXT_ATTRIBUTE = "hbase.conf";
113   public static final String ADMINS_ACL = "admins.acl";
114   public static final String BIND_ADDRESS = "bind.address";
115   public static final String SPNEGO_FILTER = "SpnegoFilter";
116   public static final String NO_CACHE_FILTER = "NoCacheFilter";
117   public static final String APP_DIR = "webapps";
118 
119   private final AccessControlList adminsAcl;
120 
121   protected final Server webServer;
122   protected String appDir;
123   protected String logDir;
124 
125   private static class ListenerInfo {
126     /**
127      * Boolean flag to determine whether the HTTP server should clean up the
128      * listener in stop().
129      */
130     private final boolean isManaged;
131     private final Connector listener;
132     private ListenerInfo(boolean isManaged, Connector listener) {
133       this.isManaged = isManaged;
134       this.listener = listener;
135     }
136   }
137 
138   private final List<ListenerInfo> listeners = Lists.newArrayList();
139 
140   protected final WebAppContext webAppContext;
141   protected final boolean findPort;
142   protected final Map<Context, Boolean> defaultContexts =
143       new HashMap<Context, Boolean>();
144   protected final List<String> filterNames = new ArrayList<String>();
145   static final String STATE_DESCRIPTION_ALIVE = " - alive";
146   static final String STATE_DESCRIPTION_NOT_LIVE = " - not live";
147 
148   /**
149    * Class to construct instances of HTTP server with specific options.
150    */
151   public static class Builder {
152     private ArrayList<URI> endpoints = Lists.newArrayList();
153     private Connector connector;
154     private Configuration conf;
155     private String[] pathSpecs;
156     private AccessControlList adminsAcl;
157     private boolean securityEnabled = false;
158     private String usernameConfKey;
159     private String keytabConfKey;
160     private boolean needsClientAuth;
161 
162     private String hostName;
163     private String appDir = APP_DIR;
164     private String logDir;
165     private boolean findPort;
166 
167     private String trustStore;
168     private String trustStorePassword;
169     private String trustStoreType;
170 
171     private String keyStore;
172     private String keyStorePassword;
173     private String keyStoreType;
174 
175     // The -keypass option in keytool
176     private String keyPassword;
177 
178     @Deprecated
179     private String name;
180     @Deprecated
181     private String bindAddress;
182     @Deprecated
183     private int port = -1;
184 
185     /**
186      * Add an endpoint that the HTTP server should listen to.
187      *
188      * @param endpoint
189      *          the endpoint of that the HTTP server should listen to. The
190      *          scheme specifies the protocol (i.e. HTTP / HTTPS), the host
191      *          specifies the binding address, and the port specifies the
192      *          listening port. Unspecified or zero port means that the server
193      *          can listen to any port.
194      */
195     public Builder addEndpoint(URI endpoint) {
196       endpoints.add(endpoint);
197       return this;
198     }
199 
200     /**
201      * Set the hostname of the http server. The host name is used to resolve the
202      * _HOST field in Kerberos principals. The hostname of the first listener
203      * will be used if the name is unspecified.
204      */
205     public Builder hostName(String hostName) {
206       this.hostName = hostName;
207       return this;
208     }
209 
210     public Builder trustStore(String location, String password, String type) {
211       this.trustStore = location;
212       this.trustStorePassword = password;
213       this.trustStoreType = type;
214       return this;
215     }
216 
217     public Builder keyStore(String location, String password, String type) {
218       this.keyStore = location;
219       this.keyStorePassword = password;
220       this.keyStoreType = type;
221       return this;
222     }
223 
224     public Builder keyPassword(String password) {
225       this.keyPassword = password;
226       return this;
227     }
228 
229     /**
230      * Specify whether the server should authorize the client in SSL
231      * connections.
232      */
233     public Builder needsClientAuth(boolean value) {
234       this.needsClientAuth = value;
235       return this;
236     }
237 
238     /**
239      * Use setAppDir() instead.
240      */
241     @Deprecated
242     public Builder setName(String name){
243       this.name = name;
244       return this;
245     }
246 
247     /**
248      * Use addEndpoint() instead.
249      */
250     @Deprecated
251     public Builder setBindAddress(String bindAddress){
252       this.bindAddress = bindAddress;
253       return this;
254     }
255 
256     /**
257      * Use addEndpoint() instead.
258      */
259     @Deprecated
260     public Builder setPort(int port) {
261       this.port = port;
262       return this;
263     }
264 
265     public Builder setFindPort(boolean findPort) {
266       this.findPort = findPort;
267       return this;
268     }
269 
270     public Builder setConf(Configuration conf) {
271       this.conf = conf;
272       return this;
273     }
274 
275     public Builder setConnector(Connector connector) {
276       this.connector = connector;
277       return this;
278     }
279 
280     public Builder setPathSpec(String[] pathSpec) {
281       this.pathSpecs = pathSpec;
282       return this;
283     }
284 
285     public Builder setACL(AccessControlList acl) {
286       this.adminsAcl = acl;
287       return this;
288     }
289 
290     public Builder setSecurityEnabled(boolean securityEnabled) {
291       this.securityEnabled = securityEnabled;
292       return this;
293     }
294 
295     public Builder setUsernameConfKey(String usernameConfKey) {
296       this.usernameConfKey = usernameConfKey;
297       return this;
298     }
299 
300     public Builder setKeytabConfKey(String keytabConfKey) {
301       this.keytabConfKey = keytabConfKey;
302       return this;
303     }
304 
305     public Builder setAppDir(String appDir) {
306         this.appDir = appDir;
307         return this;
308       }
309 
310     public Builder setLogDir(String logDir) {
311         this.logDir = logDir;
312         return this;
313       }
314 
315     public HttpServer build() throws IOException {
316 
317       // Do we still need to assert this non null name if it is deprecated?
318       if (this.name == null) {
319         throw new HadoopIllegalArgumentException("name is not set");
320       }
321 
322       // Make the behavior compatible with deprecated interfaces
323       if (bindAddress != null && port != -1) {
324         try {
325           endpoints.add(0, new URI("http", "", bindAddress, port, "", "", ""));
326         } catch (URISyntaxException e) {
327           throw new HadoopIllegalArgumentException("Invalid endpoint: "+ e);
328         }
329       }
330 
331       if (endpoints.size() == 0 && connector == null) {
332         throw new HadoopIllegalArgumentException("No endpoints specified");
333       }
334 
335       if (hostName == null) {
336         hostName = endpoints.size() == 0 ? connector.getHost() : endpoints.get(
337             0).getHost();
338       }
339 
340       if (this.conf == null) {
341         conf = new Configuration();
342       }
343 
344       HttpServer server = new HttpServer(this);
345 
346       if (this.securityEnabled) {
347         server.initSpnego(conf, hostName, usernameConfKey, keytabConfKey);
348       }
349 
350       if (connector != null) {
351         server.addUnmanagedListener(connector);
352       }
353 
354       for (URI ep : endpoints) {
355         Connector listener = null;
356         String scheme = ep.getScheme();
357         if ("http".equals(scheme)) {
358           listener = HttpServer.createDefaultChannelConnector();
359         } else if ("https".equals(scheme)) {
360           SslSocketConnector c = new SslSocketConnectorSecure();
361           c.setNeedClientAuth(needsClientAuth);
362           c.setKeyPassword(keyPassword);
363 
364           if (keyStore != null) {
365             c.setKeystore(keyStore);
366             c.setKeystoreType(keyStoreType);
367             c.setPassword(keyStorePassword);
368           }
369 
370           if (trustStore != null) {
371             c.setTruststore(trustStore);
372             c.setTruststoreType(trustStoreType);
373             c.setTrustPassword(trustStorePassword);
374           }
375           listener = c;
376 
377         } else {
378           throw new HadoopIllegalArgumentException(
379               "unknown scheme for endpoint:" + ep);
380         }
381         listener.setHeaderBufferSize(1024*64);
382         listener.setHost(ep.getHost());
383         listener.setPort(ep.getPort() == -1 ? 0 : ep.getPort());
384         server.addManagedListener(listener);
385       }
386 
387       server.loadListeners();
388       return server;
389 
390     }
391 
392   }
393 
394   /** Same as this(name, bindAddress, port, findPort, null); */
395   @Deprecated
396   public HttpServer(String name, String bindAddress, int port, boolean findPort
397       ) throws IOException {
398     this(name, bindAddress, port, findPort, new Configuration());
399   }
400 
401   @Deprecated
402   public HttpServer(String name, String bindAddress, int port,
403       boolean findPort, Configuration conf, Connector connector) throws IOException {
404     this(name, bindAddress, port, findPort, conf, null, connector, null);
405   }
406 
407   /**
408    * Create a status server on the given port. Allows you to specify the
409    * path specifications that this server will be serving so that they will be
410    * added to the filters properly.
411    *
412    * @param name The name of the server
413    * @param bindAddress The address for this server
414    * @param port The port to use on the server
415    * @param findPort whether the server should start at the given port and
416    *        increment by 1 until it finds a free port.
417    * @param conf Configuration
418    * @param pathSpecs Path specifications that this httpserver will be serving.
419    *        These will be added to any filters.
420    */
421   @Deprecated
422   public HttpServer(String name, String bindAddress, int port,
423       boolean findPort, Configuration conf, String[] pathSpecs) throws IOException {
424     this(name, bindAddress, port, findPort, conf, null, null, pathSpecs);
425   }
426 
427   /**
428    * Create a status server on the given port.
429    * The jsp scripts are taken from src/webapps/&lt;name&gt;.
430    * @param name The name of the server
431    * @param port The port to use on the server
432    * @param findPort whether the server should start at the given port and
433    *        increment by 1 until it finds a free port.
434    * @param conf Configuration
435    */
436   @Deprecated
437   public HttpServer(String name, String bindAddress, int port,
438       boolean findPort, Configuration conf) throws IOException {
439     this(name, bindAddress, port, findPort, conf, null, null, null);
440   }
441 
442   @Deprecated
443   public HttpServer(String name, String bindAddress, int port,
444       boolean findPort, Configuration conf, AccessControlList adminsAcl)
445       throws IOException {
446     this(name, bindAddress, port, findPort, conf, adminsAcl, null, null);
447   }
448 
449   /**
450    * Create a status server on the given port.
451    * The jsp scripts are taken from src/webapps/&lt;name&gt;.
452    * @param name The name of the server
453    * @param bindAddress The address for this server
454    * @param port The port to use on the server
455    * @param findPort whether the server should start at the given port and
456    *        increment by 1 until it finds a free port.
457    * @param conf Configuration
458    * @param adminsAcl {@link AccessControlList} of the admins
459    * @param connector The jetty {@link Connector} to use
460    */
461   @Deprecated
462   public HttpServer(String name, String bindAddress, int port,
463       boolean findPort, Configuration conf, AccessControlList adminsAcl,
464       Connector connector) throws IOException {
465     this(name, bindAddress, port, findPort, conf, adminsAcl, connector, null);
466   }
467 
468   /**
469    * Create a status server on the given port.
470    * The jsp scripts are taken from src/webapps/&lt;name&gt;.
471    * @param name The name of the server
472    * @param bindAddress The address for this server
473    * @param port The port to use on the server
474    * @param findPort whether the server should start at the given port and
475    *        increment by 1 until it finds a free port.
476    * @param conf Configuration
477    * @param adminsAcl {@link AccessControlList} of the admins
478    * @param connector A jetty connection listener
479    * @param pathSpecs Path specifications that this httpserver will be serving.
480    *        These will be added to any filters.
481    */
482   @Deprecated
483   public HttpServer(String name, String bindAddress, int port,
484       boolean findPort, Configuration conf, AccessControlList adminsAcl,
485       Connector connector, String[] pathSpecs) throws IOException {
486     this(new Builder().setName(name)
487         .addEndpoint(URI.create("http://" + bindAddress + ":" + port))
488         .setFindPort(findPort).setConf(conf).setACL(adminsAcl)
489         .setConnector(connector).setPathSpec(pathSpecs));
490   }
491 
492   private HttpServer(final Builder b) throws IOException {
493     this.appDir = b.appDir;
494     this.logDir = b.logDir;
495     final String appDir = getWebAppsPath(b.name);
496     this.webServer = new Server();
497     this.adminsAcl = b.adminsAcl;
498     this.webAppContext = createWebAppContext(b.name, b.conf, adminsAcl, appDir);
499     this.findPort = b.findPort;
500     initializeWebServer(b.name, b.hostName, b.conf, b.pathSpecs);
501   }
502 
503   private void initializeWebServer(String name, String hostName,
504       Configuration conf, String[] pathSpecs)
505       throws FileNotFoundException, IOException {
506 
507     Preconditions.checkNotNull(webAppContext);
508 
509     int maxThreads = conf.getInt(HTTP_MAX_THREADS, -1);
510     // If HTTP_MAX_THREADS is not configured, QueueThreadPool() will use the
511     // default value (currently 250).
512     QueuedThreadPool threadPool = maxThreads == -1 ? new QueuedThreadPool()
513         : new QueuedThreadPool(maxThreads);
514     threadPool.setDaemon(true);
515     webServer.setThreadPool(threadPool);
516 
517     ContextHandlerCollection contexts = new ContextHandlerCollection();
518     RequestLog requestLog = HttpRequestLog.getRequestLog(name);
519 
520     if (requestLog != null) {
521       RequestLogHandler requestLogHandler = new RequestLogHandler();
522       requestLogHandler.setRequestLog(requestLog);
523       HandlerCollection handlers = new HandlerCollection();
524       handlers.setHandlers(new Handler[] { requestLogHandler, contexts });
525       webServer.setHandler(handlers);
526     } else {
527       webServer.setHandler(contexts);
528     }
529 
530     final String appDir = getWebAppsPath(name);
531 
532     webServer.addHandler(webAppContext);
533 
534     addDefaultApps(contexts, appDir, conf);
535 
536     addGlobalFilter("safety", QuotingInputFilter.class.getName(), null);
537     Map<String, String> params = new HashMap<String, String>();
538     params.put("xframeoptions", conf.get("hbase.http.filter.xframeoptions.mode", "DENY"));
539     addGlobalFilter("clickjackingprevention",
540             ClickjackingPreventionFilter.class.getName(), params);
541     final FilterInitializer[] initializers = getFilterInitializers(conf);
542     if (initializers != null) {
543       conf = new Configuration(conf);
544       conf.set(BIND_ADDRESS, hostName);
545       for (FilterInitializer c : initializers) {
546         c.initFilter(this, conf);
547       }
548     }
549 
550     addDefaultServlets();
551 
552     if (pathSpecs != null) {
553       for (String path : pathSpecs) {
554         LOG.info("adding path spec: " + path);
555         addFilterPathMapping(path, webAppContext);
556       }
557     }
558   }
559 
560   private void addUnmanagedListener(Connector connector) {
561     listeners.add(new ListenerInfo(false, connector));
562   }
563 
564   private void addManagedListener(Connector connector) {
565     listeners.add(new ListenerInfo(true, connector));
566   }
567 
568   private static WebAppContext createWebAppContext(String name,
569       Configuration conf, AccessControlList adminsAcl, final String appDir) {
570     WebAppContext ctx = new WebAppContext();
571     ctx.setDisplayName(name);
572     ctx.setContextPath("/");
573     ctx.setWar(appDir + "/" + name);
574     ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, conf);
575     // for org.apache.hadoop.metrics.MetricsServlet
576     ctx.getServletContext().setAttribute(
577       org.apache.hadoop.http.HttpServer2.CONF_CONTEXT_ATTRIBUTE, conf);
578     ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
579     addNoCacheFilter(ctx);
580     return ctx;
581   }
582 
583   private static void addNoCacheFilter(WebAppContext ctxt) {
584     defineFilter(ctxt, NO_CACHE_FILTER, NoCacheFilter.class.getName(),
585         Collections.<String, String> emptyMap(), new String[] { "/*" });
586   }
587 
588   /**
589    * Create a required listener for the Jetty instance listening on the port
590    * provided. This wrapper and all subclasses must create at least one
591    * listener.
592    */
593   public Connector createBaseListener(Configuration conf) throws IOException {
594     return HttpServer.createDefaultChannelConnector();
595   }
596 
597   @InterfaceAudience.Private
598   public static Connector createDefaultChannelConnector() {
599     SelectChannelConnector ret = new SelectChannelConnector();
600     ret.setLowResourceMaxIdleTime(10000);
601     ret.setAcceptQueueSize(128);
602     ret.setResolveNames(false);
603     ret.setUseDirectBuffers(false);
604     if(Shell.WINDOWS) {
605       // result of setting the SO_REUSEADDR flag is different on Windows
606       // http://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx
607       // without this 2 NN's can start on the same machine and listen on
608       // the same port with indeterminate routing of incoming requests to them
609       ret.setReuseAddress(false);
610     }
611     return ret;
612   }
613 
614   /** Get an array of FilterConfiguration specified in the conf */
615   private static FilterInitializer[] getFilterInitializers(Configuration conf) {
616     if (conf == null) {
617       return null;
618     }
619 
620     Class<?>[] classes = conf.getClasses(FILTER_INITIALIZERS_PROPERTY);
621     if (classes == null) {
622       return null;
623     }
624 
625     FilterInitializer[] initializers = new FilterInitializer[classes.length];
626     for(int i = 0; i < classes.length; i++) {
627       initializers[i] = (FilterInitializer)ReflectionUtils.newInstance(classes[i]);
628     }
629     return initializers;
630   }
631 
632   /**
633    * Add default apps.
634    * @param appDir The application directory
635    * @throws IOException
636    */
637   protected void addDefaultApps(ContextHandlerCollection parent,
638       final String appDir, Configuration conf) throws IOException {
639     // set up the context for "/logs/" if "hadoop.log.dir" property is defined.
640     String logDir = this.logDir;
641     if (logDir == null) {
642         logDir = System.getProperty("hadoop.log.dir");
643     }
644     if (logDir != null) {
645       Context logContext = new Context(parent, "/logs");
646       logContext.setResourceBase(logDir);
647       logContext.addServlet(AdminAuthorizedServlet.class, "/*");
648       if (conf.getBoolean(
649           ServerConfigurationKeys.HBASE_JETTY_LOGS_SERVE_ALIASES,
650           ServerConfigurationKeys.DEFAULT_HBASE_JETTY_LOGS_SERVE_ALIASES)) {
651         @SuppressWarnings("unchecked")
652         Map<String, String> params = logContext.getInitParams();
653         params.put(
654             "org.mortbay.jetty.servlet.Default.aliases", "true");
655       }
656       logContext.setDisplayName("logs");
657       setContextAttributes(logContext, conf);
658       addNoCacheFilter(webAppContext);
659       defaultContexts.put(logContext, true);
660     }
661     // set up the context for "/static/*"
662     Context staticContext = new Context(parent, "/static");
663     staticContext.setResourceBase(appDir + "/static");
664     staticContext.addServlet(DefaultServlet.class, "/*");
665     staticContext.setDisplayName("static");
666     setContextAttributes(staticContext, conf);
667     defaultContexts.put(staticContext, true);
668   }
669 
670   private void setContextAttributes(Context context, Configuration conf) {
671     context.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, conf);
672     context.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
673   }
674 
675   /**
676    * Add default servlets.
677    */
678   protected void addDefaultServlets() {
679     // set up default servlets
680     addServlet("stacks", "/stacks", StackServlet.class);
681     addServlet("logLevel", "/logLevel", LogLevel.Servlet.class);
682     addServlet("metrics", "/metrics", MetricsServlet.class);
683     addServlet("jmx", "/jmx", JMXJsonServlet.class);
684     addServlet("conf", "/conf", ConfServlet.class);
685   }
686 
687   public void addContext(Context ctxt, boolean isFiltered)
688       throws IOException {
689     webServer.addHandler(ctxt);
690     addNoCacheFilter(webAppContext);
691     defaultContexts.put(ctxt, isFiltered);
692   }
693 
694   /**
695    * Add a context
696    * @param pathSpec The path spec for the context
697    * @param dir The directory containing the context
698    * @param isFiltered if true, the servlet is added to the filter path mapping
699    * @throws IOException
700    */
701   protected void addContext(String pathSpec, String dir, boolean isFiltered) throws IOException {
702     if (0 == webServer.getHandlers().length) {
703       throw new RuntimeException("Couldn't find handler");
704     }
705     WebAppContext webAppCtx = new WebAppContext();
706     webAppCtx.setContextPath(pathSpec);
707     webAppCtx.setWar(dir);
708     addContext(webAppCtx, true);
709   }
710 
711   /**
712    * Set a value in the webapp context. These values are available to the jsp
713    * pages as "application.getAttribute(name)".
714    * @param name The name of the attribute
715    * @param value The value of the attribute
716    */
717   public void setAttribute(String name, Object value) {
718     webAppContext.setAttribute(name, value);
719   }
720 
721   /**
722    * Add a Jersey resource package.
723    * @param packageName The Java package name containing the Jersey resource.
724    * @param pathSpec The path spec for the servlet
725    */
726   public void addJerseyResourcePackage(final String packageName,
727       final String pathSpec) {
728     LOG.info("addJerseyResourcePackage: packageName=" + packageName
729         + ", pathSpec=" + pathSpec);
730     final ServletHolder sh = new ServletHolder(ServletContainer.class);
731     sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
732         "com.sun.jersey.api.core.PackagesResourceConfig");
733     sh.setInitParameter("com.sun.jersey.config.property.packages", packageName);
734     webAppContext.addServlet(sh, pathSpec);
735   }
736 
737   /**
738    * Add a servlet in the server.
739    * @param name The name of the servlet (can be passed as null)
740    * @param pathSpec The path spec for the servlet
741    * @param clazz The servlet class
742    */
743   public void addServlet(String name, String pathSpec,
744       Class<? extends HttpServlet> clazz) {
745     addInternalServlet(name, pathSpec, clazz, false);
746     addFilterPathMapping(pathSpec, webAppContext);
747   }
748 
749   /**
750    * Add an internal servlet in the server.
751    * Note: This method is to be used for adding servlets that facilitate
752    * internal communication and not for user facing functionality. For
753    * servlets added using this method, filters are not enabled.
754    *
755    * @param name The name of the servlet (can be passed as null)
756    * @param pathSpec The path spec for the servlet
757    * @param clazz The servlet class
758    */
759   public void addInternalServlet(String name, String pathSpec,
760       Class<? extends HttpServlet> clazz) {
761     addInternalServlet(name, pathSpec, clazz, false);
762   }
763 
764   /**
765    * Add an internal servlet in the server, specifying whether or not to
766    * protect with Kerberos authentication.
767    * Note: This method is to be used for adding servlets that facilitate
768    * internal communication and not for user facing functionality. For
769    +   * servlets added using this method, filters (except internal Kerberos
770    * filters) are not enabled.
771    *
772    * @param name The name of the servlet (can be passed as null)
773    * @param pathSpec The path spec for the servlet
774    * @param clazz The servlet class
775    * @param requireAuth Require Kerberos authenticate to access servlet
776    */
777   public void addInternalServlet(String name, String pathSpec,
778       Class<? extends HttpServlet> clazz, boolean requireAuth) {
779     ServletHolder holder = new ServletHolder(clazz);
780     if (name != null) {
781       holder.setName(name);
782     }
783     webAppContext.addServlet(holder, pathSpec);
784 
785     if(requireAuth && UserGroupInformation.isSecurityEnabled()) {
786        LOG.info("Adding Kerberos (SPNEGO) filter to " + name);
787        ServletHandler handler = webAppContext.getServletHandler();
788        FilterMapping fmap = new FilterMapping();
789        fmap.setPathSpec(pathSpec);
790        fmap.setFilterName(SPNEGO_FILTER);
791        fmap.setDispatches(Handler.ALL);
792        handler.addFilterMapping(fmap);
793     }
794   }
795 
796   @Override
797   public void addFilter(String name, String classname,
798       Map<String, String> parameters) {
799 
800     final String[] USER_FACING_URLS = { "*.html", "*.jsp" };
801     defineFilter(webAppContext, name, classname, parameters, USER_FACING_URLS);
802     LOG.info("Added filter " + name + " (class=" + classname
803         + ") to context " + webAppContext.getDisplayName());
804     final String[] ALL_URLS = { "/*" };
805     for (Map.Entry<Context, Boolean> e : defaultContexts.entrySet()) {
806       if (e.getValue()) {
807         Context ctx = e.getKey();
808         defineFilter(ctx, name, classname, parameters, ALL_URLS);
809         LOG.info("Added filter " + name + " (class=" + classname
810             + ") to context " + ctx.getDisplayName());
811       }
812     }
813     filterNames.add(name);
814   }
815 
816   @Override
817   public void addGlobalFilter(String name, String classname,
818       Map<String, String> parameters) {
819     final String[] ALL_URLS = { "/*" };
820     defineFilter(webAppContext, name, classname, parameters, ALL_URLS);
821     for (Context ctx : defaultContexts.keySet()) {
822       defineFilter(ctx, name, classname, parameters, ALL_URLS);
823     }
824     LOG.info("Added global filter '" + name + "' (class=" + classname + ")");
825   }
826 
827   /**
828    * Define a filter for a context and set up default url mappings.
829    */
830   public static void defineFilter(Context ctx, String name,
831       String classname, Map<String,String> parameters, String[] urls) {
832 
833     FilterHolder holder = new FilterHolder();
834     holder.setName(name);
835     holder.setClassName(classname);
836     holder.setInitParameters(parameters);
837     FilterMapping fmap = new FilterMapping();
838     fmap.setPathSpecs(urls);
839     fmap.setDispatches(Handler.ALL);
840     fmap.setFilterName(name);
841     ServletHandler handler = ctx.getServletHandler();
842     handler.addFilter(holder, fmap);
843   }
844 
845   /**
846    * Add the path spec to the filter path mapping.
847    * @param pathSpec The path spec
848    * @param webAppCtx The WebApplicationContext to add to
849    */
850   protected void addFilterPathMapping(String pathSpec,
851       Context webAppCtx) {
852     ServletHandler handler = webAppCtx.getServletHandler();
853     for(String name : filterNames) {
854       FilterMapping fmap = new FilterMapping();
855       fmap.setPathSpec(pathSpec);
856       fmap.setFilterName(name);
857       fmap.setDispatches(Handler.ALL);
858       handler.addFilterMapping(fmap);
859     }
860   }
861 
862   /**
863    * Get the value in the webapp context.
864    * @param name The name of the attribute
865    * @return The value of the attribute
866    */
867   public Object getAttribute(String name) {
868     return webAppContext.getAttribute(name);
869   }
870 
871   public WebAppContext getWebAppContext(){
872     return this.webAppContext;
873   }
874 
875   public String getWebAppsPath(String appName) throws FileNotFoundException {
876       return getWebAppsPath(this.appDir, appName);
877   }
878 
879   /**
880    * Get the pathname to the webapps files.
881    * @param appName eg "secondary" or "datanode"
882    * @return the pathname as a URL
883    * @throws FileNotFoundException if 'webapps' directory cannot be found on CLASSPATH.
884    */
885   protected String getWebAppsPath(String webapps, String appName) throws FileNotFoundException {
886     URL url = getClass().getClassLoader().getResource(webapps + "/" + appName);
887     if (url == null)
888       throw new FileNotFoundException(webapps + "/" + appName
889           + " not found in CLASSPATH");
890     String urlString = url.toString();
891     return urlString.substring(0, urlString.lastIndexOf('/'));
892   }
893 
894   /**
895    * Get the port that the server is on
896    * @return the port
897    */
898   @Deprecated
899   public int getPort() {
900     return webServer.getConnectors()[0].getLocalPort();
901   }
902 
903   /**
904    * Get the address that corresponds to a particular connector.
905    *
906    * @return the corresponding address for the connector, or null if there's no
907    *         such connector or the connector is not bounded.
908    */
909   public InetSocketAddress getConnectorAddress(int index) {
910     Preconditions.checkArgument(index >= 0);
911     if (index > webServer.getConnectors().length)
912       return null;
913 
914     Connector c = webServer.getConnectors()[index];
915     if (c.getLocalPort() == -1) {
916       // The connector is not bounded
917       return null;
918     }
919 
920     return new InetSocketAddress(c.getHost(), c.getLocalPort());
921   }
922 
923   /**
924    * Set the min, max number of worker threads (simultaneous connections).
925    */
926   public void setThreads(int min, int max) {
927     QueuedThreadPool pool = (QueuedThreadPool) webServer.getThreadPool();
928     pool.setMinThreads(min);
929     pool.setMaxThreads(max);
930   }
931 
932   private void initSpnego(Configuration conf, String hostName,
933       String usernameConfKey, String keytabConfKey) throws IOException {
934     Map<String, String> params = new HashMap<String, String>();
935     String principalInConf = conf.get(usernameConfKey);
936     if (principalInConf != null && !principalInConf.isEmpty()) {
937       params.put("kerberos.principal", SecurityUtil.getServerPrincipal(
938           principalInConf, hostName));
939     }
940     String httpKeytab = conf.get(keytabConfKey);
941     if (httpKeytab != null && !httpKeytab.isEmpty()) {
942       params.put("kerberos.keytab", httpKeytab);
943     }
944     params.put(AuthenticationFilter.AUTH_TYPE, "kerberos");
945 
946     defineFilter(webAppContext, SPNEGO_FILTER,
947                  AuthenticationFilter.class.getName(), params, null);
948   }
949 
950   /**
951    * Start the server. Does not wait for the server to start.
952    */
953   public void start() throws IOException {
954     try {
955       try {
956         openListeners();
957         webServer.start();
958       } catch (IOException ex) {
959         LOG.info("HttpServer.start() threw a non Bind IOException", ex);
960         throw ex;
961       } catch (MultiException ex) {
962         LOG.info("HttpServer.start() threw a MultiException", ex);
963         throw ex;
964       }
965       // Make sure there is no handler failures.
966       Handler[] handlers = webServer.getHandlers();
967       for (int i = 0; i < handlers.length; i++) {
968         if (handlers[i].isFailed()) {
969           throw new IOException(
970               "Problem in starting http server. Server handlers failed");
971         }
972       }
973       // Make sure there are no errors initializing the context.
974       Throwable unavailableException = webAppContext.getUnavailableException();
975       if (unavailableException != null) {
976         // Have to stop the webserver, or else its non-daemon threads
977         // will hang forever.
978         webServer.stop();
979         throw new IOException("Unable to initialize WebAppContext",
980             unavailableException);
981       }
982     } catch (IOException e) {
983       throw e;
984     } catch (InterruptedException e) {
985       throw (IOException) new InterruptedIOException(
986           "Interrupted while starting HTTP server").initCause(e);
987     } catch (Exception e) {
988       throw new IOException("Problem starting http server", e);
989     }
990   }
991 
992   private void loadListeners() {
993     for (ListenerInfo li : listeners) {
994       webServer.addConnector(li.listener);
995     }
996   }
997 
998   /**
999    * Open the main listener for the server
1000    * @throws Exception
1001    */
1002   void openListeners() throws Exception {
1003     for (ListenerInfo li : listeners) {
1004       Connector listener = li.listener;
1005       if (!li.isManaged || li.listener.getLocalPort() != -1) {
1006         // This listener is either started externally or has been bound
1007         continue;
1008       }
1009       int port = listener.getPort();
1010       while (true) {
1011         // jetty has a bug where you can't reopen a listener that previously
1012         // failed to open w/o issuing a close first, even if the port is changed
1013         try {
1014           listener.close();
1015           listener.open();
1016           LOG.info("Jetty bound to port " + listener.getLocalPort());
1017           break;
1018         } catch (BindException ex) {
1019           if (port == 0 || !findPort) {
1020             BindException be = new BindException("Port in use: "
1021                 + listener.getHost() + ":" + listener.getPort());
1022             be.initCause(ex);
1023             throw be;
1024           }
1025         }
1026         // try the next port number
1027         listener.setPort(++port);
1028         Thread.sleep(100);
1029       }
1030     }
1031   }
1032 
1033   /**
1034    * stop the server
1035    */
1036   public void stop() throws Exception {
1037     MultiException exception = null;
1038     for (ListenerInfo li : listeners) {
1039       if (!li.isManaged) {
1040         continue;
1041       }
1042 
1043       try {
1044         li.listener.close();
1045       } catch (Exception e) {
1046         LOG.error(
1047             "Error while stopping listener for webapp"
1048                 + webAppContext.getDisplayName(), e);
1049         exception = addMultiException(exception, e);
1050       }
1051     }
1052 
1053     try {
1054       // clear & stop webAppContext attributes to avoid memory leaks.
1055       webAppContext.clearAttributes();
1056       webAppContext.stop();
1057     } catch (Exception e) {
1058       LOG.error("Error while stopping web app context for webapp "
1059           + webAppContext.getDisplayName(), e);
1060       exception = addMultiException(exception, e);
1061     }
1062 
1063     try {
1064       webServer.stop();
1065     } catch (Exception e) {
1066       LOG.error("Error while stopping web server for webapp "
1067           + webAppContext.getDisplayName(), e);
1068       exception = addMultiException(exception, e);
1069     }
1070 
1071     if (exception != null) {
1072       exception.ifExceptionThrow();
1073     }
1074 
1075   }
1076 
1077   private MultiException addMultiException(MultiException exception, Exception e) {
1078     if(exception == null){
1079       exception = new MultiException();
1080     }
1081     exception.add(e);
1082     return exception;
1083   }
1084 
1085   public void join() throws InterruptedException {
1086     webServer.join();
1087   }
1088 
1089   /**
1090    * Test for the availability of the web server
1091    * @return true if the web server is started, false otherwise
1092    */
1093   public boolean isAlive() {
1094     return webServer != null && webServer.isStarted();
1095   }
1096 
1097   /**
1098    * Return the host and port of the HttpServer, if live
1099    * @return the classname and any HTTP URL
1100    */
1101   @Override
1102   public String toString() {
1103     if (listeners.size() == 0) {
1104       return "Inactive HttpServer";
1105     } else {
1106       StringBuilder sb = new StringBuilder("HttpServer (")
1107         .append(isAlive() ? STATE_DESCRIPTION_ALIVE : STATE_DESCRIPTION_NOT_LIVE).append("), listening at:");
1108       for (ListenerInfo li : listeners) {
1109         Connector l = li.listener;
1110         sb.append(l.getHost()).append(":").append(l.getPort()).append("/,");
1111       }
1112       return sb.toString();
1113     }
1114   }
1115 
1116   /**
1117    * Checks the user has privileges to access to instrumentation servlets.
1118    * <p>
1119    * If <code>hadoop.security.instrumentation.requires.admin</code> is set to FALSE
1120    * (default value) it always returns TRUE.
1121    * </p><p>
1122    * If <code>hadoop.security.instrumentation.requires.admin</code> is set to TRUE
1123    * it will check that if the current user is in the admin ACLS. If the user is
1124    * in the admin ACLs it returns TRUE, otherwise it returns FALSE.
1125    * </p>
1126    *
1127    * @param servletContext the servlet context.
1128    * @param request the servlet request.
1129    * @param response the servlet response.
1130    * @return TRUE/FALSE based on the logic decribed above.
1131    */
1132   public static boolean isInstrumentationAccessAllowed(
1133     ServletContext servletContext, HttpServletRequest request,
1134     HttpServletResponse response) throws IOException {
1135     Configuration conf =
1136       (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
1137 
1138     boolean access = true;
1139     boolean adminAccess = conf.getBoolean(
1140       CommonConfigurationKeys.HADOOP_SECURITY_INSTRUMENTATION_REQUIRES_ADMIN,
1141       false);
1142     if (adminAccess) {
1143       access = hasAdministratorAccess(servletContext, request, response);
1144     }
1145     return access;
1146   }
1147 
1148   /**
1149    * Does the user sending the HttpServletRequest has the administrator ACLs? If
1150    * it isn't the case, response will be modified to send an error to the user.
1151    *
1152    * @param servletContext
1153    * @param request
1154    * @param response used to send the error response if user does not have admin access.
1155    * @return true if admin-authorized, false otherwise
1156    * @throws IOException
1157    */
1158   public static boolean hasAdministratorAccess(
1159       ServletContext servletContext, HttpServletRequest request,
1160       HttpServletResponse response) throws IOException {
1161     Configuration conf =
1162         (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
1163     // If there is no authorization, anybody has administrator access.
1164     if (!conf.getBoolean(
1165         CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
1166       return true;
1167     }
1168 
1169     String remoteUser = request.getRemoteUser();
1170     if (remoteUser == null) {
1171       response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
1172                          "Unauthenticated users are not " +
1173                          "authorized to access this page.");
1174       return false;
1175     }
1176 
1177     if (servletContext.getAttribute(ADMINS_ACL) != null &&
1178         !userHasAdministratorAccess(servletContext, remoteUser)) {
1179       response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User "
1180           + remoteUser + " is unauthorized to access this page.");
1181       return false;
1182     }
1183 
1184     return true;
1185   }
1186 
1187   /**
1188    * Get the admin ACLs from the given ServletContext and check if the given
1189    * user is in the ACL.
1190    *
1191    * @param servletContext the context containing the admin ACL.
1192    * @param remoteUser the remote user to check for.
1193    * @return true if the user is present in the ACL, false if no ACL is set or
1194    *         the user is not present
1195    */
1196   public static boolean userHasAdministratorAccess(ServletContext servletContext,
1197       String remoteUser) {
1198     AccessControlList adminsAcl = (AccessControlList) servletContext
1199         .getAttribute(ADMINS_ACL);
1200     UserGroupInformation remoteUserUGI =
1201         UserGroupInformation.createRemoteUser(remoteUser);
1202     return adminsAcl != null && adminsAcl.isUserAllowed(remoteUserUGI);
1203   }
1204 
1205   /**
1206    * A very simple servlet to serve up a text representation of the current
1207    * stack traces. It both returns the stacks to the caller and logs them.
1208    * Currently the stack traces are done sequentially rather than exactly the
1209    * same data.
1210    */
1211   public static class StackServlet extends HttpServlet {
1212     private static final long serialVersionUID = -6284183679759467039L;
1213 
1214     @Override
1215     public void doGet(HttpServletRequest request, HttpServletResponse response)
1216       throws ServletException, IOException {
1217       if (!HttpServer.isInstrumentationAccessAllowed(getServletContext(),
1218                                                      request, response)) {
1219         return;
1220       }
1221       response.setContentType("text/plain; charset=UTF-8");
1222       try (PrintStream out = new PrintStream(
1223         response.getOutputStream(), false, "UTF-8")) {
1224         Threads.printThreadInfo(out, "");
1225         out.flush();
1226       }
1227       ReflectionUtils.logThreadInfo(LOG, "jsp requested", 1);
1228     }
1229   }
1230 
1231   /**
1232    * A Servlet input filter that quotes all HTML active characters in the
1233    * parameter names and values. The goal is to quote the characters to make
1234    * all of the servlets resistant to cross-site scripting attacks.
1235    */
1236   @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
1237   public static class QuotingInputFilter implements Filter {
1238     private FilterConfig config;
1239 
1240     public static class RequestQuoter extends HttpServletRequestWrapper {
1241       private final HttpServletRequest rawRequest;
1242       public RequestQuoter(HttpServletRequest rawRequest) {
1243         super(rawRequest);
1244         this.rawRequest = rawRequest;
1245       }
1246 
1247       /**
1248        * Return the set of parameter names, quoting each name.
1249        */
1250       @SuppressWarnings("unchecked")
1251       @Override
1252       public Enumeration<String> getParameterNames() {
1253         return new Enumeration<String>() {
1254           private Enumeration<String> rawIterator =
1255             rawRequest.getParameterNames();
1256           @Override
1257           public boolean hasMoreElements() {
1258             return rawIterator.hasMoreElements();
1259           }
1260 
1261           @Override
1262           public String nextElement() {
1263             return HtmlQuoting.quoteHtmlChars(rawIterator.nextElement());
1264           }
1265         };
1266       }
1267 
1268       /**
1269        * Unquote the name and quote the value.
1270        */
1271       @Override
1272       public String getParameter(String name) {
1273         return HtmlQuoting.quoteHtmlChars(rawRequest.getParameter
1274                                      (HtmlQuoting.unquoteHtmlChars(name)));
1275       }
1276 
1277       @Override
1278       public String[] getParameterValues(String name) {
1279         String unquoteName = HtmlQuoting.unquoteHtmlChars(name);
1280         String[] unquoteValue = rawRequest.getParameterValues(unquoteName);
1281         if (unquoteValue == null) {
1282           return null;
1283         }
1284         String[] result = new String[unquoteValue.length];
1285         for(int i=0; i < result.length; ++i) {
1286           result[i] = HtmlQuoting.quoteHtmlChars(unquoteValue[i]);
1287         }
1288         return result;
1289       }
1290 
1291       @SuppressWarnings("unchecked")
1292       @Override
1293       public Map<String, String[]> getParameterMap() {
1294         Map<String, String[]> result = new HashMap<String,String[]>();
1295         Map<String, String[]> raw = rawRequest.getParameterMap();
1296         for (Map.Entry<String,String[]> item: raw.entrySet()) {
1297           String[] rawValue = item.getValue();
1298           String[] cookedValue = new String[rawValue.length];
1299           for(int i=0; i< rawValue.length; ++i) {
1300             cookedValue[i] = HtmlQuoting.quoteHtmlChars(rawValue[i]);
1301           }
1302           result.put(HtmlQuoting.quoteHtmlChars(item.getKey()), cookedValue);
1303         }
1304         return result;
1305       }
1306 
1307       /**
1308        * Quote the url so that users specifying the HOST HTTP header
1309        * can't inject attacks.
1310        */
1311       @Override
1312       public StringBuffer getRequestURL(){
1313         String url = rawRequest.getRequestURL().toString();
1314         return new StringBuffer(HtmlQuoting.quoteHtmlChars(url));
1315       }
1316 
1317       /**
1318        * Quote the server name so that users specifying the HOST HTTP header
1319        * can't inject attacks.
1320        */
1321       @Override
1322       public String getServerName() {
1323         return HtmlQuoting.quoteHtmlChars(rawRequest.getServerName());
1324       }
1325     }
1326 
1327     @Override
1328     public void init(FilterConfig config) throws ServletException {
1329       this.config = config;
1330     }
1331 
1332     @Override
1333     public void destroy() {
1334     }
1335 
1336     @Override
1337     public void doFilter(ServletRequest request,
1338                          ServletResponse response,
1339                          FilterChain chain
1340                          ) throws IOException, ServletException {
1341       HttpServletRequestWrapper quoted =
1342         new RequestQuoter((HttpServletRequest) request);
1343       HttpServletResponse httpResponse = (HttpServletResponse) response;
1344 
1345       String mime = inferMimeType(request);
1346       if (mime == null) {
1347         httpResponse.setContentType("text/plain; charset=utf-8");
1348       } else if (mime.startsWith("text/html")) {
1349         // HTML with unspecified encoding, we want to
1350         // force HTML with utf-8 encoding
1351         // This is to avoid the following security issue:
1352         // http://openmya.hacker.jp/hasegawa/security/utf7cs.html
1353         httpResponse.setContentType("text/html; charset=utf-8");
1354       } else if (mime.startsWith("application/xml")) {
1355         httpResponse.setContentType("text/xml; charset=utf-8");
1356       }
1357       chain.doFilter(quoted, httpResponse);
1358     }
1359 
1360     /**
1361      * Infer the mime type for the response based on the extension of the request
1362      * URI. Returns null if unknown.
1363      */
1364     private String inferMimeType(ServletRequest request) {
1365       String path = ((HttpServletRequest)request).getRequestURI();
1366       ContextHandler.SContext sContext = (ContextHandler.SContext)config.getServletContext();
1367       MimeTypes mimes = sContext.getContextHandler().getMimeTypes();
1368       Buffer mimeBuffer = mimes.getMimeByExtension(path);
1369       return (mimeBuffer == null) ? null : mimeBuffer.toString();
1370     }
1371 
1372   }
1373 
1374 }