From c21b6a86ceab485139235c7cb90f67f294fbe1ab Mon Sep 17 00:00:00 2001 From: Joakim Erdfelt Date: Tue, 7 Jun 2022 14:24:56 -0500 Subject: [PATCH 1/7] Cherry-pick of Improvements to PathSpec. From commit: 5b4d1dd1c64482d00919029e0a2ba4ac1f4d8e6b Signed-off-by: Joakim Erdfelt --- .../jetty/http/pathmap/AbstractPathSpec.java | 9 +- .../jetty/http/pathmap/MatchedPath.java | 76 +++++ .../jetty/http/pathmap/MatchedResource.java | 76 +++++ .../jetty/http/pathmap/PathMappings.java | 278 +++++++++++++----- .../eclipse/jetty/http/pathmap/PathSpec.java | 26 ++ .../jetty/http/pathmap/PathSpecSet.java | 12 +- .../jetty/http/pathmap/RegexPathSpec.java | 191 ++++++++++-- .../jetty/http/pathmap/ServletPathSpec.java | 76 ++++- .../http/pathmap/UriTemplatePathSpec.java | 97 +++++- .../jetty/http/pathmap/PathMappingsTest.java | 196 +++++------- .../jetty/http/pathmap/RegexPathSpecTest.java | 64 +++- .../pathmap/ServletPathSpecOrderTest.java | 5 +- .../http/pathmap/ServletPathSpecTest.java | 167 ++++++----- .../test/resources/jetty-logging.properties | 1 + .../jetty/server/CustomRequestLog.java | 12 +- .../jetty/server/ServletPathMapping.java | 51 ++++ .../org/eclipse/jetty/servlet/Invoker.java | 11 +- .../eclipse/jetty/servlet/ServletHandler.java | 72 ++++- 18 files changed, 1079 insertions(+), 341 deletions(-) create mode 100644 jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MatchedPath.java create mode 100644 jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MatchedResource.java diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/AbstractPathSpec.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/AbstractPathSpec.java index 48a076e5f561..6007ee25a0b1 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/AbstractPathSpec.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/AbstractPathSpec.java @@ -31,7 +31,12 @@ public int compareTo(PathSpec other) return diff; // Path Spec Name (alphabetical) - return getDeclaration().compareTo(other.getDeclaration()); + diff = getDeclaration().compareTo(other.getDeclaration()); + if (diff != 0) + return diff; + + // Path Implementation + return getClass().getName().compareTo(other.getClass().getName()); } @Override @@ -50,7 +55,7 @@ public final boolean equals(Object obj) @Override public final int hashCode() { - return Objects.hash(getDeclaration()); + return Objects.hash(getGroup().ordinal(), getSpecLength(), getDeclaration(), getClass().getName()); } @Override diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MatchedPath.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MatchedPath.java new file mode 100644 index 000000000000..bfe9c0c0fe16 --- /dev/null +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MatchedPath.java @@ -0,0 +1,76 @@ +// +// ======================================================================== +// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Public License v. 2.0 which is available at +// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 +// which is available at https://www.apache.org/licenses/LICENSE-2.0. +// +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== +// + +package org.eclipse.jetty.http.pathmap; + +public interface MatchedPath +{ + MatchedPath EMPTY = new MatchedPath() + { + @Override + public String getPathMatch() + { + return null; + } + + @Override + public String getPathInfo() + { + return null; + } + + @Override + public String toString() + { + return MatchedPath.class.getSimpleName() + ".EMPTY"; + } + }; + + static MatchedPath from(String pathMatch, String pathInfo) + { + return new MatchedPath() + { + @Override + public String getPathMatch() + { + return pathMatch; + } + + @Override + public String getPathInfo() + { + return pathInfo; + } + + @Override + public String toString() + { + return MatchedPath.class.getSimpleName() + "[pathMatch=" + pathMatch + ", pathInfo=" + pathInfo + "]"; + } + }; + } + + /** + * Return the portion of the path that matches a path spec. + * + * @return the path name portion of the match. + */ + String getPathMatch(); + + /** + * Return the portion of the path that is after the path spec. + * + * @return the path info portion of the match, or null if there is no portion after the {@link #getPathMatch()} + */ + String getPathInfo(); +} diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MatchedResource.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MatchedResource.java new file mode 100644 index 000000000000..7d5f97aaeff0 --- /dev/null +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/MatchedResource.java @@ -0,0 +1,76 @@ +// +// ======================================================================== +// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Public License v. 2.0 which is available at +// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 +// which is available at https://www.apache.org/licenses/LICENSE-2.0. +// +// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 +// ======================================================================== +// + +package org.eclipse.jetty.http.pathmap; + +import java.util.Map; + +/** + * The match details when using {@link PathMappings#getMatched(String)}, used to minimize return to the PathSpec or PathMappings for subsequent details + * that are now provided by the {@link MatchedPath} instance. + * + * @param the type of resource (IncludeExclude uses boolean, WebSocket uses endpoint/endpoint config, servlet uses ServletHolder, etc) + */ +public class MatchedResource +{ + private final E resource; + private final PathSpec pathSpec; + private final MatchedPath matchedPath; + + public MatchedResource(E resource, PathSpec pathSpec, MatchedPath matchedPath) + { + this.resource = resource; + this.pathSpec = pathSpec; + this.matchedPath = matchedPath; + } + + public static MatchedResource of(Map.Entry mapping, MatchedPath matchedPath) + { + return new MatchedResource<>(mapping.getValue(), mapping.getKey(), matchedPath); + } + + public MatchedPath getMatchedPath() + { + return this.matchedPath; + } + + public PathSpec getPathSpec() + { + return this.pathSpec; + } + + public E getResource() + { + return this.resource; + } + + /** + * Return the portion of the path that matches a path spec. + * + * @return the path name portion of the match. + */ + public String getPathMatch() + { + return matchedPath.getPathMatch(); + } + + /** + * Return the portion of the path that is after the path spec. + * + * @return the path info portion of the match, or null if there is no portion after the {@link #getPathMatch()} + */ + public String getPathInfo() + { + return matchedPath.getPathInfo(); + } +} diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathMappings.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathMappings.java index ba02c8a0ae74..2012d5fec9cc 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathMappings.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathMappings.java @@ -42,14 +42,17 @@ public class PathMappings implements Iterable>, Dumpable private static final Logger LOG = LoggerFactory.getLogger(PathMappings.class); private final Set> _mappings = new TreeSet<>(Comparator.comparing(MappedResource::getPathSpec)); + private boolean _optimizedExact = true; private final Index.Mutable> _exactMap = new Index.Builder>() .caseSensitive(true) .mutable() .build(); + private boolean _optimizedPrefix = true; private final Index.Mutable> _prefixMap = new Index.Builder>() .caseSensitive(true) .mutable() .build(); + private boolean _optimizedSuffix = true; private final Index.Mutable> _suffixMap = new Index.Builder>() .caseSensitive(true) .mutable() @@ -90,6 +93,26 @@ public void removeIf(Predicate> predicate) _mappings.removeIf(predicate); } + /** + * Return a list of MatchedResource matches for the specified path. + * + * @param path the path to return matches on + * @return the list of mapped resource the path matches on + */ + public List> getMatchedList(String path) + { + List> ret = new ArrayList<>(); + for (MappedResource mr : _mappings) + { + MatchedPath matchedPath = mr.getPathSpec().matched(path); + if (matchedPath != null) + { + ret.add(new MatchedResource<>(mr.getResource(), mr.getPathSpec(), matchedPath)); + } + } + return ret; + } + /** * Return a list of MappedResource matches for the specified path. * @@ -110,11 +133,11 @@ public List> getMatches(String path) ret.add(mr); break; case DEFAULT: - if (isRootPath || mr.getPathSpec().matches(path)) + if (isRootPath || mr.getPathSpec().matched(path) != null) ret.add(mr); break; default: - if (mr.getPathSpec().matches(path)) + if (mr.getPathSpec().matched(path) != null) ret.add(mr); break; } @@ -122,57 +145,93 @@ public List> getMatches(String path) return ret; } - public MappedResource getMatch(String path) + public MatchedResource getMatched(String path) { + MatchedPath matchedPath; PathSpecGroup lastGroup = null; + boolean skipRestOfGroup = false; // Search all the mappings for (MappedResource mr : _mappings) { PathSpecGroup group = mr.getPathSpec().getGroup(); + if (group == lastGroup && skipRestOfGroup) + { + continue; // skip + } + + // Run servlet spec optimizations on first hit of specific groups if (group != lastGroup) { + // New group, reset skip logic + skipRestOfGroup = false; + // New group in list, so let's look for an optimization switch (group) { case EXACT: { - int i = path.length(); - while (i >= 0) + if (_optimizedExact) { - MappedResource candidate = _exactMap.getBest(path, 0, i); - if (candidate == null) - break; - if (candidate.getPathSpec().matches(path)) - return candidate; - i = candidate.getPathSpec().getPrefix().length() - 1; + int i = path.length(); + while (i >= 0) + { + MappedResource candidate = _exactMap.getBest(path, 0, i); + if (candidate == null) + break; + + matchedPath = candidate.getPathSpec().matched(path); + if (matchedPath != null) + { + return new MatchedResource<>(candidate.getResource(), candidate.getPathSpec(), matchedPath); + } + i--; + } + // If we reached here, there's NO optimized EXACT Match possible, skip simple match below + skipRestOfGroup = true; } break; } case PREFIX_GLOB: { - int i = path.length(); - while (i >= 0) + if (_optimizedPrefix) { - MappedResource candidate = _prefixMap.getBest(path, 0, i); - if (candidate == null) - break; - if (candidate.getPathSpec().matches(path)) - return candidate; - i = candidate.getPathSpec().getPrefix().length() - 1; + int i = path.length(); + while (i >= 0) + { + MappedResource candidate = _prefixMap.getBest(path, 0, i); + if (candidate == null) + break; + + matchedPath = candidate.getPathSpec().matched(path); + if (matchedPath != null) + return new MatchedResource<>(candidate.getResource(), candidate.getPathSpec(), matchedPath); + i--; + } + // If we reached here, there's NO optimized PREFIX Match possible, skip simple match below + skipRestOfGroup = true; } break; } case SUFFIX_GLOB: { - int i = 0; - while ((i = path.indexOf('.', i + 1)) > 0) + if (_optimizedSuffix) { - MappedResource candidate = _suffixMap.get(path, i + 1, path.length() - i - 1); - if (candidate != null && candidate.getPathSpec().matches(path)) - return candidate; + int i = 0; + while ((i = path.indexOf('.', i + 1)) > 0) + { + MappedResource candidate = _suffixMap.get(path, i + 1, path.length() - i - 1); + if (candidate == null) + break; + + matchedPath = candidate.getPathSpec().matched(path); + if (matchedPath != null) + return new MatchedResource<>(candidate.getResource(), candidate.getPathSpec(), matchedPath); + } + // If we reached here, there's NO optimized SUFFIX Match possible, skip simple match below + skipRestOfGroup = true; } break; } @@ -181,8 +240,9 @@ public MappedResource getMatch(String path) } } - if (mr.getPathSpec().matches(path)) - return mr; + matchedPath = mr.getPathSpec().matched(path); + if (matchedPath != null) + return new MatchedResource<>(mr.getResource(), mr.getPathSpec(), matchedPath); lastGroup = group; } @@ -190,21 +250,28 @@ public MappedResource getMatch(String path) return null; } + /** + * @deprecated use {@link #getMatched(String)} instead + */ + @Deprecated + public MappedResource getMatch(String path) + { + throw new UnsupportedOperationException("Use .getMatched(String) instead"); + } + @Override public Iterator> iterator() { return _mappings.iterator(); } + /** + * @deprecated use {@link PathSpec#from(String)} instead + */ + @Deprecated public static PathSpec asPathSpec(String pathSpecString) { - if (pathSpecString == null) - throw new RuntimeException("Path Spec String must start with '^', '/', or '*.': got [" + pathSpecString + "]"); - - if (pathSpecString.length() == 0) - return new ServletPathSpec(""); - - return pathSpecString.charAt(0) == '^' ? new RegexPathSpec(pathSpecString) : new ServletPathSpec(pathSpecString); + return PathSpec.from(pathSpecString); } public E get(PathSpec spec) @@ -212,66 +279,84 @@ public E get(PathSpec spec) return _mappings.stream() .filter(mappedResource -> mappedResource.getPathSpec().equals(spec)) .map(MappedResource::getResource) - .findFirst().orElse(null); + .findFirst() + .orElse(null); } public boolean put(String pathSpecString, E resource) { - return put(asPathSpec(pathSpecString), resource); + return put(PathSpec.from(pathSpecString), resource); } public boolean put(PathSpec pathSpec, E resource) { MappedResource entry = new MappedResource<>(pathSpec, resource); - switch (pathSpec.getGroup()) - { - case EXACT: - String exact = pathSpec.getPrefix(); - if (exact != null) - _exactMap.put(exact, entry); - break; - case PREFIX_GLOB: - String prefix = pathSpec.getPrefix(); - if (prefix != null) - _prefixMap.put(prefix, entry); - break; - case SUFFIX_GLOB: - String suffix = pathSpec.getSuffix(); - if (suffix != null) - _suffixMap.put(suffix, entry); - break; - default: - } - boolean added = _mappings.add(entry); if (LOG.isDebugEnabled()) LOG.debug("{} {} to {}", added ? "Added" : "Ignored", entry, this); + + if (added) + { + switch (pathSpec.getGroup()) + { + case EXACT: + if (pathSpec instanceof ServletPathSpec) + { + String exact = pathSpec.getDeclaration(); + if (exact != null) + _exactMap.put(exact, entry); + } + else + { + // This is not a Servlet mapping, turn off optimization on Exact + // TODO: see if we can optimize all Regex / UriTemplate versions here too. + // Note: Example exact in Regex that can cause problems `^/a\Q/b\E/` (which is only ever matching `/a/b/`) + // Note: UriTemplate can handle exact easily enough + _optimizedExact = false; + } + break; + case PREFIX_GLOB: + if (pathSpec instanceof ServletPathSpec) + { + String prefix = pathSpec.getPrefix(); + if (prefix != null) + _prefixMap.put(prefix, entry); + } + else + { + // This is not a Servlet mapping, turn off optimization on Prefix + // TODO: see if we can optimize all Regex / UriTemplate versions here too. + // Note: Example Prefix in Regex that can cause problems `^/a/b+` or `^/a/bb*` ('b' one or more times) + // Note: Example Prefix in UriTemplate that might cause problems `/a/{b}/{c}` + _optimizedPrefix = false; + } + break; + case SUFFIX_GLOB: + if (pathSpec instanceof ServletPathSpec) + { + String suffix = pathSpec.getSuffix(); + if (suffix != null) + _suffixMap.put(suffix, entry); + } + else + { + // This is not a Servlet mapping, turn off optimization on Suffix + // TODO: see if we can optimize all Regex / UriTemplate versions here too. + // Note: Example suffix in Regex that can cause problems `^.*/path/name.ext` or `^/a/.*(ending)` + // Note: Example suffix in UriTemplate that can cause problems `/{a}/name.ext` + _optimizedSuffix = false; + } + break; + default: + } + } + return added; } @SuppressWarnings("incomplete-switch") public boolean remove(PathSpec pathSpec) { - String prefix = pathSpec.getPrefix(); - String suffix = pathSpec.getSuffix(); - switch (pathSpec.getGroup()) - { - case EXACT: - if (prefix != null) - _exactMap.remove(prefix); - break; - case PREFIX_GLOB: - if (prefix != null) - _prefixMap.remove(prefix); - break; - case SUFFIX_GLOB: - if (suffix != null) - _suffixMap.remove(suffix); - break; - default: - break; - } - Iterator> iter = _mappings.iterator(); boolean removed = false; while (iter.hasNext()) @@ -283,11 +368,54 @@ public boolean remove(PathSpec pathSpec) break; } } + if (LOG.isDebugEnabled()) LOG.debug("{} {} to {}", removed ? "Removed" : "Ignored", pathSpec, this); + + if (removed) + { + switch (pathSpec.getGroup()) + { + case EXACT: + String exact = pathSpec.getDeclaration(); + if (exact != null) + { + _exactMap.remove(exact); + // Recalculate _optimizeExact + _optimizedExact = canBeOptimized(PathSpecGroup.EXACT); + } + break; + case PREFIX_GLOB: + String prefix = pathSpec.getPrefix(); + if (prefix != null) + { + _prefixMap.remove(prefix); + // Recalculate _optimizePrefix + _optimizedPrefix = canBeOptimized(PathSpecGroup.PREFIX_GLOB); + } + break; + case SUFFIX_GLOB: + String suffix = pathSpec.getSuffix(); + if (suffix != null) + { + _suffixMap.remove(suffix); + // Recalculate _optimizeSuffix + _optimizedSuffix = canBeOptimized(PathSpecGroup.SUFFIX_GLOB); + } + break; + } + } + return removed; } + private boolean canBeOptimized(PathSpecGroup suffixGlob) + { + return _mappings.stream() + .filter((mapping) -> mapping.getPathSpec().getGroup() == suffixGlob) + .allMatch((mapping) -> mapping.getPathSpec() instanceof ServletPathSpec); + } + @Override public String toString() { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpec.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpec.java index 218a2ae7684d..73bc206856da 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpec.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpec.java @@ -13,6 +13,8 @@ package org.eclipse.jetty.http.pathmap; +import java.util.Objects; + /** * A path specification is a URI path template that can be matched against. *

@@ -20,6 +22,16 @@ */ public interface PathSpec extends Comparable { + static PathSpec from(String pathSpecString) + { + Objects.requireNonNull(pathSpecString, "null PathSpec not supported"); + + if (pathSpecString.length() == 0) + return new ServletPathSpec(""); + + return pathSpecString.charAt(0) == '^' ? new RegexPathSpec(pathSpecString) : new ServletPathSpec(pathSpecString); + } + /** * The length of the spec. * @@ -48,7 +60,9 @@ public interface PathSpec extends Comparable * * @param path the path to match against * @return the path info portion of the string + * @deprecated use {@link #matched(String)} instead */ + @Deprecated String getPathInfo(String path); /** @@ -56,7 +70,9 @@ public interface PathSpec extends Comparable * * @param path the path to match against * @return the match, or null if no match at all + * @deprecated use {@link #matched(String)} instead */ + @Deprecated String getPathMatch(String path); /** @@ -85,6 +101,16 @@ public interface PathSpec extends Comparable * * @param path the path to test * @return true if the path matches this path spec, false otherwise + * @deprecated use {@link #matched(String)} instead */ + @Deprecated boolean matches(String path); + + /** + * Get the complete matched details of the provided path. + * + * @param path the path to test + * @return the matched details, if a match was possible, or null if not able to be matched. + */ + MatchedPath matched(String path); } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecSet.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecSet.java index 8ab1e0c8853e..bd6b51ff38ce 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecSet.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/PathSpecSet.java @@ -15,6 +15,7 @@ import java.util.AbstractSet; import java.util.Iterator; +import java.util.Objects; import java.util.function.Predicate; /** @@ -29,7 +30,7 @@ public class PathSpecSet extends AbstractSet implements Predicate FORBIDDEN_ESCAPED = new HashMap<>(); + + static + { + FORBIDDEN_ESCAPED.put('s', "any whitespace"); + FORBIDDEN_ESCAPED.put('n', "newline"); + FORBIDDEN_ESCAPED.put('r', "carriage return"); + FORBIDDEN_ESCAPED.put('t', "tab"); + FORBIDDEN_ESCAPED.put('f', "form-feed"); + FORBIDDEN_ESCAPED.put('b', "bell"); + FORBIDDEN_ESCAPED.put('e', "escape"); + FORBIDDEN_ESCAPED.put('c', "control char"); + } + private final String _declaration; private final PathSpecGroup _group; private final int _pathDepth; @@ -33,34 +54,80 @@ public RegexPathSpec(String regex) declaration = regex; int specLength = declaration.length(); // build up a simple signature we can use to identify the grouping - boolean inGrouping = false; + boolean inTextList = false; + boolean inQuantifier = false; StringBuilder signature = new StringBuilder(); int pathDepth = 0; + char last = 0; for (int i = 0; i < declaration.length(); i++) { char c = declaration.charAt(i); switch (c) { - case '[': - inGrouping = true; + case '^': // ignore anchors + case '$': // ignore anchors + case '\'': // ignore escaping + case '(': // ignore grouping + case ')': // ignore grouping break; - case ']': - inGrouping = false; + case '+': // single char quantifier + case '?': // single char quantifier + case '*': // single char quantifier + case '|': // alternate match token + case '.': // any char token signature.append('g'); // glob break; - case '*': + case '{': + inQuantifier = true; + break; + case '}': + inQuantifier = false; + break; + case '[': + inTextList = true; + break; + case ']': + inTextList = false; signature.append('g'); // glob break; case '/': - if (!inGrouping) + if (!inTextList && !inQuantifier) pathDepth++; break; default: - if (!inGrouping && Character.isLetterOrDigit(c)) - signature.append('l'); // literal (exact) + if (!inTextList && !inQuantifier && Character.isLetterOrDigit(c)) + { + if (last == '\\') // escaped + { + String forbiddenReason = FORBIDDEN_ESCAPED.get(c); + if (forbiddenReason != null) + { + throw new IllegalArgumentException(String.format("%s does not support \\%c (%s) for \"%s\"", + this.getClass().getSimpleName(), c, forbiddenReason, declaration)); + } + switch (c) + { + case 'S': // any non-whitespace + case 'd': // any digits + case 'D': // any non-digits + case 'w': // any word + case 'W': // any non-word + signature.append('g'); // glob + break; + default: + signature.append('l'); // literal (exact) + break; + } + } + else // not escaped + { + signature.append('l'); // literal (exact) + } + } break; } + last = c; } Pattern pattern = Pattern.compile(declaration); @@ -72,7 +139,7 @@ public RegexPathSpec(String regex) group = PathSpecGroup.EXACT; else if (Pattern.matches("^l*g+", sig)) group = PathSpecGroup.PREFIX_GLOB; - else if (Pattern.matches("^g+l+$", sig)) + else if (Pattern.matches("^g+l+.*", sig)) group = PathSpecGroup.SUFFIX_GLOB; else group = PathSpecGroup.MIDDLE_GLOB; @@ -82,11 +149,27 @@ else if (Pattern.matches("^g+l+$", sig)) _pathDepth = pathDepth; _specLength = specLength; _pattern = pattern; + + if (LOG.isDebugEnabled()) + { + LOG.debug("Creating RegexPathSpec[{}] (signature: [{}], group: {})", + _declaration, sig, _group); + } } protected Matcher getMatcher(String path) { - return _pattern.matcher(path); + int idx = path.indexOf('?'); + if (idx >= 0) + { + // match only non-query part + return _pattern.matcher(path.substring(0, idx)); + } + else + { + // match entire path + return _pattern.matcher(path); + } } @Override @@ -176,16 +259,88 @@ public Pattern getPattern() @Override public boolean matches(final String path) { - int idx = path.indexOf('?'); - if (idx >= 0) + return getMatcher(path).matches(); + } + + @Override + public MatchedPath matched(String path) + { + Matcher matcher = getMatcher(path); + if (matcher.matches()) { - // match only non-query part - return getMatcher(path.substring(0, idx)).matches(); + return new RegexMatchedPath(this, path, matcher); } - else + return null; + } + + private class RegexMatchedPath implements MatchedPath + { + private final RegexPathSpec pathSpec; + private final String path; + private final Matcher matcher; + + public RegexMatchedPath(RegexPathSpec regexPathSpec, String path, Matcher matcher) { - // match entire path - return getMatcher(path).matches(); + this.pathSpec = regexPathSpec; + this.path = path; + this.matcher = matcher; + } + + @Override + public String getPathMatch() + { + String p = matcher.group("name"); + if (p != null) + { + return p; + } + + if (pathSpec.getGroup() == PathSpecGroup.PREFIX_GLOB && matcher.groupCount() >= 1) + { + int idx = matcher.start(1); + if (idx > 0) + { + if (this.path.charAt(idx - 1) == '/') + idx--; + return this.path.substring(0, idx); + } + } + + // default is the full path + return this.path; + } + + @Override + public String getPathInfo() + { + String p = matcher.group("info"); + if (p != null) + { + return p; + } + + // Path Info only valid for PREFIX_GLOB + if (pathSpec.getGroup() == PathSpecGroup.PREFIX_GLOB && matcher.groupCount() >= 1) + { + String pathInfo = matcher.group(1); + if ("".equals(pathInfo)) + return "/"; + else + return pathInfo; + } + + // default is null + return null; + } + + @Override + public String toString() + { + return getClass().getSimpleName() + "[" + + "pathSpec=" + pathSpec + + ", path=\"" + path + "\"" + + ", matcher=" + matcher + + ']'; } } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/ServletPathSpec.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/ServletPathSpec.java index 2ff378ee35e8..686704738f09 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/ServletPathSpec.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/ServletPathSpec.java @@ -26,8 +26,10 @@ public class ServletPathSpec extends AbstractPathSpec private final PathSpecGroup _group; private final int _pathDepth; private final int _specLength; + private final int _matchLength; private final String _prefix; private final String _suffix; + private final MatchedPath _preMatchedPath; /** * If a servlet or filter path mapping isn't a suffix mapping, ensure @@ -202,8 +204,10 @@ public ServletPathSpec(String servletPathSpec) _group = PathSpecGroup.ROOT; _pathDepth = -1; // Set pathDepth to -1 to force this to be at the end of the sort order. _specLength = 1; + _matchLength = 0; _prefix = null; _suffix = null; + _preMatchedPath = MatchedPath.from("", "/"); return; } @@ -214,8 +218,10 @@ public ServletPathSpec(String servletPathSpec) _group = PathSpecGroup.DEFAULT; _pathDepth = -1; // Set pathDepth to -1 to force this to be at the end of the sort order. _specLength = 1; + _matchLength = 0; _prefix = null; _suffix = null; + _preMatchedPath = null; return; } @@ -223,6 +229,7 @@ public ServletPathSpec(String servletPathSpec) PathSpecGroup group; String prefix; String suffix; + MatchedPath preMatchedPath; // prefix based if (servletPathSpec.charAt(0) == '/' && servletPathSpec.endsWith("/*")) @@ -230,6 +237,7 @@ public ServletPathSpec(String servletPathSpec) group = PathSpecGroup.PREFIX_GLOB; prefix = servletPathSpec.substring(0, specLength - 2); suffix = null; + preMatchedPath = MatchedPath.from(prefix, null); } // suffix based else if (servletPathSpec.charAt(0) == '*' && servletPathSpec.length() > 1) @@ -237,6 +245,7 @@ else if (servletPathSpec.charAt(0) == '*' && servletPathSpec.length() > 1) group = PathSpecGroup.SUFFIX_GLOB; prefix = null; suffix = servletPathSpec.substring(2, specLength); + preMatchedPath = null; } else { @@ -248,15 +257,15 @@ else if (servletPathSpec.charAt(0) == '*' && servletPathSpec.length() > 1) LOG.warn("Suspicious URL pattern: '{}'; see sections 12.1 and 12.2 of the Servlet specification", servletPathSpec); } + preMatchedPath = MatchedPath.from(servletPathSpec, null); } int pathDepth = 0; for (int i = 0; i < specLength; i++) { - int cp = servletPathSpec.codePointAt(i); - if (cp < 128) + char c = servletPathSpec.charAt(i); + if (c < 128) { - char c = (char)cp; if (c == '/') pathDepth++; } @@ -266,8 +275,17 @@ else if (servletPathSpec.charAt(0) == '*' && servletPathSpec.length() > 1) _group = group; _pathDepth = pathDepth; _specLength = specLength; + _matchLength = prefix == null ? 0 : prefix.length(); _prefix = prefix; _suffix = suffix; + _preMatchedPath = preMatchedPath; + + if (LOG.isDebugEnabled()) + { + LOG.debug("Creating {}[{}] (group: {}, prefix: \"{}\", suffix: \"{}\")", + getClass().getSimpleName(), + _declaration, _group, _prefix, _suffix); + } } private static void assertValidServletPathSpec(String servletPathSpec) @@ -334,6 +352,10 @@ public int getPathDepth() return _pathDepth; } + /** + * @deprecated use {@link #matched(String)}#{@link MatchedPath#getPathInfo()} instead. + */ + @Deprecated @Override public String getPathInfo(String path) { @@ -343,15 +365,19 @@ public String getPathInfo(String path) return path; case PREFIX_GLOB: - if (path.length() == (_specLength - 2)) + if (path.length() == _matchLength) return null; - return _specLength == 2 ? path : path.substring(_specLength - 2); + return path.substring(_matchLength); default: return null; } } + /** + * @deprecated use {@link #matched(String)}#{@link MatchedPath#getPathMatch()} instead. + */ + @Deprecated @Override public String getPathMatch(String path) { @@ -367,7 +393,7 @@ public String getPathMatch(String path) case PREFIX_GLOB: if (isWildcardMatch(path)) - return path.substring(0, _specLength - 2); + return path.substring(0, _matchLength); return null; case SUFFIX_GLOB: @@ -404,12 +430,44 @@ public String getSuffix() private boolean isWildcardMatch(String path) { // For a spec of "/foo/*" match "/foo" , "/foo/..." but not "/foobar" - int cpl = _specLength - 2; - if ((_group == PathSpecGroup.PREFIX_GLOB) && (path.regionMatches(0, _declaration, 0, cpl))) - return (path.length() == cpl) || ('/' == path.charAt(cpl)); + if (_group == PathSpecGroup.PREFIX_GLOB && path.length() >= _matchLength && path.regionMatches(0, _declaration, 0, _matchLength)) + return path.length() == _matchLength || path.charAt(_matchLength) == '/'; return false; } + @Override + public MatchedPath matched(String path) + { + switch (_group) + { + case EXACT: + if (_declaration.equals(path)) + return _preMatchedPath; + break; + case PREFIX_GLOB: + if (isWildcardMatch(path)) + { + if (path.length() == _matchLength) + return _preMatchedPath; + return MatchedPath.from(path.substring(0, _matchLength), path.substring(_matchLength)); + } + break; + case SUFFIX_GLOB: + if (path.regionMatches((path.length() - _specLength) + 1, _declaration, 1, _specLength - 1)) + return MatchedPath.from(path, null); + break; + case ROOT: + // Only "/" matches + if ("/".equals(path)) + return _preMatchedPath; + break; + case DEFAULT: + // If we reached this point, then everything matches + return MatchedPath.from(path, null); + } + return null; + } + @Override public boolean matches(String path) { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpec.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpec.java index 6a8453972554..906a00199b11 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpec.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpec.java @@ -197,6 +197,12 @@ else if (Pattern.matches("^v+e+", sig)) _pattern = pattern; _variables = variables; _logicalDeclaration = logicalSignature.toString(); + + if (LOG.isDebugEnabled()) + { + LOG.debug("Creating UriTemplatePathSpec[{}] (regex: \"{}\", signature: [{}], group: {}, variables: [{}])", + _declaration, regex, sig, _group, String.join(", ", _variables)); + } } /** @@ -296,7 +302,9 @@ public Map getPathParams(String path) Map ret = new HashMap<>(); int groupCount = matcher.groupCount(); for (int i = 1; i <= groupCount; i++) + { ret.put(_variables[i - 1], matcher.group(i)); + } return ret; } return null; @@ -304,7 +312,17 @@ public Map getPathParams(String path) protected Matcher getMatcher(String path) { - return _pattern.matcher(path); + int idx = path.indexOf('?'); + if (idx >= 0) + { + // match only non-query part + return _pattern.matcher(path.substring(0, idx)); + } + else + { + // match entire path + return _pattern.matcher(path); + } } @Override @@ -394,17 +412,18 @@ public Pattern getPattern() @Override public boolean matches(final String path) { - int idx = path.indexOf('?'); - if (idx >= 0) - { - // match only non-query part - return getMatcher(path.substring(0, idx)).matches(); - } - else + return getMatcher(path).matches(); + } + + @Override + public MatchedPath matched(String path) + { + Matcher matcher = getMatcher(path); + if (matcher.matches()) { - // match entire path - return getMatcher(path).matches(); + return new UriTemplatePathSpec.UriTemplateMatchedPath(this, path, matcher); } + return null; } public int getVariableCount() @@ -416,4 +435,62 @@ public String[] getVariables() { return _variables; } + + private static class UriTemplateMatchedPath implements MatchedPath + { + private final UriTemplatePathSpec pathSpec; + private final String path; + private final Matcher matcher; + + public UriTemplateMatchedPath(UriTemplatePathSpec uriTemplatePathSpec, String path, Matcher matcher) + { + this.pathSpec = uriTemplatePathSpec; + this.path = path; + this.matcher = matcher; + } + + @Override + public String getPathMatch() + { + // TODO: UriTemplatePathSpec has no concept of prefix/suffix, this should be simplified + // TODO: Treat all UriTemplatePathSpec matches as exact when it comes to pathMatch/pathInfo + if (pathSpec.getGroup() == PathSpecGroup.PREFIX_GLOB && matcher.groupCount() >= 1) + { + int idx = matcher.start(1); + if (idx > 0) + { + if (path.charAt(idx - 1) == '/') + idx--; + return path.substring(0, idx); + } + } + return path; + } + + @Override + public String getPathInfo() + { + // TODO: UriTemplatePathSpec has no concept of prefix/suffix, this should be simplified + // TODO: Treat all UriTemplatePathSpec matches as exact when it comes to pathMatch/pathInfo + if (pathSpec.getGroup() == PathSpecGroup.PREFIX_GLOB && matcher.groupCount() >= 1) + { + String pathInfo = matcher.group(1); + if ("".equals(pathInfo)) + return "/"; + else + return pathInfo; + } + return null; + } + + @Override + public String toString() + { + return getClass().getSimpleName() + "[" + + "pathSpec=" + pathSpec + + ", path=\"" + path + "\"" + + ", matcher=" + matcher + + ']'; + } + } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java index 00b5da8e920b..3af0a9e25638 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java @@ -14,8 +14,6 @@ package org.eclipse.jetty.http.pathmap; import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; @@ -24,32 +22,23 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; -// @checkstyle-disable-check : AvoidEscapedUnicodeCharactersCheck +// @checkstyle-disable-check : AvoidEscapedUnicodeCharactersCheck public class PathMappingsTest { private void assertMatch(PathMappings pathmap, String path, String expectedValue) { - String msg = String.format(".getMatch(\"%s\")", path); - MappedResource match = pathmap.getMatch(path); - assertThat(msg, match, notNullValue()); - String actualMatch = match.getResource(); + String msg = String.format(".getMatched(\"%s\")", path); + MatchedResource matched = pathmap.getMatched(path); + assertThat(msg, matched, notNullValue()); + String actualMatch = matched.getResource(); assertEquals(expectedValue, actualMatch, msg); } - public void dumpMappings(PathMappings p) - { - for (MappedResource res : p) - { - System.out.printf(" %s%n", res); - } - } - /** * Test the match order rules with a mixed Servlet and regex path specs - *

+ * *

    *
  • Exact match
  • *
  • Longest prefix match
  • @@ -70,8 +59,6 @@ public void testMixedMatchOrder() p.put(new RegexPathSpec("^/animal/.*/cam$"), "animalCam"); p.put(new RegexPathSpec("^/entrance/cam$"), "entranceCam"); - // dumpMappings(p); - assertMatch(p, "/animal/bird/eagle", "birds"); assertMatch(p, "/animal/fish/bass/sea", "fishes"); assertMatch(p, "/animal/peccary/javalina/evolution", "animals"); @@ -102,7 +89,7 @@ public void testServletMatchDefault() /** * Test the match order rules with a mixed Servlet and URI Template path specs - *

    + * *

      *
    • Exact match
    • *
    • Longest prefix match
    • @@ -122,8 +109,6 @@ public void testMixedMatchUriOrder() p.put(new UriTemplatePathSpec("/animal/{type}/{name}/cam"), "animalCam"); p.put(new UriTemplatePathSpec("/entrance/cam"), "entranceCam"); - // dumpMappings(p); - assertMatch(p, "/animal/bird/eagle", "birds"); assertMatch(p, "/animal/fish/bass/sea", "fishes"); assertMatch(p, "/animal/peccary/javalina/evolution", "animals"); @@ -136,7 +121,7 @@ public void testMixedMatchUriOrder() /** * Test the match order rules for URI Template based specs - *

      + * *

        *
      • Exact match
      • *
      • Longest prefix match
      • @@ -154,8 +139,6 @@ public void testUriTemplateMatchOrder() p.put(new UriTemplatePathSpec("/{var1}/d"), "endpointD"); p.put(new UriTemplatePathSpec("/b/{var2}"), "endpointE"); - // dumpMappings(p); - assertMatch(p, "/a/b/c", "endpointB"); assertMatch(p, "/a/d/c", "endpointA"); assertMatch(p, "/a/x/y", "endpointC"); @@ -163,8 +146,28 @@ public void testUriTemplateMatchOrder() assertMatch(p, "/b/d", "endpointE"); } + /** + * Test the match order rules for mixed Servlet and Regex path specs + */ + @Test + public void testServletAndRegexMatchOrder() + { + PathMappings p = new PathMappings<>(); + + p.put(new ServletPathSpec("/a/*"), "endpointA"); + p.put(new RegexPathSpec("^.*/middle/.*$"), "middle"); + p.put(new ServletPathSpec("*.do"), "endpointDo"); + p.put(new ServletPathSpec("/"), "default"); + + assertMatch(p, "/a/b/c", "endpointA"); + assertMatch(p, "/a/middle/c", "endpointA"); + assertMatch(p, "/b/middle/c", "middle"); + assertMatch(p, "/x/y.do", "endpointDo"); + assertMatch(p, "/b/d", "default"); + } + @Test - public void testPathMap() throws Exception + public void testPathMap() { PathMappings p = new PathMappings<>(); @@ -178,76 +181,40 @@ public void testPathMap() throws Exception p.put(new ServletPathSpec("/"), "8"); // p.put(new ServletPathSpec("/XXX:/YYY"), "9"); // special syntax from Jetty 3.1.x p.put(new ServletPathSpec(""), "10"); + // @checkstyle-disable-check : AvoidEscapedUnicodeCharactersCheck p.put(new ServletPathSpec("/\u20ACuro/*"), "11"); - - assertEquals("/Foo/bar", new ServletPathSpec("/Foo/bar").getPathMatch("/Foo/bar"), "pathMatch exact"); - assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/bar"), "pathMatch prefix"); - assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/"), "pathMatch prefix"); - assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo"), "pathMatch prefix"); - assertEquals("/Foo/bar.ext", new ServletPathSpec("*.ext").getPathMatch("/Foo/bar.ext"), "pathMatch suffix"); - assertEquals("/Foo/bar.ext", new ServletPathSpec("/").getPathMatch("/Foo/bar.ext"), "pathMatch default"); - - assertEquals(null, new ServletPathSpec("/Foo/bar").getPathInfo("/Foo/bar"), "pathInfo exact"); - assertEquals("/bar", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/bar"), "pathInfo prefix"); - assertEquals("/*", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/*"), "pathInfo prefix"); - assertEquals("/", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/"), "pathInfo prefix"); - assertEquals(null, new ServletPathSpec("/Foo/*").getPathInfo("/Foo"), "pathInfo prefix"); - assertEquals(null, new ServletPathSpec("*.ext").getPathInfo("/Foo/bar.ext"), "pathInfo suffix"); - assertEquals(null, new ServletPathSpec("/").getPathInfo("/Foo/bar.ext"), "pathInfo default"); + // @checkstyle-enable-check : AvoidEscapedUnicodeCharactersCheck p.put(new ServletPathSpec("/*"), "0"); - // assertEquals("1", p.get("/abs/path"), "Get absolute path"); - assertEquals("/abs/path", p.getMatch("/abs/path").getPathSpec().getDeclaration(), "Match absolute path"); - assertEquals("1", p.getMatch("/abs/path").getResource(), "Match absolute path"); - assertEquals("0", p.getMatch("/abs/path/xxx").getResource(), "Mismatch absolute path"); - assertEquals("0", p.getMatch("/abs/pith").getResource(), "Mismatch absolute path"); - assertEquals("2", p.getMatch("/abs/path/longer").getResource(), "Match longer absolute path"); - assertEquals("0", p.getMatch("/abs/path/").getResource(), "Not exact absolute path"); - assertEquals("0", p.getMatch("/abs/path/xxx").getResource(), "Not exact absolute path"); - - assertEquals("3", p.getMatch("/animal/bird/eagle/bald").getResource(), "Match longest prefix"); - assertEquals("4", p.getMatch("/animal/fish/shark/grey").getResource(), "Match longest prefix"); - assertEquals("5", p.getMatch("/animal/insect/bug").getResource(), "Match longest prefix"); - assertEquals("5", p.getMatch("/animal").getResource(), "mismatch exact prefix"); - assertEquals("5", p.getMatch("/animal/").getResource(), "mismatch exact prefix"); - - assertEquals("0", p.getMatch("/suffix/path.tar.gz").getResource(), "Match longest suffix"); - assertEquals("0", p.getMatch("/suffix/path.gz").getResource(), "Match longest suffix"); - assertEquals("5", p.getMatch("/animal/path.gz").getResource(), "prefix rather than suffix"); - - assertEquals("0", p.getMatch("/Other/path").getResource(), "default"); - - assertEquals("", new ServletPathSpec("/*").getPathMatch("/xxx/zzz"), "pathMatch /*"); - assertEquals("/xxx/zzz", new ServletPathSpec("/*").getPathInfo("/xxx/zzz"), "pathInfo /*"); - - assertTrue(new ServletPathSpec("/").matches("/anything"), "match /"); - assertTrue(new ServletPathSpec("/*").matches("/anything"), "match /*"); - assertTrue(new ServletPathSpec("/foo").matches("/foo"), "match /foo"); - assertTrue(!new ServletPathSpec("/foo").matches("/bar"), "!match /foo"); - assertTrue(new ServletPathSpec("/foo/*").matches("/foo"), "match /foo/*"); - assertTrue(new ServletPathSpec("/foo/*").matches("/foo/"), "match /foo/*"); - assertTrue(new ServletPathSpec("/foo/*").matches("/foo/anything"), "match /foo/*"); - assertTrue(!new ServletPathSpec("/foo/*").matches("/bar"), "!match /foo/*"); - assertTrue(!new ServletPathSpec("/foo/*").matches("/bar/"), "!match /foo/*"); - assertTrue(!new ServletPathSpec("/foo/*").matches("/bar/anything"), "!match /foo/*"); - assertTrue(new ServletPathSpec("*.foo").matches("anything.foo"), "match *.foo"); - assertTrue(!new ServletPathSpec("*.foo").matches("anything.bar"), "!match *.foo"); - assertTrue(new ServletPathSpec("/On*").matches("/On*"), "match /On*"); - assertTrue(!new ServletPathSpec("/On*").matches("/One"), "!match /One"); - - assertEquals("10", p.getMatch("/").getResource(), "match / with ''"); - - assertTrue(new ServletPathSpec("").matches("/"), "match \"\""); + assertEquals("/abs/path", p.getMatched("/abs/path").getPathSpec().getDeclaration(), "Match absolute path"); + assertEquals("1", p.getMatched("/abs/path").getResource(), "Match absolute path"); + assertEquals("0", p.getMatched("/abs/path/xxx").getResource(), "Mismatch absolute path"); + assertEquals("0", p.getMatched("/abs/pith").getResource(), "Mismatch absolute path"); + assertEquals("2", p.getMatched("/abs/path/longer").getResource(), "Match longer absolute path"); + assertEquals("0", p.getMatched("/abs/path/").getResource(), "Not exact absolute path"); + assertEquals("0", p.getMatched("/abs/path/xxx").getResource(), "Not exact absolute path"); + + assertEquals("3", p.getMatched("/animal/bird/eagle/bald").getResource(), "Match longest prefix"); + assertEquals("4", p.getMatched("/animal/fish/shark/grey").getResource(), "Match longest prefix"); + assertEquals("5", p.getMatched("/animal/insect/bug").getResource(), "Match longest prefix"); + assertEquals("5", p.getMatched("/animal").getResource(), "mismatch exact prefix"); + assertEquals("5", p.getMatched("/animal/").getResource(), "mismatch exact prefix"); + + assertEquals("0", p.getMatched("/suffix/path.tar.gz").getResource(), "Match longest suffix"); + assertEquals("0", p.getMatched("/suffix/path.gz").getResource(), "Match longest suffix"); + assertEquals("5", p.getMatched("/animal/path.gz").getResource(), "prefix rather than suffix"); + + assertEquals("0", p.getMatched("/Other/path").getResource(), "default"); + + assertEquals("10", p.getMatched("/").getResource(), "match / with ''"); } /** * See JIRA issue: JETTY-88. - * - * @throws Exception failed test */ @Test - public void testPathMappingsOnlyMatchOnDirectoryNames() throws Exception + public void testPathMappingsOnlyMatchOnDirectoryNames() { ServletPathSpec spec = new ServletPathSpec("/xyz/*"); @@ -266,40 +233,25 @@ public void testPathMappingsOnlyMatchOnDirectoryNames() throws Exception } @Test - public void testPrecidenceVsOrdering() throws Exception + public void testPrecedenceVsOrdering() { PathMappings p = new PathMappings<>(); p.put(new ServletPathSpec("/dump/gzip/*"), "prefix"); p.put(new ServletPathSpec("*.txt"), "suffix"); - assertEquals(null, p.getMatch("/foo/bar")); - assertEquals("prefix", p.getMatch("/dump/gzip/something").getResource()); - assertEquals("suffix", p.getMatch("/foo/something.txt").getResource()); - assertEquals("prefix", p.getMatch("/dump/gzip/something.txt").getResource()); + assertNull(p.getMatched("/foo/bar")); + assertEquals("prefix", p.getMatched("/dump/gzip/something").getResource()); + assertEquals("suffix", p.getMatched("/foo/something.txt").getResource()); + assertEquals("prefix", p.getMatched("/dump/gzip/something.txt").getResource()); p = new PathMappings<>(); p.put(new ServletPathSpec("*.txt"), "suffix"); p.put(new ServletPathSpec("/dump/gzip/*"), "prefix"); - assertEquals(null, p.getMatch("/foo/bar")); - assertEquals("prefix", p.getMatch("/dump/gzip/something").getResource()); - assertEquals("suffix", p.getMatch("/foo/something.txt").getResource()); - assertEquals("prefix", p.getMatch("/dump/gzip/something.txt").getResource()); - } - - @ParameterizedTest - @ValueSource(strings = { - "*", - "/foo/*/bar", - "*/foo", - "*.foo/*" - }) - public void testBadPathSpecs(String str) - { - assertThrows(IllegalArgumentException.class, () -> - { - new ServletPathSpec(str); - }); + assertNull(p.getMatched("/foo/bar")); + assertEquals("prefix", p.getMatched("/dump/gzip/something").getResource()); + assertEquals("suffix", p.getMatched("/foo/something.txt").getResource()); + assertEquals("prefix", p.getMatched("/dump/gzip/something.txt").getResource()); } @Test @@ -310,8 +262,8 @@ public void testPutRejectsDuplicates() assertThat(p.put(new UriTemplatePathSpec("/a/{var2}/c"), "resourceAA"), is(false)); assertThat(p.put(new UriTemplatePathSpec("/a/b/c"), "resourceB"), is(true)); assertThat(p.put(new UriTemplatePathSpec("/a/b/c"), "resourceBB"), is(false)); - assertThat(p.put(new ServletPathSpec("/a/b/c"), "resourceBB"), is(false)); - assertThat(p.put(new RegexPathSpec("/a/b/c"), "resourceBB"), is(false)); + assertThat(p.put(new ServletPathSpec("/a/b/c"), "resourceBB"), is(true)); + assertThat(p.put(new RegexPathSpec("/a/b/c"), "resourceBB"), is(true)); assertThat(p.put(new ServletPathSpec("/*"), "resourceC"), is(true)); assertThat(p.put(new RegexPathSpec("/(.*)"), "resourceCC"), is(true)); @@ -461,14 +413,14 @@ public void testRemoveServletPathSpec() @Test public void testAsPathSpec() { - assertThat(PathMappings.asPathSpec(""), instanceOf(ServletPathSpec.class)); - assertThat(PathMappings.asPathSpec("/"), instanceOf(ServletPathSpec.class)); - assertThat(PathMappings.asPathSpec("/*"), instanceOf(ServletPathSpec.class)); - assertThat(PathMappings.asPathSpec("/foo/*"), instanceOf(ServletPathSpec.class)); - assertThat(PathMappings.asPathSpec("*.jsp"), instanceOf(ServletPathSpec.class)); - - assertThat(PathMappings.asPathSpec("^$"), instanceOf(RegexPathSpec.class)); - assertThat(PathMappings.asPathSpec("^.*"), instanceOf(RegexPathSpec.class)); - assertThat(PathMappings.asPathSpec("^/"), instanceOf(RegexPathSpec.class)); + assertThat(PathSpec.from(""), instanceOf(ServletPathSpec.class)); + assertThat(PathSpec.from("/"), instanceOf(ServletPathSpec.class)); + assertThat(PathSpec.from("/*"), instanceOf(ServletPathSpec.class)); + assertThat(PathSpec.from("/foo/*"), instanceOf(ServletPathSpec.class)); + assertThat(PathSpec.from("*.jsp"), instanceOf(ServletPathSpec.class)); + + assertThat(PathSpec.from("^$"), instanceOf(RegexPathSpec.class)); + assertThat(PathSpec.from("^.*"), instanceOf(RegexPathSpec.class)); + assertThat(PathSpec.from("^/"), instanceOf(RegexPathSpec.class)); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java index f80374e355a1..b011dafb7ee5 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java @@ -21,6 +21,8 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class RegexPathSpecTest @@ -28,13 +30,13 @@ public class RegexPathSpecTest public static void assertMatches(PathSpec spec, String path) { String msg = String.format("Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); - assertThat(msg, spec.matches(path), is(true)); + assertNotNull(spec.matched(path), msg); } public static void assertNotMatches(PathSpec spec, String path) { String msg = String.format("!Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); - assertThat(msg, spec.matches(path), is(false)); + assertNull(spec.matched(path), msg); } @Test @@ -146,6 +148,64 @@ public void testSuffixSpec() assertNotMatches(spec, "/aa/bb.do/more"); } + @Test + public void testSuffixSpecMiddle() + { + RegexPathSpec spec = new RegexPathSpec("^.*/middle/.*$"); + assertEquals("^.*/middle/.*$", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^.*/middle/.*$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.SUFFIX_GLOB, spec.getGroup(), "Spec.group"); + + assertMatches(spec, "/a/middle/c.do"); + assertMatches(spec, "/a/b/c/d/middle/e/f"); + assertMatches(spec, "/middle/"); + + assertNotMatches(spec, "/a.do"); + assertNotMatches(spec, "/a/middle"); + assertNotMatches(spec, "/middle"); + } + + @Test + public void testSuffixSpecMiddleWithGroupings() + { + RegexPathSpec spec = new RegexPathSpec("^(.*)/middle/(.*)$"); + assertEquals("^(.*)/middle/(.*)$", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^(.*)/middle/(.*)$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.SUFFIX_GLOB, spec.getGroup(), "Spec.group"); + + assertMatches(spec, "/a/middle/c.do"); + assertMatches(spec, "/a/b/c/d/middle/e/f"); + assertMatches(spec, "/middle/"); + + assertNotMatches(spec, "/a.do"); + assertNotMatches(spec, "/a/middle"); + assertNotMatches(spec, "/middle"); + } + + @Test + public void testNamedRegexGroup() + { + RegexPathSpec spec = new RegexPathSpec("^(?(.*)/middle/)(?.*)$"); + assertEquals("^(?(.*)/middle/)(?.*)$", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^(?(.*)/middle/)(?.*)$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.SUFFIX_GLOB, spec.getGroup(), "Spec.group"); + + assertMatches(spec, "/a/middle/c.do"); + assertMatches(spec, "/a/b/c/d/middle/e/f"); + assertMatches(spec, "/middle/"); + + assertNotMatches(spec, "/a.do"); + assertNotMatches(spec, "/a/middle"); + assertNotMatches(spec, "/middle"); + + MatchedPath matchedPath = spec.matched("/a/middle/c.do"); + assertThat(matchedPath.getPathMatch(), is("/a/middle/")); + assertThat(matchedPath.getPathInfo(), is("c.do")); + } + @Test public void testEquals() { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java index 85605ac44eb1..2d46fdb377b2 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java @@ -24,7 +24,7 @@ import static org.hamcrest.Matchers.is; /** - * Tests of {@link PathMappings#getMatch(String)}, with a focus on correct mapping selection order + * Tests of {@link PathMappings#getMatched(String)}, with a focus on correct mapping selection order */ @SuppressWarnings("Duplicates") public class ServletPathSpecOrderTest @@ -53,6 +53,7 @@ public static Stream data() data.add(Arguments.of("/Other/path", "default")); // @checkstyle-disable-check : AvoidEscapedUnicodeCharactersCheck data.add(Arguments.of("/\u20ACuro/path", "money")); + // @checkstyle-enable-check : AvoidEscapedUnicodeCharactersCheck data.add(Arguments.of("/", "root")); // Extra tests @@ -87,6 +88,6 @@ public static Stream data() @MethodSource("data") public void testMatch(String inputPath, String expectedResource) { - assertThat("Match on [" + inputPath + "]", mappings.getMatch(inputPath).getResource(), is(expectedResource)); + assertThat("Match on [" + inputPath + "]", mappings.getMatched(inputPath).getResource(), is(expectedResource)); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java index ada61e6f0806..46be8fce3bc1 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java @@ -14,70 +14,48 @@ package org.eclipse.jetty.http.pathmap; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ServletPathSpecTest { - private void assertBadServletPathSpec(String pathSpec) - { - try - { - new ServletPathSpec(pathSpec); - fail("Expected IllegalArgumentException for a bad servlet pathspec on: " + pathSpec); - } - catch (IllegalArgumentException e) - { - // expected path - System.out.println(e); - } - } - private void assertMatches(ServletPathSpec spec, String path) { String msg = String.format("Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); - assertThat(msg, spec.matches(path), is(true)); + assertThat(msg, spec.matched(path), not(nullValue())); } private void assertNotMatches(ServletPathSpec spec, String path) { String msg = String.format("!Spec(\"%s\").matches(\"%s\")", spec.getDeclaration(), path); - assertThat(msg, spec.matches(path), is(false)); - } - - @Test - public void testBadServletPathSpecA() - { - assertBadServletPathSpec("foo"); - } - - @Test - public void testBadServletPathSpecB() - { - assertBadServletPathSpec("/foo/*.do"); - } - - @Test - public void testBadServletPathSpecC() - { - assertBadServletPathSpec("foo/*.do"); + assertThat(msg, spec.matched(path), is(nullValue())); } - @Test - public void testBadServletPathSpecD() - { - assertBadServletPathSpec("foo/*.*do"); - } - - @Test - public void testBadServletPathSpecE() + @ParameterizedTest + @ValueSource(strings = { + "foo", + "/foo/*.do", + "foo/*.do", + "foo/*.*do", + "*", + "*do", + "/foo/*/bar", + "*/foo", + "*.foo/*" + }) + public void testBadPathSpecs(String str) { - assertBadServletPathSpec("*do"); + assertThrows(IllegalArgumentException.class, () -> new ServletPathSpec(str)); } @Test @@ -107,16 +85,27 @@ public void testExactPathSpec() @Test public void testGetPathInfo() { - assertEquals(null, new ServletPathSpec("/Foo/bar").getPathInfo("/Foo/bar"), "pathInfo exact"); - assertEquals("/bar", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/bar"), "pathInfo prefix"); - assertEquals("/*", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/*"), "pathInfo prefix"); - assertEquals("/", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/"), "pathInfo prefix"); - assertEquals(null, new ServletPathSpec("/Foo/*").getPathInfo("/Foo"), "pathInfo prefix"); - assertEquals(null, new ServletPathSpec("*.ext").getPathInfo("/Foo/bar.ext"), "pathInfo suffix"); - assertEquals(null, new ServletPathSpec("/").getPathInfo("/Foo/bar.ext"), "pathInfo default"); - assertEquals("/", new ServletPathSpec("").getPathInfo("/"), "pathInfo root"); - assertEquals("", new ServletPathSpec("").getPathInfo(""), "pathInfo root"); - assertEquals("/xxx/zzz", new ServletPathSpec("/*").getPathInfo("/xxx/zzz"), "pathInfo default"); + ServletPathSpec spec = new ServletPathSpec("/Foo/bar"); + assertThat("PathInfo exact", spec.matched("/Foo/bar").getPathInfo(), is(nullValue())); + + spec = new ServletPathSpec("/Foo/*"); + assertThat("PathInfo prefix", spec.matched("/Foo/bar").getPathInfo(), is("/bar")); + assertThat("PathInfo prefix", spec.matched("/Foo/*").getPathInfo(), is("/*")); + assertThat("PathInfo prefix", spec.matched("/Foo/").getPathInfo(), is("/")); + assertThat("PathInfo prefix", spec.matched("/Foo").getPathInfo(), is(nullValue())); + + spec = new ServletPathSpec("*.ext"); + assertThat("PathInfo suffix", spec.matched("/Foo/bar.ext").getPathInfo(), is(nullValue())); + + spec = new ServletPathSpec("/"); + assertThat("PathInfo default", spec.matched("/Foo/bar.ext").getPathInfo(), is(nullValue())); + + spec = new ServletPathSpec(""); + assertThat("PathInfo root", spec.matched("/").getPathInfo(), is("/")); + assertThat("PathInfo root", spec.matched(""), is(nullValue())); // does not match // TODO: verify with greg + + spec = new ServletPathSpec("/*"); + assertThat("PathInfo default", spec.matched("/xxx/zzz").getPathInfo(), is("/xxx/zzz")); } @Test @@ -138,15 +127,26 @@ public void testRootPathSpec() @Test public void testPathMatch() { - assertEquals("/Foo/bar", new ServletPathSpec("/Foo/bar").getPathMatch("/Foo/bar"), "pathMatch exact"); - assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/bar"), "pathMatch prefix"); - assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/"), "pathMatch prefix"); - assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo"), "pathMatch prefix"); - assertEquals("/Foo/bar.ext", new ServletPathSpec("*.ext").getPathMatch("/Foo/bar.ext"), "pathMatch suffix"); - assertEquals("/Foo/bar.ext", new ServletPathSpec("/").getPathMatch("/Foo/bar.ext"), "pathMatch default"); - assertEquals("", new ServletPathSpec("").getPathMatch("/"), "pathInfo root"); - assertEquals("", new ServletPathSpec("").getPathMatch(""), "pathInfo root"); - assertEquals("", new ServletPathSpec("/*").getPathMatch("/xxx/zzz"), "pathMatch default"); + ServletPathSpec spec = new ServletPathSpec("/Foo/bar"); + assertThat("PathMatch exact", spec.matched("/Foo/bar").getPathMatch(), is("/Foo/bar")); + + spec = new ServletPathSpec("/Foo/*"); + assertThat("PathMatch prefix", spec.matched("/Foo/bar").getPathMatch(), is("/Foo")); + assertThat("PathMatch prefix", spec.matched("/Foo/").getPathMatch(), is("/Foo")); + assertThat("PathMatch prefix", spec.matched("/Foo").getPathMatch(), is("/Foo")); + + spec = new ServletPathSpec("*.ext"); + assertThat("PathMatch suffix", spec.matched("/Foo/bar.ext").getPathMatch(), is("/Foo/bar.ext")); + + spec = new ServletPathSpec("/"); + assertThat("PathMatch default", spec.matched("/Foo/bar.ext").getPathMatch(), is("/Foo/bar.ext")); + + spec = new ServletPathSpec(""); + assertThat("PathMatch root", spec.matched("/").getPathMatch(), is("")); + assertThat("PathMatch root", spec.matched(""), is(nullValue())); // does not match // TODO: verify with greg + + spec = new ServletPathSpec("/*"); + assertThat("PathMatch default", spec.matched("/xxx/zzz").getPathMatch(), is("")); } @Test @@ -163,9 +163,39 @@ public void testPrefixPathSpec() assertMatches(spec, "/downloads"); - assertEquals("/", spec.getPathInfo("/downloads/"), "Spec.pathInfo"); - assertEquals("/distribution.zip", spec.getPathInfo("/downloads/distribution.zip"), "Spec.pathInfo"); - assertEquals("/dist/9.0/distribution.tar.gz", spec.getPathInfo("/downloads/dist/9.0/distribution.tar.gz"), "Spec.pathInfo"); + MatchedPath matched = spec.matched("/downloads/"); + assertThat("matched.pathMatch", matched.getPathMatch(), is("/downloads")); + assertThat("matched.pathInfo", matched.getPathInfo(), is("/")); + + matched = spec.matched("/downloads/distribution.zip"); + assertThat("matched.pathMatch", matched.getPathMatch(), is("/downloads")); + assertThat("matched.pathInfo", matched.getPathInfo(), is("/distribution.zip")); + + matched = spec.matched("/downloads/dist/9.0/distribution.tar.gz"); + assertThat("matched.pathMatch", matched.getPathMatch(), is("/downloads")); + assertThat("matched.pathInfo", matched.getPathInfo(), is("/dist/9.0/distribution.tar.gz")); + } + + @Test + public void testMatches() + { + assertTrue(new ServletPathSpec("/").matches("/anything"), "match /"); + assertTrue(new ServletPathSpec("/*").matches("/anything"), "match /*"); + assertTrue(new ServletPathSpec("/foo").matches("/foo"), "match /foo"); + assertFalse(new ServletPathSpec("/foo").matches("/bar"), "!match /foo"); + assertTrue(new ServletPathSpec("/foo/*").matches("/foo"), "match /foo/*"); + assertTrue(new ServletPathSpec("/foo/*").matches("/foo/"), "match /foo/*"); + assertTrue(new ServletPathSpec("/foo/*").matches("/foo/anything"), "match /foo/*"); + assertFalse(new ServletPathSpec("/foo/*").matches("/bar"), "!match /foo/*"); + assertFalse(new ServletPathSpec("/foo/*").matches("/bar/"), "!match /foo/*"); + assertFalse(new ServletPathSpec("/foo/*").matches("/bar/anything"), "!match /foo/*"); + assertTrue(new ServletPathSpec("*.foo").matches("anything.foo"), "match *.foo"); + assertFalse(new ServletPathSpec("*.foo").matches("anything.bar"), "!match *.foo"); + assertTrue(new ServletPathSpec("/On*").matches("/On*"), "match /On*"); + assertFalse(new ServletPathSpec("/On*").matches("/One"), "!match /One"); + + assertTrue(new ServletPathSpec("").matches("/"), "match \"\""); + } @Test @@ -182,7 +212,9 @@ public void testSuffixPathSpec() assertNotMatches(spec, "/downloads/distribution.tgz"); assertNotMatches(spec, "/abs/path"); - assertEquals(null, spec.getPathInfo("/downloads/distribution.tar.gz"), "Spec.pathInfo"); + MatchedPath matched = spec.matched("/downloads/distribution.tar.gz"); + assertThat("Suffix.pathMatch", matched.getPathMatch(), is("/downloads/distribution.tar.gz")); + assertThat("Suffix.pathInfo", matched.getPathInfo(), is(nullValue())); } @Test @@ -196,5 +228,4 @@ public void testEquals() assertThat(new ServletPathSpec("/bar/foo"), not(equalTo(new ServletPathSpec("/foo/bar")))); assertThat(new ServletPathSpec("/foo"), not(equalTo(new RegexPathSpec("/foo")))); } - } diff --git a/jetty-http/src/test/resources/jetty-logging.properties b/jetty-http/src/test/resources/jetty-logging.properties index ab545e4ab63f..36ce9cee235b 100644 --- a/jetty-http/src/test/resources/jetty-logging.properties +++ b/jetty-http/src/test/resources/jetty-logging.properties @@ -2,3 +2,4 @@ #org.eclipse.jetty.LEVEL=DEBUG #org.eclipse.jetty.server.LEVEL=DEBUG #org.eclipse.jetty.http.LEVEL=DEBUG +#org.eclipse.jetty.http.pathmap.LEVEL=DEBUG diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/CustomRequestLog.java b/jetty-server/src/main/java/org/eclipse/jetty/server/CustomRequestLog.java index bd0781835e0d..4eb998d33700 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/CustomRequestLog.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/CustomRequestLog.java @@ -388,14 +388,14 @@ public RequestLog.Writer getWriter() @Override public void log(Request request, Response response) { - if (_ignorePathMap != null && _ignorePathMap.getMatch(request.getRequestURI()) != null) - return; - - if (_filter != null && !_filter.test(request, response)) - return; - try { + if (_ignorePathMap != null && _ignorePathMap.getMatched(request.getRequestURI()) != null) + return; + + if (_filter != null && !_filter.test(request, response)) + return; + StringBuilder sb = _buffers.get(); sb.setLength(0); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java index 3e4643069eb2..973fc799d274 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java @@ -13,10 +13,12 @@ package org.eclipse.jetty.server; +import java.util.Objects; import javax.servlet.http.HttpServletMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.MappingMatch; +import org.eclipse.jetty.http.pathmap.MatchedPath; import org.eclipse.jetty.http.pathmap.PathSpec; import org.eclipse.jetty.http.pathmap.ServletPathSpec; @@ -39,6 +41,55 @@ public class ServletPathMapping implements HttpServletMapping private final String _servletPath; private final String _pathInfo; + public ServletPathMapping(PathSpec pathSpec, String servletName, String pathInContext, MatchedPath matchedPath) + { + Objects.requireNonNull(pathSpec); + _servletName = (servletName == null ? "" : servletName); + _pattern = pathSpec.getDeclaration(); + _servletPath = matchedPath.getPathMatch(); + _pathInfo = matchedPath.getPathInfo(); + + switch (pathSpec.getGroup()) + { + case ROOT: + _mappingMatch = MappingMatch.CONTEXT_ROOT; + _matchValue = ""; + break; + + case DEFAULT: + _mappingMatch = MappingMatch.DEFAULT; + _matchValue = ""; + break; + + case EXACT: + _mappingMatch = MappingMatch.EXACT; + _matchValue = _pattern.startsWith("/") ? _pattern.substring(1) : _pattern; + break; + + case PREFIX_GLOB: + _mappingMatch = MappingMatch.PATH; + // TODO avoid the substring on the known servletPath! + _matchValue = _servletPath.startsWith("/") ? _servletPath.substring(1) : _servletPath; + break; + + case SUFFIX_GLOB: + _mappingMatch = MappingMatch.EXTENSION; + int dot = pathInContext.lastIndexOf('.'); + _matchValue = pathInContext.substring(pathInContext.startsWith("/") ? 1 : 0, dot); + break; + + case MIDDLE_GLOB: + default: + _mappingMatch = null; + _matchValue = ""; + break; + } + } + + /** + * @deprecated use {@link ServletPathMapping(PathSpec, String, String, MatchedPath)} instead. + */ + @Deprecated public ServletPathMapping(PathSpec pathSpec, String servletName, String pathInContext) { _servletName = (servletName == null ? "" : servletName); diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java index e775e4e810c3..7a7b8b9d9689 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java @@ -26,6 +26,7 @@ import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.pathmap.MatchedResource; import org.eclipse.jetty.server.Dispatcher; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; @@ -66,7 +67,7 @@ public class Invoker extends HttpServlet private ContextHandler _contextHandler; private ServletHandler _servletHandler; - private ServletHandler.MappedServlet _invokerEntry; + private MatchedResource _invokerEntry; private Map _parameters; private boolean _nonContextServlets; private boolean _verbose; @@ -162,16 +163,16 @@ protected void service(HttpServletRequest request, HttpServletResponse response) try (AutoLock l = _servletHandler.lock()) { // find the entry for the invoker (me) - _invokerEntry = _servletHandler.getMappedServlet(servletPath); + _invokerEntry = _servletHandler.getMatchedServlet(servletPath); // Check for existing mapping (avoid threaded race). String path = URIUtil.addPaths(servletPath, servlet); - ServletHandler.MappedServlet entry = _servletHandler.getMappedServlet(path); + MatchedResource entry = _servletHandler.getMatchedServlet(path); - if (entry != null && !entry.equals(_invokerEntry)) + if (entry != null && !entry.getResource().equals(_invokerEntry.getResource())) { // Use the holder - holder = (ServletHolder)entry.getServletHolder(); + holder = entry.getResource().getServletHolder(); } else { diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java index 1b0fc85cef7d..2ecc2714772f 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java @@ -45,6 +45,8 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.pathmap.MappedResource; +import org.eclipse.jetty.http.pathmap.MatchedPath; +import org.eclipse.jetty.http.pathmap.MatchedResource; import org.eclipse.jetty.http.pathmap.PathMappings; import org.eclipse.jetty.http.pathmap.PathSpec; import org.eclipse.jetty.http.pathmap.ServletPathSpec; @@ -353,6 +355,24 @@ public FilterHolder[] getFilters() return _filters.toArray(new FilterHolder[0]); } + /** + * ServletHolder matching path. + * + * @param target Path within _context or servlet name + * @return PathMap Entries pathspec to ServletHolder + * @deprecated Use {@link #getMatchedServlet(String)} instead + */ + @Deprecated + public MappedResource getHolderEntry(String target) + { + if (target.startsWith("/")) + { + MatchedResource matchedResource = getMatchedServlet(target); + return new MappedResource<>(matchedResource.getPathSpec(), matchedResource.getResource()); + } + return null; + } + public ServletContext getServletContext() { return _servletContext; @@ -439,15 +459,23 @@ public void doScope(String target, Request baseRequest, HttpServletRequest reque ServletHolder servletHolder = null; UserIdentity.Scope oldScope = null; - MappedServlet mappedServlet = getMappedServlet(target); - if (mappedServlet != null) + MatchedResource matched = getMatchedServlet(target); + if (matched != null) { + MappedServlet mappedServlet = matched.getResource(); servletHolder = mappedServlet.getServletHolder(); - ServletPathMapping servletPathMapping = mappedServlet.getServletPathMapping(target); - if (servletPathMapping != null) + + if (matched.getPathSpec() != null) { - // Setting the servletPathMapping also provides the servletPath and pathInfo - baseRequest.setServletPathMapping(servletPathMapping); + if (DispatcherType.INCLUDE.equals(baseRequest.getDispatcherType())) + { + ServletPathMapping servletPathMapping = new ServletPathMapping( + matched.getPathSpec(), + servletHolder.getName(), + target, + matched.getMatchedPath()); + baseRequest.setServletPathMapping(servletPathMapping); + } } } @@ -516,25 +544,39 @@ public void doHandle(String target, Request baseRequest, HttpServletRequest requ } /** - * Get MappedServlet for target. + * ServletHolder matching target path. * * @param target Path within _context or servlet name - * @return MappedServlet matched by path or name. Named servlets have a null PathSpec + * @return MatchedResource, pointing to the {@link MappedResource} for the {@link ServletHolder}, and also the pathspec specific name/info sections for the match. + * Named servlets have a null PathSpec and {@link MatchedResource}. */ - public MappedServlet getMappedServlet(String target) + public MatchedResource getMatchedServlet(String target) { if (target.startsWith("/")) { if (_servletPathMap == null) return null; - - MappedResource match = _servletPathMap.getMatch(target); - if (match == null) - return null; - return match.getResource(); + return _servletPathMap.getMatched(target); } - return _servletNameMap.get(target); + MappedServlet holder = _servletNameMap.get(target); + if (holder == null) + return null; + return new MatchedResource<>(holder, null, MatchedPath.EMPTY); + } + + /** + * ServletHolder matching path. + * + * @param target Path within _context or servlet name + * @return MappedResource to the ServletHolder. Named servlets have a null PathSpec + * @deprecated use {@link #getMatchedServlet(String)} instead + */ + @Deprecated + public MappedServlet getMappedServlet(String target) + { + MatchedResource matchedResource = getMatchedServlet(target); + return matchedResource.getResource(); } protected FilterChain getFilterChain(Request baseRequest, String pathInContext, ServletHolder servletHolder) From 547fa69215c0012859414265aee3a29f20e0b419 Mon Sep 17 00:00:00 2001 From: Joakim Erdfelt Date: Tue, 7 Jun 2022 17:03:32 -0500 Subject: [PATCH 2/7] Fixing ConstraintSecurityHandler usage of PathMappings Signed-off-by: Joakim Erdfelt --- .../org/eclipse/jetty/security/ConstraintSecurityHandler.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java index 34c0d7fee7a8..54648055fa7e 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/ConstraintSecurityHandler.java @@ -34,6 +34,7 @@ import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.pathmap.MappedResource; +import org.eclipse.jetty.http.pathmap.MatchedResource; import org.eclipse.jetty.http.pathmap.PathMappings; import org.eclipse.jetty.http.pathmap.PathSpec; import org.eclipse.jetty.server.HttpConfiguration; @@ -575,7 +576,7 @@ else if (mapping.getConstraint().isAnyAuth()) @Override protected RoleInfo prepareConstraintInfo(String pathInContext, Request request) { - MappedResource> resource = _constraintRoles.getMatch(pathInContext); + MatchedResource> resource = _constraintRoles.getMatched(pathInContext); if (resource == null) return null; From 2ec9527d6d2755a65e0004d8dd3cf792e8fb7402 Mon Sep 17 00:00:00 2001 From: Joakim Erdfelt Date: Tue, 7 Jun 2022 22:36:01 -0500 Subject: [PATCH 3/7] Fixing bad INCLUDE logic from cherry-pick in ServletHandler.doScope() Signed-off-by: Joakim Erdfelt --- .../jetty/server/ServletPathMapping.java | 14 ++++++++++++-- .../eclipse/jetty/servlet/ServletHandler.java | 17 +++++------------ 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java index 973fc799d274..c28d2946a628 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java @@ -46,42 +46,52 @@ public ServletPathMapping(PathSpec pathSpec, String servletName, String pathInCo Objects.requireNonNull(pathSpec); _servletName = (servletName == null ? "" : servletName); _pattern = pathSpec.getDeclaration(); - _servletPath = matchedPath.getPathMatch(); - _pathInfo = matchedPath.getPathInfo(); switch (pathSpec.getGroup()) { case ROOT: _mappingMatch = MappingMatch.CONTEXT_ROOT; _matchValue = ""; + _servletPath = ""; + _pathInfo = "/"; break; case DEFAULT: _mappingMatch = MappingMatch.DEFAULT; _matchValue = ""; + _servletPath = pathInContext; + _pathInfo = null; break; case EXACT: _mappingMatch = MappingMatch.EXACT; _matchValue = _pattern.startsWith("/") ? _pattern.substring(1) : _pattern; + _servletPath = _pattern; + _pathInfo = null; break; case PREFIX_GLOB: _mappingMatch = MappingMatch.PATH; + _servletPath = pathSpec.getPrefix(); // TODO avoid the substring on the known servletPath! _matchValue = _servletPath.startsWith("/") ? _servletPath.substring(1) : _servletPath; + _pathInfo = matchedPath.getPathInfo(); break; case SUFFIX_GLOB: _mappingMatch = MappingMatch.EXTENSION; int dot = pathInContext.lastIndexOf('.'); _matchValue = pathInContext.substring(pathInContext.startsWith("/") ? 1 : 0, dot); + _servletPath = pathInContext; + _pathInfo = null; break; case MIDDLE_GLOB: default: _mappingMatch = null; _matchValue = ""; + _servletPath = matchedPath.getPathMatch(); + _pathInfo = matchedPath.getPathInfo(); break; } } diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java index 2ecc2714772f..c187ccc64923 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java @@ -464,18 +464,11 @@ public void doScope(String target, Request baseRequest, HttpServletRequest reque { MappedServlet mappedServlet = matched.getResource(); servletHolder = mappedServlet.getServletHolder(); + ServletPathMapping servletPathMapping = mappedServlet.getServletPathMapping(target, matched.getMatchedPath()); - if (matched.getPathSpec() != null) + if (servletPathMapping != null) { - if (DispatcherType.INCLUDE.equals(baseRequest.getDispatcherType())) - { - ServletPathMapping servletPathMapping = new ServletPathMapping( - matched.getPathSpec(), - servletHolder.getName(), - target, - matched.getMatchedPath()); - baseRequest.setServletPathMapping(servletPathMapping); - } + baseRequest.setServletPathMapping(servletPathMapping); } } @@ -1596,12 +1589,12 @@ public ServletHolder getServletHolder() return _servletHolder; } - public ServletPathMapping getServletPathMapping(String pathInContext) + public ServletPathMapping getServletPathMapping(String pathInContext, MatchedPath matchedPath) { if (_servletPathMapping != null) return _servletPathMapping; if (_pathSpec != null) - return new ServletPathMapping(_pathSpec, _servletHolder.getName(), pathInContext); + return new ServletPathMapping(_pathSpec, _servletHolder.getName(), pathInContext, matchedPath); return null; } From 590adf286ed26879b92a9df1ee5b489e7fd53b21 Mon Sep 17 00:00:00 2001 From: Joakim Erdfelt Date: Wed, 8 Jun 2022 08:01:28 -0500 Subject: [PATCH 4/7] Cleanup of non ServletPathSpec behaviors in ServletPathMapping class Signed-off-by: Joakim Erdfelt --- .../jetty/server/ServletPathMapping.java | 117 +++++++----------- .../jetty/servlet/RegexServletTest.java | 3 +- 2 files changed, 44 insertions(+), 76 deletions(-) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java index c28d2946a628..5b9defe85380 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java @@ -13,7 +13,6 @@ package org.eclipse.jetty.server; -import java.util.Objects; import javax.servlet.http.HttpServletMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.MappingMatch; @@ -43,8 +42,48 @@ public class ServletPathMapping implements HttpServletMapping public ServletPathMapping(PathSpec pathSpec, String servletName, String pathInContext, MatchedPath matchedPath) { - Objects.requireNonNull(pathSpec); _servletName = (servletName == null ? "" : servletName); + + if (pathSpec == null) + { + _pattern = null; + _mappingMatch = null; + _matchValue = ""; + _servletPath = pathInContext; + _pathInfo = null; + return; + } + + if (pathInContext == null) + { + _pattern = pathSpec.getDeclaration(); + _mappingMatch = null; + _matchValue = ""; + _servletPath = ""; + _pathInfo = null; + return; + } + + // Path Spec types that are not ServletPathSpec + if (!(pathSpec instanceof ServletPathSpec)) + { + _pattern = pathSpec.getDeclaration(); + _mappingMatch = null; + if (matchedPath != null) + { + _servletPath = matchedPath.getPathMatch(); + _pathInfo = matchedPath.getPathInfo(); + } + else + { + _servletPath = pathInContext; + _pathInfo = null; + } + _matchValue = _servletPath.substring(_servletPath.charAt(0) == '/' ? 1 : 0); + return; + } + + // from here down is ServletPathSpec behavior _pattern = pathSpec.getDeclaration(); switch (pathSpec.getGroup()) @@ -88,83 +127,13 @@ public ServletPathMapping(PathSpec pathSpec, String servletName, String pathInCo case MIDDLE_GLOB: default: - _mappingMatch = null; - _matchValue = ""; - _servletPath = matchedPath.getPathMatch(); - _pathInfo = matchedPath.getPathInfo(); - break; + throw new IllegalStateException("ServletPathSpec of type MIDDLE_GLOB"); } } - /** - * @deprecated use {@link ServletPathMapping(PathSpec, String, String, MatchedPath)} instead. - */ - @Deprecated public ServletPathMapping(PathSpec pathSpec, String servletName, String pathInContext) { - _servletName = (servletName == null ? "" : servletName); - _pattern = pathSpec == null ? null : pathSpec.getDeclaration(); - - if (pathSpec instanceof ServletPathSpec && pathInContext != null) - { - switch (pathSpec.getGroup()) - { - case ROOT: - _mappingMatch = MappingMatch.CONTEXT_ROOT; - _matchValue = ""; - _servletPath = ""; - _pathInfo = "/"; - break; - - case DEFAULT: - _mappingMatch = MappingMatch.DEFAULT; - _matchValue = ""; - _servletPath = pathInContext; - _pathInfo = null; - break; - - case EXACT: - _mappingMatch = MappingMatch.EXACT; - _matchValue = _pattern.startsWith("/") ? _pattern.substring(1) : _pattern; - _servletPath = _pattern; - _pathInfo = null; - break; - - case PREFIX_GLOB: - _mappingMatch = MappingMatch.PATH; - _servletPath = pathSpec.getPrefix(); - // TODO avoid the substring on the known servletPath! - _matchValue = _servletPath.startsWith("/") ? _servletPath.substring(1) : _servletPath; - _pathInfo = pathSpec.getPathInfo(pathInContext); - break; - - case SUFFIX_GLOB: - _mappingMatch = MappingMatch.EXTENSION; - int dot = pathInContext.lastIndexOf('.'); - _matchValue = pathInContext.substring(pathInContext.startsWith("/") ? 1 : 0, dot); - _servletPath = pathInContext; - _pathInfo = null; - break; - - case MIDDLE_GLOB: - default: - throw new IllegalStateException(); - } - } - else if (pathSpec != null) - { - _mappingMatch = null; - _servletPath = pathSpec.getPathMatch(pathInContext); - _matchValue = _servletPath.startsWith("/") ? _servletPath.substring(1) : _servletPath; - _pathInfo = pathSpec.getPathInfo(pathInContext); - } - else - { - _mappingMatch = null; - _matchValue = ""; - _servletPath = pathInContext; - _pathInfo = null; - } + this(pathSpec, servletName, pathInContext, null); } @Override diff --git a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/RegexServletTest.java b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/RegexServletTest.java index d4e67f13c35d..bbab83b56a82 100644 --- a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/RegexServletTest.java +++ b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/RegexServletTest.java @@ -20,7 +20,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.eclipse.jetty.http.pathmap.PathMappings; import org.eclipse.jetty.http.pathmap.PathSpec; import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.Server; @@ -48,7 +47,7 @@ public void beforeEach() @Override protected PathSpec asPathSpec(String pathSpec) { - return PathMappings.asPathSpec(pathSpec); + return PathSpec.from(pathSpec); } }); From 4e419d80cc53b23b1e82a4ae0c96614d409288cd Mon Sep 17 00:00:00 2001 From: Joakim Erdfelt Date: Wed, 8 Jun 2022 08:02:07 -0500 Subject: [PATCH 5/7] Skip optional group name/info lookup if regex fails. Signed-off-by: Joakim Erdfelt --- .../jetty/http/pathmap/RegexPathSpec.java | 26 ++++++++--- .../jetty/http/pathmap/RegexPathSpecTest.java | 43 ++++++++++++++++++- 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/RegexPathSpec.java b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/RegexPathSpec.java index 71f751000c36..5fe2db237c9e 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/RegexPathSpec.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/pathmap/RegexPathSpec.java @@ -289,10 +289,17 @@ public RegexMatchedPath(RegexPathSpec regexPathSpec, String path, Matcher matche @Override public String getPathMatch() { - String p = matcher.group("name"); - if (p != null) + try { - return p; + String p = matcher.group("name"); + if (p != null) + { + return p; + } + } + catch (IllegalArgumentException ignore) + { + // ignore if group name not found. } if (pathSpec.getGroup() == PathSpecGroup.PREFIX_GLOB && matcher.groupCount() >= 1) @@ -313,10 +320,17 @@ public String getPathMatch() @Override public String getPathInfo() { - String p = matcher.group("info"); - if (p != null) + try + { + String p = matcher.group("info"); + if (p != null) + { + return p; + } + } + catch (IllegalArgumentException ignore) { - return p; + // ignore if group info not found. } // Path Info only valid for PREFIX_GLOB diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java index b011dafb7ee5..79ff15c97b37 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java @@ -129,7 +129,7 @@ public void testPrefixSpec() } @Test - public void testSuffixSpec() + public void testSuffixSpecTraditional() { RegexPathSpec spec = new RegexPathSpec("^(.*).do$"); assertEquals("^(.*).do$", spec.getDeclaration(), "Spec.pathSpec"); @@ -146,6 +146,47 @@ public void testSuffixSpec() assertNotMatches(spec, "/aa"); assertNotMatches(spec, "/aa/bb"); assertNotMatches(spec, "/aa/bb.do/more"); + + assertThat(spec.getPathMatch("/a/b/c.do"), equalTo("/a/b/c.do")); + assertThat(spec.getPathInfo("/a/b/c.do"), nullValue()); + } + + /** + * A suffix type path spec, where the beginning of the path is evaluated + * but the rest of the path is ignored. + * The beginning is starts with a glob, contains a literal, and no terminal "$". + */ + @Test + public void testSuffixSpecGlobish() + { + RegexPathSpec spec = new RegexPathSpec("^/[Hh]ello"); + assertEquals("^/[Hh]ello", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/[Hh]ello", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.SUFFIX_GLOB, spec.getGroup(), "Spec.group"); + + assertMatches(spec, "/hello"); + assertMatches(spec, "/Hello"); + + assertNotMatches(spec, "/Hello/World"); + assertNotMatches(spec, "/a"); + assertNotMatches(spec, "/aa"); + assertNotMatches(spec, "/aa/bb"); + assertNotMatches(spec, "/aa/bb.do/more"); + + assertThat(spec.getPathMatch("/hello"), equalTo("/hello")); + assertThat(spec.getPathInfo("/hello"), nullValue()); + + assertThat(spec.getPathMatch("/Hello"), equalTo("/Hello")); + assertThat(spec.getPathInfo("/Hello"), nullValue()); + + MatchedPath matchedPath = spec.matched("/hello"); + assertThat(matchedPath.getPathMatch(), equalTo("/hello")); + assertThat(matchedPath.getPathInfo(), nullValue()); + + matchedPath = spec.matched("/Hello"); + assertThat(matchedPath.getPathMatch(), equalTo("/Hello")); + assertThat(matchedPath.getPathInfo(), nullValue()); } @Test From bc1416a3c499e1253da7327b149173ebccd1a645 Mon Sep 17 00:00:00 2001 From: Joakim Erdfelt Date: Wed, 8 Jun 2022 09:17:12 -0500 Subject: [PATCH 6/7] Prevent NPE on static servletPathMappings Signed-off-by: Joakim Erdfelt --- .../jetty/server/ServletPathMapping.java | 2 +- .../org/eclipse/jetty/server/RequestTest.java | 60 +++++++++++-------- .../eclipse/jetty/servlet/ServletHandler.java | 2 +- 3 files changed, 37 insertions(+), 27 deletions(-) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java index 5b9defe85380..2d5c81fda8fa 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ServletPathMapping.java @@ -114,7 +114,7 @@ public ServletPathMapping(PathSpec pathSpec, String servletName, String pathInCo _servletPath = pathSpec.getPrefix(); // TODO avoid the substring on the known servletPath! _matchValue = _servletPath.startsWith("/") ? _servletPath.substring(1) : _servletPath; - _pathInfo = matchedPath.getPathInfo(); + _pathInfo = matchedPath != null ? matchedPath.getPathInfo() : null; break; case SUFFIX_GLOB: diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java index 8413367854f0..0b45b9a8430a 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java @@ -62,6 +62,7 @@ import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.http.UriCompliance; +import org.eclipse.jetty.http.pathmap.MatchedPath; import org.eclipse.jetty.http.pathmap.RegexPathSpec; import org.eclipse.jetty.http.pathmap.ServletPathSpec; import org.eclipse.jetty.io.Connection; @@ -2014,11 +2015,13 @@ public void testServletPathMapping() { ServletPathSpec spec; String uri; + MatchedPath matched; ServletPathMapping m; spec = null; uri = null; - m = new ServletPathMapping(spec, null, uri); + matched = null; + m = new ServletPathMapping(spec, null, uri, matched); assertThat(m.getMappingMatch(), nullValue()); assertThat(m.getMatchValue(), is("")); assertThat(m.getPattern(), nullValue()); @@ -2028,71 +2031,78 @@ public void testServletPathMapping() spec = new ServletPathSpec(""); uri = "/"; - m = new ServletPathMapping(spec, "Something", uri); + matched = spec.matched(uri); + m = new ServletPathMapping(spec, "Something", uri, matched); assertThat(m.getMappingMatch(), is(MappingMatch.CONTEXT_ROOT)); assertThat(m.getMatchValue(), is("")); assertThat(m.getPattern(), is("")); assertThat(m.getServletName(), is("Something")); - assertThat(m.getServletPath(), is(spec.getPathMatch(uri))); - assertThat(m.getPathInfo(), is(spec.getPathInfo(uri))); + assertThat(m.getServletPath(), is("")); + assertThat(m.getPathInfo(), is("/")); spec = new ServletPathSpec("/"); uri = "/some/path"; - m = new ServletPathMapping(spec, "Default", uri); + matched = spec.matched(uri); + m = new ServletPathMapping(spec, "Default", uri, matched); assertThat(m.getMappingMatch(), is(MappingMatch.DEFAULT)); assertThat(m.getMatchValue(), is("")); assertThat(m.getPattern(), is("/")); assertThat(m.getServletName(), is("Default")); - assertThat(m.getServletPath(), is(spec.getPathMatch(uri))); - assertThat(m.getPathInfo(), is(spec.getPathInfo(uri))); + assertThat(m.getServletPath(), is("/some/path")); + assertThat(m.getPathInfo(), nullValue()); spec = new ServletPathSpec("/foo/*"); uri = "/foo/bar"; - m = new ServletPathMapping(spec, "FooServlet", uri); + matched = spec.matched(uri); + m = new ServletPathMapping(spec, "FooServlet", uri, matched); assertThat(m.getMappingMatch(), is(MappingMatch.PATH)); assertThat(m.getMatchValue(), is("foo")); assertThat(m.getPattern(), is("/foo/*")); assertThat(m.getServletName(), is("FooServlet")); - assertThat(m.getServletPath(), is(spec.getPathMatch(uri))); - assertThat(m.getPathInfo(), is(spec.getPathInfo(uri))); + assertThat(m.getServletPath(), is("/foo")); + assertThat(m.getPathInfo(), is("/bar")); uri = "/foo/"; - m = new ServletPathMapping(spec, "FooServlet", uri); + matched = spec.matched(uri); + m = new ServletPathMapping(spec, "FooServlet", uri, matched); assertThat(m.getMappingMatch(), is(MappingMatch.PATH)); assertThat(m.getMatchValue(), is("foo")); assertThat(m.getPattern(), is("/foo/*")); assertThat(m.getServletName(), is("FooServlet")); - assertThat(m.getServletPath(), is(spec.getPathMatch(uri))); - assertThat(m.getPathInfo(), is(spec.getPathInfo(uri))); + assertThat(m.getServletPath(), is("/foo")); + assertThat(m.getPathInfo(), is("/")); uri = "/foo"; - m = new ServletPathMapping(spec, "FooServlet", uri); + matched = spec.matched(uri); + m = new ServletPathMapping(spec, "FooServlet", uri, matched); assertThat(m.getMappingMatch(), is(MappingMatch.PATH)); assertThat(m.getMatchValue(), is("foo")); assertThat(m.getPattern(), is("/foo/*")); assertThat(m.getServletName(), is("FooServlet")); - assertThat(m.getServletPath(), is(spec.getPathMatch(uri))); - assertThat(m.getPathInfo(), is(spec.getPathInfo(uri))); + assertThat(m.getServletPath(), is("/foo")); + assertThat(m.getPathInfo(), nullValue()); spec = new ServletPathSpec("*.jsp"); uri = "/foo/bar.jsp"; - m = new ServletPathMapping(spec, "JspServlet", uri); + matched = spec.matched(uri); + m = new ServletPathMapping(spec, "JspServlet", uri, matched); assertThat(m.getMappingMatch(), is(MappingMatch.EXTENSION)); assertThat(m.getMatchValue(), is("foo/bar")); assertThat(m.getPattern(), is("*.jsp")); assertThat(m.getServletName(), is("JspServlet")); - assertThat(m.getServletPath(), is(spec.getPathMatch(uri))); - assertThat(m.getPathInfo(), is(spec.getPathInfo(uri))); + assertThat(m.getServletPath(), is("/foo/bar.jsp")); + assertThat(m.getPathInfo(), nullValue()); spec = new ServletPathSpec("/catalog"); uri = "/catalog"; - m = new ServletPathMapping(spec, "CatalogServlet", uri); + matched = spec.matched(uri); + m = new ServletPathMapping(spec, "CatalogServlet", uri, matched); assertThat(m.getMappingMatch(), is(MappingMatch.EXACT)); assertThat(m.getMatchValue(), is("catalog")); assertThat(m.getPattern(), is("/catalog")); assertThat(m.getServletName(), is("CatalogServlet")); - assertThat(m.getServletPath(), is(spec.getPathMatch(uri))); - assertThat(m.getPathInfo(), is(spec.getPathInfo(uri))); + assertThat(m.getServletPath(), is("/catalog")); + assertThat(m.getPathInfo(), nullValue()); } @Test @@ -2102,7 +2112,7 @@ public void testRegexPathMapping() ServletPathMapping m; spec = new RegexPathSpec("^/.*$"); - m = new ServletPathMapping(spec, "Something", "/some/path"); + m = new ServletPathMapping(spec, "Something", "/some/path", spec.matched("/some/path")); assertThat(m.getMappingMatch(), nullValue()); assertThat(m.getPattern(), is(spec.getDeclaration())); assertThat(m.getServletName(), is("Something")); @@ -2111,7 +2121,7 @@ public void testRegexPathMapping() assertThat(m.getMatchValue(), is("some/path")); spec = new RegexPathSpec("^/some(/.*)?$"); - m = new ServletPathMapping(spec, "Something", "/some/path"); + m = new ServletPathMapping(spec, "Something", "/some/path", spec.matched("/some/path")); assertThat(m.getMappingMatch(), nullValue()); assertThat(m.getPattern(), is(spec.getDeclaration())); assertThat(m.getServletName(), is("Something")); @@ -2119,7 +2129,7 @@ public void testRegexPathMapping() assertThat(m.getPathInfo(), is("/path")); assertThat(m.getMatchValue(), is("some")); - m = new ServletPathMapping(spec, "Something", "/some"); + m = new ServletPathMapping(spec, "Something", "/some", spec.matched("/some")); assertThat(m.getMappingMatch(), nullValue()); assertThat(m.getPattern(), is(spec.getDeclaration())); assertThat(m.getServletName(), is("Something")); diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java index c187ccc64923..7c14b7c058cb 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java @@ -1563,7 +1563,7 @@ public static class MappedServlet switch (pathSpec.getGroup()) { case EXACT: - _servletPathMapping = new ServletPathMapping(_pathSpec, _servletHolder.getName(), _pathSpec.getPrefix()); + _servletPathMapping = new ServletPathMapping(_pathSpec, _servletHolder.getName(), _pathSpec.getDeclaration()); break; case ROOT: _servletPathMapping = new ServletPathMapping(_pathSpec, _servletHolder.getName(), "/"); From eb36ebfe20ac4b7d496024ee3fa7fd76e13faa5a Mon Sep 17 00:00:00 2001 From: Joakim Erdfelt Date: Wed, 8 Jun 2022 10:52:34 -0500 Subject: [PATCH 7/7] Update WebSocketMappings to use new PathMappings.getMatched(String) Signed-off-by: Joakim Erdfelt --- .../eclipse/jetty/websocket/core/server/WebSocketMappings.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jetty-websocket/websocket-core-server/src/main/java/org/eclipse/jetty/websocket/core/server/WebSocketMappings.java b/jetty-websocket/websocket-core-server/src/main/java/org/eclipse/jetty/websocket/core/server/WebSocketMappings.java index 2f1831d08395..068d9c509bc1 100644 --- a/jetty-websocket/websocket-core-server/src/main/java/org/eclipse/jetty/websocket/core/server/WebSocketMappings.java +++ b/jetty-websocket/websocket-core-server/src/main/java/org/eclipse/jetty/websocket/core/server/WebSocketMappings.java @@ -20,6 +20,7 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.pathmap.MappedResource; +import org.eclipse.jetty.http.pathmap.MatchedResource; import org.eclipse.jetty.http.pathmap.PathMappings; import org.eclipse.jetty.http.pathmap.PathSpec; import org.eclipse.jetty.http.pathmap.RegexPathSpec; @@ -208,7 +209,7 @@ public boolean removeMapping(PathSpec pathSpec) */ public WebSocketNegotiator getMatchedNegotiator(String target, Consumer pathSpecConsumer) { - MappedResource mapping = this.mappings.getMatch(target); + MatchedResource mapping = this.mappings.getMatched(target); if (mapping == null) return null;