diff --git a/sshfs/spec.py b/sshfs/spec.py index 6e196b2..9b22f87 100644 --- a/sshfs/spec.py +++ b/sshfs/spec.py @@ -1,6 +1,5 @@ import asyncio import posixpath -import shlex import stat import weakref from contextlib import AsyncExitStack, suppress @@ -35,11 +34,13 @@ def _quote(path): - """Quote a path for a POSIX shell as a command's file argument.""" + """Quote a str or bytes path for a POSIX shell, as bytes.""" + if isinstance(path, str): + path = path.encode() # Without "./", commands read "-r" as an option and "-" as stdin - if path.startswith("-"): - path = "./" + path - return shlex.quote(path) + if path.startswith(b"-"): + path = b"./" + path + return b"'" + path.replace(b"'", b"'\\''") + b"'" class SSHFileSystem(AsyncFileSystem): @@ -136,6 +137,14 @@ def _get_kwargs_from_urls(urlpath): out.pop("protocol", None) return out + @classmethod + def _parent(cls, path): + path = cls._strip_protocol(path) + # The same parents as fsspec's _parent gives. _strip_protocol keeps + # trailing slashes in bytes paths, so they are removed here. + sep = b"/" if isinstance(path, bytes) else "/" + return path.rstrip(sep).rpartition(sep)[0] + @wrap_exceptions async def _connect( self, @@ -223,14 +232,15 @@ async def _info(self, path, **kwargs): attributes = await channel.stat(path) info = self._decode_attributes(attributes) - path = path.rstrip("/") + sep = b"/" if isinstance(path, bytes) else "/" + path = path.rstrip(sep) if info["type"] == "directory": - path += "/" + path += sep info["name"] = path return info @wrap_exceptions - async def _modified(self, path: str, **kwargs) -> datetime: + async def _modified(self, path: str | bytes, **kwargs) -> datetime: path_info = await self._info(path) return path_info["mtime"] @@ -290,8 +300,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 {_quote(lpath)} {_quote(rpath)}" - await self._execute(cmd) + await self._execute_with_paths(b"cp", lpath, rpath) @wrap_exceptions async def _ls(self, path, detail=True, **kwargs): @@ -301,7 +310,7 @@ async def _ls(self, path, detail=True, **kwargs): infos = [] for file_attr in file_attrs: - if file_attr.filename in ["", ".", ".."]: + if file_attr.filename in ("", ".", "..", b"", b".", b".."): continue info = self._decode_attributes(file_attr.attrs) info["name"] = posixpath.join(path, file_attr.filename) @@ -381,16 +390,15 @@ async def _checksum(self, path): path = self._strip_protocol(path) system = await self._get_system() if system == "Linux": - command = "md5sum" + program = b"md5sum" part = 0 elif system == "Darwin": - command = "md5" + program = b"md5" part = -1 else: raise ValueError(f"{system!r} doesn't support checksum operation") - cmd = f"{command} {_quote(path)}" - result = await self._execute(cmd) + result = await self._execute_with_paths(program, path) parts = result.stdout.strip().split() assert len(parts) >= 1 @@ -416,6 +424,15 @@ async def _execute(self, *args, **kwargs): execute = sync_wrapper(_execute) + async def _execute_with_paths(self, program, *paths): + """Run a program with str or bytes paths as its arguments.""" + # asyncssh sends a bytes command as is, so paths that aren't valid + # UTF-8 reach the shell unchanged. + command = b" ".join((program, *map(_quote, paths))) + # Output can include those paths, and failing to decode it strictly + # closes the SSH connection. + return await self._execute(command, errors="replace") + def _open(self, path, *args, **kwargs): path = self._strip_protocol(path) return SSHFile(self, path, *args, **kwargs) diff --git a/tests/test_sshfs.py b/tests/test_sshfs.py index 5899bc0..987ba37 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -12,7 +12,13 @@ import fsspec import pytest -from asyncssh.sftp import SFTPAttrs, SFTPClient, SFTPFailure, SFTPOpUnsupported +from asyncssh.sftp import ( + SFTPAttrs, + SFTPClient, + SFTPFailure, + SFTPName, + SFTPOpUnsupported, +) from sshfs import SSHFileSystem from sshfs.file import SSHFile @@ -77,6 +83,30 @@ def fs_hard_queue(ssh_server, user="user"): ) +@pytest.fixture +def fs_bytes(ssh_server): + return SSHFileSystem( + host=ssh_server.host, + port=ssh_server.port, + username="user", + client_keys=[USERS["user"]], + sftp_client_kwargs={"path_encoding": None}, + ) + + +@pytest.fixture +def non_utf8_file(tmp_path): + # mock-ssh-server decodes SFTP paths as UTF-8, so only the methods that + # run shell commands can be tested with a name that isn't valid UTF-8 + path = os.fsencode(tmp_path) + b"/name-\xff" + try: + with open(path, "wb") as file: + file.write(b"data") + except OSError: + pytest.skip("the filesystem rejects names that aren't valid UTF-8") + return path + + def strip_keys(info): for key in ["name", "time", "mtime", "atime"]: info.pop(key, None) @@ -137,24 +167,16 @@ def test_sftp_client_kwargs(ssh_server, tmp_path, user="user"): assert fs.exists(file) -def test_sftp_client_kwargs_path_encoding(ssh_server, tmp_path, user="user"): +def test_sftp_client_kwargs_path_encoding(fs_bytes, tmp_path): # path_encoding=None makes asyncssh deliver remote paths as raw # bytes instead of str, for servers with non-UTF-8 file names (#39). - fs = SSHFileSystem( - host=ssh_server.host, - port=ssh_server.port, - username=user, - client_keys=[USERS[user]], - sftp_client_kwargs={"path_encoding": None}, - ) - directory = tmp_path / "path_encoding_probe" directory.mkdir() (directory / "data.txt").write_bytes(b"data") encoded = str(directory).encode() - assert fs.ls(encoded, detail=False) == [encoded + b"/data.txt"] - assert fs.cat_file(encoded + b"/data.txt") == b"data" + assert fs_bytes.ls(encoded, detail=False) == [encoded + b"/data.txt"] + assert fs_bytes.cat_file(encoded + b"/data.txt") == b"data" def test_info(fs, remote_dir, plain_remote_dir): @@ -173,6 +195,30 @@ def test_info(fs, remote_dir, plain_remote_dir): assert details["name"] == plain_remote_dir + "/dir/" +def test_bytes_info(fs_bytes, tmp_path): + (tmp_path / "dir").mkdir() + (tmp_path / "dir" / "a.txt").write_bytes(b"data") + directory = os.fsencode(tmp_path / "dir") + file = directory + b"/a.txt" + + details = fs_bytes.info(file) + assert details["type"] == "file" + assert details["name"] == file + assert details["size"] == 4 + assert fs_bytes.exists(file) + assert fs_bytes.isfile(file) + assert fs_bytes.size(file) == 4 + assert fs_bytes.modified(file) == details["mtime"] + + details = fs_bytes.info(directory) + assert details["type"] == "directory" + assert details["name"] == directory + b"/" + assert fs_bytes.isdir(directory) + + assert fs_bytes.info(directory + b"/")["name"] == directory + b"/" + assert fs_bytes.info(b"/")["name"] == b"/" + + def test_info_timestamps_are_tz_aware_utc(fs, remote_dir): fs.touch(remote_dir + "/a.txt") details = fs.info(remote_dir + "/a.txt") @@ -242,6 +288,16 @@ def test_move_copy_fallback_failure_keeps_source( assert fs.cat_file(remote_dir + "/a.txt") == b"data" +def test_bytes_move_copy_fallback(fs_bytes, tmp_path, no_posix_rename): + source = tmp_path / "a file ' $name" + source.write_bytes(b"data") + + fs_bytes.mv(os.fsencode(source), os.fsencode(tmp_path / "moved")) + + assert not source.exists() + assert (tmp_path / "moved").read_bytes() == b"data" + + def test_copy(fs, remote_dir): fs.touch(remote_dir + "/a.txt") initial_info = fs.info(remote_dir + "/a.txt") @@ -264,6 +320,29 @@ def test_cp_file_leading_dash(fs, tmp_path, monkeypatch): assert (tmp_path / "-r-copy").read_bytes() == b"data" +def test_bytes_cp_file(fs_bytes, tmp_path): + (tmp_path / "a file ' $name").write_bytes(b"data") + fs_bytes.cp_file( + os.fsencode(tmp_path / "a file ' $name"), + os.fsencode(tmp_path / "copy ' $name"), + ) + assert (tmp_path / "copy ' $name").read_bytes() == b"data" + + +def test_bytes_cp_file_non_utf8_name(fs_bytes, non_utf8_file): + fs_bytes.cp_file(non_utf8_file, non_utf8_file + b"-copy") + with open(non_utf8_file + b"-copy", "rb") as file: + assert file.read() == b"data" + + +def test_bytes_cp_file_missing_non_utf8_name(fs_bytes, tmp_path): + path = os.fsencode(tmp_path) + b"/missing-\xff" + with pytest.raises(FileNotFoundError): + fs_bytes.cp_file(path, path + b"-copy") + # The error output must not close the connection + assert fs_bytes.ls(os.fsencode(tmp_path)) == [] + + def test_rm(fs, remote_dir): fs.touch(remote_dir + "/a.txt") fs.rm(remote_dir + "/a.txt") @@ -282,6 +361,17 @@ def test_rm(fs, remote_dir): assert not fs.exists(remote_dir + "/dir") +def test_bytes_rm(fs_bytes, tmp_path): + (tmp_path / "a.txt").write_bytes(b"data") + fs_bytes.rm(os.fsencode(tmp_path / "a.txt")) + assert not (tmp_path / "a.txt").exists() + + (tmp_path / "dir").mkdir() + (tmp_path / "dir" / "a.txt").write_bytes(b"data") + fs_bytes.rm(os.fsencode(tmp_path / "dir"), recursive=True) + assert not (tmp_path / "dir").exists() + + def test_checksum(fs, remote_dir): data = b"iterative.ai" @@ -304,6 +394,24 @@ def test_checksum_leading_dash(fs, tmp_path, monkeypatch, name): assert checksum == hashlib.md5(b"data").hexdigest() +def test_bytes_checksum(fs_bytes, tmp_path): + (tmp_path / "a file ' $name").write_bytes(b"data") + path = os.fsencode(tmp_path / "a file ' $name") + assert fs_bytes.checksum(path) == hashlib.md5(b"data").hexdigest() + + +def test_bytes_checksum_non_utf8_name(fs_bytes, non_utf8_file): + checksum = hashlib.md5(b"data").hexdigest() + assert fs_bytes.checksum(non_utf8_file) == checksum + + +def test_bytes_checksum_missing_non_utf8_name(fs_bytes, tmp_path): + with pytest.raises(FileNotFoundError): + fs_bytes.checksum(os.fsencode(tmp_path) + b"/missing-\xff") + # The error output must not close the connection + assert fs_bytes.ls(os.fsencode(tmp_path)) == [] + + def test_ls(fs, remote_dir, plain_remote_dir): fs.mkdir(remote_dir + "dir/") files = set() @@ -327,6 +435,25 @@ def test_ls(fs, remote_dir, plain_remote_dir): assert dirs == expected +@pytest.mark.parametrize("detail", [True, False]) +def test_bytes_ls_omits_dot_entries(fs_bytes, tmp_path, monkeypatch, detail): + (tmp_path / "data").write_bytes(b"data") + path = os.fsencode(tmp_path) + original = SFTPClient.readdir + + async def readdir(channel, path): + entries = await original(channel, path) + attrs = await channel.stat(path) + return entries + [ + SFTPName(name, attrs=attrs) for name in (b"", b".", b"..") + ] + + monkeypatch.setattr(SFTPClient, "readdir", readdir) + listing = fs_bytes.ls(path, detail=detail) + names = [info["name"] for info in listing] if detail else listing + assert names == [path + b"/data"] + + def test_walk(fs, remote_dir, plain_remote_dir): fs.mkdir(remote_dir + "/a") fs.mkdir(remote_dir + "/a/b") @@ -391,6 +518,31 @@ def __fspath__(self): assert strip(["foo/bar/1", "foo/bar/2"]) == ["foo/bar/1", "foo/bar/2"] +@pytest.mark.parametrize( + "path, parent", + [ + ("ssh://host/a/b", "/a"), + ("/a/b", "/a"), + ("/a/b/", "/a"), + ("/a", ""), + ("/", ""), + ("a/b", "a"), + ("a", ""), + ("", ""), + (b"/a/b", b"/a"), + (b"/a/b/", b"/a"), + (b"/a", b""), + (b"/", b""), + (b"a/b", b"a"), + (b"a", b""), + (b"", b""), + ], +) +def test_parent(path, parent): + # Bytes paths get the same parents as str paths + assert SSHFileSystem._parent(path) == parent + + def test_mkdir(fs, remote_dir): fs.mkdir(remote_dir + "dir/") assert fs.isdir(remote_dir + "dir/") @@ -585,6 +737,14 @@ async def put(self, lpath, rpath, **kwargs): assert uploads == ["/a.txt"] +@pytest.mark.parametrize("file_path", [b"a.txt", b"dir/a.txt"]) +def test_bytes_put_file(fs_bytes, tmp_path, file_path): + (tmp_path / "upload.txt").write_bytes(b"data") + remote_file = os.fsencode(tmp_path) + b"/" + file_path + fs_bytes.put_file(str(tmp_path / "upload.txt"), remote_file) + assert (tmp_path / os.fsdecode(file_path)).read_bytes() == b"data" + + @pytest.mark.parametrize("file_path", ["a.txt", "dir/a.txt"]) def test_get_file(fs, remote_dir, file_path, tmp_path): remote_file = remote_dir + f"/{file_path}" @@ -598,6 +758,13 @@ def test_get_file(fs, remote_dir, file_path, tmp_path): assert local_file.read_bytes() == b"data" +def test_bytes_get_file(fs_bytes, tmp_path): + (tmp_path / "a.txt").write_bytes(b"data") + local_file = tmp_path / "downloaded.txt" + fs_bytes.get_file(os.fsencode(tmp_path / "a.txt"), str(local_file)) + assert local_file.read_bytes() == b"data" + + def test_concurrency_for_raw_commands(fs, remote_dir): with fs.open(remote_dir + "/cp_data", "wb") as stream: stream.write(b"hello!") @@ -676,3 +843,9 @@ async def open(self, path, mode): monkeypatch.setattr(SFTPClient, "open", open) fs.pipe_file("/a.txt", b"data") assert written == {"/a.txt": b"data"} + + +@pytest.mark.parametrize("file_path", [b"a.txt", b"dir/a.txt"]) +def test_bytes_pipe_file(fs_bytes, tmp_path, file_path): + fs_bytes.pipe_file(os.fsencode(tmp_path) + b"/" + file_path, b"data") + assert (tmp_path / os.fsdecode(file_path)).read_bytes() == b"data"