Skip to content
Open
14 changes: 14 additions & 0 deletions docs/reference/command-line-interface/transfer.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ 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' .
```

Wildcard patterns do not match hidden entries unless the pattern component starts with `.` (for
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`.

---

The full `multipass help transfer` output explains the available options:
Expand Down
2 changes: 2 additions & 0 deletions include/multipass/ssh/sftp_client.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <filesystem>
#include <functional>
#include <iostream>
#include <vector>

#include <QFlags>

Expand Down Expand Up @@ -54,6 +55,7 @@ class SFTPClient
SFTPClient(SSHSessionUPtr ssh_session);

virtual bool is_remote_dir(const fs::path& path);
virtual std::vector<fs::path> 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);
Expand Down
27 changes: 23 additions & 4 deletions src/client/cli/cmd/transfer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,27 @@ mp::ReturnCodeVariant cmd::Transfer::run(mp::ArgParser* parser)
if (const auto args = std::get_if<InstanceSourcesLocalTarget>(&arguments); args)
{
auto& [sources, target] = *args;
std::vector<fs::path> 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));
Comment thread
onatozmenn marked this conversation as resolved.
Resolved
}

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<LocalSourcesInstanceTarget>(&arguments); args)
Expand All @@ -85,7 +97,14 @@ mp::ReturnCodeVariant cmd::Transfer::run(mp::ArgParser* parser)
flags.testFlag(SFTPClient::Flag::MakeParent));

if (const auto args = std::get_if<ToCout>(&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)
{
Expand Down
188 changes: 182 additions & 6 deletions src/ssh/sftp_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,91 @@
#include <multipass/ssh/throw_on_error.h>
#include <multipass/utils.h>

#include <algorithm>
#include <array>
#include <fcntl.h>
#include <fmt/std.h>
#include <functional>
#include <iterator>
#include <string_view>

#include <QRegularExpression>

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<std::string> split_remote_path(const std::string_view path)
{
std::vector<std::string> 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;
}
Comment thread
tobe2098 marked this conversation as resolved.
Resolved
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
{
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)
Expand Down Expand Up @@ -73,10 +146,112 @@ 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;
}

std::vector<fs::path> SFTPClient::expand_remote_path(const fs::path& path)
{
const auto remote_path = path.generic_string();

// 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<std::string>{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 remote_entry_type(sftp.get(), candidate) == RemoteEntryType::missing;
});
if (candidates.empty())
throw SFTPError{"no matches found: {}", path};
}
continue;
}

std::vector<std::string> matches;
const QRegularExpression expression{
QRegularExpression::wildcardToRegularExpression(QString::fromStdString(component))};
Comment thread
onatozmenn marked this conversation as resolved.
Resolved
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)
{
// 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)};
Comment thread
tobe2098 marked this conversation as resolved.
Resolved
}

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;
}

// 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) {
return remote_entry_type(sftp.get(), candidate) != RemoteEntryType::directory;
});

if (candidates.empty())
throw SFTPError{"no matches found: {}", path};
}

std::vector<fs::path> 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
{
Expand Down Expand Up @@ -118,9 +293,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))
{
Expand Down Expand Up @@ -187,7 +361,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<fs::perms>(source_perms)))
throw SFTPError{"cannot set permissions for local file {}", target_path};
}
Expand Down Expand Up @@ -421,7 +596,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,
Expand Down
2 changes: 1 addition & 1 deletion src/ssh/sftp_dir_iterator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
20 changes: 20 additions & 0 deletions tests/cli/cli_transfer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
1 change: 1 addition & 0 deletions tests/unit/c_mock_defines.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ add_c_mocks(
sftp_stat
sftp_lstat
sftp_opendir
sftp_closedir
sftp_readdir
sftp_readlink
sftp_mkdir
Expand Down
1 change: 1 addition & 0 deletions tests/unit/mock_sftp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions tests/unit/mock_sftp.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions tests/unit/mock_sftp_client.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<fs::path>, expand_remote_path, (const fs::path& path), (override));
MOCK_METHOD(bool,
push,
(const fs::path& source_path, const fs::path& target_path, Flags flags),
Expand Down
Loading