@Override public void addElement(StringBuilder buf, Date date, Request request, Response response, long time) { // Don't need to flush since trigger for log message is after the // response has been committed long length = response.getBytesWritten(false); if (length <= 0) { // Protect against nulls and unexpected types as these values // may be set by untrusted applications Object start = request.getAttribute(Globals.SENDFILE_FILE_START_ATTR); if (start instanceof Long) { Object end = request.getAttribute(Globals.SENDFILE_FILE_END_ATTR); if (end instanceof Long) { length = ((Long) end).longValue() - ((Long) start).longValue(); } } } if (length <= 0 && conversion) { buf.append('-'); } else { buf.append(length); } }
/** * Look for the X509 certificate chain in the Request under the key * <code>javax.servlet.request.X509Certificate</code>. If not found, trigger * extracting the certificate chain from the Coyote request. * * @param request Request to be processed * * @return The X509 certificate chain if found, <code>null</code> * otherwise. */ protected X509Certificate[] getRequestCertificates(final Request request) throws IllegalStateException { X509Certificate certs[] = (X509Certificate[]) request.getAttribute(Globals.CERTIFICATES_ATTR); if ((certs == null) || (certs.length < 1)) { try { request.getCoyoteRequest().action(ActionCode.REQ_SSL_CERTIFICATE, null); certs = (X509Certificate[]) request.getAttribute(Globals.CERTIFICATES_ATTR); } catch (IllegalStateException ise) { // Request body was too large for save buffer // Return null which will trigger an auth failure } } return certs; }
private File validateGlobalXsltFile() { File result = null; String base = System.getProperty(Globals.CATALINA_BASE_PROP); if (base != null) { File baseConf = new File(base, "conf"); result = validateGlobalXsltFile(baseConf); } if (result == null) { String home = System.getProperty(Globals.CATALINA_HOME_PROP); if (home != null && !home.equals(base)) { File homeConf = new File(home, "conf"); result = validateGlobalXsltFile(homeConf); } } return result; }
/** * Start this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void startInternal() throws LifecycleException { try { CatalinaCluster catclust = (CatalinaCluster)this.getCluster(); if (this.context == null) this.context = new ReplApplContext(this); if ( catclust != null ) { ReplicatedMap<String,Object> map = new ReplicatedMap<String,Object>(this, catclust.getChannel(),DEFAULT_REPL_TIMEOUT, getName(),getClassLoaders()); map.setChannelSendOptions(mapSendOptions); ((ReplApplContext)this.context).setAttributeMap(map); if (getAltDDName() != null) context.setAttribute(Globals.ALT_DD_ATTR, getAltDDName()); } super.startInternal(); } catch ( Exception x ) { log.error("Unable to start ReplicatedContext",x); throw new LifecycleException("Failed to start ReplicatedContext",x); } }
@Override public boolean check(Permission permission) { if (!Globals.IS_SECURITY_ENABLED) { return true; } Policy currentPolicy = Policy.getPolicy(); if (currentPolicy != null) { ResourceEntry entry = findResourceInternal("/", "/", false); if (entry != null) { CodeSource cs = new CodeSource( entry.codeBase, (java.security.cert.Certificate[]) null); PermissionCollection pc = currentPolicy.getPermissions(cs); if (pc.implies(permission)) { return true; } } } return false; }
/** * Return the value of the specified initialization parameter, or * <code>null</code> if this parameter does not exist. * * @param name * Name of the initialization parameter to retrieve */ @Override public String getInitParameter(final String name) { // Special handling for XML settings as the context setting must // always override anything that might have been set by an application. if (Globals.JASPER_XML_VALIDATION_TLD_INIT_PARAM.equals(name) && context.getTldValidation()) { return "true"; } if (Globals.JASPER_XML_VALIDATION_INIT_PARAM.equals(name) && context.getXmlValidation()) { return "true"; } if (Globals.JASPER_XML_BLOCK_EXTERNAL_INIT_PARAM.equals(name)) { if (!context.getXmlBlockExternal()) { // System admin has explicitly changed the default return "false"; } } return parameters.get(name); }
/** * 设置catalina.home属性,如果用户未设置则使用当前的工作目录 * Set the <code>catalina.home</code> System property to the current * working directory if it has not been set. */ private void setCatalinaHome() { if (System.getProperty(Globals.CATALINA_HOME_PROP) != null) return; File bootstrapJar = new File(System.getProperty("user.dir"), "bootstrap.jar"); if (bootstrapJar.exists()) { try { System.setProperty (Globals.CATALINA_HOME_PROP, (new File(System.getProperty("user.dir"), "..")) .getCanonicalPath()); } catch (Exception e) { // Ignore System.setProperty(Globals.CATALINA_HOME_PROP, System.getProperty("user.dir")); } } else { System.setProperty(Globals.CATALINA_HOME_PROP, System.getProperty("user.dir")); } }
/** * Invoke the next Valve in the sequence. When the invoke returns, check * the response state, and output an error report is necessary. * * @param request The servlet request to be processed * @param response The servlet response to be created * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); Throwable throwable = (Throwable) request.getAttribute(Globals.EXCEPTION_ATTR); if (response.isCommitted()) { return; } if (throwable != null) { // The response is an error response.setError(); // Reset the response (if possible) try { response.reset(); } catch (IllegalStateException e) { ; } response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } response.setSuspended(false); try { report(request, response, throwable); } catch (Throwable tt) { ; } }
/** * Forward this request and response to another resource for processing. * Any runtime exception, IOException, or ServletException thrown by the * called servlet will be propogated to the caller. * * @param request The servlet request to be forwarded * @param response The servlet response to be forwarded * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedForward dp = new PrivilegedForward(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { doForward(request,response); } }
@Override public void addElement(StringBuilder buf, Date date, Request request, Response response, long time) { // Don't need to flush since trigger for log message is after the // response has been committed long length = response.getBytesWritten(false); if (length <= 0) { // Protect against nulls and unexpected types as these values // may be set by untrusted applications Object start = request.getAttribute( Globals.SENDFILE_FILE_START_ATTR); if (start instanceof Long) { Object end = request.getAttribute( Globals.SENDFILE_FILE_END_ATTR); if (end instanceof Long) { length = ((Long) end).longValue() - ((Long) start).longValue(); } } } if (length <= 0 && conversion) { buf.append('-'); } else { buf.append(length); } }
/** * Override the <code>setAttribute()</code> method of the wrapped request. * * @param name * Name of the attribute to set * @param value * Value of the attribute to set */ @Override public void setAttribute(String name, Object value) { if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) { dispatcherType = (DispatcherType) value; return; } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) { requestDispatcherPath = value; return; } if (!setSpecial(name, value)) { getRequest().setAttribute(name, value); } }
/** * Obtain the declared methods for a class taking account of any security * manager that may be configured. */ public static Method[] getDeclaredMethods(final Class<?> clazz) { Method[] methods = null; if (Globals.IS_SECURITY_ENABLED) { methods = AccessController.doPrivileged( new PrivilegedAction<Method[]>(){ @Override public Method[] run(){ return clazz.getDeclaredMethods(); } }); } else { methods = clazz.getDeclaredMethods(); } return methods; }
@Override public URL getResource(String path) throws MalformedURLException { if (Globals.IS_SECURITY_ENABLED) { try { return (URL) invokeMethod(context, "getResource", new Object[]{path}); } catch(Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof MalformedURLException){ throw (MalformedURLException)t; } return null; } } else { return context.getResource(path); } }
/** * Return the value of the specified initialization parameter, or * <code>null</code> if this parameter does not exist. * * @param name Name of the initialization parameter to retrieve */ @Override public String getInitParameter(final String name) { // Special handling for XML settings as the context setting must // always override anything that might have been set by an application. if (Globals.JASPER_XML_VALIDATION_TLD_INIT_PARAM.equals(name) && context.getTldValidation()) { return "true"; } if (Globals.JASPER_XML_VALIDATION_INIT_PARAM.equals(name) && context.getXmlValidation()) { return "true"; } if (Globals.JASPER_XML_BLOCK_EXTERNAL_INIT_PARAM.equals(name)) { if (!context.getXmlBlockExternal()) { // System admin has explicitly changed the default return "false"; } } return parameters.get(name); }
/** * Return the names of the context's initialization parameters, or an * empty enumeration if the context has no initialization parameters. */ @Override public Enumeration<String> getInitParameterNames() { Set<String> names = new HashSet<String>(); names.addAll(parameters.keySet()); // Special handling for XML settings as these attributes will always be // available if they have been set on the context if (context.getTldValidation()) { names.add(Globals.JASPER_XML_VALIDATION_TLD_INIT_PARAM); } if (context.getXmlValidation()) { names.add(Globals.JASPER_XML_VALIDATION_INIT_PARAM); } if (!context.getXmlBlockExternal()) { names.add(Globals.JASPER_XML_BLOCK_EXTERNAL_INIT_PARAM); } return Collections.enumeration(names); }
@Override public ClassLoader getClassLoader() { ClassLoader result = context.getLoader().getClassLoader(); if (Globals.IS_SECURITY_ENABLED) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); ClassLoader parent = result; while (parent != null) { if (parent == tccl) { break; } parent = parent.getParent(); } if (parent == null) { System.getSecurityManager().checkPermission( new RuntimePermission("getClassLoader")); } } return result; }
/** * Forward this request and response to another resource for processing. * Any runtime exception, IOException, or ServletException thrown by the * called servlet will be propagated to the caller. * * @param request The servlet request to be forwarded * @param response The servlet response to be forwarded * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ @Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedForward dp = new PrivilegedForward(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { doForward(request,response); } }
/** * Include the response from another resource in the current response. * Any runtime exception, IOException, or ServletException thrown by the * called servlet will be propagated to the caller. * * @param request The servlet request that is including this one * @param response The servlet response to be appended to * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ @Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedInclude dp = new PrivilegedInclude(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { doInclude(request, response); } }
@Override public void dispatch(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (Globals.IS_SECURITY_ENABLED) { try { PrivilegedDispatch dp = new PrivilegedDispatch(request,response); AccessController.doPrivileged(dp); } catch (PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; throw (IOException) e; } } else { doDispatch(request, response); } }
@Override public void setDateHeader(String name, long date) { if (isCommitted()) { return; } if(Globals.IS_SECURITY_ENABLED) { AccessController.doPrivileged(new DateHeaderPrivilegedAction (name, date, false)); } else { response.setDateHeader(name, date); } }
/** * Return the <code>SecurityManager</code> only if Security is enabled AND * package protection mechanism is enabled. */ public static boolean isPackageProtectionEnabled(){ if (packageDefinitionEnabled && Globals.IS_SECURITY_ENABLED){ return true; } return false; }
@Override public ServletContext getServletContext() { if (context == null) { context = new ReplApplContext(this); if (getAltDDName() != null) context.setAttribute(Globals.ALT_DD_ATTR,getAltDDName()); } return ((ReplApplContext)context).getFacade(); }
private void bind(Context context) { // Bind the context CL to the current thread if (clBindRequired && context.getLoader() != null) { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(context.getLoader().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader()); } } }
/** * Process the event, using the security manager if the option is enabled. * * @param event the event to process * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ @Override public void doFilterEvent(CometEvent event) throws IOException, ServletException { if( Globals.IS_SECURITY_ENABLED ) { final CometEvent ev = event; try { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction<Void>() { @Override public Void run() throws ServletException, IOException { internalDoFilterEvent(ev); return null; } } ); } catch( PrivilegedActionException pe) { Exception e = pe.getException(); if (e instanceof ServletException) throw (ServletException) e; else if (e instanceof IOException) throw (IOException) e; else if (e instanceof RuntimeException) throw (RuntimeException) e; else throw new ServletException(e.getMessage(), e); } } else { internalDoFilterEvent(event); } }
protected void initBaseDir() { String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP); if (basedir == null) { basedir = System.getProperty(Globals.CATALINA_BASE_PROP); } if (basedir == null) { basedir = catalinaHome; } if (basedir == null) { // Create a temp dir. basedir = System.getProperty("user.dir") + "/tomcat." + port; File home = new File(basedir); home.mkdir(); if (!home.isAbsolute()) { try { basedir = home.getCanonicalPath(); } catch (IOException e) { basedir = home.getAbsolutePath(); } } } if (catalinaHome == null) { System.setProperty(Globals.CATALINA_HOME_PROP, basedir); } System.setProperty(Globals.CATALINA_BASE_PROP, basedir); }
private void doDispatch(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Set up to handle the specified request and response State state = new State(request, response, false); // Create a wrapped response to use for this request wrapResponse(state); ApplicationHttpRequest wrequest = (ApplicationHttpRequest) wrapRequest(state); if (queryString != null) { wrequest.setQueryParams(queryString); } wrequest.setAttribute(Globals.DISPATCHER_TYPE_ATTR, DispatcherType.ASYNC); wrequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); wrequest.setContextPath(context.getPath()); wrequest.setRequestURI(requestURI); wrequest.setServletPath(servletPath); wrequest.setPathInfo(pathInfo); if (queryString != null) { wrequest.setQueryString(queryString); wrequest.setQueryParams(queryString); } invoke(state.outerRequest, state.outerResponse, state); }
/** * 通过系统属性取替换对应的占位参数${} * 查找${位置,然后查找} 的位置,截取中间内容去替换,不支持嵌套的${}. * * * System property replacement in the given string. * * @param str The original string * @return the modified string */ protected String replace(String str) { // Implementation is copied from ClassLoaderLogManager.replace(), // but added special processing for catalina.home and catalina.base. String result = str; int pos_start = str.indexOf("${"); if (pos_start >= 0) { StringBuilder builder = new StringBuilder(); int pos_end = -1; while (pos_start >= 0) { builder.append(str, pos_end + 1, pos_start); pos_end = str.indexOf('}', pos_start + 2); if (pos_end < 0) { pos_end = pos_start - 1; break; } String propName = str.substring(pos_start + 2, pos_end); String replacement; if (propName.length() == 0) { replacement = null; } else if (Globals.CATALINA_HOME_PROP.equals(propName)) { replacement = getCatalinaHome(); } else if (Globals.CATALINA_BASE_PROP.equals(propName)) { replacement = getCatalinaBase(); } else { replacement = System.getProperty(propName); } if (replacement != null) { builder.append(replacement); } else { builder.append(str, pos_start, pos_end + 1); } pos_start = str.indexOf("${", pos_end + 1); } builder.append(str, pos_end + 1, str.length()); result = builder.toString(); } return result; }
/** * Return a File object representing the base directory for the * entire servlet container (i.e. the Engine container if present). */ protected File engineBase() { String base=System.getProperty(Globals.CATALINA_BASE_PROP); if( base == null ) { StandardEngine eng=(StandardEngine)this.getParent().getParent(); base=eng.getBaseDir(); } return (new File(base)); }
/** * Set the <code>catalina.base</code> System property to the current * working directory if it has not been set. */ private void setCatalinaBase() { if (System.getProperty(Globals.CATALINA_BASE_PROP) != null) return; if (System.getProperty(Globals.CATALINA_HOME_PROP) != null) System.setProperty(Globals.CATALINA_BASE_PROP, System.getProperty(Globals.CATALINA_HOME_PROP)); else System.setProperty(Globals.CATALINA_BASE_PROP, System.getProperty("user.dir")); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // cast once HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // indicate that we're in SSI processing req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); // setup to capture output ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream(); ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(config.getServletContext(), req, res, basos); // process remainder of filter chain chain.doFilter(req, responseIncludeWrapper); // we can't assume the chain flushed its output responseIncludeWrapper.flushOutputStreamOrWriter(); byte[] bytes = basos.toByteArray(); // get content type String contentType = responseIncludeWrapper.getContentType(); // is this an allowed type for SSI processing? if (contentTypeRegEx.matcher(contentType).matches()) { String encoding = res.getCharacterEncoding(); // set up SSI processing SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver(config.getServletContext(), req, res, isVirtualWebappRelative, debug, encoding); SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, debug, allowExec); // prepare readers/writers Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), encoding); ByteArrayOutputStream ssiout = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(ssiout, encoding)); // do SSI processing long lastModified = ssiProcessor.process(reader, responseIncludeWrapper.getLastModified(), writer); // set output bytes writer.flush(); bytes = ssiout.toByteArray(); // override headers if (expires != null) { res.setDateHeader("expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } if (lastModified > 0) { res.setDateHeader("last-modified", lastModified); } res.setContentLength(bytes.length); Matcher shtmlMatcher = shtmlRegEx.matcher(responseIncludeWrapper.getContentType()); if (shtmlMatcher.matches()) { // Convert shtml mime type to ordinary html mime type but // preserve // encoding, if any. String enc = shtmlMatcher.group(1); res.setContentType("text/html" + ((enc != null) ? enc : "")); } } // write output OutputStream out = null; try { out = res.getOutputStream(); } catch (IllegalStateException e) { // Ignore, will try to use a writer } if (out == null) { res.getWriter().write(new String(bytes)); } else { out.write(bytes); } }
/** * Test if a given name is one of the special Servlet-spec SSL attributes. */ static boolean isSSLAttribute(String name) { return Globals.CERTIFICATES_ATTR.equals(name) || Globals.CIPHER_SUITE_ATTR.equals(name) || Globals.KEY_SIZE_ATTR.equals(name) || Globals.SSL_SESSION_ID_ATTR.equals(name) || Globals.SSL_SESSION_ID_TOMCAT_ATTR.equals(name) || Globals.SSL_SESSION_MGR_ATTR.equals(name); }
@Override public Enumeration<String> getAttributeNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetAttributePrivilegedAction()); } else { return request.getAttributeNames(); } }
@Override public String getCharacterEncoding() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetCharacterEncodingPrivilegedAction()); } else { return request.getCharacterEncoding(); } }
/** * Override the <code>getAttribute()</code> method of the wrapped request. * * @param name Name of the attribute to retrieve */ @Override public Object getAttribute(String name) { if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) { return dispatcherType; } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) { if ( requestDispatcherPath != null ){ return requestDispatcherPath.toString(); } else { return null; } } int pos = getSpecial(name); if (pos == -1) { return getRequest().getAttribute(name); } else { if ((specialAttributes[pos] == null) && (specialAttributes[5] == null) && (pos >= 5)) { // If it's a forward special attribute, and null, it means this // is an include, so we check the wrapped request since // the request could have been forwarded before the include return getRequest().getAttribute(name); } else { return specialAttributes[pos]; } } }
protected String getBaseDir() { Container engineC = context.getParent().getParent(); if (engineC instanceof StandardEngine) { return ((StandardEngine) engineC).getBaseDir(); } return System.getProperty(Globals.CATALINA_BASE_PROP); }
private boolean isGoodRequest(ServletRequest request) { // Trigger parsing of parameters request.getParameter("none"); // Detect failure if (request.getAttribute(Globals.PARAMETER_PARSE_FAILED_ATTR) != null) { return false; } return true; }