This is an automated email from the ASF dual-hosted git repository. Croway pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/camel.git
commit 95f2d34b1f3e25347b6a73a243305f48ae81c8be Author: croway <[email protected]> AuthorDate: Mon Nov 23 18:56:08 2026 +0100 CAMEL-27453: camel-ftp - handleDirectoryParserAbsoluteResult: change into a listed directory by its name With handleDirectoryParserAbsoluteResult, a recursive poll changed into a listed sub directory by the absolute path that the server listed, and built the path of its files from it, so the files could not be downloaded, and a listed directory outside the polled directory was changed into. Change into the directory by its name, relative to the directory being listed, and skip a listed directory whose absolute path is not in that directory. The absolute path of a listed directory may start with / or with a drive or a backslash, as a server on Windows can list it. A relative listed directory is taken only when it is one name, a directory name of . or .. is refused also when not stepwise, and a listed file is still matched by the name the server listed, so that filters with a path keep matching it. --- .../camel/component/file/remote/FtpUtils.java | 2 +- .../camel/component/file/remote/FtpConsumer.java | 58 ++++++++- .../camel/component/file/remote/FakeFtpServer.java | 8 +- .../remote/FtpConsumerListedDirectoryNameTest.java | 130 ++++++++++++++++++++- .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 10 ++ 5 files changed, 196 insertions(+), 12 deletions(-) diff --git a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/FtpUtils.java b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/FtpUtils.java index d7438002f3d9..c94a9a5c6e5c 100644 --- a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/FtpUtils.java +++ b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/FtpUtils.java @@ -42,7 +42,7 @@ public final class FtpUtils { public static String extractDirNameFromAbsolutePath(String path) { // default is unix so try with '/' // otherwise force File.separator - if (path.endsWith("/") || path.endsWith("\\")) { + while (path.length() > 1 && (path.endsWith("/") || path.endsWith("\\"))) { path = path.substring(0, path.length() - 1); } return FileUtil.stripPath(path); diff --git a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpConsumer.java b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpConsumer.java index 43b7af393a2f..26947aae1eb1 100644 --- a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpConsumer.java +++ b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpConsumer.java @@ -201,21 +201,26 @@ public class FtpConsumer extends RemoteFileConsumer<FTPFile> { if (endpoint.isRecursive() && depth < endpoint.getMaxDepth()) { // a server that lists the absolute path of each entry (handleDirectoryParserAbsoluteResult) names the directory // by its last segment - String directoryName = ((FtpConfiguration) endpoint.getConfiguration()).isHandleDirectoryParserAbsoluteResult() - ? FtpUtils.extractDirNameFromAbsolutePath(file.getName()) : file.getName(); - if (isStepwise() && !FtpUtils.isSubDirectoryName(directoryName)) { + boolean absoluteResult = ((FtpConfiguration) endpoint.getConfiguration()).isHandleDirectoryParserAbsoluteResult(); + String directoryName = absoluteResult ? FtpUtils.extractDirNameFromAbsolutePath(file.getName()) : file.getName(); + if ((isStepwise() || absoluteResult) && !FtpUtils.isSubDirectoryName(directoryName)) { LOG.debug("Skipping directory as its name is not the name of a directory in {}: {}", absolutePath, file.getName()); return false; } + if (absoluteResult && !isListedIn(file.getName(), absolutePath, directoryName)) { + LOG.debug("Skipping directory as its absolute path is not in {}: {}", absolutePath, file.getName()); + return false; + } // calculate the absolute file path using util class String absoluteFilePath = absoluteFilePath(absolutePath, file.getName()); Supplier<GenericFile<FTPFile>> remote = Suppliers.memorize(() -> asRemoteFile(absolutePath, absoluteFilePath, file, getEndpoint().getCharset())); Supplier<String> relativePath = getRelativeFilePath(endpointPath, null, absolutePath, file); - if (isValidFile(dynamic, remote, file.getName(), absoluteFilePath, relativePath, true, files)) { - // recursive scan and add the sub files and folders - String subDirectory = file.getName(); + if (isValidFile(dynamic, remote, directoryName, absoluteFilePath, relativePath, true, files)) { + // recursive scan and add the sub files and folders, changing into the directory by its name, relative + // to the directory being listed + String subDirectory = directoryName; String path = ObjectHelper.isNotEmpty(absolutePath) ? absolutePath + "/" + subDirectory : subDirectory; boolean canPollMore = pollSubDirectory(dynamic, path, subDirectory, fileList, depth); if (!canPollMore) { @@ -226,6 +231,47 @@ public class FtpConsumer extends RemoteFileConsumer<FTPFile> { return false; } + /** + * Whether a directory entry, as listed by the server, is in the directory being listed. A server that lists the + * absolute path of each entry (handleDirectoryParserAbsoluteResult) lists the entries of the listed directory, so + * the absolute path ends with the path of the listed directory and the name of the entry. A relative name must be + * the name of the entry, followed by / at most, as a relative path of more than one name is not an entry of the + * listed directory. Both paths are compacted first. + * + * @param listed the name of the entry as listed + * @param absolutePath the path of the listed directory + * @param directoryName the name of the entry + * @return <tt>true</tt> if the entry is in the listed directory + */ + private static boolean isListedIn(String listed, String absolutePath, String directoryName) { + if (!isAbsolute(listed)) { + // one name, which may end with a /, as a relative path of more than one name is not an entry of the listed + // directory + String name = listed; + while (name.length() > 1 && name.endsWith("/")) { + name = name.substring(0, name.length() - 1); + } + return name.indexOf('/') == -1 && name.indexOf('\\') == -1 && name.equals(directoryName); + } + String path = GenericFileHelper.compactPathForContainment(listed, '/'); + String directory = FileUtil.stripLeadingSeparator( + GenericFileHelper.compactPathForContainment(absolutePath != null ? absolutePath : "", '/')); + String expected = directory.isEmpty() ? directoryName : directory + "/" + directoryName; + return path.endsWith("/" + expected); + } + + /** + * Whether a path from a listing starts at a root: with a / or a \, or with a drive such as C:/ or C:\. + */ + private static boolean isAbsolute(String path) { + char first = path.charAt(0); + if (first == '/' || first == '\\') { + return true; + } + return path.length() > 2 && path.charAt(1) == ':' && (path.charAt(2) == '/' || path.charAt(2) == '\\') + && (first >= 'a' && first <= 'z' || first >= 'A' && first <= 'Z'); + } + private void handleFile( Exchange dynamic, String absolutePath, List<GenericFile<FTPFile>> fileList, int depth, FTPFile[] files, FTPFile file) { diff --git a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FakeFtpServer.java b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FakeFtpServer.java index f8fd3876acb2..1bab08ef1367 100644 --- a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FakeFtpServer.java +++ b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FakeFtpServer.java @@ -70,6 +70,7 @@ final class FakeFtpServer implements Closeable { private final Map<String, byte[]> files = new ConcurrentHashMap<>(); private final Set<String> directories = ConcurrentHashMap.newKeySet(); private final Map<String, List<String>> listedDirectories = new ConcurrentHashMap<>(); + private volatile boolean absoluteNames; private final List<Connection> connections = new CopyOnWriteArrayList<>(); private final List<String> commands = new CopyOnWriteArrayList<>(); private final AtomicInteger connectionIds = new AtomicInteger(); @@ -97,6 +98,11 @@ final class FakeFtpServer implements Closeable { files.put(file, content); } + /** Lists the absolute path of each file, as some servers do, instead of its name. */ + void listAbsoluteNames() { + absoluteNames = true; + } + /** * Lists a directory entry with the given name in the listing of the directory, whatever the name is, as a server * can. @@ -298,7 +304,7 @@ final class FakeFtpServer implements Closeable { StringBuilder listing = new StringBuilder(); for (Map.Entry<String, byte[]> e : new TreeMap<>(files).entrySet()) { if (parentOf(e.getKey()).equals(dir)) { - String name = e.getKey().substring(e.getKey().lastIndexOf('/') + 1); + String name = absoluteNames ? e.getKey() : e.getKey().substring(e.getKey().lastIndexOf('/') + 1); if (cmd.equals("NLST")) { listing.append(name).append("\r\n"); } else { diff --git a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpConsumerListedDirectoryNameTest.java b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpConsumerListedDirectoryNameTest.java index 873f81b26638..fa8684187875 100644 --- a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpConsumerListedDirectoryNameTest.java +++ b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpConsumerListedDirectoryNameTest.java @@ -85,26 +85,148 @@ class FtpConsumerListedDirectoryNameTest extends CamelTestSupport { @Test void pollsListedDirectoryWithAbsoluteNameOfServerListingAbsolutePaths() throws Exception { - // a server that lists the absolute path of each entry + assertPollsListedDirectoryWithAbsoluteName(""); + } + + @Test + void pollsListedDirectoryWithAbsoluteNameOfServerListingAbsolutePathsNotStepwise() throws Exception { + assertPollsListedDirectoryWithAbsoluteName("&stepwise=false"); + } + + private void assertPollsListedDirectoryWithAbsoluteName(String options) throws Exception { + // a server that lists the absolute path of each entry, in equivalent forms + server.listAbsoluteNames(); server.addFile("/inbox/real/deep.txt", "deep".getBytes(StandardCharsets.UTF_8)); + server.addFile("/inbox/second/two.txt", "two".getBytes(StandardCharsets.UTF_8)); + server.addFile("/inbox/third/three.txt", "three".getBytes(StandardCharsets.UTF_8)); server.addListedDirectory("/inbox", "/inbox/real"); + server.addListedDirectory("/inbox", "/inbox/second//"); + server.addListedDirectory("/inbox", "/inbox/./third"); + server.addFile("/inbox/fourth/four.txt", "four".getBytes(StandardCharsets.UTF_8)); + server.addFile("/inbox/fifth/five.txt", "five".getBytes(StandardCharsets.UTF_8)); + // a path with a drive, and with backslashes, as a server on Windows can list + server.addListedDirectory("/inbox", "C:/inbox/fourth"); + server.addListedDirectory("/inbox", "\\inbox\\fifth"); + List<String> received = pollInbox(options); + + // the poll changes into each listed directory by its name, and downloads its file + await().atMost(10, TimeUnit.SECONDS).until(() -> received.size() >= 5); + TimeUnit.MILLISECONDS.sleep(500); + assertEquals(List.of("fifth/five.txt=five", "fourth/four.txt=four", "real/deep.txt=deep", "second/two.txt=two", + "third/three.txt=three"), received.stream().sorted().toList()); + } + + @Test + void pollsListedRelativeDirectoryWithTrailingSeparator() throws Exception { + server.addFile("/inbox/child/report.txt", "report".getBytes(StandardCharsets.UTF_8)); + server.addListedDirectory("/inbox", "child/"); + List<String> received = pollInbox(""); + + await().atMost(10, TimeUnit.SECONDS).until(() -> received.contains("child/report.txt=report")); + } + + @Test + void entersListedAbsoluteDirectoryByItsNameInTheListedDirectory() throws Exception { + // /x/inbox/real ends like /inbox/real, but the poll changes into real in the listed directory + server.listAbsoluteNames(); + server.addFile("/inbox/real/deep.txt", "deep".getBytes(StandardCharsets.UTF_8)); + server.addFile("/x/inbox/real/other.txt", "other".getBytes(StandardCharsets.UTF_8)); + server.addListedDirectory("/inbox", "/x/inbox/real"); + List<String> received = pollInbox(""); + + await().atMost(10, TimeUnit.SECONDS).until(() -> !received.isEmpty()); + TimeUnit.MILLISECONDS.sleep(500); + assertEquals(List.of("real/deep.txt=deep"), received); + } + + @Test + void skipsListedDirectoriesThatAreNotOneDirectoryOfTheListedDirectory() throws Exception { + server.addFile("/inbox/hello.txt", "hello".getBytes(StandardCharsets.UTF_8)); + server.addFile("/inbox/.camel/archived.txt", "archived".getBytes(StandardCharsets.UTF_8)); + server.addFile("/inbox/group/child/grouped.txt", "grouped".getBytes(StandardCharsets.UTF_8)); + server.addFile("/inbox/child/single.txt", "single".getBytes(StandardCharsets.UTF_8)); + server.addFile("/inbox/real/deep.txt", "deep".getBytes(StandardCharsets.UTF_8)); + // a hidden directory by its absolute path, relative paths, and . and .. by their absolute paths + server.addListedDirectory("/inbox", "/inbox/.camel"); + server.addListedDirectory("/inbox", "group/child"); + server.addListedDirectory("/inbox", "missing/../child"); + // a relative name that ends with a backslash, and a drive root + server.addListedDirectory("/inbox", "child\\"); + server.addListedDirectory("/inbox", "C:/"); + server.addListedDirectory("/inbox", "/inbox/."); + server.addListedDirectory("/inbox", "/inbox/real/.."); + for (String options : new String[] { "", "&stepwise=false" }) { + List<String> listed = new CopyOnWriteArrayList<>(); + context.getRegistry().bind("listed", (GenericFileFilter<Object>) file -> { + listed.add(file.getFileNameOnly()); + return true; + }); + List<String> received = pollInbox(options + "&filter=#listed"); + + // the poll lists every directory it changes into before it hands over the first file + await().atMost(10, TimeUnit.SECONDS).until(() -> !received.isEmpty()); + assertEquals(List.of("hello.txt"), listed, options); + assertEquals(List.of("hello.txt=hello"), received, options); + context.getRouteController().stopRoute("poll"); + context.removeRoute("poll"); + } + } + + @Test + void skipsListedAbsoluteDirectoryThatIsNotInTheListedDirectory() throws Exception { + // a server that lists the absolute path of each entry, and lists /etc in /inbox + server.addFile("/inbox/hello.txt", "hello".getBytes(StandardCharsets.UTF_8)); + server.addFile("/etc/secret.txt", "secret".getBytes(StandardCharsets.UTF_8)); + server.addListedDirectory("/inbox", "/etc"); List<String> listed = new CopyOnWriteArrayList<>(); context.getRegistry().bind("listed", (GenericFileFilter<Object>) file -> { listed.add(file.getFileNameOnly()); return true; }); + List<String> received = new CopyOnWriteArrayList<>(); context.addRoutes(new RouteBuilder() { @Override public void configure() { from("ftp://[email protected]:" + server.port() + "/inbox?password=secret&passiveMode=true" + "&recursive=true&handleDirectoryParserAbsoluteResult=true&filter=#listed&noop=true" + "&initialDelay=0&delay=600000") - .to("mock:result"); + .process(e -> received.add(e.getMessage().getHeader(Exchange.FILE_NAME, String.class))); } }); - // the poll changes into the listed directory and lists its file - await().atMost(10, TimeUnit.SECONDS).until(() -> listed.contains("deep.txt")); + await().atMost(10, TimeUnit.SECONDS).until(() -> received.contains("hello.txt")); + TimeUnit.MILLISECONDS.sleep(500); + + assertEquals(List.of("hello.txt"), received); + assertFalse(listed.contains("secret.txt"), listed.toString()); + assertFalse(server.commands().stream().anyMatch(c -> c.equals("CWD /etc") || c.equals("CWD etc")), + server.commands().toString()); + } + + @Test + void downloadsNamedFileWithoutListing() throws Exception { + // the name of the file to download is not from a listing, and is matched as given + server.addFile("/inbox/report.txt", "report".getBytes(StandardCharsets.UTF_8)); + List<String> received = pollInbox("&useList=false&fileName=/inbox/report.txt"); + + await().atMost(10, TimeUnit.SECONDS).until(() -> received.contains("report.txt=report")); + } + + private List<String> pollInbox(String options) throws Exception { + List<String> received = new CopyOnWriteArrayList<>(); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from("ftp://[email protected]:" + server.port() + "/inbox?password=secret&passiveMode=true" + + "&recursive=true&handleDirectoryParserAbsoluteResult=true&noop=true&initialDelay=0&delay=600000" + + options) + .routeId("poll") + .convertBodyTo(String.class) + .process(e -> received.add(e.getMessage().getHeader(Exchange.FILE_NAME, String.class) + "=" + + e.getMessage().getBody(String.class))); + } + }); + return received; } @Test diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc index 9d89cf369ff7..fc5381c5fe67 100644 --- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc +++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc @@ -576,6 +576,16 @@ not refused. When the endpoint has a directory, an absolute name is relative to it, as before. To write files at absolute paths from an endpoint without a directory, set `jailStartingDirectory=false` on the endpoint. +=== camel-ftp - handleDirectoryParserAbsoluteResult: a recursive poll changes into a listed directory by its name + +With `handleDirectoryParserAbsoluteResult=true` (for a server that lists the absolute path of each entry), a recursive +poll now changes into a listed sub directory by its name, relative to the directory that it lists, instead of the +absolute path that the server listed, and skips a listed directory whose absolute path is not in the directory that it +lists. The files of such a sub directory are now downloaded from that directory; before, their download could fail, as +their path was built from the absolute path of the sub directory. A listed sub directory is matched by its name, so a +hidden directory (whose name starts with a dot) is skipped, as with other servers. Listed files are matched as listed, +as before. + === camel-ai-resource - fixed resourceUri cannot contain braces Starting in Camel 4.24, `ai-resource` rejects a fixed `resourceUri` containing `{` or `}` at route startup. The MCP SDK interprets those characters as URI-template expressions. Routes that intend variable path segments must use `uriTemplate` instead, for example `+ai-resource:customer?uriTemplate=camel:///customers/{id}+`. If the braces are literal URI characters, percent-encode them as `%7B` and `%7D`.
