Memory leak with sftp_open when access type has O_APPEND enabled
Hi everyone. I'm testing this great library with stable version-0.10 and have encountered a memory leak issue.
When you open a remote file using sftp_open and the access type has O_APPEND enabled, this results in a memory leak. This is because sftp_open calls sftp_stat to retrieve information from the file but the sftp_attributes structure is not freed.
To reproduce this issue, call sftp_open with access type: O_WRONLY | O_APPEND
sftp_open(sftp, remote path, O_WRONLY | O_APPEND, S_IRWXU)
The problem is in the file: src/sftp.c inside the sftp_open function on line 1884
Here I call sftp_stat to get the sftp_attributes structure but it is never freed.
stat_data = sftp_stat(sftp, file);
To fix the problem, we need to call:
sftp_attributes_free(stat_data);
before return. Here the error reported by valgrind:
==27369== HEAP SUMMARY:
==27369== in use at exit: 144 bytes in 1 blocks
==27369== total heap usage: 2,798 allocs, 2,797 frees, 416,882 bytes allocated
==27369==
==27369== Searching for pointers to 1 not-freed blocks
==27369== Checked 186,200 bytes
==27369==
==27369== 144 bytes in 1 blocks are definitely lost in loss record 1 of 1
==27369== at 0x4C33B25: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27369== by 0x4E8E4D2: sftp_parse_attr (in /usr/lib/x86_64-linux-gnu/libssh.so.4.9.6)
==27369== by 0x4E91F1D: sftp_stat (in /usr/lib/x86_64-linux-gnu/libssh.so.4.9.6)
==27369== by 0x4E92214: sftp_open (in /usr/lib/x86_64-linux-gnu/libssh.so.4.9.6)
==27369== by 0x13CCB8: Ftp::SFTPClient::PrepareUploadFile(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned int, bool) (sftpclient.cpp:110)
==27369== by 0x13D728: Ftp::SFTPClient::ProcessUpload(unsigned int, std::iostream&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool, std::function<void (unsigned long, unsigned long)>*) (sftpclient.cpp:151)
==27369== by 0x13EC5F: Ftp::SFTPClient::AppendFile(std::iostream&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::function<void (unsigned long, unsigned long)>*) (sftpclient.cpp:276)
==27369== by 0x13C007: main (main.cpp:104)
==27369==
==27369== LEAK SUMMARY:
==27369== definitely lost: 144 bytes in 1 blocks
==27369== indirectly lost: 0 bytes in 0 blocks
==27369== possibly lost: 0 bytes in 0 blocks
==27369== still reachable: 0 bytes in 0 blocks
==27369== suppressed: 0 bytes in 0 blocks
==27369==
==27369== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==27369== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
I'm attaching the patch to solve the problem.
Greetings