Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix large SFTP reads #638

Open
wants to merge 8 commits into
base: devel
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/changelog-fragments/638.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Fixed reading files over SFTP that go over the pre-defined chunk size.

Prior to this change, the files could end up being corrupted, ending up with the last read chunk written to the file instead of the entire payload.

-- by :user:`Jakuje`.
25 changes: 13 additions & 12 deletions src/pylibsshext/sftp.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -89,18 +89,19 @@ cdef class SFTP:

rf = sftp.sftp_open(self._libssh_sftp_session, remote_file_b, O_RDONLY, sftp.S_IRWXU)
if rf is NULL:
raise LibsshSFTPException("Opening remote file [%s] for read failed with error [%s]" % (remote_file, self._get_sftp_error_str()))

while True:
file_data = sftp.sftp_read(rf, <void *>read_buffer, sizeof(char) * 1024)
if file_data == 0:
break
elif file_data < 0:
sftp.sftp_close(rf)
raise LibsshSFTPException("Reading data from remote file [%s] failed with error [%s]"
% (remote_file, self._get_sftp_error_str()))

with open(local_file, 'wb+') as f:
raise LibsshSFTPException("Opening remote file [%s] for read failed with error [%s]"
% (remote_file, self._get_sftp_error_str()))
Jakuje marked this conversation as resolved.
Show resolved Hide resolved

with open(local_file, 'wb') as f:
while True:
file_data = sftp.sftp_read(rf, <void *>read_buffer, sizeof(char) * 1024)
if file_data == 0:
break
elif file_data < 0:
sftp.sftp_close(rf)
raise LibsshSFTPException("Reading data from remote file [%s] failed with error [%s]"
% (remote_file, self._get_sftp_error_str()))

bytes_written = f.write(read_buffer[:file_data])
if bytes_written and file_data != bytes_written:
sftp.sftp_close(rf)
Expand Down
50 changes: 45 additions & 5 deletions tests/unit/sftp_test.py
Jakuje marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

"""Tests suite for sftp."""

import random
import string
import uuid
Jakuje marked this conversation as resolved.
Show resolved Hide resolved

import pytest
Expand All @@ -18,11 +20,21 @@ def sftp_session(ssh_client_session):
del sftp_sess # noqa: WPS420


@pytest.fixture
def transmit_payload():
"""Generate a binary test payload."""
uuid_name = uuid.uuid4()
return 'Hello, {name!s}'.format(name=uuid_name).encode()
@pytest.fixture(
params=(32, 1024 + 1),
ids=('small-payload', 'large-payload'),
)
def transmit_payload(request: pytest.FixtureRequest):
"""Generate binary test payloads of assorted sizes.

The choice 32 is arbitrary small value.

The choice 1024 + 1 is meant to be 1B larger than the chunk size used in
sftp.pyx to make sure we excercise at least two rounds of reading/writing.
"""
payload_len = request.param
random_bytes = [ord(random.choice(string.printable)) for _ in range(payload_len)]
return bytes(random_bytes)


@pytest.fixture
Expand All @@ -48,6 +60,22 @@ def dst_path(file_paths_pair):
return path


@pytest.fixture
def other_payload():
"""Generate a binary test payload."""
uuid_name = uuid.uuid4()
return 'Original content: {name!s}'.format(name=uuid_name).encode()


@pytest.fixture
def dst_exists_path(file_paths_pair, other_payload):
"""Return a data destination path."""
path = file_paths_pair[1]
path.write_bytes(other_payload)
assert path.exists()
return path


def test_make_sftp(sftp_session):
"""Smoke-test SFTP instance creation."""
assert sftp_session
Expand All @@ -63,3 +91,15 @@ def test_get(dst_path, src_path, sftp_session, transmit_payload):
"""Check that SFTP file download works."""
sftp_session.get(str(src_path), str(dst_path))
assert dst_path.read_bytes() == transmit_payload


def test_get_existing(dst_exists_path, src_path, sftp_session, transmit_payload):
"""Check that SFTP file download works when target file exists."""
sftp_session.get(str(src_path), str(dst_exists_path))
assert dst_exists_path.read_bytes() == transmit_payload


def test_put_existing(dst_exists_path, src_path, sftp_session, transmit_payload):
"""Check that SFTP file upload works when target file exists."""
sftp_session.put(str(src_path), str(dst_exists_path))
assert dst_exists_path.read_bytes() == transmit_payload
Loading