diff --git a/sshfs/spec.py b/sshfs/spec.py index 6e196b2..62ca757 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,11 @@ def _quote(path): - """Quote a path for a POSIX shell as a command's file argument.""" + """Quote an encoded path as a shell command's file argument.""" # 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): @@ -69,7 +68,7 @@ def __init__( sftp_client_kwargs: dict | None Options passed to `SSHClientConnection.start_sftp_client` (e.g. env, send_env, path_encoding, path_errors, - sftp_version). + sftp_version). path_errors defaults to "surrogateescape". Notes ----- @@ -77,10 +76,15 @@ def __init__( SSH connection. The host, username, and port in string URLs are ignored; operations use only the path on the connected server. + File names that aren't valid UTF-8 are returned as str with + surrogate escapes, the way ``os.listdir`` returns them, and such a + str names the same file when it is passed back. For a server whose + names use another encoding, set ``path_encoding``. + Bytes paths (and path-likes whose ``__fspath__`` returns bytes) are sent to the server unchanged: protocol prefixes are not stripped and trailing slashes are kept. With ``sftp_client_kwargs={"path_encoding": None}``, - paths must be bytes. + paths must be bytes, and only some methods support them. """ super().__init__(self, **kwargs) @@ -93,7 +97,15 @@ def __init__( ) _client_args = kwargs.copy() _client_args.setdefault("known_hosts", None) - sftp_client_kwargs = sftp_client_kwargs or {} + sftp_client_kwargs = { + "path_errors": "surrogateescape", + **(sftp_client_kwargs or {}), + } + # Shell commands encode paths the same way as the SFTP client + self._path_encoding = ( + sftp_client_kwargs.get("path_encoding") or "utf-8" + ) + self._path_errors = sftp_client_kwargs["path_errors"] self._stack = AsyncExitStack() self.active_executors = 0 @@ -290,8 +302,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): @@ -381,16 +392,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 +426,19 @@ async def _execute(self, *args, **kwargs): execute = sync_wrapper(_execute) + async def _execute_with_paths(self, program, *paths): + """Run a program with remote paths as its arguments.""" + # The paths are encoded the same way as for the SFTP client, before + # quoting, since some encodings produce quote characters. asyncssh + # would encode a str command as strict UTF-8 instead. + paths = [ + p.encode(self._path_encoding, self._path_errors) for p in paths + ] + command = b" ".join([program, *map(_quote, paths)]) + # The output can include those names, 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..1e3857d 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -77,6 +77,19 @@ def fs_hard_queue(ssh_server, user="user"): ) +@pytest.fixture +def non_utf8_file(tmp_path): + # The mock server encodes SFTP names as strict UTF-8, so only the methods + # that run shell commands can be tested with names that aren'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 os.fsdecode(path) + + def strip_keys(info): for key in ["name", "time", "mtime", "atime"]: info.pop(key, None) @@ -130,13 +143,27 @@ def test_sftp_client_kwargs(ssh_server, tmp_path, user="user"): client_keys=[USERS[user]], sftp_client_kwargs={"sftp_version": 3}, ) - assert fs._pool.sftp_client_kwargs == {"sftp_version": 3} + assert fs._pool.sftp_client_kwargs == { + "path_errors": "surrogateescape", + "sftp_version": 3, + } file = posixpath.join(tmp_path, "sftp_client_kwargs_probe") fs.touch(file) assert fs.exists(file) +def test_sftp_client_kwargs_path_errors(ssh_server, user="user"): + fs = SSHFileSystem( + host=ssh_server.host, + port=ssh_server.port, + username=user, + client_keys=[USERS[user]], + sftp_client_kwargs={"path_errors": "strict"}, + ) + assert fs._pool.sftp_client_kwargs == {"path_errors": "strict"} + + def test_sftp_client_kwargs_path_encoding(ssh_server, tmp_path, user="user"): # path_encoding=None makes asyncssh deliver remote paths as raw # bytes instead of str, for servers with non-UTF-8 file names (#39). @@ -264,6 +291,20 @@ def test_cp_file_leading_dash(fs, tmp_path, monkeypatch): assert (tmp_path / "-r-copy").read_bytes() == b"data" +def test_cp_file_non_utf8_name(fs, non_utf8_file): + fs.cp_file(non_utf8_file, non_utf8_file + "-copy") + with open(non_utf8_file + "-copy", "rb") as file: + assert file.read() == b"data" + + +def test_cp_file_missing_non_utf8_name(fs, tmp_path): + path = str(tmp_path) + "/missing-\udcff" + with pytest.raises(FileNotFoundError): + fs.cp_file(path, path + "-copy") + # The error output must not close the connection + assert fs.ls(str(tmp_path)) == [] + + def test_rm(fs, remote_dir): fs.touch(remote_dir + "/a.txt") fs.rm(remote_dir + "/a.txt") @@ -304,6 +345,49 @@ def test_checksum_leading_dash(fs, tmp_path, monkeypatch, name): assert checksum == hashlib.md5(b"data").hexdigest() +def test_checksum_non_utf8_name(fs, non_utf8_file): + checksum = hashlib.md5(b"data").hexdigest() + assert fs.checksum(non_utf8_file) == checksum + + +def test_checksum_missing_non_utf8_name(fs, tmp_path): + with pytest.raises(FileNotFoundError): + fs.checksum(str(tmp_path) + "/missing-\udcff") + # The error output must not close the connection + assert fs.ls(str(tmp_path)) == [] + + +def test_checksum_path_encoding(ssh_server, non_utf8_file, user="user"): + fs = SSHFileSystem( + host=ssh_server.host, + port=ssh_server.port, + username=user, + client_keys=[USERS[user]], + sftp_client_kwargs={"path_encoding": "latin-1"}, + ) + # Latin-1 decodes the file name b"name-\xff" as "name-ÿ" + path = os.fsencode(non_utf8_file).decode("latin-1") + assert fs.checksum(path) == hashlib.md5(b"data").hexdigest() + + +def test_checksum_path_encoding_quoting( + ssh_server, tmp_path, monkeypatch, user="user" +): + # HZ encodes "А" as b"~{'!~}", so quoting the path before encoding it + # would end the shell argument early and run the rest as a command + monkeypatch.chdir(tmp_path) + fs = SSHFileSystem( + host=ssh_server.host, + port=ssh_server.port, + username=user, + client_keys=[USERS[user]], + sftp_client_kwargs={"path_encoding": "hz"}, + ) + with pytest.raises(FileNotFoundError): + fs.checksum("А;touch injected;#") + assert not (tmp_path / "injected").exists() + + def test_ls(fs, remote_dir, plain_remote_dir): fs.mkdir(remote_dir + "dir/") files = set()