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 8dca61cd4b1d025f286d97822adc8b4f50b252e4
Author: croway <[email protected]>
AuthorDate: Mon Nov 23 18:56:07 2026 +0100

    CAMEL-27453: camel-ftp, camel-mina-sftp - stepwise: stay in the current 
directory for a path that compacts to it
    
    A stepwise change of directory compacts the path, and changes up when the
    current directory starts with it. A relative path that compacts to empty,
    such as sub/.., is the current directory, but every current directory
    starts with the empty string, so the change went up to the root of the
    server. Stay in the current directory for such a path, and only change up
    when the path is the current directory or one of its parent directories,
    not a path that merely starts with the same characters.
    
    A stepwise recursive poll changes into a listed directory one segment at
    a time, and back to its parent afterwards, so it now skips a listed
    directory whose name is not the name of one directory: blank, . or .., or
    with a / or a \ in it, such as sub/.., which would otherwise leave the
    poll in another directory. With handleDirectoryParserAbsoluteResult, the
    name checked is the last segment of the listed absolute path.
---
 .../file/remote/AbstractSftpConsumer.java          |   5 +
 .../camel/component/file/remote/FtpUtils.java      |  14 ++
 .../camel/component/file/remote/FtpConsumer.java   |   9 ++
 .../component/file/remote/SftpOperations.java      |  17 ++-
 .../camel/component/file/remote/FakeFtpServer.java |  16 ++
 .../remote/FtpConsumerListedDirectoryNameTest.java | 128 ++++++++++++++++
 .../sftp/integration/HomeDirectorySftpServer.java  |  79 ++++++++++
 .../integration/SftpStepwiseChangeDirectoryIT.java | 143 ++++++++++++++++++
 .../file/remote/mina/MinaSftpOperations.java       |  17 ++-
 .../mina/integration/HomeDirectorySftpServer.java  |  79 ++++++++++
 .../MinaSftpStepwiseChangeDirectoryIT.java         | 165 +++++++++++++++++++++
 11 files changed, 668 insertions(+), 4 deletions(-)

diff --git 
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/AbstractSftpConsumer.java
 
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/AbstractSftpConsumer.java
index 3fac8170f33f..3b79ac4b6128 100644
--- 
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/AbstractSftpConsumer.java
+++ 
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/AbstractSftpConsumer.java
@@ -299,6 +299,11 @@ public abstract class AbstractSftpConsumer extends 
RemoteFileConsumer<SftpRemote
 
         if (file.isDirectory()) {
             if (endpoint.isRecursive() && depth < endpoint.getMaxDepth()) {
+                if (isStepwise() && 
!FtpUtils.isSubDirectoryName(file.getFilename())) {
+                    LOG.debug("Skipping directory as its name is not the name 
of a directory in {}: {}", absolutePath,
+                            file.getFilename());
+                    return true;
+                }
                 String absoluteFilePath = 
FtpUtils.absoluteFilePath(absolutePath, file.getFilename());
                 Supplier<GenericFile<SftpRemoteFile>> remote
                         = Suppliers.memorize(
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 9048966fce18..d7438002f3d9 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
@@ -142,6 +142,20 @@ public final class FtpUtils {
         }
     }
 
+    /**
+     * Whether a directory name from a listing of the server is the name of 
one directory in the listed directory: not
+     * blank, not . or .., and without a / or a \. A stepwise recursive poll 
changes into such a directory one segment
+     * at a time, and back to its parent afterwards, so a name such as sub/.. 
or a\b would leave the poll in another
+     * directory than the listed one.
+     *
+     * @param  name the name of the directory, as listed
+     * @return      <tt>true</tt> if the poll can change into the directory
+     */
+    public static boolean isSubDirectoryName(String name) {
+        return name != null && !name.isBlank() && !".".equals(name) && 
!"..".equals(name) && name.indexOf('/') == -1
+                && name.indexOf('\\') == -1;
+    }
+
     public static String absoluteFilePath(String absolutePath, String name) {
         boolean absolute = FileUtil.hasLeadingSeparator(absolutePath);
 
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 2a7cf6dc4a68..43b7af393a2f 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
@@ -199,6 +199,15 @@ public class FtpConsumer extends 
RemoteFileConsumer<FTPFile> {
             Exchange dynamic,
             String absolutePath, List<GenericFile<FTPFile>> fileList, int 
depth, FTPFile[] files, FTPFile file) {
         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)) {
+                LOG.debug("Skipping directory as its name is not the name of a 
directory in {}: {}", absolutePath,
+                        file.getName());
+                return false;
+            }
             // calculate the absolute file path using util class
             String absoluteFilePath = absoluteFilePath(absolutePath, 
file.getName());
             Supplier<GenericFile<FTPFile>> remote
diff --git 
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
 
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
index d350ffc2d9b7..eb54b1fb95bc 100644
--- 
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
+++ 
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
@@ -1123,16 +1123,21 @@ public class SftpOperations
             if (LOG.isTraceEnabled()) {
                 LOG.trace("Compacted path: {} -> {} using separator: {}", 
before, path, separatorChar);
             }
+            if (path.isEmpty()) {
+                // the path is the current directory (such as sub/..), so stay 
in it
+                return;
+            }
 
             // not stepwise should change directory in one operation
             if (!endpoint.getConfiguration().isStepwise()) {
                 doChangeDirectory(path);
                 return;
             }
-            if (getCurrentDirectory().startsWith(path)) {
+            String current = getCurrentDirectory();
+            if (isDirectoryOrParentOf(path, current)) {
                 // extract the path segment relative to the target path and 
make
                 // sure it keeps the preceding '/' for the regex op
-                String p = getCurrentDirectory().substring(path.length() - 
(path.endsWith("/") ? 1 : 0));
+                String p = current.substring(path.length() - 
(path.endsWith("/") ? 1 : 0));
                 if (p.isEmpty()) {
                     return;
                 }
@@ -1176,6 +1181,14 @@ public class SftpOperations
         }
     }
 
+    /**
+     * Whether the path is the directory itself or one of its parent 
directories. A path that only starts with the same
+     * characters, such as /home/cam for /home/camel, is not.
+     */
+    private static boolean isDirectoryOrParentOf(String path, String 
directory) {
+        return directory.equals(path) || 
directory.startsWith(path.endsWith("/") ? path : path + "/");
+    }
+
     private void doChangeDirectory(String path) {
         if (path == null || ".".equals(path) || ObjectHelper.isEmpty(path)) {
             return;
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 19a0028cf9db..f8fd3876acb2 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
@@ -69,6 +69,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 final List<Connection> connections = new CopyOnWriteArrayList<>();
     private final List<String> commands = new CopyOnWriteArrayList<>();
     private final AtomicInteger connectionIds = new AtomicInteger();
@@ -96,6 +97,14 @@ final class FakeFtpServer implements Closeable {
         files.put(file, content);
     }
 
+    /**
+     * Lists a directory entry with the given name in the listing of the 
directory, whatever the name is, as a server
+     * can.
+     */
+    void addListedDirectory(String directory, String name) {
+        listedDirectories.computeIfAbsent(normalize(directory), d -> new 
CopyOnWriteArrayList<>()).add(name);
+    }
+
     Map<String, byte[]> files() {
         return files;
     }
@@ -298,6 +307,13 @@ final class FakeFtpServer implements Closeable {
                     }
                 }
             }
+            for (String name : listedDirectories.getOrDefault(dir, List.of())) 
{
+                if (cmd.equals("NLST")) {
+                    listing.append(name).append("\r\n");
+                } else {
+                    listing.append("drwxr-xr-x 1 camel camel 0 Jan 01  2025 
").append(name).append("\r\n");
+                }
+            }
             transfer(listing.toString().getBytes(StandardCharsets.UTF_8));
         }
 
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
new file mode 100644
index 000000000000..873f81b26638
--- /dev/null
+++ 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpConsumerListedDirectoryNameTest.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.remote;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.file.GenericFileFilter;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A recursive stepwise poll changes into a listed directory, and back to its 
parent afterwards. Verifies that a listed
+ * directory name that is not the name of one directory in the listed 
directory, such as sub/.. or a blank name, is
+ * skipped rather than leaving the poll in another directory.
+ */
+class FtpConsumerListedDirectoryNameTest extends CamelTestSupport {
+
+    private FakeFtpServer server;
+
+    @BeforeEach
+    void startServer() throws Exception {
+        server = new FakeFtpServer();
+    }
+
+    @AfterEach
+    void stopServer() throws Exception {
+        server.close();
+    }
+
+    @Test
+    void skipsListedDirectoryThatIsNotADirectoryInTheListedDirectory() throws 
Exception {
+        server.addFile("/inbox/hello.txt", 
"hello".getBytes(StandardCharsets.UTF_8));
+        server.addFile("/inbox/real/deep.txt", 
"deep".getBytes(StandardCharsets.UTF_8));
+        server.addFile("/outside.txt", 
"outside".getBytes(StandardCharsets.UTF_8));
+        server.addListedDirectory("/inbox", "sub/..");
+        server.addListedDirectory("/inbox", "sub\\..");
+        server.addListedDirectory("/inbox", " ");
+        server.addListedDirectory("/inbox", "real");
+        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&maxDepth=3&noop=true&initialDelay=0&delay=600000")
+                        .process(e -> 
received.add(e.getMessage().getHeader(Exchange.FILE_NAME, String.class)));
+            }
+        });
+
+        await().atMost(10, TimeUnit.SECONDS).until(() -> received.size() >= 2);
+        // nothing more arrives: the poll does not list the inbox again 
through sub/..
+        TimeUnit.MILLISECONDS.sleep(500);
+
+        assertEquals(2, received.size(), received.toString());
+        assertTrue(received.contains("hello.txt"), received.toString());
+        assertTrue(received.contains("real/deep.txt"), received.toString());
+        // the poll never changes into the listed names
+        assertFalse(server.commands().stream().anyMatch(c -> c.startsWith("CWD 
sub")), server.commands().toString());
+    }
+
+    @Test
+    void pollsListedDirectoryWithAbsoluteNameOfServerListingAbsolutePaths() 
throws Exception {
+        // a server that lists the absolute path of each entry
+        server.addFile("/inbox/real/deep.txt", 
"deep".getBytes(StandardCharsets.UTF_8));
+        server.addListedDirectory("/inbox", "/inbox/real");
+        List<String> listed = new CopyOnWriteArrayList<>();
+        context.getRegistry().bind("listed", (GenericFileFilter<Object>) file 
-> {
+            listed.add(file.getFileNameOnly());
+            return true;
+        });
+        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");
+            }
+        });
+
+        // the poll changes into the listed directory and lists its file
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
listed.contains("deep.txt"));
+    }
+
+    @Test
+    void subDirectoryNames() {
+        assertTrue(FtpUtils.isSubDirectoryName("sub"));
+        assertTrue(FtpUtils.isSubDirectoryName("a..b"));
+        assertTrue(FtpUtils.isSubDirectoryName("...dir"));
+        assertTrue(FtpUtils.isSubDirectoryName("http:"));
+        assertTrue(FtpUtils.isSubDirectoryName(" a "));
+        assertFalse(FtpUtils.isSubDirectoryName(null));
+        assertFalse(FtpUtils.isSubDirectoryName(""));
+        assertFalse(FtpUtils.isSubDirectoryName("."));
+        assertFalse(FtpUtils.isSubDirectoryName(".."));
+        assertFalse(FtpUtils.isSubDirectoryName("sub/.."));
+        assertFalse(FtpUtils.isSubDirectoryName("sub/dir"));
+        assertFalse(FtpUtils.isSubDirectoryName("sub\\.."));
+        assertFalse(FtpUtils.isSubDirectoryName("\\sub"));
+        assertFalse(FtpUtils.isSubDirectoryName("a\\b"));
+        assertFalse(FtpUtils.isSubDirectoryName(" "));
+    }
+}
diff --git 
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/HomeDirectorySftpServer.java
 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/HomeDirectorySftpServer.java
new file mode 100644
index 000000000000..304fff21e757
--- /dev/null
+++ 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/HomeDirectorySftpServer.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.remote.sftp.integration;
+
+import java.io.IOException;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.server.channel.ChannelSession;
+import org.apache.sshd.server.command.Command;
+import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
+import org.apache.sshd.sftp.server.DirectoryHandle;
+import org.apache.sshd.sftp.server.SftpSubsystem;
+import org.apache.sshd.sftp.server.SftpSubsystemFactory;
+
+/**
+ * An SFTP server whose root is a local directory and whose login directory is 
a directory below it, as on most servers,
+ * and that can report a listed file or directory under another name.
+ */
+final class HomeDirectorySftpServer {
+
+    private HomeDirectorySftpServer() {
+    }
+
+    /**
+     * @param root    the local directory that is the root of the server
+     * @param home    the login directory, an absolute path on the server
+     * @param renames the names to report in a listing instead of the names of 
the files and directories
+     */
+    static SshServer start(Path root, String home, Map<String, String> 
renames) throws IOException {
+        SshServer sshd = SshServer.setUpDefaultServer();
+        sshd.setPort(0);
+        sshd.setKeyPairProvider(new 
SimpleGeneratorHostKeyProvider(root.resolveSibling("hostkey.ser")));
+        sshd.setPasswordAuthenticator((username, password, session) -> true);
+        sshd.setFileSystemFactory(new 
VirtualFileSystemFactory(root.toAbsolutePath()));
+        SftpSubsystemFactory factory = new SftpSubsystemFactory() {
+            @Override
+            public Command createSubsystem(ChannelSession channel) throws 
IOException {
+                return new SftpSubsystem(channel, this) {
+                    @Override
+                    public Path getDefaultDirectory() {
+                        return fileSystem.getPath(home);
+                    }
+
+                    @Override
+                    protected void writeDirEntry(
+                            int id, DirectoryHandle dir, Map<String, Path> 
entries, Buffer buffer, int index, Path f,
+                            String shortName, LinkOption... options)
+                            throws IOException {
+                        super.writeDirEntry(id, dir, entries, buffer, index, 
f, renames.getOrDefault(shortName, shortName),
+                                options);
+                    }
+                };
+            }
+        };
+        sshd.setSubsystemFactories(List.of(factory));
+        sshd.start();
+        return sshd;
+    }
+}
diff --git 
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseChangeDirectoryIT.java
 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseChangeDirectoryIT.java
new file mode 100644
index 000000000000..0911dcdc8df1
--- /dev/null
+++ 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseChangeDirectoryIT.java
@@ -0,0 +1,143 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.remote.sftp.integration;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.file.GenericFileFilter;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.sshd.server.SshServer;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A stepwise operation changes into the directory of a file one segment at a 
time. Verifies that a directory that is
+ * the current directory once compacted, such as sub/.., is not taken as a 
parent of the current directory, on a server
+ * whose login directory is not its root.
+ */
+class SftpStepwiseChangeDirectoryIT extends CamelTestSupport {
+
+    private final Set<String> listed = ConcurrentHashMap.newKeySet();
+    private Path root;
+    private SshServer sshd;
+
+    private void startServer(Map<String, String> renames) throws Exception {
+        root = Paths.get("target", "sftp-home", getClass().getSimpleName() + 
"-" + System.nanoTime(), "root")
+                .toAbsolutePath();
+        Files.createDirectories(root.resolve("home/camel/inbox/sub"));
+        Files.createDirectories(root.resolve("home/camel/inbox/real"));
+        Files.createDirectories(root.resolve("home/camel/inbox/blank"));
+        Files.writeString(root.resolve("home/camel/inbox/real/deep.txt"), 
"Deep in the inbox");
+        Files.writeString(root.resolve("home/camel/inbox/hello.txt"), "Hello 
from the inbox");
+        Files.writeString(root.resolve("home/camel/listed.txt"), "Hello from 
the login directory");
+        Files.writeString(root.resolve("outside.txt"), "Outside the login 
directory");
+        sshd = HomeDirectorySftpServer.start(root, "/home/camel", renames);
+    }
+
+    @AfterEach
+    void stopServer() throws Exception {
+        if (sshd != null) {
+            sshd.stop();
+        }
+    }
+
+    private String uri(String directory, String options) {
+        return "sftp://camel@localhost:"; + sshd.getPort() + "/" + directory
+               + 
"?password=secret&strictHostKeyChecking=no&useUserKnownHostsFile=false" + 
options;
+    }
+
+    @Test
+    void uploadIntoCurrentDirectory() throws Exception {
+        startServer(Map.of());
+
+        template.sendBodyAndHeader(uri("", ""), "Hello", Exchange.FILE_NAME, 
"sub/../uploaded.txt");
+
+        assertTrue(Files.exists(root.resolve("home/camel/uploaded.txt")));
+        assertFalse(Files.exists(root.resolve("uploaded.txt")));
+    }
+
+    @Test
+    void downloadFromCurrentDirectory() throws Exception {
+        // the server lists listed.txt as sub/../outside.txt, which is not in 
the login directory
+        startServer(Map.of("listed.txt", "sub/../outside.txt"));
+        Files.writeString(root.resolve("home/camel/real.txt"), "Real file in 
the login directory");
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        // the real file shows the poll was done, and nothing else is 
downloaded
+        mock.expectedBodiesReceived("Real file in the login directory");
+        mock.setAssertPeriod(1000);
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(uri("", 
"&delete=true&initialDelay=0&delay=60000")).convertBodyTo(String.class).to("mock:result");
+            }
+        });
+
+        mock.assertIsSatisfied();
+        assertTrue(Files.exists(root.resolve("outside.txt")));
+    }
+
+    @Test
+    void uploadIntoAbsoluteDirectoryWhoseNameStartsLikeTheLoginDirectory() 
throws Exception {
+        // /home/cam is not a parent of the login directory /home/camel
+        startServer(Map.of());
+        Files.createDirectories(root.resolve("home/cam"));
+
+        template.sendBodyAndHeader(uri("", "&jailStartingDirectory=false"), 
"Hello", Exchange.FILE_NAME, "/home/cam/cam.txt");
+
+        assertTrue(Files.exists(root.resolve("home/cam/cam.txt")));
+    }
+
+    @Test
+    void pollSubDirectoryThatIsTheCurrentDirectory() throws Exception {
+        // the server lists the sub directory of the inbox as sub/.., which is 
the inbox, and another one with a blank
+        // name, and the poll skips both
+        startServer(Map.of("sub", "sub/..", "blank", " "));
+        context.getRegistry().bind("listed", (GenericFileFilter<Object>) file 
-> {
+            listed.add(file.getFileNameOnly());
+            return true;
+        });
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedBodiesReceivedInAnyOrder("Hello from the inbox", "Deep in 
the inbox");
+        mock.setAssertPeriod(1000);
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(uri("inbox", 
"&recursive=true&maxDepth=3&noop=true&filter=#listed&initialDelay=0&delay=60000"))
+                        .convertBodyTo(String.class).to("mock:result");
+            }
+        });
+
+        mock.assertIsSatisfied();
+        // nothing is listed outside the inbox
+        assertFalse(listed.contains("outside.txt"), listed.toString());
+        assertFalse(listed.contains("home"), listed.toString());
+        assertFalse(listed.contains("listed.txt"), listed.toString());
+    }
+}
diff --git 
a/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
 
b/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
index 338d1c11afbe..26983a0c4303 100644
--- 
a/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
+++ 
b/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
@@ -1143,16 +1143,21 @@ public class MinaSftpOperations
             if (LOG.isTraceEnabled()) {
                 LOG.trace("Compacted path: {} -> {} using separator: {}", 
before, path, separatorChar);
             }
+            if (path.isEmpty()) {
+                // the path is the current directory (such as sub/..), so stay 
in it
+                return;
+            }
 
             // not stepwise should change directory in one operation
             if (!endpoint.getConfiguration().isStepwise()) {
                 doChangeDirectory(path);
                 return;
             }
-            if (getCurrentDirectory().startsWith(path)) {
+            String current = getCurrentDirectory();
+            if (isDirectoryOrParentOf(path, current)) {
                 // extract the path segment relative to the target path and 
make
                 // sure it keeps the preceding '/' for the regex op
-                String p = getCurrentDirectory().substring(path.length() - 
(path.endsWith("/") ? 1 : 0));
+                String p = current.substring(path.length() - 
(path.endsWith("/") ? 1 : 0));
                 if (p.isEmpty()) {
                     return;
                 }
@@ -1196,6 +1201,14 @@ public class MinaSftpOperations
         }
     }
 
+    /**
+     * Whether the path is the directory itself or one of its parent 
directories. A path that only starts with the same
+     * characters, such as /home/cam for /home/camel, is not.
+     */
+    private static boolean isDirectoryOrParentOf(String path, String 
directory) {
+        return directory.equals(path) || 
directory.startsWith(path.endsWith("/") ? path : path + "/");
+    }
+
     private void doChangeDirectory(String path) {
         if (path == null || ".".equals(path) || ObjectHelper.isEmpty(path)) {
             return;
diff --git 
a/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/HomeDirectorySftpServer.java
 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/HomeDirectorySftpServer.java
new file mode 100644
index 000000000000..52f246502fad
--- /dev/null
+++ 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/HomeDirectorySftpServer.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.remote.mina.integration;
+
+import java.io.IOException;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.server.channel.ChannelSession;
+import org.apache.sshd.server.command.Command;
+import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
+import org.apache.sshd.sftp.server.DirectoryHandle;
+import org.apache.sshd.sftp.server.SftpSubsystem;
+import org.apache.sshd.sftp.server.SftpSubsystemFactory;
+
+/**
+ * An SFTP server whose root is a local directory and whose login directory is 
a directory below it, as on most servers,
+ * and that can report a listed file or directory under another name.
+ */
+final class HomeDirectorySftpServer {
+
+    private HomeDirectorySftpServer() {
+    }
+
+    /**
+     * @param root    the local directory that is the root of the server
+     * @param home    the login directory, an absolute path on the server
+     * @param renames the names to report in a listing instead of the names of 
the files and directories
+     */
+    static SshServer start(Path root, String home, Map<String, String> 
renames) throws IOException {
+        SshServer sshd = SshServer.setUpDefaultServer();
+        sshd.setPort(0);
+        sshd.setKeyPairProvider(new 
SimpleGeneratorHostKeyProvider(root.resolveSibling("hostkey.ser")));
+        sshd.setPasswordAuthenticator((username, password, session) -> true);
+        sshd.setFileSystemFactory(new 
VirtualFileSystemFactory(root.toAbsolutePath()));
+        SftpSubsystemFactory factory = new SftpSubsystemFactory() {
+            @Override
+            public Command createSubsystem(ChannelSession channel) throws 
IOException {
+                return new SftpSubsystem(channel, this) {
+                    @Override
+                    public Path getDefaultDirectory() {
+                        return fileSystem.getPath(home);
+                    }
+
+                    @Override
+                    protected void writeDirEntry(
+                            int id, DirectoryHandle dir, Map<String, Path> 
entries, Buffer buffer, int index, Path f,
+                            String shortName, LinkOption... options)
+                            throws IOException {
+                        super.writeDirEntry(id, dir, entries, buffer, index, 
f, renames.getOrDefault(shortName, shortName),
+                                options);
+                    }
+                };
+            }
+        };
+        sshd.setSubsystemFactories(List.of(factory));
+        sshd.start();
+        return sshd;
+    }
+}
diff --git 
a/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpStepwiseChangeDirectoryIT.java
 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpStepwiseChangeDirectoryIT.java
new file mode 100644
index 000000000000..81bc42cc96ce
--- /dev/null
+++ 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpStepwiseChangeDirectoryIT.java
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.remote.mina.integration;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.file.GenericFileFilter;
+import org.apache.camel.component.file.remote.mina.MinaSftpEndpoint;
+import org.apache.camel.component.file.remote.mina.MinaSftpOperations;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.sshd.server.SshServer;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A stepwise operation changes into the directory of a file one segment at a 
time. Verifies that a directory that is
+ * the current directory once compacted, such as sub/.., is not taken as a 
parent of the current directory, on a server
+ * whose login directory is not its root.
+ */
+class MinaSftpStepwiseChangeDirectoryIT extends CamelTestSupport {
+
+    private final Set<String> listed = ConcurrentHashMap.newKeySet();
+    private Path root;
+    private SshServer sshd;
+
+    private void startServer(Map<String, String> renames) throws Exception {
+        root = Paths.get("target", "sftp-home", getClass().getSimpleName() + 
"-" + System.nanoTime(), "root")
+                .toAbsolutePath();
+        Files.createDirectories(root.resolve("home/camel/inbox/sub"));
+        Files.createDirectories(root.resolve("home/cam"));
+        Files.createDirectories(root.resolve("home/camel/inbox/real"));
+        Files.createDirectories(root.resolve("home/camel/inbox/blank"));
+        Files.writeString(root.resolve("home/camel/inbox/real/deep.txt"), 
"Deep in the inbox");
+        Files.writeString(root.resolve("home/camel/inbox/hello.txt"), "Hello 
from the inbox");
+        Files.writeString(root.resolve("home/camel/listed.txt"), "Hello from 
the login directory");
+        Files.writeString(root.resolve("outside.txt"), "Outside the login 
directory");
+        sshd = HomeDirectorySftpServer.start(root, "/home/camel", renames);
+    }
+
+    @AfterEach
+    void stopServer() throws Exception {
+        if (sshd != null) {
+            sshd.stop();
+        }
+    }
+
+    private String uri(String directory, String options) {
+        return "mina-sftp://camel@localhost:"; + sshd.getPort() + "/" + 
directory
+               + 
"?password=secret&strictHostKeyChecking=no&useUserKnownHostsFile=false" + 
options;
+    }
+
+    @Test
+    void changeIntoPathThatIsTheCurrentDirectory() throws Exception {
+        startServer(Map.of());
+        MinaSftpEndpoint endpoint = context.getEndpoint(uri("", ""), 
MinaSftpEndpoint.class);
+        MinaSftpOperations operations = (MinaSftpOperations) 
endpoint.createRemoteFileOperations();
+        operations.connect(endpoint.getConfiguration(), null);
+        try {
+            // a relative current directory
+            operations.changeCurrentDirectory("inbox");
+            operations.changeCurrentDirectory("sub/..");
+            assertEquals("inbox", operations.getCurrentDirectory());
+
+            // an absolute current directory
+            operations.changeCurrentDirectory("/home/camel/inbox");
+            String inbox = operations.getCurrentDirectory();
+            assertTrue(inbox.endsWith("/home/camel/inbox"), inbox);
+            operations.changeCurrentDirectory("sub/..");
+            assertEquals(inbox, operations.getCurrentDirectory());
+
+            // a parent directory, and a directory whose name only starts like 
the current one
+            operations.changeCurrentDirectory("/home/camel");
+            
assertTrue(operations.getCurrentDirectory().endsWith("/home/camel"), 
operations.getCurrentDirectory());
+            operations.changeCurrentDirectory("/home/cam");
+            assertTrue(operations.getCurrentDirectory().endsWith("/home/cam"), 
operations.getCurrentDirectory());
+        } finally {
+            operations.disconnect();
+        }
+    }
+
+    @Test
+    void uploadIntoCurrentDirectory() throws Exception {
+        startServer(Map.of());
+
+        template.sendBodyAndHeader(uri("", ""), "Hello", Exchange.FILE_NAME, 
"sub/../uploaded.txt");
+
+        assertTrue(Files.exists(root.resolve("home/camel/uploaded.txt")));
+        assertFalse(Files.exists(root.resolve("uploaded.txt")));
+    }
+
+    @Test
+    void downloadFromCurrentDirectory() throws Exception {
+        // the server lists listed.txt as sub/../outside.txt, which is not in 
the login directory
+        startServer(Map.of("listed.txt", "sub/../outside.txt"));
+        Files.writeString(root.resolve("home/camel/real.txt"), "Real file in 
the login directory");
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        // the real file shows the poll was done, and nothing else is 
downloaded
+        mock.expectedBodiesReceived("Real file in the login directory");
+        mock.setAssertPeriod(1000);
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(uri("", 
"&delete=true&initialDelay=0&delay=60000")).convertBodyTo(String.class).to("mock:result");
+            }
+        });
+
+        mock.assertIsSatisfied();
+        assertTrue(Files.exists(root.resolve("outside.txt")));
+    }
+
+    @Test
+    void pollSubDirectoryThatIsTheCurrentDirectory() throws Exception {
+        // the server lists the sub directory of the inbox as sub/.., which is 
the inbox, and another one with a blank
+        // name, and the poll skips both
+        startServer(Map.of("sub", "sub/..", "blank", " "));
+        context.getRegistry().bind("listed", (GenericFileFilter<Object>) file 
-> {
+            listed.add(file.getFileNameOnly());
+            return true;
+        });
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedBodiesReceivedInAnyOrder("Hello from the inbox", "Deep in 
the inbox");
+        mock.setAssertPeriod(1000);
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(uri("inbox", 
"&recursive=true&maxDepth=3&noop=true&filter=#listed&initialDelay=0&delay=60000"))
+                        .convertBodyTo(String.class).to("mock:result");
+            }
+        });
+
+        mock.assertIsSatisfied();
+        // nothing is listed outside the inbox
+        assertFalse(listed.contains("outside.txt"), listed.toString());
+        assertFalse(listed.contains("home"), listed.toString());
+        assertFalse(listed.contains("listed.txt"), listed.toString());
+    }
+}

Reply via email to