This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27054-ftp-crlf-4.18.x in repository https://gitbox.apache.org/repos/asf/camel.git
commit bb3b1b6869e36f86fa9c103cabc01c4b479a162a Author: Claus Ibsen <[email protected]> AuthorDate: Thu Nov 19 16:40:56 2026 +0100 CAMEL-27054: camel-ftp - refuse a file or directory name with a carriage return or line feed FtpOperations (also used by ftps) checks every remote file or directory name before it sends a command for it, and refuses a name with a carriage return or a line feed with a GenericFileOperationFailedException. Nothing is sent to the server for it. siteCommand is unchanged. Backport of #30211 to camel-4.18.x. The FakeFtpServer test helper (from CAMEL-26999/CAMEL-27000, not on this branch) comes along with the tests. The upgrade guide note for this release is on main. The new tests use camel-test-junit5 on this branch. (cherry picked from commit 9d7c28bb470242877e4109e1453830565f3847ac) Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../camel-ftp/src/main/docs/ftp-component.adoc | 7 + .../camel/component/file/remote/FtpOperations.java | 32 ++ .../camel/component/file/remote/FakeFtpServer.java | 402 +++++++++++++++++++++ .../remote/FtpProducerFileNameLineBreakTest.java | 154 ++++++++ .../FtpProducerFileNameLineBreakIT.java | 87 +++++ 5 files changed, 682 insertions(+) diff --git a/components/camel-ftp/src/main/docs/ftp-component.adoc b/components/camel-ftp/src/main/docs/ftp-component.adoc index 67b217e73d0f..e5f93d131972 100644 --- a/components/camel-ftp/src/main/docs/ftp-component.adoc +++ b/components/camel-ftp/src/main/docs/ftp-component.adoc @@ -184,6 +184,13 @@ It is only a single endpoint that does not support concurrent consumers. The FTP producer does *not* have this issue, it supports concurrency. +=== File and directory names with a line break + +The FTP control connection sends one command per line, so a remote file or directory name with a carriage return or +a line feed cannot be sent as the argument of one command. The `ftp` and `ftps` components refuse such a name with a +`GenericFileOperationFailedException` before they send any command for it, for example when the producer writes a file +whose `CamelFileName` header has a line break. Remove or replace these characters in the name before the producer. + [[FTP-DefaultWhenConsumingFiles]] === Default when consuming files diff --git a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java index 0b942b47248a..9d1955afd3c7 100644 --- a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java +++ b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java @@ -324,6 +324,7 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { @Override public boolean deleteFile(String name) throws GenericFileOperationFailedException { log.debug("Deleting file: {}", name); + checkName(name); boolean result; String target = name; @@ -364,6 +365,8 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { @Override public boolean renameFile(String from, String to) throws GenericFileOperationFailedException { log.debug("Renaming file: {} to: {}", from, to); + checkName(from); + checkName(to); try { reconnectIfNecessary(null); return client.rename(from, to); @@ -376,6 +379,7 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { public boolean buildDirectory(String directory, boolean absolute) throws GenericFileOperationFailedException { // must normalize directory first directory = endpoint.getConfiguration().normalizePath(directory); + checkName(directory); log.trace("buildDirectory({})", directory); try { @@ -407,6 +411,7 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { @Override public boolean retrieveFile(String name, Exchange exchange, long size) throws GenericFileOperationFailedException { + checkName(name); // store the name of the file to download on the listener clientActivityListener.setDownload(true); clientActivityListener.setRemoteFileName(name); @@ -674,6 +679,8 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { public boolean storeFile(String name, Exchange exchange, long size) throws GenericFileOperationFailedException { // must normalize name first name = endpoint.getConfiguration().normalizePath(name); + // before the listener and the client, so nothing is sent for a name that is refused + checkName(name); // store the name of the file to upload on the listener clientActivityListener.setDownload(false); @@ -816,6 +823,7 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { @Override public boolean storeFileDirectly(String name, String payload) throws GenericFileOperationFailedException { + checkName(name); ByteArrayInputStream bis = new ByteArrayInputStream(payload.getBytes()); try { return client.storeFile(name, bis); @@ -829,6 +837,7 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { @Override public boolean existsFile(String name) throws GenericFileOperationFailedException { log.trace("existsFile({})", name); + checkName(name); if (endpoint.isFastExistsCheck()) { return fastExistsFile(name); } @@ -861,6 +870,7 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { protected boolean fastExistsFile(String name) throws GenericFileOperationFailedException { log.trace("fastExistsFile({})", name); + checkName(name); try { String[] names = client.listNames(name); if (names == null) { @@ -890,6 +900,7 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { if (org.apache.camel.util.ObjectHelper.isEmpty(path)) { return; } + checkName(path); // must compact path so FTP server can traverse correctly // use the ftp utils implementation of the compact path @@ -978,6 +989,7 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { if (org.apache.camel.util.ObjectHelper.isEmpty(path)) { path = "."; } + checkName(path); try { return client.listFiles(path); @@ -1007,6 +1019,26 @@ public class FtpOperations implements RemoteFileOperations<FTPFile> { } } + /** + * The FTP control connection sends one command per line, so a file or directory name with a carriage return or a + * line feed cannot be sent as the argument of a single command. Such a name is refused before any command is sent. + * The message gives the character and its index, not the name. + */ + private static void checkName(String name) { + if (name == null) { + return; + } + for (int i = 0; i < name.length(); i++) { + char ch = name.charAt(i); + if (ch == '\r' || ch == '\n') { + throw new GenericFileOperationFailedException( + String.format("Cannot use the file or directory name: it has the character U+%04X at index %d, and a" + + " carriage return or a line feed cannot be sent in an FTP command", + (int) ch, i)); + } + } + } + protected FTPClient getFtpClient() { return client; } 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 new file mode 100644 index 000000000000..19a0028cf9db --- /dev/null +++ b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FakeFtpServer.java @@ -0,0 +1,402 @@ +/* + * 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.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; + +/** + * A minimal in-memory FTP server (passive mode only) that can stop answering on a connection that stays open, as a + * server that hangs, or a network path that is lost without closing the connection, does. + * <p> + * It serves the commands the ftp client sends with the default options and {@code passiveMode=true}: login, SYST, TYPE, + * PWD, CWD, CDUP, MKD, NOOP, PASV, LIST, NLST, RETR, STOR, DELE, RNFR/RNTO, SIZE, MDTM and QUIT. A silent connection + * keeps reading and records every command it receives, but never answers again. New connections are served normally, so + * a client that opens a new connection recovers. + */ +final class FakeFtpServer implements Closeable { + + /** How the server stops answering when the trigger command arrives. */ + enum Stall { + /** The trigger command gets no reply: the client waits for the reply on the control connection. */ + BEFORE_REPLY, + /** + * The trigger RETR gets its 150 reply and half of the file on the data connection, then nothing more on either + * connection: the client waits on the data connection. + */ + MID_TRANSFER + } + + private final ServerSocket serverSocket; + private final ExecutorService executor = Executors.newCachedThreadPool(r -> { + Thread t = new Thread(r, "fake-ftp-server"); + t.setDaemon(true); + return t; + }); + private final Map<String, byte[]> files = new ConcurrentHashMap<>(); + private final Set<String> directories = ConcurrentHashMap.newKeySet(); + private final List<Connection> connections = new CopyOnWriteArrayList<>(); + private final List<String> commands = new CopyOnWriteArrayList<>(); + private final AtomicInteger connectionIds = new AtomicInteger(); + private volatile Predicate<String> trigger; + private volatile Stall stall = Stall.BEFORE_REPLY; + private volatile boolean closed; + + FakeFtpServer() throws IOException { + serverSocket = new ServerSocket(0, 50, InetAddress.getLoopbackAddress()); + directories.add("/"); + executor.execute(this::acceptLoop); + } + + int port() { + return serverSocket.getLocalPort(); + } + + void addFile(String path, byte[] content) { + String file = normalize(path); + String parent = parentOf(file); + while (!parent.equals("/")) { + directories.add(parent); + parent = parentOf(parent); + } + files.put(file, content); + } + + Map<String, byte[]> files() { + return files; + } + + /** + * The first connection that receives a command matching {@code command} stops answering, from that command on. + */ + void stallOn(Predicate<String> command, Stall how) { + this.stall = how; + this.trigger = command; + } + + /** Every open connection stops answering from now on. New connections are served. */ + void silenceOpenConnections() { + connections.forEach(c -> c.silent = true); + } + + /** The commands the client sent on a connection after that connection stopped answering. */ + List<String> commandsOnSilentConnections() { + List<String> answer = new ArrayList<>(); + connections.forEach(c -> answer.addAll(c.unanswered)); + return answer; + } + + /** Every command line the server received, on any connection, in the order received. */ + List<String> commands() { + return commands; + } + + /** How many control connections the client has opened so far. */ + int connectionsOpened() { + return connectionIds.get(); + } + + /** How many connections that stopped answering the client has not closed. */ + long silentConnectionsOpen() { + return connections.stream().filter(c -> c.silent && !c.ended).count(); + } + + @Override + public void close() throws IOException { + closed = true; + serverSocket.close(); + for (Connection c : connections) { + c.close(); + } + executor.shutdownNow(); + } + + private void acceptLoop() { + while (!closed) { + try { + Socket socket = serverSocket.accept(); + Connection c = new Connection(socket, connectionIds.incrementAndGet()); + connections.add(c); + executor.execute(c); + } catch (IOException e) { + // closed + return; + } + } + } + + private final class Connection implements Runnable { + + private final Socket socket; + private final int id; + private final List<String> unanswered = new CopyOnWriteArrayList<>(); + private volatile boolean silent; + private volatile boolean ended; + private ServerSocket passive; + // a data connection left open by a stalled transfer + private Socket stalledData; + private OutputStream out; + private String cwd = "/"; + private String renameFrom; + + Connection(Socket socket, int id) { + this.socket = socket; + this.id = id; + } + + @Override + public void run() { + try { + BufferedReader in = new BufferedReader( + new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); + out = socket.getOutputStream(); + reply("220 fake FTP server ready (connection " + id + ")"); + String line; + while ((line = in.readLine()) != null) { + commands.add(line); + Predicate<String> t = trigger; + if (!silent && t != null && t.test(line)) { + // one shot: only the first matching connection stalls + trigger = null; + if (stall == Stall.MID_TRANSFER && line.startsWith("RETR ")) { + startTransferThenStall(line.substring(5).trim()); + } + silent = true; + continue; + } + if (silent) { + unanswered.add(line); + continue; + } + if (!handle(line)) { + break; + } + } + } catch (IOException e) { + // the client or the test closed the connection + } finally { + ended = true; + close(); + } + } + + private boolean handle(String line) throws IOException { + int space = line.indexOf(' '); + String cmd = (space < 0 ? line : line.substring(0, space)).toUpperCase(); + String arg = space < 0 ? "" : line.substring(space + 1).trim(); + switch (cmd) { + case "USER" -> reply("331 Password required"); + case "PASS" -> reply("230 Logged in"); + case "SYST" -> reply("215 UNIX Type: L8"); + case "TYPE", "MODE", "STRU", "OPTS", "SITE", "NOOP" -> reply("200 OK"); + case "PWD", "XPWD" -> reply("257 \"" + cwd + "\" is the current directory"); + case "CWD" -> { + String dir = resolve(arg); + if (directories.contains(dir)) { + cwd = dir; + reply("250 OK"); + } else { + reply("550 No such directory"); + } + } + case "CDUP" -> { + cwd = parentOf(cwd); + reply("250 OK"); + } + case "MKD" -> { + directories.add(resolve(arg)); + reply("257 \"" + resolve(arg) + "\" created"); + } + case "PASV" -> { + closePassive(); + passive = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + passive.setSoTimeout(10000); + int p = passive.getLocalPort(); + reply("227 Entering Passive Mode (127,0,0,1," + (p >> 8) + "," + (p & 0xff) + ")"); + } + case "LIST", "NLST" -> list(cmd, arg); + case "RETR" -> retrieve(arg); + case "STOR" -> store(arg); + case "DELE" -> reply(files.remove(resolve(arg)) != null ? "250 Deleted" : "550 No such file"); + case "RNFR" -> { + renameFrom = resolve(arg); + reply(files.containsKey(renameFrom) ? "350 Ready for RNTO" : "550 No such file"); + } + case "RNTO" -> { + byte[] data = renameFrom != null ? files.remove(renameFrom) : null; + if (data != null) { + addFile(resolve(arg), data); + reply("250 Renamed"); + } else { + reply("550 No such file"); + } + } + case "SIZE" -> { + byte[] data = files.get(resolve(arg)); + reply(data != null ? "213 " + data.length : "550 No such file"); + } + case "MDTM" -> reply(files.containsKey(resolve(arg)) ? "213 20250101000000" : "550 No such file"); + case "QUIT" -> { + reply("221 Bye"); + return false; + } + default -> reply("502 Command not implemented"); + } + return true; + } + + private void list(String cmd, String arg) throws IOException { + String dir = cwd; + for (String token : arg.split(" ")) { + if (!token.isEmpty() && !token.startsWith("-")) { + dir = resolve(token); + } + } + 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); + if (cmd.equals("NLST")) { + listing.append(name).append("\r\n"); + } else { + listing.append("-rw-r--r-- 1 camel camel ").append(e.getValue().length) + .append(" Jan 01 2025 ").append(name).append("\r\n"); + } + } + } + transfer(listing.toString().getBytes(StandardCharsets.UTF_8)); + } + + private void retrieve(String arg) throws IOException { + byte[] data = files.get(resolve(arg)); + if (data == null) { + reply("550 No such file"); + return; + } + transfer(data); + } + + private void transfer(byte[] data) throws IOException { + reply("150 Opening data connection"); + try (Socket d = passive.accept(); OutputStream o = d.getOutputStream()) { + o.write(data); + } finally { + closePassive(); + } + reply("226 Transfer complete"); + } + + private void startTransferThenStall(String arg) throws IOException { + byte[] data = files.get(resolve(arg)); + reply("150 Opening data connection"); + stalledData = passive.accept(); + OutputStream o = stalledData.getOutputStream(); + o.write(data, 0, data.length / 2); + o.flush(); + // the rest of the file and the 226 reply never come, and the data connection stays open + } + + private void store(String arg) throws IOException { + reply("150 Opening data connection"); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try (Socket d = passive.accept(); InputStream i = d.getInputStream()) { + i.transferTo(bos); + } finally { + closePassive(); + } + addFile(resolve(arg), bos.toByteArray()); + reply("226 Transfer complete"); + } + + private String resolve(String path) { + if (path.isEmpty()) { + return cwd; + } + return normalize(path.startsWith("/") ? path : cwd + "/" + path); + } + + private void reply(String line) throws IOException { + out.write((line + "\r\n").getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + + private void closePassive() { + if (passive != null) { + try { + passive.close(); + } catch (IOException e) { + // ignore + } + passive = null; + } + } + + void close() { + closePassive(); + try { + if (stalledData != null) { + stalledData.close(); + } + socket.close(); + } catch (IOException e) { + // ignore + } + } + } + + static String normalize(String path) { + List<String> parts = new ArrayList<>(); + for (String p : path.split("/")) { + if (p.isEmpty() || p.equals(".")) { + continue; + } + if (p.equals("..")) { + if (!parts.isEmpty()) { + parts.remove(parts.size() - 1); + } + } else { + parts.add(p); + } + } + return "/" + String.join("/", parts); + } + + static String parentOf(String path) { + int i = path.lastIndexOf('/'); + return i <= 0 ? "/" : path.substring(0, i); + } +} diff --git a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpProducerFileNameLineBreakTest.java b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpProducerFileNameLineBreakTest.java new file mode 100644 index 000000000000..db312964d7a8 --- /dev/null +++ b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpProducerFileNameLineBreakTest.java @@ -0,0 +1,154 @@ +/* + * 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.Set; + +import org.apache.camel.CamelExecutionException; +import org.apache.camel.Exchange; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.file.GenericFileOperationFailedException; +import org.apache.camel.test.junit5.CamelTestSupport; +import org.apache.commons.net.ftp.FTPFile; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The FTP control connection sends one command per line, so the ftp producer and the ftp operations refuse a file or + * directory name with a carriage return or a line feed, and send nothing to the server for it. + */ +public class FtpProducerFileNameLineBreakTest extends CamelTestSupport { + + private static final String EXISTING = "/outbox/existing.txt"; + + private FakeFtpServer server; + + @BeforeEach + void startServer() throws Exception { + server = new FakeFtpServer(); + server.addFile(EXISTING, "existing".getBytes(StandardCharsets.UTF_8)); + } + + @AfterEach + void stopServer() throws Exception { + server.close(); + } + + private String ftpUri(String options) { + String uri = "ftp://[email protected]:" + server.port() + + "/outbox?password=secret&passiveMode=true&soTimeout=5000&timeout=5000"; + return options.isEmpty() ? uri : uri + "&" + options; + } + + private void addRoute(String options) throws Exception { + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from("direct:upload").to(ftpUri(options)); + } + }); + } + + @ParameterizedTest + @ValueSource(strings = { + "before\nafter.txt", "before\rafter.txt", "before\r\nafter.txt", "before\r\nafter/hello.txt", + "sub/before\nafter.txt" }) + void fileNameWithLineBreakIsRefused(String name) throws Exception { + addRoute(""); + + assertRefused(name); + } + + @ParameterizedTest + @ValueSource(strings = { + "stepwise=false", "tempFileName=${file:name}.tmp", "tempPrefix=tmp-", "fileExist=Move&moveExisting=old", + "fileExist=Append", "fileExist=Fail", "fileExist=Ignore&fastExistsCheck=true", "chmod=640", + "doneFileName=${file:name}.done" }) + void fileNameWithLineBreakIsRefusedWithOption(String options) throws Exception { + addRoute(options); + + assertRefused("before\r\nafter.txt"); + } + + @Test + void plainFileNameIsStored() throws Exception { + addRoute("tempFileName=${file:name}.tmp&doneFileName=${file:name}.done&chmod=640"); + + template.sendBodyAndHeader("direct:upload", "hello", Exchange.FILE_NAME, "hello.txt"); + + assertEquals("hello", new String(server.files().get("/outbox/hello.txt"), StandardCharsets.UTF_8)); + assertTrue(server.files().containsKey("/outbox/hello.txt.done")); + } + + @Test + void operationsRefuseNameWithLineBreak() throws Exception { + FtpEndpoint<FTPFile> endpoint = context.getEndpoint(ftpUri(""), FtpEndpoint.class); + RemoteFileOperations<FTPFile> operations = endpoint.createRemoteFileOperations(); + operations.connect(endpoint.getConfiguration(), null); + Exchange exchange = endpoint.createExchange(); + String name = "before\nafter.txt"; + try { + List<Executable> calls = List.of( + () -> operations.deleteFile(name), + () -> operations.renameFile("existing.txt", name), + () -> operations.renameFile(name, "renamed.txt"), + () -> operations.buildDirectory(name, false), + () -> operations.existsFile(name), + () -> operations.changeCurrentDirectory(name), + () -> operations.listFiles(name), + () -> operations.storeFileDirectly(name, "hello"), + () -> operations.retrieveFile(name, exchange, 5)); + for (Executable call : calls) { + GenericFileOperationFailedException e = assertThrows(GenericFileOperationFailedException.class, call); + assertTrue(e.getMessage().contains("U+000A at index 6"), e.getMessage()); + } + } finally { + operations.disconnect(); + } + + assertNothingSentFor(); + } + + private void assertRefused(String name) { + CamelExecutionException e = assertThrows(CamelExecutionException.class, + () -> template.sendBodyAndHeader("direct:upload", "hello", Exchange.FILE_NAME, name)); + GenericFileOperationFailedException cause = assertIsInstanceOf(GenericFileOperationFailedException.class, e.getCause()); + assertTrue(cause.getMessage().contains("a carriage return or a line feed cannot be sent in an FTP command"), + cause.getMessage()); + + assertNothingSentFor(); + assertEquals(Set.of(EXISTING), server.files().keySet()); + } + + private void assertNothingSentFor() { + List<String> sent = server.commands().stream() + .filter(command -> command.contains("before") || command.contains("after")) + .toList(); + assertEquals(List.of(), sent, "Commands received for the refused name: " + server.commands()); + } +} diff --git a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpProducerFileNameLineBreakIT.java b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpProducerFileNameLineBreakIT.java new file mode 100644 index 000000000000..483e90ee0b03 --- /dev/null +++ b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpProducerFileNameLineBreakIT.java @@ -0,0 +1,87 @@ +/* + * 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.integration; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; + +import org.apache.camel.CamelExecutionException; +import org.apache.camel.Exchange; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.file.GenericFileOperationFailedException; +import org.junit.jupiter.api.Test; + +import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The ftp producer refuses a file or directory name with a carriage return or a line feed, as the FTP control + * connection sends one command per line, and the server gets no file or directory for it. + */ +public class FtpProducerFileNameLineBreakIT extends FtpServerTestSupport { + + private String getFtpUrl() { + return "ftp://admin@localhost:{{ftp.server.port}}/upload/linebreak?password=admin"; + } + + @Test + public void testFileNameWithLineBreakIsRefused() throws Exception { + CamelExecutionException e = assertThrows(CamelExecutionException.class, + () -> template.sendBodyAndHeader("direct:start", "Hello World", Exchange.FILE_NAME, "before\r\nafter.txt")); + GenericFileOperationFailedException cause = assertIsInstanceOf(GenericFileOperationFailedException.class, e.getCause()); + assertTrue(cause.getMessage().contains("the character U+000D"), cause.getMessage()); + + assertEquals(List.of(), serverEntriesNamed("before", "after")); + } + + @Test + public void testDirectoryNameWithLineBreakIsRefused() throws Exception { + CamelExecutionException e = assertThrows(CamelExecutionException.class, + () -> template.sendBodyAndHeader("direct:start", "Hello World", Exchange.FILE_NAME, "before\nafter/hello.txt")); + assertIsInstanceOf(GenericFileOperationFailedException.class, e.getCause()); + + assertEquals(List.of(), serverEntriesNamed("before", "after")); + } + + @Test + public void testPlainFileNameIsStored() throws Exception { + template.sendBodyAndHeader("direct:start", "Hello World", Exchange.FILE_NAME, "hello.txt"); + + assertEquals("Hello World", Files.readString(service.ftpFile("upload/linebreak/hello.txt"))); + } + + private List<Path> serverEntriesNamed(String... parts) throws Exception { + try (Stream<Path> entries = Files.walk(service.getFtpRootDir())) { + return entries.filter(p -> Stream.of(parts).anyMatch(part -> p.getFileName().toString().contains(part))) + .toList(); + } + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("direct:start").to(getFtpUrl()); + } + }; + } +}
