From 109302690e5b246b4d675b7019ddd1fa22481e7d Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Wed, 22 Jul 2026 00:30:54 +0300 Subject: [PATCH 01/10] [cli] Expand remote transfer wildcards Expand quoted instance-to-host wildcard patterns through SFTP directory listings without invoking a remote shell. Reuse the existing multi-source transfer path and require directory targets when a pattern yields multiple files. Add unit, CLI, and documentation coverage for #3885. --- .../command-line-interface/transfer.md | 10 ++ include/multipass/ssh/sftp_client.h | 2 + src/client/cli/cmd/transfer.cpp | 18 ++- src/ssh/sftp_client.cpp | 125 ++++++++++++++++++ tests/cli/cli_transfer_test.py | 20 +++ tests/unit/mock_sftp_client.h | 1 + tests/unit/test_cli_client.cpp | 71 +++++++++- tests/unit/test_sftp_client.cpp | 94 +++++++++++++ 8 files changed, 336 insertions(+), 5 deletions(-) diff --git a/docs/reference/command-line-interface/transfer.md b/docs/reference/command-line-interface/transfer.md index de23c99c37..da2b182c52 100644 --- a/docs/reference/command-line-interface/transfer.md +++ b/docs/reference/command-line-interface/transfer.md @@ -43,6 +43,16 @@ multipass transfer --recursive ample-pigeon:dir . ```{caution}Symbolic links are not followed during recursive transfer.``` +When copying from an instance to the host, source paths can contain `*`, `?`, and character-range +wildcards. Quote the source so that your host shell passes the pattern to Multipass unchanged: + +```{code-block} text +multipass transfer 'ample-pigeon:logs/*.txt' . +``` + +If the pattern matches multiple files, the destination must be a directory. Wildcards in local +source paths are expanded by the host shell as usual. + --- The full `multipass help transfer` output explains the available options: diff --git a/include/multipass/ssh/sftp_client.h b/include/multipass/ssh/sftp_client.h index dfc91964cc..d31bc8dde4 100644 --- a/include/multipass/ssh/sftp_client.h +++ b/include/multipass/ssh/sftp_client.h @@ -24,6 +24,7 @@ #include #include #include +#include #include @@ -54,6 +55,7 @@ class SFTPClient SFTPClient(SSHSessionUPtr ssh_session); virtual bool is_remote_dir(const fs::path& path); + virtual std::vector expand_remote_path(const fs::path& path); virtual bool push(const fs::path& source_path, const fs::path& target_path, Flags flags = {}); virtual bool pull(const fs::path& source_path, const fs::path& target_path, Flags flags = {}); virtual void from_cin(std::istream& cin, const fs::path& target_path, bool make_parent); diff --git a/src/client/cli/cmd/transfer.cpp b/src/client/cli/cmd/transfer.cpp index 91035560b3..614de04e32 100644 --- a/src/client/cli/cmd/transfer.cpp +++ b/src/client/cli/cmd/transfer.cpp @@ -58,15 +58,27 @@ mp::ReturnCodeVariant cmd::Transfer::run(mp::ArgParser* parser) if (const auto args = std::get_if(&arguments); args) { auto& [sources, target] = *args; + std::vector expanded_sources; + for (auto [source, source_end] = sources.equal_range(instance_name); + source != source_end; + ++source) + { + auto matches = sftp_client->expand_remote_path(source->second); + std::move(matches.begin(), + matches.end(), + std::back_inserter(expanded_sources)); + } + std::error_code err; - if (sources.size() > 1 && !MP_FILEOPS.is_directory(target, err) && !err) + if ((sources.size() > 1 || expanded_sources.size() > 1) && + !MP_FILEOPS.is_directory(target, err) && !err) throw std::runtime_error{ fmt::format("Target {:?} is not a directory", target)}; else if (err) throw std::runtime_error{ fmt::format("Cannot access {:?}: {}", target, err.message())}; - for (auto [s, s_end] = sources.equal_range(instance_name); s != s_end; ++s) - success &= sftp_client->pull(s->second, target, flags); + for (const auto& source : expanded_sources) + success &= sftp_client->pull(source, target, flags); } if (const auto args = std::get_if(&arguments); args) diff --git a/src/ssh/sftp_client.cpp b/src/ssh/sftp_client.cpp index 33f5513422..adc8bd5997 100644 --- a/src/ssh/sftp_client.cpp +++ b/src/ssh/sftp_client.cpp @@ -27,16 +27,63 @@ #include #include +#include #include #include #include #include +#include #include +#include + constexpr int file_mode = 0664; const std::string stream_file_name{"stream_output.dat"}; const char* log_category = "sftp"; +namespace +{ +bool has_wildcards(const std::string_view value) +{ + return value.find_first_of("*?[") != std::string_view::npos; +} + +std::vector split_remote_path(const std::string_view path) +{ + std::vector components; + for (std::size_t begin = 0; begin < path.size();) + { + begin = path.find_first_not_of('/', begin); + if (begin == std::string_view::npos) + break; + + const auto end = path.find('/', begin); + components.emplace_back(path.substr(begin, end - begin)); + begin = end == std::string_view::npos ? path.size() : end + 1; + } + return components; +} + +std::string append_remote_component(const std::string_view path, const std::string_view component) +{ + if (path.empty()) + return std::string{component}; + if (path == "/") + return fmt::format("/{}", component); + return fmt::format("{}/{}", path, component); +} + +bool wildcard_matches(const std::string_view pattern, + const std::string_view name, + const QRegularExpression& expression) +{ + if (name.starts_with('.') && !pattern.starts_with('.')) + return false; + + return expression.match(QString::fromStdString(std::string{name})).hasMatch(); +} +} // namespace + namespace multipass { namespace mpl = logging; @@ -77,6 +124,84 @@ bool SFTPClient::is_remote_dir(const fs::path& path) return attr && attr->type == SSH_FILEXFER_TYPE_DIRECTORY; } +std::vector SFTPClient::expand_remote_path(const fs::path& path) +{ + const auto remote_path = path.generic_string(); + if (!has_wildcards(remote_path)) + return {path}; + + auto candidates = std::vector{remote_path.starts_with('/') ? "/" : ""}; + auto expanded_pattern = false; + + for (const auto& component : split_remote_path(remote_path)) + { + if (!has_wildcards(component)) + { + std::transform(candidates.begin(), + candidates.end(), + candidates.begin(), + [&component](const auto& candidate) { + return append_remote_component(candidate, component); + }); + + if (expanded_pattern) + { + std::erase_if(candidates, [this](const auto& candidate) { + return !mp_sftp_stat(sftp.get(), candidate.c_str()); + }); + if (candidates.empty()) + throw SFTPError{"no matches found: {}", path}; + } + continue; + } + + std::vector matches; + const QRegularExpression expression{ + QRegularExpression::wildcardToRegularExpression(QString::fromStdString(component))}; + for (const auto& candidate : candidates) + { + const auto directory_path = candidate.empty() ? "." : candidate; + auto directory = mp_sftp_opendir(sftp.get(), directory_path.c_str()); + if (!directory) + { + if (expanded_pattern) + continue; + throw SFTPError{"cannot open remote directory '{}': {}", + directory_path, + MP_LIBSSH.ssh_get_error(sftp->session)}; + } + + while (auto entry = mp_sftp_readdir(sftp.get(), directory.get())) + { + const std::string_view name{entry->name}; + if (name != "." && name != ".." && wildcard_matches(component, name, expression)) + matches.emplace_back(append_remote_component(candidate, name)); + } + + if (!MP_LIBSSH.sftp_dir_eof(directory.get())) + throw SFTPError{"cannot read remote directory '{}': {}", + directory_path, + MP_LIBSSH.ssh_get_error(sftp->session)}; + } + + if (matches.empty()) + throw SFTPError{"no matches found: {}", path}; + + std::sort(matches.begin(), matches.end()); + matches.erase(std::unique(matches.begin(), matches.end()), matches.end()); + candidates = std::move(matches); + expanded_pattern = true; + } + + std::vector paths; + paths.reserve(candidates.size()); + std::transform(candidates.begin(), + candidates.end(), + std::back_inserter(paths), + [](auto& candidate) { return fs::path{std::move(candidate)}; }); + return paths; +} + bool SFTPClient::push(const fs::path& source_path, const fs::path& target_path, const Flags flags) try { diff --git a/tests/cli/cli_transfer_test.py b/tests/cli/cli_transfer_test.py index d97d593aca..585ca04523 100644 --- a/tests/cli/cli_transfer_test.py +++ b/tests/cli/cli_transfer_test.py @@ -46,6 +46,26 @@ def test_transfer_single_file(self, instance): assert pull_file.exists() assert pull_file.read_text() == "hello from the other side" + def test_transfer_remote_wildcard(self, instance): + """Transfer files matching a wildcard from the guest to the host.""" + with TempDirectory() as tmp: + source = tmp / "wildcard-source" + source.mkdir() + (source / "first.txt").write_text("first") + (source / "second.txt").write_text("second") + (source / "ignored.log").write_text("ignored") + + assert multipass("transfer", "--recursive", str(source), f"{instance}:") + + target = tmp / "wildcard-target" + target.mkdir() + assert multipass( + "transfer", f"{instance}:wildcard-source/*.txt", str(target) + ) + assert (target / "first.txt").read_text() == "first" + assert (target / "second.txt").read_text() == "second" + assert not (target / "ignored.log").exists() + def test_transfer_single_file_create_parents(self, instance): """Transfer a single file from the host to guest where the target is a nested folder structure.""" diff --git a/tests/unit/mock_sftp_client.h b/tests/unit/mock_sftp_client.h index ab1d337685..6769635d0e 100644 --- a/tests/unit/mock_sftp_client.h +++ b/tests/unit/mock_sftp_client.h @@ -25,6 +25,7 @@ namespace multipass::test struct MockSFTPClient : public SFTPClient { MOCK_METHOD(bool, is_remote_dir, (const fs::path& path), (override)); + MOCK_METHOD(std::vector, expand_remote_path, (const fs::path& path), (override)); MOCK_METHOD(bool, push, (const fs::path& source_path, const fs::path& target_path, Flags flags), diff --git a/tests/unit/test_cli_client.cpp b/tests/unit/test_cli_client.cpp index fe3c6d6fe4..9173ff328b 100644 --- a/tests/unit/test_cli_client.cpp +++ b/tests/unit/test_cli_client.cpp @@ -675,6 +675,8 @@ TEST_F(Client, transferCmdInstanceSourceLocalTarget) EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient) .WillOnce(Return(std::move(mocked_sftp_client))); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"foo"})) + .WillOnce(Return(std::vector{"foo"})); EXPECT_CALL(*mocked_sftp_client_p, pull).WillOnce(Return(true)); EXPECT_CALL(mock_daemon, ssh_info) .WillOnce([](auto, grpc::ServerReaderWriter* server) { @@ -686,13 +688,72 @@ TEST_F(Client, transferCmdInstanceSourceLocalTarget) EXPECT_EQ(send_command({"transfer", "test-vm:foo", "bar"}), mp::ReturnCode::Ok); } +TEST_F(Client, transferCmdExpandsRemoteWildcard) +{ + auto [mocked_file_ops, mocked_file_ops_guard] = mpt::MockFileOps::inject(); + auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject(); + auto mocked_sftp_client = std::make_unique(); + auto mocked_sftp_client_p = mocked_sftp_client.get(); + + EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient) + .WillOnce(Return(std::move(mocked_sftp_client))); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"dir/*.txt"})) + .WillOnce(Return(std::vector{"dir/first.txt", "dir/second.txt"})); + EXPECT_CALL(*mocked_file_ops, is_directory(fs::path{"target"}, _)).WillOnce(Return(true)); + EXPECT_CALL(*mocked_sftp_client_p, pull(fs::path{"dir/first.txt"}, fs::path{"target"}, _)) + .WillOnce(Return(true)); + EXPECT_CALL(*mocked_sftp_client_p, pull(fs::path{"dir/second.txt"}, fs::path{"target"}, _)) + .WillOnce(Return(true)); + EXPECT_CALL(mock_daemon, ssh_info) + .WillOnce([](auto, grpc::ServerReaderWriter* server) { + mp::SSHInfoReply reply; + reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}}); + server->Write(reply); + return grpc::Status{}; + }); + + EXPECT_EQ(send_command({"transfer", "test-vm:dir/*.txt", "target"}), mp::ReturnCode::Ok); +} + +TEST_F(Client, transferCmdRemoteWildcardMatchesRequireDirectoryTarget) +{ + auto [mocked_file_ops, mocked_file_ops_guard] = mpt::MockFileOps::inject(); + auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject(); + auto mocked_sftp_client = std::make_unique(); + auto mocked_sftp_client_p = mocked_sftp_client.get(); + + EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient) + .WillOnce(Return(std::move(mocked_sftp_client))); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"dir/*.txt"})) + .WillOnce(Return(std::vector{"dir/first.txt", "dir/second.txt"})); + EXPECT_CALL(*mocked_file_ops, is_directory(fs::path{"target"}, _)).WillOnce(Return(false)); + EXPECT_CALL(mock_daemon, ssh_info) + .WillOnce([](auto, grpc::ServerReaderWriter* server) { + mp::SSHInfoReply reply; + reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}}); + server->Write(reply); + return grpc::Status{}; + }); + + std::stringstream err; + EXPECT_EQ(send_command({"transfer", "test-vm:dir/*.txt", "target"}, trash_stream, err), + mp::ReturnCode::CommandFail); + EXPECT_THAT(err.str(), HasSubstr("Target \"target\" is not a directory")); +} + TEST_F(Client, transferCmdInstanceSourcesLocalTargetNotDir) { auto [mocked_file_ops, mocked_file_ops_guard] = mpt::MockFileOps::inject(); auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject(); + auto mocked_sftp_client = std::make_unique(); + auto mocked_sftp_client_p = mocked_sftp_client.get(); EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient) - .WillOnce(Return(std::make_unique())); + .WillOnce(Return(std::move(mocked_sftp_client))); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"foo"})) + .WillOnce(Return(std::vector{"foo"})); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"baz"})) + .WillOnce(Return(std::vector{"baz"})); EXPECT_CALL(*mocked_file_ops, is_directory(_, _)).WillOnce(Return(false)); EXPECT_CALL(mock_daemon, ssh_info) .WillOnce([](auto, grpc::ServerReaderWriter* server) { @@ -712,9 +773,15 @@ TEST_F(Client, transferCmdInstanceSourcesLocalTargetCannotAccess) { auto [mocked_file_ops, mocked_file_ops_guard] = mpt::MockFileOps::inject(); auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject(); + auto mocked_sftp_client = std::make_unique(); + auto mocked_sftp_client_p = mocked_sftp_client.get(); EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient) - .WillOnce(Return(std::make_unique())); + .WillOnce(Return(std::move(mocked_sftp_client))); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"foo"})) + .WillOnce(Return(std::vector{"foo"})); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"baz"})) + .WillOnce(Return(std::vector{"baz"})); auto err = std::make_error_code(std::errc::permission_denied); EXPECT_CALL(*mocked_file_ops, is_directory(_, _)).WillOnce([&](auto, std::error_code& e) { e = err; diff --git a/tests/unit/test_sftp_client.cpp b/tests/unit/test_sftp_client.cpp index a8e555d5cd..b1e010f156 100644 --- a/tests/unit/test_sftp_client.cpp +++ b/tests/unit/test_sftp_client.cpp @@ -75,6 +75,13 @@ fs::path canon(const fs::path& path) return fs::weakly_canonical(path); } +sftp_dir get_dummy_sftp_dir(const fs::path& name) +{ + auto dir = static_cast(calloc(1, sizeof(struct sftp_dir_struct))); + dir->name = strdup(name.string().c_str()); + return dir; +} + struct SFTPClient : public testing::Test { SFTPClient() @@ -165,6 +172,93 @@ TEST_F(SFTPClient, isDir) EXPECT_FALSE(sftp_client.is_remote_dir("not/a/directory")); } +TEST_F(SFTPClient, leavesRemotePathWithoutWildcardsUnchanged) +{ + REPLACE_SFTP_INIT(); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT(sftp_client.expand_remote_path("dir/file.txt"), + ElementsAre(fs::path{"dir/file.txt"})); +} + +TEST_F(SFTPClient, expandsRemoteWildcard) +{ + REPLACE_SFTP_INIT(); + + std::vector entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "third.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, ".hidden.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "second.log"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "first.txt"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + REPLACE(sftp_readdir, [&, index = 0](auto...) mutable { return entries[index++]; }); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT(sftp_client.expand_remote_path("dir/*.txt"), + ElementsAre(fs::path{"dir/first.txt"}, fs::path{"dir/third.txt"})); +} + +TEST_F(SFTPClient, expandsWildcardsAcrossRemotePathComponents) +{ + REPLACE_SFTP_INIT(); + + auto root_index = 0; + auto first_release_index = 0; + auto second_release_index = 0; + std::vector root_entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "release-b"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "release-a"), + nullptr, + }; + std::vector first_release_entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "first.txt"), + nullptr, + }; + std::vector second_release_entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "second.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "ignored.log"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + REPLACE(sftp_readdir, [&](auto, auto directory) -> sftp_attributes { + const std::string_view path{directory->name}; + if (path == ".") + return root_entries[root_index++]; + if (path == "release-a/logs") + return first_release_entries[first_release_index++]; + + return second_release_entries[second_release_index++]; + }); + REPLACE(sftp_stat, + [](auto, auto path) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, path); }); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT( + sftp_client.expand_remote_path("release-*/logs/*.txt"), + ElementsAre(fs::path{"release-a/logs/first.txt"}, fs::path{"release-b/logs/second.txt"})); +} + +TEST_F(SFTPClient, throwsWhenRemoteWildcardHasNoMatches) +{ + REPLACE_SFTP_INIT(); + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + REPLACE(sftp_readdir, [](auto...) { return nullptr; }); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + + auto sftp_client = make_sftp_client(); + + MP_EXPECT_THROW_THAT(sftp_client.expand_remote_path("dir/*.txt"), + mp::SFTPError, + mpt::match_what(StrEq("no matches found: dir/*.txt"))); +} + TEST_F(SFTPClient, pushFileSuccess) { std::string test_data = "test_data"; From 15c89b2d75a3a37c816e8f060b89a054a24562f1 Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Wed, 22 Jul 2026 01:06:21 +0300 Subject: [PATCH 02/10] [test] Fix wildcard test compilation --- tests/unit/test_cli_client.cpp | 1 + tests/unit/test_sftp_client.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_cli_client.cpp b/tests/unit/test_cli_client.cpp index 9173ff328b..1006a1e7e3 100644 --- a/tests/unit/test_cli_client.cpp +++ b/tests/unit/test_cli_client.cpp @@ -63,6 +63,7 @@ namespace mp = multipass; namespace mcp = multipass::cli::platform; namespace mpt = multipass::test; namespace mpu = multipass::utils; +namespace fs = mp::fs; using namespace testing; namespace diff --git a/tests/unit/test_sftp_client.cpp b/tests/unit/test_sftp_client.cpp index b1e010f156..b63799b039 100644 --- a/tests/unit/test_sftp_client.cpp +++ b/tests/unit/test_sftp_client.cpp @@ -194,7 +194,8 @@ TEST_F(SFTPClient, expandsRemoteWildcard) nullptr, }; REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); - REPLACE(sftp_readdir, [&, index = 0](auto...) mutable { return entries[index++]; }); + auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; + REPLACE(sftp_readdir, read_dir); REPLACE(sftp_dir_eof, [](auto...) { return true; }); auto sftp_client = make_sftp_client(); From 4e51dbf61aae20dd0c6f7bc325c0634e87e9c8b7 Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Wed, 22 Jul 2026 02:30:04 +0300 Subject: [PATCH 03/10] [test] Mock SFTP directory cleanup --- tests/unit/c_mock_defines.cmake | 1 + tests/unit/mock_sftp.cpp | 1 + tests/unit/mock_sftp.h | 1 + tests/unit/test_sftp_client.cpp | 11 +++++++++-- 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/unit/c_mock_defines.cmake b/tests/unit/c_mock_defines.cmake index 946371aefa..61a87f476b 100644 --- a/tests/unit/c_mock_defines.cmake +++ b/tests/unit/c_mock_defines.cmake @@ -81,6 +81,7 @@ add_c_mocks( sftp_stat sftp_lstat sftp_opendir + sftp_closedir sftp_readdir sftp_readlink sftp_mkdir diff --git a/tests/unit/mock_sftp.cpp b/tests/unit/mock_sftp.cpp index ea3a8b6627..154752019e 100644 --- a/tests/unit/mock_sftp.cpp +++ b/tests/unit/mock_sftp.cpp @@ -29,6 +29,7 @@ IMPL_MOCK_DEFAULT(1, sftp_close); IMPL_MOCK_DEFAULT(2, sftp_stat); IMPL_MOCK_DEFAULT(2, sftp_lstat); IMPL_MOCK_DEFAULT(2, sftp_opendir); +IMPL_MOCK_DEFAULT(1, sftp_closedir); IMPL_MOCK_DEFAULT(2, sftp_readdir); IMPL_MOCK_DEFAULT(2, sftp_readlink); IMPL_MOCK_DEFAULT(3, sftp_mkdir); diff --git a/tests/unit/mock_sftp.h b/tests/unit/mock_sftp.h index a2346b12ad..fae1ee6702 100644 --- a/tests/unit/mock_sftp.h +++ b/tests/unit/mock_sftp.h @@ -32,6 +32,7 @@ DECL_MOCK(sftp_close); DECL_MOCK(sftp_stat); DECL_MOCK(sftp_lstat); DECL_MOCK(sftp_opendir); +DECL_MOCK(sftp_closedir); DECL_MOCK(sftp_readdir); DECL_MOCK(sftp_readlink); DECL_MOCK(sftp_mkdir); diff --git a/tests/unit/test_sftp_client.cpp b/tests/unit/test_sftp_client.cpp index b63799b039..2b6a40d3b8 100644 --- a/tests/unit/test_sftp_client.cpp +++ b/tests/unit/test_sftp_client.cpp @@ -92,10 +92,16 @@ struct SFTPClient : public testing::Test return sftp; }}, free_sftp{mock_sftp_free, [](sftp_session sftp) { std::free(sftp); }}, - close_sftp{mock_sftp_close, [](sftp_file file) { + close_sftp{mock_sftp_close, + [](sftp_file file) { std::free(file); return SSH_OK; - }} + }}, + close_sftp_dir{mock_sftp_closedir, [](sftp_dir dir) { + std::free(dir->name); + std::free(dir); + return SSH_OK; + }} { } @@ -114,6 +120,7 @@ struct SFTPClient : public testing::Test MockScope sftp_new; MockScope free_sftp; MockScope close_sftp; + MockScope close_sftp_dir; sftp_limits_struct limits{32768, 32768, 32768, 0}; From fca5108a589abd6ea7d96889384f8f80fdf72727 Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Sun, 27 Sep 2026 13:52:12 +0300 Subject: [PATCH 04/10] [cli] Expand wildcards for transfer output --- src/client/cli/cmd/transfer.cpp | 9 ++++- tests/unit/test_cli_client.cpp | 46 ++++++++++++++++++++++++ tests/unit/test_sftp_client.cpp | 64 +++++++++++++++++++++++++++++++++ 3 files changed, 118 insertions(+), 1 deletion(-) diff --git a/src/client/cli/cmd/transfer.cpp b/src/client/cli/cmd/transfer.cpp index 614de04e32..c90de99387 100644 --- a/src/client/cli/cmd/transfer.cpp +++ b/src/client/cli/cmd/transfer.cpp @@ -97,7 +97,14 @@ mp::ReturnCodeVariant cmd::Transfer::run(mp::ArgParser* parser) flags.testFlag(SFTPClient::Flag::MakeParent)); if (const auto args = std::get_if(&arguments); args) - sftp_client->to_cout(args->source, term->cout()); + { + const auto matches = sftp_client->expand_remote_path(args->source); + if (matches.size() != 1) + throw std::runtime_error{ + fmt::format("Cannot write multiple matches to stdout for source {:?}", + args->source)}; + sftp_client->to_cout(matches.front(), term->cout()); + } } catch (const std::exception& e) { diff --git a/tests/unit/test_cli_client.cpp b/tests/unit/test_cli_client.cpp index 1006a1e7e3..4db7cb4647 100644 --- a/tests/unit/test_cli_client.cpp +++ b/tests/unit/test_cli_client.cpp @@ -908,6 +908,8 @@ TEST_F(Client, transferCmdStdoutGoodSourceOk) EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient) .WillOnce(Return(std::move(mocked_sftp_client))); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"foo"})) + .WillOnce(Return(std::vector{"foo"})); EXPECT_CALL(*mocked_sftp_client_p, to_cout); EXPECT_CALL(mock_daemon, ssh_info) .WillOnce([](auto, grpc::ServerReaderWriter* server) { @@ -920,6 +922,50 @@ TEST_F(Client, transferCmdStdoutGoodSourceOk) EXPECT_EQ(send_command({"transfer", "test-vm1:foo", "-"}), mp::ReturnCode::Ok); } +TEST_F(Client, transferCmdStdoutExpandsSingleWildcardMatch) +{ + auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject(); + auto mocked_sftp_client = std::make_unique(); + auto mocked_sftp_client_p = mocked_sftp_client.get(); + + EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient) + .WillOnce(Return(std::move(mocked_sftp_client))); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"foo/*.txt"})) + .WillOnce(Return(std::vector{"foo/only.txt"})); + EXPECT_CALL(*mocked_sftp_client_p, to_cout(fs::path{"foo/only.txt"}, _)); + EXPECT_CALL(mock_daemon, ssh_info) + .WillOnce([](auto, grpc::ServerReaderWriter* server) { + mp::SSHInfoReply reply; + reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}}); + server->Write(reply); + return grpc::Status{}; + }); + + EXPECT_EQ(send_command({"transfer", "test-vm1:foo/*.txt", "-"}), mp::ReturnCode::Ok); +} + +TEST_F(Client, transferCmdStdoutRejectsMultipleWildcardMatches) +{ + auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject(); + auto mocked_sftp_client = std::make_unique(); + auto mocked_sftp_client_p = mocked_sftp_client.get(); + + EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient) + .WillOnce(Return(std::move(mocked_sftp_client))); + EXPECT_CALL(*mocked_sftp_client_p, expand_remote_path(fs::path{"foo/*.txt"})) + .WillOnce(Return(std::vector{"foo/first.txt", "foo/second.txt"})); + EXPECT_CALL(*mocked_sftp_client_p, to_cout).Times(0); + EXPECT_CALL(mock_daemon, ssh_info) + .WillOnce([](auto, grpc::ServerReaderWriter* server) { + mp::SSHInfoReply reply; + reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}}); + server->Write(reply); + return grpc::Status{}; + }); + + EXPECT_EQ(send_command({"transfer", "test-vm1:foo/*.txt", "-"}), mp::ReturnCode::CommandFail); +} + TEST_F(Client, transferCmdStdoutBadSourceFails) { EXPECT_THAT(send_command({"transfer", "foo", "-"}), Eq(mp::ReturnCode::CommandLineError)); diff --git a/tests/unit/test_sftp_client.cpp b/tests/unit/test_sftp_client.cpp index 2b6a40d3b8..10d281236c 100644 --- a/tests/unit/test_sftp_client.cpp +++ b/tests/unit/test_sftp_client.cpp @@ -211,6 +211,70 @@ TEST_F(SFTPClient, expandsRemoteWildcard) ElementsAre(fs::path{"dir/first.txt"}, fs::path{"dir/third.txt"})); } +TEST_F(SFTPClient, expandsQuestionMarkWildcard) +{ + REPLACE_SFTP_INIT(); + + std::vector entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "fileA.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "file1.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "file10.txt"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; + REPLACE(sftp_readdir, read_dir); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT(sftp_client.expand_remote_path("dir/file?.txt"), + ElementsAre(fs::path{"dir/file1.txt"}, fs::path{"dir/fileA.txt"})); +} + +TEST_F(SFTPClient, expandsCharacterRangeWildcard) +{ + REPLACE_SFTP_INIT(); + + std::vector entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "c.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "a.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "d.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "b.txt"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; + REPLACE(sftp_readdir, read_dir); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT(sftp_client.expand_remote_path("dir/[a-c].txt"), + ElementsAre(fs::path{"dir/a.txt"}, fs::path{"dir/b.txt"}, fs::path{"dir/c.txt"})); +} + +TEST_F(SFTPClient, expandsExplicitDotPrefixedWildcard) +{ + REPLACE_SFTP_INIT(); + + std::vector entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "visible.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, ".hidden.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, ".hidden.log"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; + REPLACE(sftp_readdir, read_dir); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT(sftp_client.expand_remote_path("dir/.*.txt"), + ElementsAre(fs::path{"dir/.hidden.txt"})); +} + TEST_F(SFTPClient, expandsWildcardsAcrossRemotePathComponents) { REPLACE_SFTP_INIT(); From 2cadee2654164e038a8977593b7fbfd65403173e Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Sun, 27 Sep 2026 13:58:52 +0300 Subject: [PATCH 05/10] [cli] Preserve POSIX paths for remote transfers --- .../command-line-interface/transfer.md | 6 +++-- src/ssh/sftp_client.cpp | 14 +++++++----- src/ssh/sftp_dir_iterator.cpp | 2 +- tests/unit/test_sftp_client.cpp | 22 ++++++++++++++----- tests/unit/test_sftp_dir_iterator.cpp | 17 ++++++++++++++ 5 files changed, 46 insertions(+), 15 deletions(-) diff --git a/docs/reference/command-line-interface/transfer.md b/docs/reference/command-line-interface/transfer.md index da2b182c52..89a7cb0796 100644 --- a/docs/reference/command-line-interface/transfer.md +++ b/docs/reference/command-line-interface/transfer.md @@ -50,8 +50,10 @@ wildcards. Quote the source so that your host shell passes the pattern to Multip multipass transfer 'ample-pigeon:logs/*.txt' . ``` -If the pattern matches multiple files, the destination must be a directory. Wildcards in local -source paths are expanded by the host shell as usual. +Wildcard patterns do not match hidden entries unless the pattern component starts with `.` (for +example, `logs/.*.txt`). When copying to a host directory, multiple matches require a directory +destination; writing to `-` requires exactly one match. Wildcards in local source paths are expanded +by the host shell as usual. --- diff --git a/src/ssh/sftp_client.cpp b/src/ssh/sftp_client.cpp index adc8bd5997..bc37a43e09 100644 --- a/src/ssh/sftp_client.cpp +++ b/src/ssh/sftp_client.cpp @@ -120,7 +120,8 @@ SFTPClient::SFTPClient(SSHSessionUPtr ssh_session) bool SFTPClient::is_remote_dir(const fs::path& path) { - auto attr = mp_sftp_stat(sftp.get(), path.string().c_str()); + const auto remote_path = path.generic_string(); + auto attr = mp_sftp_stat(sftp.get(), remote_path.c_str()); return attr && attr->type == SSH_FILEXFER_TYPE_DIRECTORY; } @@ -243,9 +244,8 @@ catch (const SFTPError& e) bool SFTPClient::pull(const fs::path& source_path, const fs::path& target_path, const Flags flags) try { - auto source = source_path.string(); - utils::trim_end(source, - [](char ch) { return ch == '/' || ch == fs::path::preferred_separator; }); + auto source = source_path.generic_string(); + utils::trim_end(source, [](char ch) { return ch == '/'; }); if (is_remote_dir(source_path)) { @@ -312,7 +312,8 @@ void SFTPClient::pull_file(const fs::path& source_path, const fs::path& target_p if (!pre_existed) { - auto source_perms = mp_sftp_stat(sftp.get(), source_path.string().c_str())->permissions; + const auto remote_source = source_path.generic_string(); + auto source_perms = mp_sftp_stat(sftp.get(), remote_source.c_str())->permissions; if (!MP_PLATFORM.set_permissions(target_path, static_cast(source_perms))) throw SFTPError{"cannot set permissions for local file {}", target_path}; } @@ -546,7 +547,8 @@ void SFTPClient::do_push_file(std::istream& source, const fs::path& target_path) void SFTPClient::do_pull_file(const fs::path& source_path, std::ostream& target) { - auto remote_file = mp_sftp_open(sftp.get(), source_path.string().c_str(), O_RDONLY, 0); + const auto remote_path = source_path.generic_string(); + auto remote_file = mp_sftp_open(sftp.get(), remote_path.c_str(), O_RDONLY, 0); if (!remote_file) throw SFTPError{"cannot open remote file {}: {}", source_path, diff --git a/src/ssh/sftp_dir_iterator.cpp b/src/ssh/sftp_dir_iterator.cpp index d29f78dedd..272f6a2175 100644 --- a/src/ssh/sftp_dir_iterator.cpp +++ b/src/ssh/sftp_dir_iterator.cpp @@ -37,7 +37,7 @@ void SFTPDirIterator::push_dir(const std::string& path) SFTPDirIterator::SFTPDirIterator(sftp_session sftp, const fs::path& path) : sftp(sftp) { - push_dir(path.string()); + push_dir(path.generic_string()); next(); } diff --git a/tests/unit/test_sftp_client.cpp b/tests/unit/test_sftp_client.cpp index 10d281236c..d796b3803a 100644 --- a/tests/unit/test_sftp_client.cpp +++ b/tests/unit/test_sftp_client.cpp @@ -56,7 +56,7 @@ sftp_attributes get_dummy_sftp_attr(uint8_t type = SSH_FILEXFER_TYPE_REGULAR, auto attr = static_cast( calloc(1, sizeof(struct sftp_attributes_struct))); attr->type = type; - attr->name = strdup(name.string().c_str()); + attr->name = strdup(name.generic_string().c_str()); attr->permissions = perms; return attr; } @@ -78,7 +78,7 @@ fs::path canon(const fs::path& path) sftp_dir get_dummy_sftp_dir(const fs::path& name) { auto dir = static_cast(calloc(1, sizeof(struct sftp_dir_struct))); - dir->name = strdup(name.string().c_str()); + dir->name = strdup(name.generic_string().c_str()); return dir; } @@ -490,6 +490,8 @@ TEST_F(SFTPClient, pushFileCannotSetPerms) TEST_F(SFTPClient, pullFileSuccess) { std::string test_data = "test_data"; + std::string opened_remote_path; + std::vector remote_stat_paths; REPLACE_SFTP_INIT(); EXPECT_CALL(*mock_sftp_utils, get_local_file_target(source_path, target_path, _)) @@ -499,7 +501,10 @@ TEST_F(SFTPClient, pullFileSuccess) EXPECT_CALL(*mock_file_ops, open_write(target_path, _)) .WillOnce(Return(std::make_unique(test_file.rdbuf()))); EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(false)); - REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); + REPLACE(sftp_open, [&](auto sftp, auto path, auto...) { + opened_remote_path = path; + return get_dummy_sftp_file(sftp); + }); auto mocked_sftp_read = [&, read = false](auto, void* data, auto) mutable { strcpy((char*)data, test_data.c_str()); @@ -508,8 +513,10 @@ TEST_F(SFTPClient, pullFileSuccess) REPLACE(sftp_read, mocked_sftp_read); mode_t perms = 0777; - REPLACE(sftp_stat, - [&](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "", perms); }); + REPLACE(sftp_stat, [&](auto, auto path) { + remote_stat_paths.emplace_back(path); + return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "", perms); + }); std::filesystem::perms written_perms; EXPECT_CALL(mock_platform, set_permissions(target_path, static_cast(perms), _)) @@ -523,6 +530,9 @@ TEST_F(SFTPClient, pullFileSuccess) EXPECT_TRUE(sftp_client.pull(source_path, target_path)); EXPECT_EQ(test_data, test_file.str()); EXPECT_EQ(static_cast(perms), written_perms); + EXPECT_EQ(source_path.generic_string(), opened_remote_path); + EXPECT_THAT(remote_stat_paths, + ElementsAre(source_path.generic_string(), source_path.generic_string())); } TEST_F(SFTPClient, pullFileKeepsExistingTargetPermissions) @@ -1100,7 +1110,7 @@ TEST_F(SFTPClient, pullDirRejectsEscapingEntry) EXPECT_CALL(*mock_sftp_utils, make_SFTPDirIterator(_, source_path)) .WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); - const auto entry_name = (source_path / "../../../evil").string(); + const auto entry_name = (source_path / "../../../evil").generic_string(); EXPECT_CALL(*iter_p, next) .WillOnce(Return(make_unique_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, entry_name))); diff --git a/tests/unit/test_sftp_dir_iterator.cpp b/tests/unit/test_sftp_dir_iterator.cpp index 37f47436f4..44cd519e58 100644 --- a/tests/unit/test_sftp_dir_iterator.cpp +++ b/tests/unit/test_sftp_dir_iterator.cpp @@ -101,6 +101,23 @@ TEST(SFTPDirIterator, success) "dir/dir3/file6")); } +TEST(SFTPDirIterator, opensNestedRemotePathsWithForwardSlashes) +{ + const auto remote_path = mp::fs::path{"release-a/logs"}; + std::string opened_remote_path; + + REPLACE(sftp_opendir, [&](auto, auto path) { + opened_remote_path = path; + return get_dummy_dir("release-a/logs"); + }); + REPLACE(sftp_readdir, [](auto...) { return nullptr; }); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + + mp::SFTPDirIterator iter{nullptr, remote_path}; + + EXPECT_EQ(remote_path.generic_string(), opened_remote_path); +} + TEST(SFTPDirIterator, failOpendir) { REPLACE(sftp_opendir, [](auto...) { return nullptr; }); From 8361a08e649da65890e5b94bbc2302459aa8473a Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Thu, 12 Nov 2026 21:16:11 +0300 Subject: [PATCH 06/10] [cli] Address remote wildcard review comments Check for an existing literal path before expanding wildcards, so remote names such as a_[0].txt keep working. Cover literal paths and [[] patterns in the unit tests, simplify component splitting, and document literal-path precedence. --- .../command-line-interface/transfer.md | 4 +- src/ssh/sftp_client.cpp | 9 +++- tests/unit/test_sftp_client.cpp | 51 ++++++++++++++++++- 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/docs/reference/command-line-interface/transfer.md b/docs/reference/command-line-interface/transfer.md index 89a7cb0796..9c8159047a 100644 --- a/docs/reference/command-line-interface/transfer.md +++ b/docs/reference/command-line-interface/transfer.md @@ -53,7 +53,9 @@ multipass transfer 'ample-pigeon:logs/*.txt' . Wildcard patterns do not match hidden entries unless the pattern component starts with `.` (for example, `logs/.*.txt`). When copying to a host directory, multiple matches require a directory destination; writing to `-` requires exactly one match. Wildcards in local source paths are expanded -by the host shell as usual. +by the host shell as usual. A path that exists literally is transferred as-is, even if it contains +wildcard characters; to match a literal `[` in a pattern, put it in a character class, as in +`logs/a_[[]*].txt`. --- diff --git a/src/ssh/sftp_client.cpp b/src/ssh/sftp_client.cpp index bc37a43e09..6667cb34cf 100644 --- a/src/ssh/sftp_client.cpp +++ b/src/ssh/sftp_client.cpp @@ -59,7 +59,7 @@ std::vector split_remote_path(const std::string_view path) const auto end = path.find('/', begin); components.emplace_back(path.substr(begin, end - begin)); - begin = end == std::string_view::npos ? path.size() : end + 1; + begin = end; } return components; } @@ -128,7 +128,10 @@ bool SFTPClient::is_remote_dir(const fs::path& path) std::vector SFTPClient::expand_remote_path(const fs::path& path) { const auto remote_path = path.generic_string(); - if (!has_wildcards(remote_path)) + + // A literal path takes precedence, so names containing wildcard characters (such as + // "a_[0].txt") can still be transferred without escaping the brackets. + if (!has_wildcards(remote_path) || mp_sftp_stat(sftp.get(), remote_path.c_str())) return {path}; auto candidates = std::vector{remote_path.starts_with('/') ? "/" : ""}; @@ -163,6 +166,8 @@ std::vector SFTPClient::expand_remote_path(const fs::path& path) { const auto directory_path = candidate.empty() ? "." : candidate; auto directory = mp_sftp_opendir(sftp.get(), directory_path.c_str()); + // TODO: distinguish a path that is not a directory from other failures when + // opening it. if (!directory) { if (expanded_pattern) diff --git a/tests/unit/test_sftp_client.cpp b/tests/unit/test_sftp_client.cpp index d796b3803a..5e99d2b2f6 100644 --- a/tests/unit/test_sftp_client.cpp +++ b/tests/unit/test_sftp_client.cpp @@ -200,6 +200,7 @@ TEST_F(SFTPClient, expandsRemoteWildcard) get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "first.txt"), nullptr, }; + REPLACE(sftp_stat, [](auto...) { return nullptr; }); REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; REPLACE(sftp_readdir, read_dir); @@ -221,6 +222,7 @@ TEST_F(SFTPClient, expandsQuestionMarkWildcard) get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "file10.txt"), nullptr, }; + REPLACE(sftp_stat, [](auto...) { return nullptr; }); REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; REPLACE(sftp_readdir, read_dir); @@ -243,6 +245,7 @@ TEST_F(SFTPClient, expandsCharacterRangeWildcard) get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "b.txt"), nullptr, }; + REPLACE(sftp_stat, [](auto...) { return nullptr; }); REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; REPLACE(sftp_readdir, read_dir); @@ -254,6 +257,45 @@ TEST_F(SFTPClient, expandsCharacterRangeWildcard) ElementsAre(fs::path{"dir/a.txt"}, fs::path{"dir/b.txt"}, fs::path{"dir/c.txt"})); } +TEST_F(SFTPClient, keepsExistingLiteralPathContainingWildcardCharacters) +{ + REPLACE_SFTP_INIT(); + + REPLACE(sftp_stat, [](auto, auto path) { + return std::string_view{path} == "dir/a_[0].txt" + ? get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, path) + : nullptr; + }); + REPLACE(sftp_opendir, [](auto...) { return nullptr; }); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT(sftp_client.expand_remote_path("dir/a_[0].txt"), + ElementsAre(fs::path{"dir/a_[0].txt"})); +} + +TEST_F(SFTPClient, expandsEscapedLiteralBracketWildcard) +{ + REPLACE_SFTP_INIT(); + + std::vector entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "a_[0].txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "a_[*].txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "a_0.txt"), + nullptr, + }; + REPLACE(sftp_stat, [](auto...) { return nullptr; }); + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; + REPLACE(sftp_readdir, read_dir); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT(sftp_client.expand_remote_path("dir/a_[[]*].txt"), + ElementsAre(fs::path{"dir/a_[*].txt"}, fs::path{"dir/a_[0].txt"})); +} + TEST_F(SFTPClient, expandsExplicitDotPrefixedWildcard) { REPLACE_SFTP_INIT(); @@ -264,6 +306,7 @@ TEST_F(SFTPClient, expandsExplicitDotPrefixedWildcard) get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, ".hidden.log"), nullptr, }; + REPLACE(sftp_stat, [](auto...) { return nullptr; }); REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; REPLACE(sftp_readdir, read_dir); @@ -306,8 +349,11 @@ TEST_F(SFTPClient, expandsWildcardsAcrossRemotePathComponents) return second_release_entries[second_release_index++]; }); - REPLACE(sftp_stat, - [](auto, auto path) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, path); }); + REPLACE(sftp_stat, [](auto, auto path) { + return std::string_view{path} == "release-*/logs/*.txt" + ? nullptr + : get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, path); + }); REPLACE(sftp_dir_eof, [](auto...) { return true; }); auto sftp_client = make_sftp_client(); @@ -320,6 +366,7 @@ TEST_F(SFTPClient, expandsWildcardsAcrossRemotePathComponents) TEST_F(SFTPClient, throwsWhenRemoteWildcardHasNoMatches) { REPLACE_SFTP_INIT(); + REPLACE(sftp_stat, [](auto...) { return nullptr; }); REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); REPLACE(sftp_readdir, [](auto...) { return nullptr; }); REPLACE(sftp_dir_eof, [](auto...) { return true; }); From 9ebaa8da26b5433606f75013082fbcc2b9c4cf29 Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Mon, 16 Nov 2026 20:17:15 +0300 Subject: [PATCH 07/10] [cli] Harden remote wildcard expansion Propagate directory open failures after a wildcard so permission or connection errors are not hidden behind a partial transfer. Only SSH_FX_NO_SUCH_FILE, which also covers non-directory candidates on SFTP v3, is treated as a non-match. Honor a trailing slash on the source pattern by keeping only directory candidates and reporting no matches when none remain. Add unit tests for error propagation, non-directory candidates, and trailing-slash filtering. --- src/ssh/sftp_client.cpp | 25 +++++- tests/unit/test_sftp_client.cpp | 131 ++++++++++++++++++++++++++++++++ 2 files changed, 153 insertions(+), 3 deletions(-) diff --git a/src/ssh/sftp_client.cpp b/src/ssh/sftp_client.cpp index 6667cb34cf..b913ca1aa3 100644 --- a/src/ssh/sftp_client.cpp +++ b/src/ssh/sftp_client.cpp @@ -166,12 +166,18 @@ std::vector SFTPClient::expand_remote_path(const fs::path& path) { const auto directory_path = candidate.empty() ? "." : candidate; auto directory = mp_sftp_opendir(sftp.get(), directory_path.c_str()); - // TODO: distinguish a path that is not a directory from other failures when - // opening it. if (!directory) { - if (expanded_pattern) + // Once a wildcard has been expanded, a candidate may be a regular file that + // matched it; descending into it then legitimately fails. OpenSSH reports + // ENOTDIR as SSH_FX_NO_SUCH_FILE, so only that error is treated as a + // non-matching branch. Permission or connection failures must fail the + // transfer instead of silently dropping matches. + // TODO: distinguish a vanished entry from a non-directory; SFTP v3 reports + // both as SSH_FX_NO_SUCH_FILE. + if (expanded_pattern && MP_LIBSSH.sftp_get_error(sftp.get()) == SSH_FX_NO_SUCH_FILE) continue; + throw SFTPError{"cannot open remote directory '{}': {}", directory_path, MP_LIBSSH.ssh_get_error(sftp->session)}; @@ -199,6 +205,19 @@ std::vector SFTPClient::expand_remote_path(const fs::path& path) expanded_pattern = true; } + // Splitting the pattern drops a trailing slash, so restore its meaning here: a source + // ending in '/' only matches directories. + if (remote_path.ends_with('/')) + { + std::erase_if(candidates, [this](const auto& candidate) { + const auto attr = mp_sftp_stat(sftp.get(), candidate.c_str()); + return !attr || attr->type != SSH_FILEXFER_TYPE_DIRECTORY; + }); + + if (candidates.empty()) + throw SFTPError{"no matches found: {}", path}; + } + std::vector paths; paths.reserve(candidates.size()); std::transform(candidates.begin(), diff --git a/tests/unit/test_sftp_client.cpp b/tests/unit/test_sftp_client.cpp index 5e99d2b2f6..48801368d2 100644 --- a/tests/unit/test_sftp_client.cpp +++ b/tests/unit/test_sftp_client.cpp @@ -363,6 +363,137 @@ TEST_F(SFTPClient, expandsWildcardsAcrossRemotePathComponents) ElementsAre(fs::path{"release-a/logs/first.txt"}, fs::path{"release-b/logs/second.txt"})); } +TEST_F(SFTPClient, throwsWhenWildcardExpansionCannotOpenDirectory) +{ + REPLACE_SFTP_INIT(); + + auto root_index = 0; + std::vector root_entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "release-b"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "release-a"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) -> sftp_dir { + if (std::string_view{path} == "release-b/logs") + return nullptr; + + return get_dummy_sftp_dir(path); + }); + REPLACE(sftp_readdir, [&](auto, auto directory) -> sftp_attributes { + return std::string_view{directory->name} == "." ? root_entries[root_index++] : nullptr; + }); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + REPLACE(sftp_stat, [](auto, auto path) { + return std::string_view{path} == "release-*/logs/*.txt" + ? nullptr + : get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, path); + }); + REPLACE(sftp_get_error, [](auto...) { return SSH_FX_PERMISSION_DENIED; }); + auto err = "SFTP server: Permission denied"; + REPLACE(ssh_get_error, [&](auto...) { return err; }); + + auto sftp_client = make_sftp_client(); + + MP_EXPECT_THROW_THAT( + sftp_client.expand_remote_path("release-*/logs/*.txt"), + mp::SFTPError, + mpt::match_what( + StrEq(fmt::format("cannot open remote directory 'release-b/logs': {}", err)))); +} + +TEST_F(SFTPClient, skipsNonDirectoryCandidatesAfterWildcard) +{ + REPLACE_SFTP_INIT(); + + auto root_index = 0; + std::vector root_entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "release-b"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "release-a"), + nullptr, + }; + auto first_entry_returned = false; + REPLACE(sftp_opendir, [](auto, auto path) -> sftp_dir { + // "release-b/logs" is a regular file, so descending into it is not a match. + return std::string_view{path} == "release-b/logs" ? nullptr : get_dummy_sftp_dir(path); + }); + REPLACE(sftp_readdir, [&](auto, auto directory) -> sftp_attributes { + const std::string_view path{directory->name}; + if (path == ".") + return root_entries[root_index++]; + if (path == "release-a/logs" && !first_entry_returned) + { + first_entry_returned = true; + return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "first.txt"); + } + + return nullptr; + }); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + REPLACE(sftp_stat, [](auto, auto path) { + return std::string_view{path} == "release-*/logs/*.txt" + ? nullptr + : get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, path); + }); + REPLACE(sftp_get_error, [](auto...) { return SSH_FX_NO_SUCH_FILE; }); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT(sftp_client.expand_remote_path("release-*/logs/*.txt"), + ElementsAre(fs::path{"release-a/logs/first.txt"})); +} + +TEST_F(SFTPClient, trailingSlashPatternOnlyMatchesDirectories) +{ + REPLACE_SFTP_INIT(); + + std::vector entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "ignored.txt"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "subdir"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; + REPLACE(sftp_readdir, read_dir); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + REPLACE(sftp_stat, [](auto, auto path) { + const std::string_view remote_path{path}; + return remote_path == "dir/*/" + ? nullptr + : get_dummy_sftp_attr(remote_path == "dir/subdir" ? SSH_FILEXFER_TYPE_DIRECTORY + : SSH_FILEXFER_TYPE_REGULAR, + path); + }); + + auto sftp_client = make_sftp_client(); + + EXPECT_THAT(sftp_client.expand_remote_path("dir/*/"), ElementsAre(fs::path{"dir/subdir"})); +} + +TEST_F(SFTPClient, throwsWhenTrailingSlashPatternMatchesNoDirectories) +{ + REPLACE_SFTP_INIT(); + + std::vector entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "ignored.txt"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; + REPLACE(sftp_readdir, read_dir); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + REPLACE(sftp_stat, [](auto, auto path) { + return std::string_view{path} == "dir/*/" + ? nullptr + : get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, path); + }); + + auto sftp_client = make_sftp_client(); + + MP_EXPECT_THROW_THAT(sftp_client.expand_remote_path("dir/*/"), + mp::SFTPError, + mpt::match_what(StrEq("no matches found: dir/*/"))); +} + TEST_F(SFTPClient, throwsWhenRemoteWildcardHasNoMatches) { REPLACE_SFTP_INIT(); From 55433805f49db4adee295506d97adc15fa132366 Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Mon, 16 Nov 2026 20:18:29 +0300 Subject: [PATCH 08/10] [cli] Propagate wildcard stat failures When filtering literal components after a wildcard, only SSH_FX_NO_SUCH_FILE is treated as a non-match. Permission or connection errors now fail the transfer instead of silently dropping candidates. Add a unit test for an inaccessible path component. --- src/ssh/sftp_client.cpp | 12 +++++++++++- tests/unit/test_sftp_client.cpp | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/ssh/sftp_client.cpp b/src/ssh/sftp_client.cpp index b913ca1aa3..ee785565cf 100644 --- a/src/ssh/sftp_client.cpp +++ b/src/ssh/sftp_client.cpp @@ -151,7 +151,17 @@ std::vector SFTPClient::expand_remote_path(const fs::path& path) if (expanded_pattern) { std::erase_if(candidates, [this](const auto& candidate) { - return !mp_sftp_stat(sftp.get(), candidate.c_str()); + if (mp_sftp_stat(sftp.get(), candidate.c_str())) + return false; + + // A candidate that no longer exists simply stops matching. Other failures, + // such as permission problems, must not silently truncate the transfer. + if (MP_LIBSSH.sftp_get_error(sftp.get()) != SSH_FX_NO_SUCH_FILE) + throw SFTPError{"cannot access remote path '{}': {}", + candidate, + MP_LIBSSH.ssh_get_error(sftp->session)}; + + return true; }); if (candidates.empty()) throw SFTPError{"no matches found: {}", path}; diff --git a/tests/unit/test_sftp_client.cpp b/tests/unit/test_sftp_client.cpp index 48801368d2..87bc64980b 100644 --- a/tests/unit/test_sftp_client.cpp +++ b/tests/unit/test_sftp_client.cpp @@ -442,6 +442,40 @@ TEST_F(SFTPClient, skipsNonDirectoryCandidatesAfterWildcard) ElementsAre(fs::path{"release-a/logs/first.txt"})); } +TEST_F(SFTPClient, throwsWhenWildcardPathComponentCannotBeAccessed) +{ + REPLACE_SFTP_INIT(); + + auto root_index = 0; + std::vector root_entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "release-b"), + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "release-a"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + REPLACE(sftp_readdir, [&](auto, auto directory) -> sftp_attributes { + return std::string_view{directory->name} == "." ? root_entries[root_index++] : nullptr; + }); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + REPLACE(sftp_stat, [](auto, auto path) -> sftp_attributes { + const std::string_view remote_path{path}; + if (remote_path == "release-*/logs/*.txt" || remote_path == "release-b/logs") + return nullptr; + + return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, path); + }); + REPLACE(sftp_get_error, [](auto...) { return SSH_FX_PERMISSION_DENIED; }); + auto err = "SFTP server: Permission denied"; + REPLACE(ssh_get_error, [&](auto...) { return err; }); + + auto sftp_client = make_sftp_client(); + + MP_EXPECT_THROW_THAT( + sftp_client.expand_remote_path("release-*/logs/*.txt"), + mp::SFTPError, + mpt::match_what(StrEq(fmt::format("cannot access remote path 'release-b/logs': {}", err)))); +} + TEST_F(SFTPClient, trailingSlashPatternOnlyMatchesDirectories) { REPLACE_SFTP_INIT(); From a1a9ef2f453937a490dd2f6e5bb9dceee826d1dc Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Mon, 16 Nov 2026 20:19:43 +0300 Subject: [PATCH 09/10] [cli] Unify remote entry checks Route existence and directory checks after wildcard expansion through one helper so a missing entry is the only condition treated as a non-match. Permission and connection failures now propagate from the trailing-slash filter too. Add a unit test for an inaccessible trailing-slash candidate. --- src/ssh/sftp_client.cpp | 41 ++++++++++++++++++++++----------- tests/unit/test_sftp_client.cpp | 25 ++++++++++++++++++++ 2 files changed, 53 insertions(+), 13 deletions(-) diff --git a/src/ssh/sftp_client.cpp b/src/ssh/sftp_client.cpp index ee785565cf..596a0b8559 100644 --- a/src/ssh/sftp_client.cpp +++ b/src/ssh/sftp_client.cpp @@ -86,6 +86,32 @@ bool wildcard_matches(const std::string_view pattern, namespace multipass { +namespace +{ +enum class RemoteEntryType +{ + missing, + non_directory, + directory, +}; + +RemoteEntryType remote_entry_type(sftp_session sftp, const std::string& path) +{ + if (auto attr = mp_sftp_stat(sftp, path.c_str())) + return attr->type == SSH_FILEXFER_TYPE_DIRECTORY ? RemoteEntryType::directory + : RemoteEntryType::non_directory; + + // A missing entry simply stops matching; other failures, such as permission problems, + // must not silently truncate the transfer. + if (MP_LIBSSH.sftp_get_error(sftp) != SSH_FX_NO_SUCH_FILE) + throw SFTPError{"cannot access remote path '{}': {}", + path, + MP_LIBSSH.ssh_get_error(sftp->session)}; + + return RemoteEntryType::missing; +} +} // namespace + namespace mpl = logging; SFTPSessionUPtr make_sftp_session(ssh_session session) @@ -151,17 +177,7 @@ std::vector SFTPClient::expand_remote_path(const fs::path& path) if (expanded_pattern) { std::erase_if(candidates, [this](const auto& candidate) { - if (mp_sftp_stat(sftp.get(), candidate.c_str())) - return false; - - // A candidate that no longer exists simply stops matching. Other failures, - // such as permission problems, must not silently truncate the transfer. - if (MP_LIBSSH.sftp_get_error(sftp.get()) != SSH_FX_NO_SUCH_FILE) - throw SFTPError{"cannot access remote path '{}': {}", - candidate, - MP_LIBSSH.ssh_get_error(sftp->session)}; - - return true; + return remote_entry_type(sftp.get(), candidate) == RemoteEntryType::missing; }); if (candidates.empty()) throw SFTPError{"no matches found: {}", path}; @@ -220,8 +236,7 @@ std::vector SFTPClient::expand_remote_path(const fs::path& path) if (remote_path.ends_with('/')) { std::erase_if(candidates, [this](const auto& candidate) { - const auto attr = mp_sftp_stat(sftp.get(), candidate.c_str()); - return !attr || attr->type != SSH_FILEXFER_TYPE_DIRECTORY; + return remote_entry_type(sftp.get(), candidate) != RemoteEntryType::directory; }); if (candidates.empty()) diff --git a/tests/unit/test_sftp_client.cpp b/tests/unit/test_sftp_client.cpp index 87bc64980b..cc9b03a288 100644 --- a/tests/unit/test_sftp_client.cpp +++ b/tests/unit/test_sftp_client.cpp @@ -528,6 +528,31 @@ TEST_F(SFTPClient, throwsWhenTrailingSlashPatternMatchesNoDirectories) mpt::match_what(StrEq("no matches found: dir/*/"))); } +TEST_F(SFTPClient, throwsWhenTrailingSlashPatternCannotAccessCandidate) +{ + REPLACE_SFTP_INIT(); + + std::vector entries{ + get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "subdir"), + nullptr, + }; + REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_sftp_dir(path); }); + auto read_dir = [&, index = 0](auto...) mutable { return entries[index++]; }; + REPLACE(sftp_readdir, read_dir); + REPLACE(sftp_dir_eof, [](auto...) { return true; }); + REPLACE(sftp_stat, [](auto...) { return nullptr; }); + REPLACE(sftp_get_error, [](auto...) { return SSH_FX_PERMISSION_DENIED; }); + auto err = "SFTP server: Permission denied"; + REPLACE(ssh_get_error, [&](auto...) { return err; }); + + auto sftp_client = make_sftp_client(); + + MP_EXPECT_THROW_THAT( + sftp_client.expand_remote_path("dir/*/"), + mp::SFTPError, + mpt::match_what(StrEq(fmt::format("cannot access remote path 'dir/subdir': {}", err)))); +} + TEST_F(SFTPClient, throwsWhenRemoteWildcardHasNoMatches) { REPLACE_SFTP_INIT(); From 72f386450ef6eca213dc22e8750e20b571bf5684 Mon Sep 17 00:00:00 2001 From: onatozmenn Date: Mon, 16 Nov 2026 20:20:32 +0300 Subject: [PATCH 10/10] [docs] Document wildcard directory patterns Note that remote transfer patterns ending in '/' only match directories. --- docs/reference/command-line-interface/transfer.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/reference/command-line-interface/transfer.md b/docs/reference/command-line-interface/transfer.md index 9c8159047a..432073f0c0 100644 --- a/docs/reference/command-line-interface/transfer.md +++ b/docs/reference/command-line-interface/transfer.md @@ -51,11 +51,11 @@ multipass transfer 'ample-pigeon:logs/*.txt' . ``` Wildcard patterns do not match hidden entries unless the pattern component starts with `.` (for -example, `logs/.*.txt`). When copying to a host directory, multiple matches require a directory -destination; writing to `-` requires exactly one match. Wildcards in local source paths are expanded -by the host shell as usual. A path that exists literally is transferred as-is, even if it contains -wildcard characters; to match a literal `[` in a pattern, put it in a character class, as in -`logs/a_[[]*].txt`. +example, `logs/.*.txt`), and a pattern ending in `/` matches directories only. When copying to a +host directory, multiple matches require a directory destination; writing to `-` requires exactly +one match. Wildcards in local source paths are expanded by the host shell as usual. A path that +exists literally is transferred as-is, even if it contains wildcard characters; to match a literal +`[` in a pattern, put it in a character class, as in `logs/a_[[]*].txt`. ---