From 8c7d5d76bb1486fc39c2a371e77bfa37463281c0 Mon Sep 17 00:00:00 2001 From: JamesWrigley Date: Sat, 12 Oct 2024 21:05:30 +0200 Subject: [PATCH] Always check lib.sftp_dir_eof() in readdir() `lib.sftp_readdir()` can return null if there was an error or if it's at the end of the directory. --- docs/src/changelog.md | 6 ++++++ src/sftp.jl | 23 +++++++++++++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/docs/src/changelog.md b/docs/src/changelog.md index 6022030..dd03822 100644 --- a/docs/src/changelog.md +++ b/docs/src/changelog.md @@ -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 diff --git a/src/sftp.jl b/src/sftp.jl index f51470d..0c1f830 100644 --- a/src/sftp.jl +++ b/src/sftp.jl @@ -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)) + end + end + # Read contents while isopen(sftp) attr_ptr = @lockandblock sftp.session lib.sftp_readdir(sftp.ptr, dir_ptr) @@ -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)) + 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]