This is an automated email from the ASF dual-hosted git repository. remm pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/main by this push: new 45a8d532d0 Implement WebDAV If header processing 45a8d532d0 is described below commit 45a8d532d0e1de7e1ccaedc820f09b4f3ffba877 Author: remm <r...@apache.org> AuthorDate: Sun Oct 20 14:13:01 2024 +0200 Implement WebDAV If header processing Uses code from Apache Jackrabbit. Add strict flag for the if header processing since some edge situations are annoying. Fix shared locks entry in the main lock map, and prevent its expiration. Fix non compliant lock renewal (needed a request on the locked resource). Fix a couple instance of missing lock depth checks and shared lock matching issue. Lockdiscovery is supposed to be there even if there are no locks. --- .../apache/catalina/servlets/WebdavServlet.java | 344 ++++++-- .../tomcat/util/http/LocalStrings.properties | 3 + .../apache/tomcat/util/http/WebdavIfHeader.java | 943 +++++++++++++++++++++ .../catalina/servlets/TestWebdavServlet.java | 161 +++- webapps/docs/changelog.xml | 4 + 5 files changed, 1370 insertions(+), 85 deletions(-) diff --git a/java/org/apache/catalina/servlets/WebdavServlet.java b/java/org/apache/catalina/servlets/WebdavServlet.java index fd12574655..15f5d398d6 100644 --- a/java/org/apache/catalina/servlets/WebdavServlet.java +++ b/java/org/apache/catalina/servlets/WebdavServlet.java @@ -31,6 +31,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Deque; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -60,6 +61,7 @@ import org.apache.tomcat.util.buf.HexUtils; import org.apache.tomcat.util.http.ConcurrentDateFormat; import org.apache.tomcat.util.http.FastHttpDateFormat; import org.apache.tomcat.util.http.RequestUtil; +import org.apache.tomcat.util.http.WebdavIfHeader; import org.apache.tomcat.util.security.ConcurrentMessageDigest; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -204,6 +206,19 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen protected static final String DEFAULT_NAMESPACE = "DAV:"; + /** + * Supported locks. + */ + protected static final String SUPPORTED_LOCKS = + "<D:lockentry>" + + "<D:lockscope><D:exclusive/></D:lockscope>" + + "<D:locktype><D:write/></D:locktype>" + + "</D:lockentry>" + + "<D:lockentry>" + + "<D:lockscope><D:shared/></D:lockscope>" + + "<D:locktype><D:write/></D:locktype>" + + "</D:lockentry>"; + /** * Simple date format for the creation date ISO representation (partial). */ @@ -243,6 +258,12 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen private boolean allowSpecialPaths = false; + /** + * Is the if header processing strict. + */ + private boolean strictIfProcessing = false; + + // --------------------------------------------------------- Public Methods @Override @@ -273,6 +294,10 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen if (getServletConfig().getInitParameter("allowSpecialPaths") != null) { allowSpecialPaths = Boolean.parseBoolean(getServletConfig().getInitParameter("allowSpecialPaths")); } + + if (getServletConfig().getInitParameter("strictIfProcessing") != null) { + strictIfProcessing = Boolean.parseBoolean(getServletConfig().getInitParameter("strictIfProcessing")); + } } @@ -302,7 +327,6 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen } } - // ------------------------------------------------------ Protected Methods /** @@ -404,7 +428,97 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen return false; } - // FIXME : Process the WebDAV If header + // Process the WebDAV If header using Apache Jackrabbit code + String ifHeaderValue = request.getHeader("If"); + if (ifHeaderValue != null) { + WebdavIfHeader ifHeader = new WebdavIfHeader(getUriPrefix(request), ifHeaderValue); + if (!ifHeader.hasValue()) { + // Allow bad if syntax, will only be used for lock tokens + return !strictIfProcessing; + } + String path = getRelativePath(request); + // Get all hrefs from the if header + Iterator<String> hrefs = ifHeader.getResources(); + + String currentPath = null; + String currentHref = null; + WebResource currentWebResource = null; + if (hrefs.hasNext()) { + currentHref = hrefs.next(); + currentPath = getPathFromHref(currentHref, request); + currentWebResource = resources.getResource(currentPath); + } else { + currentPath = path; + currentHref = getEncodedPath(path, resource, request); + currentWebResource = resource; + } + + // Iterate over all resources + do { + boolean exists = currentWebResource != null && currentWebResource.exists(); + String eTag = exists ? generateETag(currentWebResource) : ""; + + // Collect all locks active on resource + ArrayList<String> lockTokens = new ArrayList<>(); + // No lock evaluation for non existing paths in strict mode + // Problem: when doing a put with a locked parent folder, need to submit a tagged production with + // the parent path and the token, simply submitting the token in the if would fail the precondition. + if (!strictIfProcessing || exists) { + String parentPath = currentPath; + do { + LockInfo parentLock = resourceLocks.get(parentPath); + if (parentLock != null) { + if (parentLock.hasExpired()) { + resourceLocks.remove(parentPath); + } else { + if ((parentPath != currentPath && parentLock.depth > 0) || parentPath == currentPath) { + if (parentLock.isExclusive()) { + lockTokens.add("opaquelocktoken:" + parentLock.token); + } else { + for (String token : parentLock.sharedTokens) { + if (sharedLocks.get(token) == null) { + parentLock.sharedTokens.remove(token); + } + } + if (parentLock.sharedTokens.isEmpty()) { + resourceLocks.remove(parentLock.path); + } + for (String token : parentLock.sharedTokens) { + LockInfo sharedLock = sharedLocks.get(token); + if (sharedLock != null) { + if ((parentPath != currentPath && sharedLock.depth > 0) || parentPath == currentPath) { + lockTokens.add("opaquelocktoken:" + token); + } + } + } + } + } + } + } + int slash = parentPath.lastIndexOf('/'); + if (slash < 0) { + break; + } + parentPath = parentPath.substring(0, slash); + } while (true); + } + + // Evaluation + if (ifHeader.matches(currentHref, lockTokens, eTag)) { + return true; + } + + if (hrefs.hasNext()) { + currentHref = hrefs.next(); + currentPath = getPathFromHref(currentHref, request); + currentWebResource = resources.getResource(currentPath); + } else { + break; + } + } while (true); + + return false; + } return true; } @@ -468,6 +582,61 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen return rewriteUrl(href); } + private String getUriPrefix(HttpServletRequest request) { + return request.getScheme() + "://" + request.getServerName(); + } + + private String getPathFromHref(String href, HttpServletRequest req) { + + if (href == null || href.isEmpty()) { + return null; + } + + URI hrefUri; + try { + hrefUri = new URI(href); + } catch (URISyntaxException e) { + return null; + } + + String hrefPath = hrefUri.getPath(); + + // Avoid path traversals + if (!hrefPath.equals(RequestUtil.normalize(hrefPath))) { + return null; + } + + if (hrefUri.isAbsolute()) { + if (!req.getServerName().equals(hrefUri.getHost())) { + return null; + } + } + + if (hrefPath.length() > 1 && hrefPath.endsWith("/")) { + hrefPath = hrefPath.substring(0, hrefPath.length() - 1); + } + + // Verify context path + String reqContextPath = getPathPrefix(req); + if (!hrefPath.startsWith(reqContextPath + "/")) { + return null; + } + + // Remove context path & servlet path + hrefPath = hrefPath.substring(reqContextPath.length()); + + if (debug > 0) { + log(href + " Href path: " + hrefPath); + } + + // Protect special subdirectories + if (isSpecialPath(hrefPath)) { + return null; + } + + return hrefPath; + } + @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("DAV", "1,2"); @@ -574,6 +743,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen WebResource resource = resources.getResource(path); if (!checkIfHeaders(req, resp, resource)) { + resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return; } @@ -671,6 +841,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen WebResource resource = resources.getResource(path); if (!checkIfHeaders(req, resp, resource)) { + resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return; } if (!resource.exists()) { @@ -883,6 +1054,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen WebResource resource = resources.getResource(path); if (!checkIfHeaders(req, resp, resource)) { + resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return; } @@ -936,15 +1108,17 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen String path = getRelativePath(req); - if (isLocked(path, req)) { - resp.sendError(WebdavStatus.SC_LOCKED); + WebResource resource = resources.getResource(path); + if (!checkIfHeaders(req, resp, resource)) { + resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return; } - WebResource resource = resources.getResource(path); - if (!checkIfHeaders(req, resp, resource)) { + if (isLocked(path, req)) { + resp.sendError(WebdavStatus.SC_LOCKED); return; } + if (resource.isDirectory()) { sendNotAllowed(req, resp); return; @@ -1024,6 +1198,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen WebResource resource = resources.getResource(path); if (!checkIfHeaders(req, resp, resource)) { + resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return; } @@ -1306,6 +1481,8 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen if (!resources.write(path, new ByteArrayInputStream(new byte[0]), false)) { resp.sendError(WebdavStatus.SC_CONFLICT); return; + } else { + resp.setStatus(HttpServletResponse.SC_CREATED); } } @@ -1318,8 +1495,12 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen // Checking if there is already a shared lock on this path LockInfo sharedLock = resourceLocks.get(path); if (sharedLock == null) { - resourceLocks.put(path, lock); - sharedLock = lock; + sharedLock = new LockInfo(maxDepth); + sharedLock.scope = "shared"; + sharedLock.path = path; + sharedLock.lockroot = lock.lockroot; + sharedLock.depth = maxDepth; + resourceLocks.put(path, sharedLock); } sharedLock.sharedTokens.add(lockToken); sharedLocks.put(lockToken, lock); @@ -1338,28 +1519,53 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } - // Checking resource locks - - LockInfo toRenew = resourceLocks.get(path); - - if (toRenew != null) { - if (toRenew.isExclusive()) { - if (ifHeader.contains(toRenew.token)) { - toRenew.expiresAt = lock.expiresAt; - lock = toRenew; - } - } else { - for (String token : toRenew.sharedTokens) { - if (ifHeader.contains(token)) { - toRenew = sharedLocks.get(token); - if (toRenew != null) { - toRenew.expiresAt = lock.expiresAt; - lock = toRenew; + LockInfo toRenew = null; + String parentPath = path; + do { + LockInfo parentLock = resourceLocks.get(parentPath); + if (parentLock != null) { + if (parentLock.hasExpired()) { + resourceLocks.remove(parentPath); + } else { + if ((parentPath != path && parentLock.depth > 0) || parentPath == path) { + if (parentLock.isExclusive()) { + if (ifHeader.contains(parentLock.token) + && (parentLock.principal == null || parentLock.principal.equals(req.getRemoteUser()))) { + toRenew = parentLock; + break; + } + } else { + for (String token : parentLock.sharedTokens) { + if (ifHeader.contains(token)) { + LockInfo sharedLock = sharedLocks.get(token); + if (sharedLock != null + && (sharedLock.principal == null || sharedLock.principal.equals(req.getRemoteUser()))) { + if ((parentPath != path && sharedLock.depth > 0) || parentPath == path) { + toRenew = sharedLock; + break; + } + } + } + } } } } } + int slash = parentPath.lastIndexOf('/'); + if (slash < 0) { + break; + } + parentPath = parentPath.substring(0, slash); + } while (true); + + if (toRenew != null) { + if (!toRenew.hasExpired()) { + toRenew.expiresAt = lock.expiresAt; + } else { + toRenew = null; + } } + lock = toRenew; } // Set the status, then generate the XML response containing @@ -1370,7 +1576,9 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); - lock.toXML(generatedXML); + if (lock != null) { + lock.toXML(generatedXML); + } generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING); @@ -1402,6 +1610,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen WebResource resource = resources.getResource(path); if (!checkIfHeaders(req, resp, resource)) { + resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return; } @@ -1431,13 +1640,15 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen if (lockTokenHeader.contains(token)) { LockInfo lock = sharedLocks.get(token); if (lock == null || lock.principal == null || lock.principal.equals(req.getRemoteUser())) { - parentLock.sharedTokens.remove(token); - if (parentLock.sharedTokens.isEmpty()) { - resourceLocks.remove(parentPath); + if ((parentPath != path && lock.depth > 0) || parentPath == path) { + parentLock.sharedTokens.remove(token); + if (parentLock.sharedTokens.isEmpty()) { + resourceLocks.remove(parentPath); + } + sharedLocks.remove(token); + unlocked = true; + break; } - sharedLocks.remove(token); - unlocked = true; - break; } } } @@ -1504,6 +1715,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen */ private boolean isLocked(String path, String principal, String ifHeader) { + boolean unmatchedSharedLock = false; // Check if the resource or a parent is already locked String parentPath = path; do { @@ -1514,26 +1726,26 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen } else { if ((parentPath != path && parentLock.depth > 0) || parentPath == path) { if (parentLock.isExclusive()) { - if (ifHeader.contains(parentLock.token) + if (ifHeader.contains(":" + parentLock.token + ">") && (parentLock.principal == null || parentLock.principal.equals(principal))) { return false; } + return true; } else { for (String token : parentLock.sharedTokens) { - if (ifHeader.contains(token)) { - if (principal == null) { - return false; - } else { - LockInfo lock = sharedLocks.get(token); - if (lock == null || lock.principal == null || lock.principal.equals(principal)) { + LockInfo lock = sharedLocks.get(token); + if (lock != null) { + if ((parentPath != path && lock.depth > 0) || parentPath == path) { + if (ifHeader.contains(":" + token + ">") + && (lock == null || lock.principal == null || lock.principal.equals(principal))) { return false; } + unmatchedSharedLock = true; } } } } } - return true; } } int slash = parentPath.lastIndexOf('/'); @@ -1543,7 +1755,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen parentPath = parentPath.substring(0, slash); } while (true); - return false; + return unmatchedSharedLock; } @@ -1567,6 +1779,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen return false; } if (!checkIfHeaders(req, resp, source)) { + resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } @@ -1819,6 +2032,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen private boolean deleteResource(String path, HttpServletRequest req, HttpServletResponse resp) throws IOException { WebResource resource = resources.getResource(path); if (!checkIfHeaders(req, resp, resource)) { + resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } return deleteResource(path, req, resp, true); @@ -2104,12 +2318,8 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen } propfindResource(path, null, false, generatedXML); - String supportedLocks = "<D:lockentry>" + "<D:lockscope><D:exclusive/></D:lockscope>" + - "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>" + "<D:lockentry>" + - "<D:lockscope><D:shared/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + - "</D:lockentry>"; generatedXML.writeElement("D", "supportedlock", XMLWriter.OPENING); - generatedXML.writeRaw(supportedLocks); + generatedXML.writeRaw(SUPPORTED_LOCKS); generatedXML.writeElement("D", "supportedlock", XMLWriter.CLOSING); generateLockDiscovery(path, generatedXML); @@ -2209,17 +2419,11 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen generatedXML.writeElement("D", "resourcetype", XMLWriter.CLOSING); } } else if (property.equals("supportedlock")) { - supportedLocks = "<D:lockentry>" + "<D:lockscope><D:exclusive/></D:lockscope>" + - "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>" + "<D:lockentry>" + - "<D:lockscope><D:shared/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + - "</D:lockentry>"; generatedXML.writeElement("D", "supportedlock", XMLWriter.OPENING); - generatedXML.writeRaw(supportedLocks); + generatedXML.writeRaw(SUPPORTED_LOCKS); generatedXML.writeElement("D", "supportedlock", XMLWriter.CLOSING); } else if (property.equals("lockdiscovery")) { - if (!generateLockDiscovery(path, generatedXML)) { - propertiesNotFound.add(propertyNode); - } + generateLockDiscovery(path, generatedXML); } else { propertiesNotFound.add(propertyNode); } @@ -2282,12 +2486,10 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen * * @param path Path * @param generatedXML XML data to which the locks info will be appended - * - * @return <code>true</code> if at least one lock was displayed */ - private boolean generateLockDiscovery(String path, XMLWriter generatedXML) { + private void generateLockDiscovery(String path, XMLWriter generatedXML) { - boolean wroteStart = false; + generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); String parentPath = path; do { @@ -2298,23 +2500,17 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen } else { if ((parentPath != path && parentLock.depth > 0) || parentPath == path) { if (parentLock.isExclusive()) { - if (!wroteStart) { - wroteStart = true; - generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); - } parentLock.toXML(generatedXML); } else { for (String lockToken : parentLock.sharedTokens) { - parentLock = sharedLocks.get(lockToken); - if (parentLock != null) { - if (parentLock.hasExpired()) { + LockInfo sharedLock = sharedLocks.get(lockToken); + if (sharedLock != null) { + if (sharedLock.hasExpired()) { sharedLocks.remove(lockToken); } else { - if (!wroteStart) { - wroteStart = true; - generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); + if ((parentPath != path && sharedLock.depth > 0) || parentPath == path) { + sharedLock.toXML(generatedXML); } - parentLock.toXML(generatedXML); } } } @@ -2329,13 +2525,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen parentPath = parentPath.substring(0, slash); } while (true); - if (wroteStart) { - generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING); - } else { - return false; - } - - return true; + generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING); } @@ -2448,7 +2638,7 @@ public class WebdavServlet extends DefaultServlet implements PeriodicEventListen * @return true if the lock has expired. */ public boolean hasExpired() { - return System.currentTimeMillis() > expiresAt; + return sharedTokens.size() == 0 && System.currentTimeMillis() > expiresAt; } diff --git a/java/org/apache/tomcat/util/http/LocalStrings.properties b/java/org/apache/tomcat/util/http/LocalStrings.properties index 102ef873fd..9d0a6f0b3e 100644 --- a/java/org/apache/tomcat/util/http/LocalStrings.properties +++ b/java/org/apache/tomcat/util/http/LocalStrings.properties @@ -40,3 +40,6 @@ rfc6265CookieProcessor.invalidAttributeValue=An invalid attribute value [{1}] wa rfc6265CookieProcessor.invalidCharInValue=An invalid character [{0}] was present in the Cookie value rfc6265CookieProcessor.invalidDomain=An invalid domain [{0}] was specified for this cookie rfc6265CookieProcessor.invalidPath=An invalid path [{0}] was specified for this cookie + +webdavifheader.unexpectedCharacter=Unexpected character [{0}] in state [{1}], expected any of [{2}] +webdavifheader.ioError=IO Problem catching up to any of [{0}] diff --git a/java/org/apache/tomcat/util/http/WebdavIfHeader.java b/java/org/apache/tomcat/util/http/WebdavIfHeader.java new file mode 100644 index 0000000000..fbca45cdfc --- /dev/null +++ b/java/org/apache/tomcat/util/http/WebdavIfHeader.java @@ -0,0 +1,943 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.tomcat.util.http; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import org.apache.juli.logging.Log; +import org.apache.juli.logging.LogFactory; +import org.apache.tomcat.util.res.StringManager; + +/** + * The <code>IfHeader</code> class represents the state lists defined + * through the HTTP <em>If</em> header, which is specified in RFC 2518 as + * follows : + * <pre> + * If = "If" ":" ( 1*No-tag-list | 1*Tagged-list) + * No-tag-list = List + * Tagged-list = Resource 1*List + * Resource = Coded-URL + * List = "(" 1*(["Not"](State-etag | "[" entity-tag "]")) ")" + * State-etag = Coded-URL + * Coded-URL = "<" absoluteURI ">" + * </pre> + * <p> + * Reformulating this specification into proper EBNF as specified by N. Wirth + * we get the following productions, which map to the parse METHODS of this + * class. Any whitespace is ignored except for white space surrounding and + * within words which is considered significant. + * <pre> + * If = "If:" ( Tagged | Untagged ). + * Tagged = { "<" Word ">" Untagged } . + * Untagged = { "(" IfList ")" } . + * IfList = { [ "Not" ] ( ("<" Word ">" ) | ( "[" Word "]" ) ) } . + * Word = characters . + * </pre> + * <p> + * An <em>If</em> header either contains untagged <em>IfList</em> entries or + * tagged <em>IfList</em> entries but not a mixture of both. An <em>If</em> + * header containing tagged entries is said to be of <em>tagged</em> type while + * an <em>If</em> header containing untagged entries is said to be of + * <em>untagged</em> type. + * <p> + * An <em>IfList</em> is a list of tokens - words enclosed in <em>< ></em> + * - and etags - words enclosed in <em>[ ]</em>. An <em>IfList</em> matches a + * (token, etag) tuple if all entries in the list match. If an entry in the list + * is prefixed with the word <em>Not</em> (parsed case insensitively) the entry + * must not match the concrete token or etag. + * <p> + * Example: The <em>ifList</em> <code>(<token> [etag])</code> only matches + * if the concret token has the value <code>token</code> and the conrete etag + * has the value <code>etag</code>. On the other hand, the <em>ifList</em> + * <code>(Not <notoken>)</code> matches any token which is not + * <code>notoken</code> (in this case the concrete value of the etag is + * not taken into consideration). + * + * This class was contributed by Apache Jackrabbit + * + * @author Felix Meschberger + */ +public class WebdavIfHeader { + + private static final Log log = LogFactory.getLog(WebdavIfHeader.class); + private static final StringManager sm = + StringManager.getManager(WebdavIfHeader.class.getPackage().getName()); + + /** + * The string representation of the header value + */ + private final String headerValue; + + /** + * The list of untagged state entries + */ + private final IfHeaderInterface ifHeader; + + /** + * The list of resources present in the If header. + */ + private List<String> resources = new ArrayList<String>(); + + /** + * The list of all positive tokens present in the If header. + */ + private List<String> allTokens = new ArrayList<String>(); + + /** + * The list of all NOT tokens present in the If header. + */ + private List<String> allNotTokens = new ArrayList<String>(); + + private String uriPrefix; + + /** + * Create a Untagged <code>IfHeader</code> if the given lock tokens. + * + * @param tokens the tokens + */ + public WebdavIfHeader(String[] tokens) throws IOException { + allTokens.addAll(Arrays.asList(tokens)); + StringBuffer b = new StringBuffer(); + for (String token : tokens) { + b.append("(").append("<"); + b.append(token); + b.append(">").append(")"); + } + headerValue = b.toString(); + ifHeader = parse(); + } + + /** + * Parses the <em>If</em> header and creates and internal representation + * which is easy to query. + * + * @param uriPrefix The uri prefix to use for the absolute href + * @param ifHeaderValue the if header + */ + public WebdavIfHeader(String uriPrefix, String ifHeaderValue) throws IOException { + this.uriPrefix = uriPrefix; + headerValue = ifHeaderValue; + ifHeader = parse(); + } + + /** + * Return {@link DavConstants#HEADER_IF If} + * + * @return {@link DavConstants#HEADER_IF If} + * @see DavConstants#HEADER_IF + */ + public String getHeaderName() { + return "If"; + } + + /** + * Return the String representation of the If header present on + * the given request or <code>null</code>. + * + * @return If header value as String or <code>null</code>. + */ + public String getHeaderValue() { + return headerValue; + } + + /** + * Returns true if an If header was present in the given request. False otherwise. + * + * @return true if an If header was present. + */ + public boolean hasValue() { + return ifHeader != null; + } + + /** + * Tries to match the contents of the <em>If</em> header with the given + * token and etag values with the restriction to only check for the tag. + * <p> + * If the <em>If</em> header is of untagged type, the untagged <em>IfList</em> + * is matched against the token and etag given: A match of the token and + * etag is found if at least one of the <em>IfList</em> entries match the + * token and etag tuple. + * + * @param tag The tag to identify the <em>IfList</em> to match the token + * and etag against. + * @param tokens The tokens to compare. + * @param etag The ETag value to compare. + * + * @return If the <em>If</em> header is of untagged type the result is + * <code>true</code> if any of the <em>IfList</em> entries matches + * the token and etag values. For tagged type <em>If</em> header the + * result is <code>true</code> if either no entry for the given tag + * exists in the <em>If</em> header or if the <em>IfList</em> for the + * given tag matches the token and etag given. + */ + public boolean matches(String tag, List<String> tokens, String etag) { + if (ifHeader == null) { + if (log.isTraceEnabled()) { + log.trace("matches: No If header, assume match"); + } + return true; + } else { + return ifHeader.matches(tag, tokens, etag); + } + } + + /** + * @return an iterator over all resources present in the if header. + */ + public Iterator<String> getResources() { + return resources.iterator(); + } + + /** + * @return an iterator over all tokens present in the if header, that were + * not denied by a leading NOT statement. + */ + public Iterator<String> getAllTokens() { + return allTokens.iterator(); + } + + /** + * @return an iterator over all NOT tokens present in the if header, that + * were explicitly denied. + */ + public Iterator<String> getAllNotTokens() { + return allNotTokens.iterator(); + } + + /** + * Parse the original header value and build the internal IfHeaderInterface + * object that is easy to query. + */ + private IfHeaderInterface parse() + throws IOException { + IfHeaderInterface ifHeader; + if (headerValue != null && headerValue.length() > 0) { + StringReader reader = null; + int firstChar = 0; + + try { + reader = new StringReader(headerValue); + // get the first character to decide - expect '(' or '<' + try { + reader.mark(1); + firstChar = readWhiteSpace(reader); + reader.reset(); + } catch (IOException ignore) { + // may be thrown according to API but is only thrown by the + // StringReader class if the reader is already closed. + } + + if (firstChar == '(') { + ifHeader = parseUntagged(reader); + } else if (firstChar == '<') { + ifHeader = parseTagged(reader); + } else { + logIllegalState("If", firstChar, "(<", null); + ifHeader = null; + } + + } finally { + if (reader != null) { + reader.close(); + } + } + + } else { + if (log.isTraceEnabled()) { + log.trace("IfHeader: No If header in request"); + } + ifHeader = null; + } + return ifHeader; + } + + //---------- internal IF header parser ------------------------------------- + /** + * Parses a tagged type <em>If</em> header. This method implements the + * <em>Tagged</em> production given in the class comment : + * <pre> + * Tagged = { "<" Word ">" Untagged } . + * </pre> + * + * @param reader the reader + * @return the parsed map + */ + private IfHeaderMap parseTagged(StringReader reader) + throws IOException { + IfHeaderMap map = new IfHeaderMap(); + while (true) { + // read next non-white space + int c = readWhiteSpace(reader); + if (c < 0) { + // end of input, no more entries + break; + } else if (c == '<') { + // start a tag with an IfList + String resource = readWord(reader, '>'); + if (resource != null) { + // go to untagged after reading the resource + map.put(resource, parseUntagged(reader)); + resources.add(resource); + } else { + break; + } + } else { + // unexpected character + // catchup to end of input or start of a tag + logIllegalState("Tagged", c, "<", reader); + } + } + + return map; + } + + /** + * Parses an untagged type <em>If</em> header. This method implements the + * <em>Untagged</em> production given in the class comment : + * <pre> + * Untagged = { "(" IfList ")" } . + * </pre> + * + * @param reader The <code>StringReader</code> to read from for parsing + * + * @return An <code>ArrayList</code> of {@link IfList} entries. + */ + private IfHeaderList parseUntagged(StringReader reader) + throws IOException { + IfHeaderList list = new IfHeaderList(); + while (true) { + // read next non white space + reader.mark(1); + int c = readWhiteSpace(reader); + if (c < 0) { + // end of input, no more IfLists + break; + + } else if (c == '(') { + // start of an IfList, parse + list.add(parseIfList(reader)); + + } else if (c == '<') { + // start of a tag, return current list + reader.reset(); + break; + + } else { + // unexpected character + // catchup to end of input or start of an IfList + logIllegalState("Untagged", c, "(", reader); + } + } + return list; + } + + /** + * Parses an <em>IfList</em> in the <em>If</em> header. This method + * implements the <em>Tagged</em> production given in the class comment : + * <pre> + * IfList = { [ "Not" ] ( ("<" Word ">" ) | ( "[" Word "]" ) ) } . + * </pre> + * + * @param reader The <code>StringReader</code> to read from for parsing + * + * @return The {@link IfList} for the input <em>IfList</em>. + * + * @throws IOException if a problem occurs during reading. + */ + private IfList parseIfList(StringReader reader) throws IOException { + IfList res = new IfList(); + boolean positive = true; + String word; + + ReadLoop: + while (true) { + int nextChar = readWhiteSpace(reader); + switch (nextChar) { + case 'N': + case 'n': + // read not + + // check whether o or O + int not = reader.read(); + if (not != 'o' && not != 'O') { + logIllegalState("IfList-Not", not, "o", null); + break; + } + + // check whether t or T + not = reader.read(); + if (not !='t' && not != 'T') { + logIllegalState("IfList-Not", not, "t", null); + break; + } + + // read Not ok + positive = false; + break; + + case '<': + // state token + word = readWord(reader, '>'); + if (word != null) { + res.add(new IfListEntryToken(word, positive)); + // also add the token to the list of all tokens + if (positive) { + allTokens.add(word); + } else { + allNotTokens.add(word); + } + positive = true; + } + break; + + case '[': + // etag + word = readWord(reader, ']'); + if (word != null) { + res.add(new IfListEntryEtag(word, positive)); + positive = true; + } + break; + + case ')': + // correct end of list, end the loop + if (log.isTraceEnabled()) { + log.trace("parseIfList: End of If list, terminating loop"); + } + break ReadLoop; + + default: + logIllegalState("IfList", nextChar, "nN<[)", reader); + + // abort loop if EOF + if (nextChar < 0) { + break ReadLoop; + } + + break; + } + } + + // return the current list anyway + return res; + } + + /** + * Returns the first non-whitespace character from the reader or -1 if + * the end of the reader is encountered. + * + * @param reader The <code>Reader</code> to read from + * + * @return The first non-whitespace character or -1 in case of EOF. + * + * @throws IOException if a problem occurs during reading. + */ + private int readWhiteSpace(Reader reader) throws IOException { + int c = reader.read(); + while (c >= 0 && Character.isWhitespace((char) c)) { + c = reader.read(); + } + return c; + } + + /** + * Reads from the input until the end character is encountered and returns + * the string up to but not including this end character. If the end of input + * is reached before reading the end character <code>null</code> is + * returned. + * <p> + * Note that this method does not support any escaping. + * + * @param reader The <code>Reader</code> to read from + * @param end The ending character limiting the word. + * + * @return The string read up to but not including the ending character or + * <code>null</code> if the end of input is reached before the ending + * character has been read. + * + * @throws IOException if a problem occurs during reading. + */ + private String readWord(Reader reader, char end) throws IOException { + StringBuffer buf = new StringBuffer(); + + // read the word value + int c = reader.read(); + for (; c >= 0 && c != end; c=reader.read()) { + buf.append((char) c); + } + + // check whether we succeeded + if (c < 0) { + log.error("readWord: Unexpected end of input reading word"); + return null; + } + + // build the string and return it + return buf.toString(); + } + + /** + * Logs an unexpected character with the corresponding state and list of + * expected characters. If the reader parameter is not null, characters + * are read until either the end of the input is reached or any of the + * characters in the expChar string is read. + * + * @param state The name of the current parse state. This method logs this + * name in the message. The intended value would probably be the + * name of the EBNF production during which the error occurs. + * @param effChar The effective character read. + * @param expChar The list of characters acceptable in the current state. + * @param reader The reader to be caught up to any of the expected + * characters. If <code>null</code> the input is not caught up to + * any of the expected characters (of course ;-). + */ + private void logIllegalState(String state, int effChar, String expChar, + StringReader reader) { + + // format the effective character to be logged + String effString = (effChar < 0) ? "<EOF>" : String.valueOf((char) effChar); + + // log the error + log.error(sm.getString("webdavifheader.unexpectedCharacter", effString, state, expChar)); + + // catch up if a reader is given + if (reader != null && effChar >= 0) { + try { + if (log.isTraceEnabled()) { + log.trace("logIllegalState: Catch up to any of "+expChar); + } + do { + reader.mark(1); + effChar = reader.read(); + } while (effChar >= 0 && expChar.indexOf(effChar) < 0); + if (effChar >= 0) { + reader.reset(); + } + } catch (IOException ioe) { + log.error(sm.getString("webdavifheader.ioError", expChar)); + } + } + } + + //---------- internal If header structure ---------------------------------- + + /** + * The <code>IfListEntry</code> abstract class is the base class for + * entries in an <em>IfList</em> production. This abstract base class + * provides common functionality to both types of entries, namely tokens + * enclosed in angle brackets (<code>< ></code>) and etags enclosed + * in square brackets (<code>[ ]</code>). + */ + private abstract static class IfListEntry { + + /** + * The entry string value - the semantics of this value depends on the + * implementing class. + */ + protected final String value; + + /** Flag to indicate, whether this is a positive match or not */ + protected final boolean positive; + + /** The cached result of the {@link #toString} method. */ + protected String stringValue; + + /** + * Sets up the final fields of this abstract class. The meaning of + * value parameter depends solely on the implementing class. From the + * point of view of this abstract class, it is simply a string value. + * + * @param value The string value of this instance + * @param positive <code>true</code> if matches are positive + */ + protected IfListEntry(String value, boolean positive) { + this.value = value; + this.positive = positive; + } + + /** + * Matches the value from the parameter to the internal string value. + * If the parameter and the {@link #value} field match, the method + * returns <code>true</code> for positive matches and <code>false</code> + * for negative matches. + * <p> + * This helper method can be called by implementations to evaluate the + * concrete match on the correct value parameter. See + * {@link #match(String, String)} for the external API method. + * + * @param value The string value to compare to the {@link #value} + * field. + * + * @return <code>true</code> if the value parameter and the + * {@link #value} field match and the {@link #positive} field is + * <code>true</code> or if the values do not match and the + * {@link #positive} field is <code>false</code>. + */ + protected boolean match(String value) { + return positive == this.value.equals(value); + } + + /** + * Matches the entry's value to the the token or etag. Depending on the + * concrete implementation, only one of the parameters may be evaluated + * while the other may be ignored. + * <p> + * Implementing METHODS may call the helper method {@link #match(String)} + * for the actual matching. + * + * @param token The token value to compare + * @param etag The etag value to compare + * + * @return <code>true</code> if the token/etag matches the <em>IfList</em> + * entry. + */ + public abstract boolean match(String token, String etag); + + /** + * Returns a short type name for the implementation. This method is + * used by the {@link #toString} method to build the string representation + * if the instance. + * + * @return The type name of the implementation. + */ + protected abstract String getType(); + + /** + * @return the value of this entry + */ + protected String getValue() { + return value; + } + + /** + * Returns the String representation of this entry. This method uses the + * {@link #getType} to build the string representation. + * + * @return the String representation of this entry. + */ + @Override + public String toString() { + if (stringValue == null) { + stringValue = getType() + ": " + (positive ? "" : "!") + getValue(); + } + return stringValue; + } + } + + /** + * The <code>IfListEntryToken</code> extends the {@link IfListEntry} + * abstract class to represent an entry for token matching. + */ + private static class IfListEntryToken extends IfListEntry { + + /** + * Creates a token matching entry. + * + * @param token The token value pertinent to this instance. + * @param positive <code>true</code> if this is a positive match entry. + */ + IfListEntryToken(String token, boolean positive) { + super(token, positive); + } + + /** + * Matches the token parameter to the stored token value and returns + * <code>true</code> if the values match and if the match is positive. + * <code>true</code> is also returned for negative matches if the values + * do not match. + * + * @param token The token value to compare + * @param etag The etag value to compare, which is ignored in this + * implementation. + * + * @return <code>true</code> if the token matches the <em>IfList</em> + * entry's token value. + */ + @Override + public boolean match(String token, String etag) { + return token == null || super.match(token); + } + + /** + * Returns the type name of this implementation, which is fixed to + * be <em>Token</em>. + * + * @return The fixed string <em>Token</em> as the type name. + */ + @Override + protected String getType() { + return "Token"; + } + } + + /** + * The <code>IfListEntryToken</code> extends the {@link IfListEntry} + * abstract class to represent an entry for etag matching. + */ + private static class IfListEntryEtag extends IfListEntry { + + /** + * Creates an etag matching entry. + * + * @param etag The etag value pertinent to this instance. + * @param positive <code>true</code> if this is a positive match entry. + */ + IfListEntryEtag(String etag, boolean positive) { + super(etag, positive); + } + + /** + * Matches the etag parameter to the stored etag value and returns + * <code>true</code> if the values match and if the match is positive. + * <code>true</code> is also returned for negative matches if the values + * do not match. + * + * @param token The token value to compare, which is ignored in this + * implementation. + * @param etag The etag value to compare + * + * @return <code>true</code> if the etag matches the <em>IfList</em> + * entry's etag value. + */ + @Override + public boolean match(String token, String etag) { + return super.match(etag); + } + + /** + * Returns the type name of this implementation, which is fixed to + * be <em>ETag</em>. + * + * @return The fixed string <em>ETag</em> as the type name. + */ + @Override + protected String getType() { + return "ETag"; + } + } + + /** + * The <code>IfList</code> class extends the <code>ArrayList</code> class + * with the limitation to only support adding {@link IfListEntry} objects + * and adding a {@link #match} method. + * <p> + * This class is a container for data contained in the <em>If</em> + * production <em>IfList</em> + * <pre> + * IfList = { [ "Not" ] ( ("<" Word ">" ) | ( "[" Word "]" ) ) } . + * </pre> + * <p> + */ + private static class IfList extends ArrayList<IfListEntry> { + + private static final long serialVersionUID = 1L; + + /** + * Adds the {@link IfListEntry} at the end of the list. + * + * @param entry The {@link IfListEntry} to add to the list + * + * @return <code>true</code> (as per the general contract of Collection.add). + */ + @Override + public boolean add(IfListEntry entry) { + return super.add(entry); + } + + /** + * Adds the {@link IfListEntry} at the indicated position of the list. + * + * @param index the index + * @param entry the entry + * + * @throws IndexOutOfBoundsException if index is out of range + * <code>(index < 0 || index > size())</code>. + */ + @Override + public void add(int index, IfListEntry entry) { + super.add(index, entry); + } + + /** + * Returns <code>true</code> if all {@link IfListEntry} objects in the + * list match the given token and etag. If the list is entry, it is + * considered to match the token and etag. + * + * @param tokens The token to compare. + * @param etag The etag to compare. + * + * @return <code>true</code> if all entries in the list match the + * given tag and token. + */ + public boolean match(List<String> tokens, String etag) { + if (log.isTraceEnabled()) { + log.trace("match: Trying to match token=" + tokens + ", etag=" + etag); + } + for (int i=0; i < size(); i++) { + IfListEntry ile = get(i); + boolean match = false; + for (String token : tokens) { + if (ile.match(token, etag)) { + match = true; + } + } + if (!match) { + if (log.isTraceEnabled()) { + log.trace("match: Entry " + i + "-" + ile + " does not match"); + } + return false; + } + } + // invariant: all entries matched + + return true; + } + } + + /** + * The <code>IfHeaderInterface</code> interface abstracts away the difference of + * tagged and untagged <em>If</em> header lists. The single method provided + * by this interface is to check whether a request may be applied to a + * resource with given token and etag. + */ + private interface IfHeaderInterface { + + /** + * Matches the resource, token, and etag against this + * <code>IfHeaderInterface</code> instance. + * + * @param resource The resource to match this instance against. This + * must be absolute URI of the resource as defined in Section 3 + * (URI Syntactic Components) of RFC 2396 Uniform Resource + * Identifiers (URI): Generic Syntax. + * @param tokens The resource's lock token to match + * @param etag The resource's etag to match + * + * @return <code>true</code> if the header matches the resource with + * token and etag, which means that the request is applicable + * to the resource according to the <em>If</em> header. + */ + boolean matches(String resource, List<String> tokens, String etag); + } + + /** + * The <code>IfHeaderList</code> class implements the {@link IfHeaderInterface} + * interface to support untagged lists of {@link IfList}s. This class + * implements the data container for the production : + * <pre> + * Untagged = { "(" IfList ")" } . + * </pre> + */ + private static class IfHeaderList extends ArrayList<IfList> implements IfHeaderInterface { + + private static final long serialVersionUID = 1L; + + /** + * Matches a list of {@link IfList}s against the token and etag. If any of + * the {@link IfList}s matches, the method returns <code>true</code>. + * On the other hand <code>false</code> is only returned if non of the + * {@link IfList}s match. + * + * @param resource The resource to match, which is ignored by this + * implementation. A value of <code>null</code> is therefor + * acceptable. + * @param tokens The tokens to compare. + * @param etag The ETag value to compare. + * + * @return <code>True</code> if any of the {@link IfList}s matches the token + * and etag, else <code>false</code> is returned. + */ + public boolean matches(String resource, List<String> tokens, String etag) { + if (log.isTraceEnabled()) { + log.trace("matches: Trying to match token=" + tokens + ", etag=" + etag); + } + + for (IfList il : this) { + if (il.match(tokens, etag)) { + if (log.isTraceEnabled()) { + log.trace("matches: Found match with " + il); + } + return true; + } + } + // invariant: no match found + + return false; + } + } + + /** + * The <code>IfHeaderMap</code> class implements the {@link IfHeaderInterface} + * interface to support tagged lists of {@link IfList}s. This class + * implements the data container for the production : + * <pre> + * Tagged = { "<" Word ">" "(" IfList ")" } . + * </pre> + */ + private class IfHeaderMap extends HashMap<String, IfHeaderList> implements IfHeaderInterface { + + private static final long serialVersionUID = 1L; + + /** + * Matches the token and etag for the given resource. If the resource is + * not mentioned in the header, a match is assumed and <code>true</code> + * is returned in this case. + * + * @param resource The absolute URI of the resource for which to find + * a match. + * @param tokens The tokens to compare. + * @param etag The etag to compare. + * + * @return <code>true</code> if either no entry exists for the resource + * or if the entry for the resource matches the token and etag. + */ + public boolean matches(String resource, List<String> tokens, String etag) { + if (log.isTraceEnabled()) { + log.trace("matches: Trying to match resource=" + resource + ", token=" + tokens + "," + etag); + } + + String uri; + String path; + if (resource.startsWith("/")) { + path = resource; + uri = WebdavIfHeader.this.uriPrefix + resource; + } else { + path = resource.substring(WebdavIfHeader.this.uriPrefix.length()); + uri = resource; + } + IfHeaderList list = get(path); + if (list == null) { + list = get(uri); + } + if (list == null) { + if (log.isTraceEnabled()) { + log.trace("matches: No entry for tag " + resource + ", assuming mismatch"); + } + return false; + } else { + return list.matches(resource, tokens, etag); + } + } + } +} diff --git a/test/org/apache/catalina/servlets/TestWebdavServlet.java b/test/org/apache/catalina/servlets/TestWebdavServlet.java index 3b09c4cbdf..8272381a56 100644 --- a/test/org/apache/catalina/servlets/TestWebdavServlet.java +++ b/test/org/apache/catalina/servlets/TestWebdavServlet.java @@ -17,6 +17,7 @@ package org.apache.catalina.servlets; import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; @@ -276,7 +277,7 @@ public class TestWebdavServlet extends TomcatBaseTest { SimpleHttpClient.CRLF + LOCK_BODY }); client.connect(); client.processRequest(true); - Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode()); + Assert.assertEquals(HttpServletResponse.SC_CREATED, client.getStatusCode()); Assert.assertTrue(client.getResponseBody().contains("opaquelocktoken:")); client.setRequest(new String[] { "PROPFIND / HTTP/1.1" + SimpleHttpClient.CRLF + @@ -419,7 +420,7 @@ public class TestWebdavServlet extends TomcatBaseTest { client.setRequest(new String[] { "PUT /myfolder/file4.txt HTTP/1.1" + SimpleHttpClient.CRLF + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + "Content-Length: 6" + SimpleHttpClient.CRLF + - "If: " + lockToken + SimpleHttpClient.CRLF + + "If: (" + lockToken + ")" + SimpleHttpClient.CRLF + "Connection: Close" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + CONTENT }); client.connect(); @@ -453,7 +454,7 @@ public class TestWebdavServlet extends TomcatBaseTest { SimpleHttpClient.CRLF + LOCK_BODY }); client.connect(); client.processRequest(true); - Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode()); + Assert.assertEquals(HttpServletResponse.SC_CREATED, client.getStatusCode()); Assert.assertTrue(client.getResponseBody().contains("opaquelocktoken:")); String lockTokenFile = null; for (String header : client.getResponseHeaders()) { @@ -463,6 +464,17 @@ public class TestWebdavServlet extends TomcatBaseTest { } Assert.assertNotNull(lockTokenFile); + client.setRequest(new String[] { "LOCK /myfolder HTTP/1.1" + SimpleHttpClient.CRLF + + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + + "Content-Length: " + LOCK_BODY.length() + SimpleHttpClient.CRLF + + "Connection: Close" + SimpleHttpClient.CRLF + + SimpleHttpClient.CRLF + LOCK_BODY }); + client.connect(); + client.processRequest(true); + Assert.assertEquals(WebdavStatus.SC_MULTI_STATUS, client.getStatusCode()); + Assert.assertTrue(client.getResponseBody().contains("/myfolder/file5.txt")); + Assert.assertTrue(client.getResponseBody().contains("HTTP/1.1 423")); + client.setRequest(new String[] { "PUT /myfolder/file5.txt HTTP/1.1" + SimpleHttpClient.CRLF + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + "Content-Length: 6" + SimpleHttpClient.CRLF + @@ -476,7 +488,7 @@ public class TestWebdavServlet extends TomcatBaseTest { client.setRequest(new String[] { "PUT /myfolder/file5.txt HTTP/1.1" + SimpleHttpClient.CRLF + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + "Content-Length: 6" + SimpleHttpClient.CRLF + - "If: " + lockTokenFile + SimpleHttpClient.CRLF + + "If: (" + lockTokenFile + ")" + SimpleHttpClient.CRLF + "Connection: Close" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + CONTENT }); client.connect(); @@ -486,7 +498,7 @@ public class TestWebdavServlet extends TomcatBaseTest { // Verify that this also removes the lock by doing another PUT without the token client.setRequest(new String[] { "DELETE /myfolder/file5.txt HTTP/1.1" + SimpleHttpClient.CRLF + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + - "If: " + lockTokenFile + SimpleHttpClient.CRLF + + "If: (" + lockTokenFile + ")" + SimpleHttpClient.CRLF + "Connection: Close" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF }); client.connect(); @@ -530,10 +542,19 @@ public class TestWebdavServlet extends TomcatBaseTest { client.processRequest(true); Assert.assertEquals(WebdavStatus.SC_LOCKED, client.getStatusCode()); + client.setRequest(new String[] { "COPY /myfolder HTTP/1.1" + SimpleHttpClient.CRLF + + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + + "Destination: /myfolder2" + SimpleHttpClient.CRLF + + "Connection: Close" + SimpleHttpClient.CRLF + + SimpleHttpClient.CRLF }); + client.connect(); + client.processRequest(true); + Assert.assertEquals(WebdavStatus.SC_CREATED, client.getStatusCode()); + // Delete /myfolder/file4.txt client.setRequest(new String[] { "DELETE /myfolder/file4.txt HTTP/1.1" + SimpleHttpClient.CRLF + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + - "If: " + lockToken + SimpleHttpClient.CRLF + + "If: (" + lockToken + ")" + SimpleHttpClient.CRLF + "Connection: Close" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF }); client.connect(); @@ -580,6 +601,14 @@ public class TestWebdavServlet extends TomcatBaseTest { client.processRequest(true); Assert.assertEquals(HttpServletResponse.SC_NO_CONTENT, client.getStatusCode()); + client.setRequest(new String[] { "DELETE /myfolder2 HTTP/1.1" + SimpleHttpClient.CRLF + + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + + "Connection: Close" + SimpleHttpClient.CRLF + + SimpleHttpClient.CRLF }); + client.connect(); + client.processRequest(true); + Assert.assertEquals(HttpServletResponse.SC_NO_CONTENT, client.getStatusCode()); + client.setRequest(new String[] { "PROPFIND / HTTP/1.1" + SimpleHttpClient.CRLF + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + "Connection: Close" + SimpleHttpClient.CRLF + @@ -697,7 +726,7 @@ public class TestWebdavServlet extends TomcatBaseTest { client.setRequest(new String[] { "LOCK /myfolder/myfolder2/myfolder4/myfolder5 HTTP/1.1" + SimpleHttpClient.CRLF + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + - "If: " + lockToken + SimpleHttpClient.CRLF + + "If: (" + lockToken + ")" + SimpleHttpClient.CRLF + "Content-Length: " + LOCK_BODY.length() + SimpleHttpClient.CRLF + "Connection: Close" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + LOCK_BODY }); @@ -706,6 +735,16 @@ public class TestWebdavServlet extends TomcatBaseTest { // This should conflict, submitting a token does not help Assert.assertEquals(WebdavStatus.SC_LOCKED, client.getStatusCode()); + // Lock refresh /myfolder + client.setRequest(new String[] { "LOCK /myfolder HTTP/1.1" + SimpleHttpClient.CRLF + + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + + "If: (" + lockToken + ")" + SimpleHttpClient.CRLF + + "Connection: Close" + SimpleHttpClient.CRLF + + SimpleHttpClient.CRLF }); + client.connect(); + client.processRequest(true); + Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode()); + client.setRequest(new String[] { "LOCK /myfolder/myfolder2/myfolder4 HTTP/1.1" + SimpleHttpClient.CRLF + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + "Content-Length: " + LOCK_SHARED_BODY.length() + SimpleHttpClient.CRLF + @@ -761,7 +800,7 @@ public class TestWebdavServlet extends TomcatBaseTest { client.setRequest(new String[] { "PUT /myfolder/myfolder2/myfolder4/myfolder5/file4.txt HTTP/1.1" + SimpleHttpClient.CRLF + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + - "If: " + lockToken2 + SimpleHttpClient.CRLF + + "If: (" + lockToken + ")" + SimpleHttpClient.CRLF + "Content-Length: 6" + SimpleHttpClient.CRLF + "Connection: Close" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + CONTENT }); @@ -826,6 +865,112 @@ public class TestWebdavServlet extends TomcatBaseTest { } + @Test + public void testIfHeader() throws Exception { + Tomcat tomcat = getTomcatInstance(); + + // Create a temp webapp that can be safely written to + File tempWebapp = new File(getTemporaryDirectory(), "webdav-if"); + File folder = new File(tempWebapp, "/myfolder/myfolder2/myfolder4/myfolder5"); + Assert.assertTrue(folder.mkdirs()); + File file = new File(folder, "myfile.txt"); + try (FileOutputStream fos = new FileOutputStream(file)) { + fos.write(CONTENT.getBytes()); + } + folder = new File(tempWebapp, "/myfolder/myfolder3/myfolder6"); + Assert.assertTrue(folder.mkdirs()); + folder = new File(tempWebapp, "/myfolder/myfolder7/myfolder8/myfolder9"); + Assert.assertTrue(folder.mkdirs()); + Context ctxt = tomcat.addContext("", tempWebapp.getAbsolutePath()); + Wrapper webdavServlet = Tomcat.addServlet(ctxt, "webdav", new WebdavServlet()); + webdavServlet.addInitParameter("listings", "true"); + webdavServlet.addInitParameter("secret", "foo"); + webdavServlet.addInitParameter("readonly", "false"); + ctxt.addServletMappingDecoded("/*", "webdav"); + tomcat.start(); + + Client client = new Client(); + client.setPort(getPort()); + + client.setRequest(new String[] { "LOCK /myfolder/myfolder3 HTTP/1.1" + SimpleHttpClient.CRLF + + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + + "Content-Length: " + LOCK_BODY.length() + SimpleHttpClient.CRLF + + "Connection: Close" + SimpleHttpClient.CRLF + + SimpleHttpClient.CRLF + LOCK_BODY }); + client.connect(); + client.processRequest(true); + Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode()); + Assert.assertTrue(client.getResponseBody().contains("opaquelocktoken:")); + String lockToken = null; + for (String header : client.getResponseHeaders()) { + if (header.startsWith("Lock-Token: ")) { + lockToken = header.substring("Lock-Token: ".length()); + } + } + Assert.assertNotNull(lockToken); + + client.setRequest(new String[] { "LOCK /myfolder/myfolder7 HTTP/1.1" + SimpleHttpClient.CRLF + + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + + "Content-Length: " + LOCK_SHARED_BODY.length() + SimpleHttpClient.CRLF + + "Connection: Close" + SimpleHttpClient.CRLF + + SimpleHttpClient.CRLF + LOCK_SHARED_BODY }); + client.connect(); + client.processRequest(true); + Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode()); + Assert.assertTrue(client.getResponseBody().contains("opaquelocktoken:")); + String lockToken2 = null; + for (String header : client.getResponseHeaders()) { + if (header.startsWith("Lock-Token: ")) { + lockToken2 = header.substring("Lock-Token: ".length()); + } + } + Assert.assertNotNull(lockToken2); + + client.setRequest(new String[] { "LOCK /myfolder/myfolder7/myfolder8 HTTP/1.1" + SimpleHttpClient.CRLF + + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + + "Content-Length: " + LOCK_SHARED_BODY.length() + SimpleHttpClient.CRLF + + "Connection: Close" + SimpleHttpClient.CRLF + + SimpleHttpClient.CRLF + LOCK_SHARED_BODY }); + client.connect(); + client.processRequest(true); + Assert.assertEquals(HttpServletResponse.SC_OK, client.getStatusCode()); + Assert.assertTrue(client.getResponseBody().contains("opaquelocktoken:")); + String lockToken3 = null; + for (String header : client.getResponseHeaders()) { + if (header.startsWith("Lock-Token: ")) { + lockToken3 = header.substring("Lock-Token: ".length()); + } + } + Assert.assertNotNull(lockToken3); + + client.setRequest(new String[] { "PUT /myfolder/myfolder2/myfolder4/myfolder5/file4.txt HTTP/1.1" + SimpleHttpClient.CRLF + + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + + "If: </myfolder/myfolder3/myfolder6> (<opaquelocktoken:5e1e2275b1cd9c17845e7e08>)" + // Obvious wrong token + " </myfolder/myfolder7/myfolder8/myfolder9> (" + lockToken + " " + lockToken2 + " " + lockToken3 + ")" + // lockToken is not there + " </myfolder/myfolder2/myfolder4> (<opaquelocktoken:7329872398754923752> [W/\"4-1729375899470\"])" + // Not locked + " </myfolder/myfolder7/myfolder8> (" + lockToken + ")" + SimpleHttpClient.CRLF + // lockToken is not there + "Content-Length: 6" + SimpleHttpClient.CRLF + + "Connection: Close" + SimpleHttpClient.CRLF + + SimpleHttpClient.CRLF + CONTENT }); + client.connect(); + client.processRequest(true); + Assert.assertEquals(WebdavStatus.SC_PRECONDITION_FAILED, client.getStatusCode()); + + client.setRequest(new String[] { "PUT /myfolder/myfolder2/myfolder4/myfolder5/file4.txt HTTP/1.1" + SimpleHttpClient.CRLF + + "Host: localhost:" + getPort() + SimpleHttpClient.CRLF + + "If: </myfolder/myfolder3/myfolder6> (<opaquelocktoken:5e1e2275b1cd9c17845e7e08>)" + // Obvious wrong token + " </myfolder/myfolder2/myfolder4> (<opaquelocktoken:7329872398754923752> [W/\"4-1729375899470\"])" + // Not locked + " </myfolder/myfolder7/myfolder8> (" + lockToken + ")" + // lockToken is not there + " </myfolder/myfolder7/myfolder8/myfolder9> (" + lockToken2 + " " + lockToken3 + ")" + SimpleHttpClient.CRLF + // Correct + "Content-Length: 6" + SimpleHttpClient.CRLF + + "Connection: Close" + SimpleHttpClient.CRLF + + SimpleHttpClient.CRLF + CONTENT }); + client.connect(); + client.processRequest(true); + Assert.assertEquals(WebdavStatus.SC_CREATED, client.getStatusCode()); + + } + private static final class Client extends SimpleHttpClient { @Override diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index 74453cbb91..b869ae9d30 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -135,6 +135,10 @@ Rewrite implementation of WebDAV shared locks to comply with RFC 4918. (remm) </update> + <update> + Implement WebDAV <code>If</code> header using code from the Apache + Jackrabbit project. (remm) + </update> <!-- Entries for backport and removal before 12.0.0-M1 below this line --> <update> <bug>69374</bug>: Properly separate between table header and body --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org