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