Search in sources :

Example 6 with PrivilegedGetTccl

use of org.apache.tomcat.util.security.PrivilegedGetTccl in project tomcat70 by apache.

the class ParserUtils method parseXMLDocument.

// --------------------------------------------------------- Public Methods
/**
 * Parse the specified XML document, and return a <code>TreeNode</code>
 * that corresponds to the root node of the document tree.
 *
 * @param location Location (eg URI) of the XML document being parsed
 * @param is Input source containing the deployment descriptor
 *
 * @exception JasperException if an input/output error occurs
 * @exception JasperException if a parsing error occurs
 */
public TreeNode parseXMLDocument(String location, InputSource is) throws JasperException {
    Document document = null;
    // Perform an XML parse of this document, via JAXP
    ClassLoader original;
    if (Constants.IS_SECURITY_ENABLED) {
        PrivilegedGetTccl pa = new PrivilegedGetTccl();
        original = AccessController.doPrivileged(pa);
    } else {
        original = Thread.currentThread().getContextClassLoader();
    }
    try {
        if (Constants.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(ParserUtils.class.getClassLoader());
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(ParserUtils.class.getClassLoader());
        }
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(validating);
        if (validating) {
            // Enable DTD validation
            factory.setFeature("http://xml.org/sax/features/validation", true);
            // Enable schema validation
            factory.setFeature("http://apache.org/xml/features/validation/schema", true);
        }
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(entityResolverInstance);
        XmlErrorHandler handler = new XmlErrorHandler();
        builder.setErrorHandler(handler);
        document = builder.parse(is);
        if (!handler.getErrors().isEmpty()) {
            // throw the first to indicate there was a error during processing
            throw handler.getErrors().iterator().next();
        }
    } catch (ParserConfigurationException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", location), ex);
    } catch (SAXParseException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml.line", location, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex);
    } catch (SAXException sx) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", location), sx);
    } catch (IOException io) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", location), io);
    } finally {
        if (Constants.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(original);
        }
    }
    // Convert the resulting document to a graph of TreeNodes
    return (convert(null, document.getDocumentElement()));
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) JasperException(org.apache.jasper.JasperException) PrivilegedGetTccl(org.apache.tomcat.util.security.PrivilegedGetTccl) SAXParseException(org.xml.sax.SAXParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) XmlErrorHandler(org.apache.tomcat.util.descriptor.XmlErrorHandler) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl)

Example 7 with PrivilegedGetTccl

use of org.apache.tomcat.util.security.PrivilegedGetTccl in project tomcat70 by apache.

the class DefaultServlet method renderXml.

/**
 * Return an InputStream to an HTML representation of the contents
 * of this directory.
 *
 * @param contextPath Context path to which our internal paths are
 *  relative
 */
protected InputStream renderXml(String contextPath, CacheEntry cacheEntry, Source xsltSource) throws IOException, ServletException {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\"?>");
    sb.append("<listing ");
    sb.append(" contextPath='");
    sb.append(contextPath);
    sb.append("'");
    sb.append(" directory='");
    sb.append(cacheEntry.name);
    sb.append("' ");
    sb.append(" hasParent='").append(!cacheEntry.name.equals("/"));
    sb.append("'>");
    sb.append("<entries>");
    try {
        // Render the directory entries within this directory
        NamingEnumeration<NameClassPair> enumeration = resources.list(cacheEntry.name);
        // rewriteUrl(contextPath) is expensive. cache result for later reuse
        String rewrittenContextPath = rewriteUrl(contextPath);
        while (enumeration.hasMoreElements()) {
            NameClassPair ncPair = enumeration.nextElement();
            String resourceName = ncPair.getName();
            String trimmed = resourceName;
            if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile))
                continue;
            if ((cacheEntry.name + trimmed).equals(contextXsltFile))
                continue;
            CacheEntry childCacheEntry = resources.lookupCache(cacheEntry.name + resourceName);
            if (!childCacheEntry.exists) {
                continue;
            }
            sb.append("<entry");
            sb.append(" type='").append((childCacheEntry.context != null) ? "dir" : "file").append("'");
            sb.append(" urlPath='").append(rewrittenContextPath).append(rewriteUrl(cacheEntry.name + resourceName)).append((childCacheEntry.context != null) ? "/" : "").append("'");
            if (childCacheEntry.resource != null) {
                sb.append(" size='").append(renderSize(childCacheEntry.attributes.getContentLength())).append("'");
            }
            sb.append(" date='").append(childCacheEntry.attributes.getLastModifiedHttp()).append("'");
            sb.append(">");
            sb.append(RequestUtil.filter(trimmed));
            if (childCacheEntry.context != null)
                sb.append("/");
            sb.append("</entry>");
        }
    } catch (NamingException e) {
        // Something went wrong
        throw new ServletException("Error accessing resource", e);
    }
    sb.append("</entries>");
    String readme = getReadme(cacheEntry.context);
    if (readme != null) {
        sb.append("<readme><![CDATA[");
        sb.append(readme);
        sb.append("]]></readme>");
    }
    sb.append("</listing>");
    // Prevent possible memory leak. Ensure Transformer and
    // TransformerFactory are not loaded from the web application.
    ClassLoader original;
    if (Globals.IS_SECURITY_ENABLED) {
        PrivilegedGetTccl pa = new PrivilegedGetTccl();
        original = AccessController.doPrivileged(pa);
    } else {
        original = Thread.currentThread().getContextClassLoader();
    }
    try {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(DefaultServlet.class.getClassLoader());
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(DefaultServlet.class.getClassLoader());
        }
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xmlSource = new StreamSource(new StringReader(sb.toString()));
        Transformer transformer = tFactory.newTransformer(xsltSource);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
        StreamResult out = new StreamResult(osWriter);
        transformer.transform(xmlSource, out);
        osWriter.flush();
        return (new ByteArrayInputStream(stream.toByteArray()));
    } catch (TransformerException e) {
        throw new ServletException("XSL transformer error", e);
    } finally {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(original);
        }
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CacheEntry(org.apache.naming.resources.CacheEntry) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) ServletException(javax.servlet.ServletException) ByteArrayInputStream(java.io.ByteArrayInputStream) NameClassPair(javax.naming.NameClassPair) PrivilegedGetTccl(org.apache.tomcat.util.security.PrivilegedGetTccl) StringReader(java.io.StringReader) NamingException(javax.naming.NamingException) OutputStreamWriter(java.io.OutputStreamWriter) TransformerException(javax.xml.transform.TransformerException) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl)

Example 8 with PrivilegedGetTccl

use of org.apache.tomcat.util.security.PrivilegedGetTccl in project Payara by payara.

the class DefaultServlet method renderXml.

private InputStream renderXml(String contextPath, CacheEntry cacheEntry, Source xsltSource, ProxyDirContext proxyDirContext) throws IOException, ServletException {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\"?>");
    sb.append("<listing ");
    sb.append(" contextPath='");
    sb.append(contextPath);
    sb.append("'");
    sb.append(" directory='");
    sb.append(cacheEntry.name);
    sb.append("' ");
    sb.append(" hasParent='").append(!cacheEntry.name.equals("/"));
    sb.append("'>");
    sb.append("<entries>");
    try {
        // Render the directory entries within this directory
        Enumeration<NameClassPair> enumeration = proxyDirContext.list(cacheEntry.name);
        if (sortedBy.equals(SortedBy.LAST_MODIFIED)) {
            ArrayList<NameClassPair> list = Collections.list(enumeration);
            Comparator<NameClassPair> c = new LastModifiedComparator(proxyDirContext, cacheEntry.name);
            Collections.sort(list, c);
            enumeration = Collections.enumeration(list);
        } else if (sortedBy.equals(SortedBy.SIZE)) {
            ArrayList<NameClassPair> list = Collections.list(enumeration);
            Comparator<NameClassPair> c = new SizeComparator(proxyDirContext, cacheEntry.name);
            Collections.sort(list, c);
            enumeration = Collections.enumeration(list);
        }
        // rewriteUrl(contextPath) is expensive. cache result for later reuse
        String rewrittenContextPath = rewriteUrl(contextPath);
        while (enumeration.hasMoreElements()) {
            NameClassPair ncPair = enumeration.nextElement();
            String resourceName = ncPair.getName();
            String trimmed = resourceName;
            if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF") || trimmed.equalsIgnoreCase(localXsltFile))
                continue;
            if ((cacheEntry.name + trimmed).equals(contextXsltFile))
                continue;
            CacheEntry childCacheEntry = proxyDirContext.lookupCache(cacheEntry.name + resourceName);
            if (!childCacheEntry.exists) {
                continue;
            }
            sb.append("<entry");
            sb.append(" type='").append((childCacheEntry.context != null) ? "dir" : "file").append("'");
            sb.append(" urlPath='").append(rewrittenContextPath).append(rewriteUrl(cacheEntry.name + resourceName)).append((childCacheEntry.context != null) ? "/" : "").append("'");
            if (childCacheEntry.resource != null) {
                sb.append(" size='").append(renderSize(childCacheEntry.attributes.getContentLength())).append("'");
            }
            sb.append(" date='").append(childCacheEntry.attributes.getLastModifiedHttp()).append("'");
            sb.append(">");
            sb.append(HtmlEntityEncoder.encodeXSS(trimmed));
            if (childCacheEntry.context != null)
                sb.append("/");
            sb.append("</entry>");
        }
    } catch (NamingException e) {
        // Something went wrong
        throw new ServletException("Error accessing resource", e);
    }
    sb.append("</entries>");
    String readme = getReadme(cacheEntry.context);
    if (readme != null) {
        sb.append("<readme><![CDATA[");
        sb.append(readme);
        sb.append("]]></readme>");
    }
    sb.append("</listing>");
    // Prevent possible memory leak. Ensure Transformer and
    // TransformerFactory are not loaded from the web application.
    ClassLoader original;
    if (Globals.IS_SECURITY_ENABLED) {
        PrivilegedGetTccl pa = new PrivilegedGetTccl();
        original = AccessController.doPrivileged(pa);
    } else {
        original = Thread.currentThread().getContextClassLoader();
    }
    try {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(DefaultServlet.class.getClassLoader());
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(DefaultServlet.class.getClassLoader());
        }
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xmlSource = new StreamSource(new StringReader(sb.toString()));
        Transformer transformer = tFactory.newTransformer(xsltSource);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
        StreamResult out = new StreamResult(osWriter);
        transformer.transform(xmlSource, out);
        osWriter.flush();
        return (new ByteArrayInputStream(stream.toByteArray()));
    } catch (Exception e) {
        log("directory transform failure: " + e.getMessage());
        return renderHtml(contextPath, cacheEntry);
    } finally {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(original);
        }
    }
}
Also used : Transformer(javax.xml.transform.Transformer) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) ServletException(javax.servlet.ServletException) StringReader(java.io.StringReader) NamingException(javax.naming.NamingException) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl) TransformerFactory(javax.xml.transform.TransformerFactory) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CacheEntry(org.apache.naming.resources.CacheEntry) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) UnavailableException(javax.servlet.UnavailableException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ByteArrayInputStream(java.io.ByteArrayInputStream) NameClassPair(javax.naming.NameClassPair) PrivilegedGetTccl(org.apache.tomcat.util.security.PrivilegedGetTccl) OutputStreamWriter(java.io.OutputStreamWriter)

Example 9 with PrivilegedGetTccl

use of org.apache.tomcat.util.security.PrivilegedGetTccl in project tomcat by apache.

the class StandardContext method bind.

@Override
public ClassLoader bind(boolean usePrivilegedAction, ClassLoader originalClassLoader) {
    Loader loader = getLoader();
    ClassLoader webApplicationClassLoader = null;
    if (loader != null) {
        webApplicationClassLoader = loader.getClassLoader();
    }
    if (originalClassLoader == null) {
        if (usePrivilegedAction) {
            PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl();
            originalClassLoader = AccessController.doPrivileged(pa);
        } else {
            originalClassLoader = Thread.currentThread().getContextClassLoader();
        }
    }
    if (webApplicationClassLoader == null || webApplicationClassLoader == originalClassLoader) {
        // null to indicate this.
        return null;
    }
    ThreadBindingListener threadBindingListener = getThreadBindingListener();
    if (usePrivilegedAction) {
        PrivilegedAction<Void> pa = new PrivilegedSetTccl(webApplicationClassLoader);
        AccessController.doPrivileged(pa);
    } else {
        Thread.currentThread().setContextClassLoader(webApplicationClassLoader);
    }
    if (threadBindingListener != null) {
        try {
            threadBindingListener.bind();
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            log.error(sm.getString("standardContext.threadBindingListenerError", getName()), t);
        }
    }
    return originalClassLoader;
}
Also used : ThreadBindingListener(org.apache.catalina.ThreadBindingListener) PrivilegedGetTccl(org.apache.tomcat.util.security.PrivilegedGetTccl) WebappLoader(org.apache.catalina.loader.WebappLoader) Loader(org.apache.catalina.Loader) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl)

Example 10 with PrivilegedGetTccl

use of org.apache.tomcat.util.security.PrivilegedGetTccl in project tomcat by apache.

the class DefaultServlet method renderXml.

/**
 * Return an InputStream to an XML representation of the contents this
 * directory.
 *
 * @param request     The HttpServletRequest being served
 * @param contextPath Context path to which our internal paths are relative
 * @param resource    The associated resource
 * @param xsltSource  The XSL stylesheet
 * @param encoding    The encoding to use to process the readme (if any)
 *
 * @return the XML data
 *
 * @throws IOException an IO error occurred
 * @throws ServletException rendering error
 */
protected InputStream renderXml(HttpServletRequest request, String contextPath, WebResource resource, Source xsltSource, String encoding) throws IOException, ServletException {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\"?>");
    sb.append("<listing ");
    sb.append(" contextPath='");
    sb.append(contextPath);
    sb.append('\'');
    sb.append(" directory='");
    sb.append(resource.getName());
    sb.append("' ");
    sb.append(" hasParent='").append(!resource.getName().equals("/"));
    sb.append("'>");
    sb.append("<entries>");
    String[] entries = resources.list(resource.getWebappPath());
    // rewriteUrl(contextPath) is expensive. cache result for later reuse
    String rewrittenContextPath = rewriteUrl(contextPath);
    String directoryWebappPath = resource.getWebappPath();
    for (String entry : entries) {
        if (entry.equalsIgnoreCase("WEB-INF") || entry.equalsIgnoreCase("META-INF") || entry.equalsIgnoreCase(localXsltFile)) {
            continue;
        }
        if ((directoryWebappPath + entry).equals(contextXsltFile)) {
            continue;
        }
        WebResource childResource = resources.getResource(directoryWebappPath + entry);
        if (!childResource.exists()) {
            continue;
        }
        sb.append("<entry");
        sb.append(" type='").append(childResource.isDirectory() ? "dir" : "file").append('\'');
        sb.append(" urlPath='").append(rewrittenContextPath).append(rewriteUrl(directoryWebappPath + entry)).append(childResource.isDirectory() ? "/" : "").append('\'');
        if (childResource.isFile()) {
            sb.append(" size='").append(renderSize(childResource.getContentLength())).append('\'');
        }
        sb.append(" date='").append(childResource.getLastModifiedHttp()).append('\'');
        sb.append('>');
        sb.append(Escape.htmlElementContent(entry));
        if (childResource.isDirectory()) {
            sb.append('/');
        }
        sb.append("</entry>");
    }
    sb.append("</entries>");
    String readme = getReadme(resource, encoding);
    if (readme != null) {
        sb.append("<readme><![CDATA[");
        sb.append(readme);
        sb.append("]]></readme>");
    }
    sb.append("</listing>");
    // Prevent possible memory leak. Ensure Transformer and
    // TransformerFactory are not loaded from the web application.
    ClassLoader original;
    if (Globals.IS_SECURITY_ENABLED) {
        PrivilegedGetTccl pa = new PrivilegedGetTccl();
        original = AccessController.doPrivileged(pa);
    } else {
        original = Thread.currentThread().getContextClassLoader();
    }
    try {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(DefaultServlet.class.getClassLoader());
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(DefaultServlet.class.getClassLoader());
        }
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xmlSource = new StreamSource(new StringReader(sb.toString()));
        Transformer transformer = tFactory.newTransformer(xsltSource);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        OutputStreamWriter osWriter = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
        StreamResult out = new StreamResult(osWriter);
        transformer.transform(xmlSource, out);
        osWriter.flush();
        return new ByteArrayInputStream(stream.toByteArray());
    } catch (TransformerException e) {
        throw new ServletException(sm.getString("defaultServlet.xslError"), e);
    } finally {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(original);
        }
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) WebResource(org.apache.catalina.WebResource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) ServletException(jakarta.servlet.ServletException) ByteArrayInputStream(java.io.ByteArrayInputStream) PrivilegedGetTccl(org.apache.tomcat.util.security.PrivilegedGetTccl) StringReader(java.io.StringReader) OutputStreamWriter(java.io.OutputStreamWriter) TransformerException(javax.xml.transform.TransformerException) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl)

Aggregations

PrivilegedGetTccl (org.apache.tomcat.util.security.PrivilegedGetTccl)11 PrivilegedSetTccl (org.apache.tomcat.util.security.PrivilegedSetTccl)11 InputSource (org.xml.sax.InputSource)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 OutputStreamWriter (java.io.OutputStreamWriter)5 StringReader (java.io.StringReader)5 Source (javax.xml.transform.Source)5 Transformer (javax.xml.transform.Transformer)5 TransformerFactory (javax.xml.transform.TransformerFactory)5 DOMSource (javax.xml.transform.dom.DOMSource)5 StreamResult (javax.xml.transform.stream.StreamResult)5 StreamSource (javax.xml.transform.stream.StreamSource)5 ServletException (javax.servlet.ServletException)4 TransformerException (javax.xml.transform.TransformerException)4 IOException (java.io.IOException)3 WebResource (org.apache.catalina.WebResource)3 SAXException (org.xml.sax.SAXException)3 NameClassPair (javax.naming.NameClassPair)2 NamingException (javax.naming.NamingException)2