diff --git a/sshfs/spec.py b/sshfs/spec.py index 2338040..d054854 100644 --- a/sshfs/spec.py +++ b/sshfs/spec.py @@ -34,6 +34,14 @@ _DEFAULT_MAX_SESSIONS = 10 +def _quote(path): + """Quote a path for a POSIX shell as a command's file argument.""" + # Without "./", commands read "-r" as an option and "-" as stdin + if path.startswith("-"): + path = "./" + path + return shlex.quote(path) + + class SSHFileSystem(AsyncFileSystem): def __init__( self, @@ -280,7 +288,7 @@ async def _get_file( async def _cp_file(self, lpath, rpath, **kwargs): lpath = self._strip_protocol(lpath) rpath = self._strip_protocol(rpath) - cmd = f"cp {shlex.quote(lpath)} {shlex.quote(rpath)}" + cmd = f"cp {_quote(lpath)} {_quote(rpath)}" await self._execute(cmd) @wrap_exceptions @@ -379,7 +387,7 @@ async def _checksum(self, path): else: raise ValueError(f"{system!r} doesn't support checksum operation") - cmd = f"{command} {shlex.quote(path)}" + cmd = f"{command} {_quote(path)}" result = await self._execute(cmd) parts = result.stdout.strip().split() diff --git a/tests/test_sshfs.py b/tests/test_sshfs.py index 494f523..319edde 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -254,6 +254,15 @@ def test_copy(fs, remote_dir): assert strip_keys(initial_info) == strip_keys(secondary_info) +def test_cp_file_leading_dash(fs, tmp_path, monkeypatch): + # A relative path is the only way to start a name with "-". The mock + # server resolves it against the current directory. + monkeypatch.chdir(tmp_path) + (tmp_path / "-r").write_bytes(b"data") + fs.cp_file("-r", "-r-copy") + assert (tmp_path / "-r-copy").read_bytes() == b"data" + + def test_rm(fs, remote_dir): fs.touch(remote_dir + "/a.txt") fs.rm(remote_dir + "/a.txt") @@ -282,6 +291,18 @@ def test_checksum(fs, remote_dir): assert fs.checksum(remote_dir + "/a.txt") == checksum +@pytest.mark.parametrize("name", ["-", "-r"]) +def test_checksum_leading_dash(fs, tmp_path, monkeypatch, name): + # A relative path is the only way to start a name with "-". The mock + # server resolves it against the current directory. + monkeypatch.chdir(tmp_path) + (tmp_path / name).write_bytes(b"data") + # md5sum and md5 read stdin when they get "-" or no file, and the + # command's stdin is never closed, so a regression hangs without timeout + checksum = fs.checksum(name, timeout=10) + assert checksum == hashlib.md5(b"data").hexdigest() + + def test_ls(fs, remote_dir, plain_remote_dir): fs.mkdir(remote_dir + "dir/") files = set()