Search in sources :

Example 11 with SAXException

use of org.xml.sax.SAXException in project tomcat by apache.

the class WebdavStatus method doMkcol.

/**
     * MKCOL Method.
     * @param req The Servlet request
     * @param resp The Servlet response
     * @throws ServletException If an error occurs
     * @throws IOException If an IO error occurs
     */
protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (readOnly) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }
    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }
    String path = getRelativePath(req);
    WebResource resource = resources.getResource(path);
    // path
    if (resource.exists()) {
        // Get allowed methods
        StringBuilder methodsAllowed = determineMethodsAllowed(req);
        resp.addHeader("Allow", methodsAllowed.toString());
        resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
        return;
    }
    if (req.getContentLengthLong() > 0) {
        DocumentBuilder documentBuilder = getDocumentBuilder();
        try {
            // Document document =
            documentBuilder.parse(new InputSource(req.getInputStream()));
            // TODO : Process this request body
            resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED);
            return;
        } catch (SAXException saxe) {
            // Parse error - assume invalid content
            resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE);
            return;
        }
    }
    if (resources.mkdir(path)) {
        resp.setStatus(WebdavStatus.SC_CREATED);
        // Removing any lock-null resource which would be present
        lockNullResources.remove(path);
    } else {
        resp.sendError(WebdavStatus.SC_CONFLICT, WebdavStatus.getStatusText(WebdavStatus.SC_CONFLICT));
    }
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) WebResource(org.apache.catalina.WebResource) SAXException(org.xml.sax.SAXException)

Example 12 with SAXException

use of org.xml.sax.SAXException in project tomcat by apache.

the class WebdavStatus method doLock.

/**
     * LOCK Method.
     * @param req The Servlet request
     * @param resp The Servlet response
     * @throws ServletException If an error occurs
     * @throws IOException If an IO error occurs
     */
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (readOnly) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }
    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }
    LockInfo lock = new LockInfo();
    // Parsing lock request
    // Parsing depth header
    String depthStr = req.getHeader("Depth");
    if (depthStr == null) {
        lock.depth = maxDepth;
    } else {
        if (depthStr.equals("0")) {
            lock.depth = 0;
        } else {
            lock.depth = maxDepth;
        }
    }
    // Parsing timeout header
    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = req.getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        int commaPos = lockDurationStr.indexOf(',');
        // If multiple timeouts, just use the first
        if (commaPos != -1) {
            lockDurationStr = lockDurationStr.substring(0, commaPos);
        }
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = Integer.parseInt(lockDurationStr.substring(7));
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = Integer.parseInt(lockDurationStr);
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000);
    int lockRequestType = LOCK_CREATION;
    Node lockInfoNode = null;
    DocumentBuilder documentBuilder = getDocumentBuilder();
    try {
        Document document = documentBuilder.parse(new InputSource(req.getInputStream()));
        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (IOException e) {
        lockRequestType = LOCK_REFRESH;
    } catch (SAXException e) {
        lockRequestType = LOCK_REFRESH;
    }
    if (lockInfoNode != null) {
        // Reading lock information
        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;
        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch(currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String nodeName = currentNode.getNodeName();
                    if (nodeName.endsWith("lockscope")) {
                        lockScopeNode = currentNode;
                    }
                    if (nodeName.endsWith("locktype")) {
                        lockTypeNode = currentNode;
                    }
                    if (nodeName.endsWith("owner")) {
                        lockOwnerNode = currentNode;
                    }
                    break;
            }
        }
        if (lockScopeNode != null) {
            childList = lockScopeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch(currentNode.getNodeType()) {
                    case Node.TEXT_NODE:
                        break;
                    case Node.ELEMENT_NODE:
                        String tempScope = currentNode.getNodeName();
                        if (tempScope.indexOf(':') != -1) {
                            lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                        } else {
                            lock.scope = tempScope;
                        }
                        break;
                }
            }
            if (lock.scope == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }
        if (lockTypeNode != null) {
            childList = lockTypeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch(currentNode.getNodeType()) {
                    case Node.TEXT_NODE:
                        break;
                    case Node.ELEMENT_NODE:
                        String tempType = currentNode.getNodeName();
                        if (tempType.indexOf(':') != -1) {
                            lock.type = tempType.substring(tempType.indexOf(':') + 1);
                        } else {
                            lock.type = tempType;
                        }
                        break;
                }
            }
            if (lock.type == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }
        if (lockOwnerNode != null) {
            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch(currentNode.getNodeType()) {
                    case Node.TEXT_NODE:
                        lock.owner += currentNode.getNodeValue();
                        break;
                    case Node.ELEMENT_NODE:
                        strWriter = new StringWriter();
                        domWriter = new DOMWriter(strWriter, true);
                        domWriter.print(currentNode);
                        lock.owner += strWriter.toString();
                        break;
                }
            }
            if (lock.owner == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            lock.owner = "";
        }
    }
    String path = getRelativePath(req);
    lock.path = path;
    WebResource resource = resources.getResource(path);
    Enumeration<LockInfo> locksList = null;
    if (lockRequestType == LOCK_CREATION) {
        // Generating lock id
        String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-" + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-" + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        String lockToken = MD5Encoder.encode(ConcurrentMessageDigest.digestMD5(lockTokenStr.getBytes(StandardCharsets.ISO_8859_1)));
        if (resource.isDirectory() && lock.depth == maxDepth) {
            // Locking a collection (and all its member resources)
            // Checking if a child resource of this collection is
            // already locked
            Vector<String> lockPaths = new Vector<>();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            locksList = resourceLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            if (!lockPaths.isEmpty()) {
                // One of the child paths was locked
                // We generate a multistatus error report
                Enumeration<String> lockPathsList = lockPaths.elements();
                resp.setStatus(WebdavStatus.SC_CONFLICT);
                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();
                generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING);
                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement("D", "response", XMLWriter.OPENING);
                    generatedXML.writeElement("D", "href", XMLWriter.OPENING);
                    generatedXML.writeText(lockPathsList.nextElement());
                    generatedXML.writeElement("D", "href", XMLWriter.CLOSING);
                    generatedXML.writeElement("D", "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " " + WebdavStatus.getStatusText(WebdavStatus.SC_LOCKED));
                    generatedXML.writeElement("D", "status", XMLWriter.CLOSING);
                    generatedXML.writeElement("D", "response", XMLWriter.CLOSING);
                }
                generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);
                Writer writer = resp.getWriter();
                writer.write(generatedXML.toString());
                writer.close();
                return;
            }
            boolean addLock = true;
            // Checking if there is already a shared lock on this path
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = locksList.nextElement();
                if (currentLock.path.equals(lock.path)) {
                    if (currentLock.isExclusive()) {
                        resp.sendError(WebdavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            resp.sendError(WebdavStatus.SC_LOCKED);
                            return;
                        }
                    }
                    currentLock.tokens.addElement(lockToken);
                    lock = currentLock;
                    addLock = false;
                }
            }
            if (addLock) {
                lock.tokens.addElement(lockToken);
                collectionLocks.addElement(lock);
            }
        } else {
            // Locking a single resource
            // Retrieving an already existing lock on that resource
            LockInfo presentLock = resourceLocks.get(lock.path);
            if (presentLock != null) {
                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.tokens.addElement(lockToken);
                    lock = presentLock;
                }
            } else {
                lock.tokens.addElement(lockToken);
                resourceLocks.put(lock.path, lock);
                // Checking if a resource exists at this path
                if (!resource.exists()) {
                    // "Creating" a lock-null resource
                    int slash = lock.path.lastIndexOf('/');
                    String parentPath = lock.path.substring(0, slash);
                    Vector<String> lockNulls = lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector<>();
                        lockNullResources.put(parentPath, lockNulls);
                    }
                    lockNulls.addElement(lock.path);
                }
                // Add the Lock-Token header as by RFC 2518 8.10.1
                // - only do this for newly created locks
                resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");
            }
        }
    }
    if (lockRequestType == LOCK_REFRESH) {
        String ifHeader = req.getHeader("If");
        if (ifHeader == null)
            ifHeader = "";
        // Checking resource locks
        LockInfo toRenew = resourceLocks.get(path);
        Enumeration<String> tokenList = null;
        if (toRenew != null) {
            // At least one of the tokens of the locks must have been given
            tokenList = toRenew.tokens.elements();
            while (tokenList.hasMoreElements()) {
                String token = tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }
        }
        // Checking inheritable collection locks
        Enumeration<LockInfo> collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {
                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = tokenList.nextElement();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.expiresAt = lock.expiresAt;
                        lock = toRenew;
                    }
                }
            }
        }
    }
    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement("D", DEFAULT_NAMESPACE, "prop", XMLWriter.OPENING);
    generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING);
    lock.toXML(generatedXML);
    generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING);
    generatedXML.writeElement("D", "prop", XMLWriter.CLOSING);
    resp.setStatus(WebdavStatus.SC_OK);
    resp.setContentType("text/xml; charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();
}
Also used : InputSource(org.xml.sax.InputSource) DOMWriter(org.apache.catalina.util.DOMWriter) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) WebResource(org.apache.catalina.WebResource) IOException(java.io.IOException) Document(org.w3c.dom.Document) XMLWriter(org.apache.catalina.util.XMLWriter) SAXException(org.xml.sax.SAXException) StringWriter(java.io.StringWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Vector(java.util.Vector) XMLWriter(org.apache.catalina.util.XMLWriter) DOMWriter(org.apache.catalina.util.DOMWriter) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 13 with SAXException

use of org.xml.sax.SAXException in project tomcat by apache.

the class ErrorDispatcher method dispatch.

//*********************************************************************
// Private utility methods
/**
     * Dispatches the given JSP parse error to the configured error handler.
     *
     * The given error code is localized. If it is not found in the
     * resource bundle for localized error messages, it is used as the error
     * message.
     *
     * @param where Error location
     * @param errCode Error code
     * @param args Arguments for parametric replacement
     * @param e Parsing exception
     * @throws JasperException An error occurred
     */
private void dispatch(Mark where, String errCode, Object[] args, Exception e) throws JasperException {
    String file = null;
    String errMsg = null;
    int line = -1;
    int column = -1;
    boolean hasLocation = false;
    // Localize
    if (errCode != null) {
        errMsg = Localizer.getMessage(errCode, args);
    } else if (e != null) {
        // give a hint about what's wrong
        errMsg = e.getMessage();
    }
    // Get error location
    if (where != null) {
        if (jspcMode) {
            // Get the full URL of the resource that caused the error
            try {
                file = where.getURL().toString();
            } catch (MalformedURLException me) {
                // Fallback to using context-relative path
                file = where.getFile();
            }
        } else {
            // Get the context-relative resource path, so as to not
            // disclose any local filesystem details
            file = where.getFile();
        }
        line = where.getLineNumber();
        column = where.getColumnNumber();
        hasLocation = true;
    }
    // Get nested exception
    Exception nestedEx = e;
    if ((e instanceof SAXException) && (((SAXException) e).getException() != null)) {
        nestedEx = ((SAXException) e).getException();
    }
    if (hasLocation) {
        errHandler.jspError(file, line, column, errMsg, nestedEx);
    } else {
        errHandler.jspError(errMsg, nestedEx);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) MalformedURLException(java.net.MalformedURLException) SAXException(org.xml.sax.SAXException) JasperException(org.apache.jasper.JasperException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException)

Example 14 with SAXException

use of org.xml.sax.SAXException in project tomcat by apache.

the class JspDocumentParser method parseCustomAction.

/*
     * Checks if the XML element with the given tag name is a custom action,
     * and returns the corresponding Node object.
     */
private Node parseCustomAction(String qName, String localName, String uri, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start, Node parent) throws SAXException {
    // Check if this is a user-defined (custom) tag
    TagLibraryInfo tagLibInfo = pageInfo.getTaglib(uri);
    if (tagLibInfo == null) {
        return null;
    }
    TagInfo tagInfo = tagLibInfo.getTag(localName);
    TagFileInfo tagFileInfo = tagLibInfo.getTagFile(localName);
    if (tagInfo == null && tagFileInfo == null) {
        throw new SAXParseException(Localizer.getMessage("jsp.error.xml.bad_tag", localName, uri), locator);
    }
    Class<?> tagHandlerClass = null;
    if (tagInfo != null) {
        String handlerClassName = tagInfo.getTagClassName();
        try {
            tagHandlerClass = ctxt.getClassLoader().loadClass(handlerClassName);
        } catch (Exception e) {
            throw new SAXParseException(Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), locator, e);
        }
    }
    String prefix = getPrefix(qName);
    Node.CustomTag ret = null;
    if (tagInfo != null) {
        ret = new Node.CustomTag(qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagInfo, tagHandlerClass);
    } else {
        ret = new Node.CustomTag(qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagFileInfo);
    }
    return ret;
}
Also used : TagFileInfo(javax.servlet.jsp.tagext.TagFileInfo) SAXParseException(org.xml.sax.SAXParseException) TagInfo(javax.servlet.jsp.tagext.TagInfo) TagLibraryInfo(javax.servlet.jsp.tagext.TagLibraryInfo) JasperException(org.apache.jasper.JasperException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException)

Example 15 with SAXException

use of org.xml.sax.SAXException in project tomcat by apache.

the class TagPluginManager method init.

private void init(ErrorDispatcher err) throws JasperException {
    if (initialized)
        return;
    String blockExternalString = ctxt.getInitParameter(Constants.XML_BLOCK_EXTERNAL_INIT_PARAM);
    boolean blockExternal;
    if (blockExternalString == null) {
        blockExternal = true;
    } else {
        blockExternal = Boolean.parseBoolean(blockExternalString);
    }
    TagPluginParser parser;
    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(TagPluginManager.class.getClassLoader());
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(TagPluginManager.class.getClassLoader());
        }
        parser = new TagPluginParser(ctxt, blockExternal);
        Enumeration<URL> urls = ctxt.getClassLoader().getResources(META_INF_JASPER_TAG_PLUGINS_XML);
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            parser.parse(url);
        }
        URL url = ctxt.getResource(TAG_PLUGINS_XML);
        if (url != null) {
            parser.parse(url);
        }
    } catch (IOException | SAXException e) {
        throw new JasperException(e);
    } finally {
        if (Constants.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(original);
        }
    }
    Map<String, String> plugins = parser.getPlugins();
    tagPlugins = new HashMap<>(plugins.size());
    for (Map.Entry<String, String> entry : plugins.entrySet()) {
        try {
            String tagClass = entry.getKey();
            String pluginName = entry.getValue();
            Class<?> pluginClass = ctxt.getClassLoader().loadClass(pluginName);
            TagPlugin plugin = (TagPlugin) pluginClass.newInstance();
            tagPlugins.put(tagClass, plugin);
        } catch (Exception e) {
            err.jspError(e);
        }
    }
    initialized = true;
}
Also used : IOException(java.io.IOException) URL(java.net.URL) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) JasperException(org.apache.jasper.JasperException) SAXException(org.xml.sax.SAXException) JasperException(org.apache.jasper.JasperException) PrivilegedGetTccl(org.apache.tomcat.util.security.PrivilegedGetTccl) TagPlugin(org.apache.jasper.compiler.tagplugin.TagPlugin) TagPluginParser(org.apache.tomcat.util.descriptor.tagplugin.TagPluginParser) HashMap(java.util.HashMap) Map(java.util.Map) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl)

Aggregations

SAXException (org.xml.sax.SAXException)1084 IOException (java.io.IOException)653 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)387 Document (org.w3c.dom.Document)258 DocumentBuilder (javax.xml.parsers.DocumentBuilder)213 InputSource (org.xml.sax.InputSource)205 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)158 InputStream (java.io.InputStream)141 Element (org.w3c.dom.Element)115 File (java.io.File)109 NodeList (org.w3c.dom.NodeList)106 SAXParseException (org.xml.sax.SAXParseException)104 Node (org.w3c.dom.Node)91 StringReader (java.io.StringReader)83 TransformerException (javax.xml.transform.TransformerException)82 ByteArrayInputStream (java.io.ByteArrayInputStream)81 SAXParser (javax.xml.parsers.SAXParser)76 ArrayList (java.util.ArrayList)71 FileInputStream (java.io.FileInputStream)64 XMLReader (org.xml.sax.XMLReader)56