Skip to content

Commit

Permalink
Always check lib.sftp_dir_eof() in readdir()
Browse files Browse the repository at this point in the history
`lib.sftp_readdir()` can return null if there was an error or if it's at the end
of the directory.
  • Loading branch information
JamesWrigley committed Oct 12, 2024
1 parent cf8fc39 commit 8c7d5d7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
6 changes: 6 additions & 0 deletions docs/src/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ CurrentModule = LibSSH
This documents notable changes in LibSSH.jl. The format is based on [Keep a
Changelog](https://keepachangelog.com).

## Unreleased

### Fixed

- Improved handling of possible errors in [`Base.readdir()`](@ref).

## [v0.6.0] - 2024-10-11

### Added
Expand Down
23 changes: 17 additions & 6 deletions src/sftp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,14 @@ function Base.readdir(dir::AbstractString, sftp::SftpSession;
throw(SftpException("Couldn't open path", dir, sftp))
end

# Helper function to close the lib.sftp_dir
close_directory = () -> begin
ret = @lockandblock sftp.session lib.sftp_closedir(dir_ptr)
if ret == SSH_ERROR
throw(SftpException("Closing remote directory failed", dir, sftp))

Check warning on line 383 in src/sftp.jl

View check run for this annotation

Codecov / codecov/patch

src/sftp.jl#L383

Added line #L383 was not covered by tests
end
end

# Read contents
while isopen(sftp)
attr_ptr = @lockandblock sftp.session lib.sftp_readdir(sftp.ptr, dir_ptr)
Expand All @@ -387,15 +395,18 @@ function Base.readdir(dir::AbstractString, sftp::SftpSession;
push!(entries, attr)
end
else
break
if lib.sftp_dir_eof(dir_ptr) == 1
# We've reached the end of the directories
break
else
# Something's gone wrong
close_directory()
throw(SftpException("Couldn't get directory contents", dir, sftp))

Check warning on line 404 in src/sftp.jl

View check run for this annotation

Codecov / codecov/patch

src/sftp.jl#L403-L404

Added lines #L403 - L404 were not covered by tests
end
end
end

# Close directory
ret = @lockandblock sftp.session lib.sftp_closedir(dir_ptr)
if ret == SSH_ERROR
throw(SftpException("Closing remote directory failed", dir, sftp))
end
close_directory()

if only_names
entry_names = [x.name for x in entries]
Expand Down

0 comments on commit 8c7d5d7

Please sign in to comment.