Closing an SSH channel properly involves more steps than just "closing it" on one side.
First, the documentation for libssh2_channel_close()
says it sends "an SSH_MSG_CLOSE packet to the remote host which serves as instruction that no further data will be sent to it", which is OK, but also that "the remote host may still send data back until it sends its own close message in response".
This command should be therefore followed by libssh2_channel_wait_closed()
, which handles the rest of the communication "until the remote host closes the named channel".
Additionally, as described e.g. in comment for this libssh2 commit, "sending SSH_MSG_CHANNEL_CLOSE without channel EOF is explicitly allowed in RFC 4254, but some non-conforming servers will hang or time out when the channel is closed before EOF".
Thus performing another combo of libssh2_channel_send_eof()
and libssh2_channel_wait_eof()
before the close operation itself might be necessary too for compatibility.
Since libssh2 version 1.2.5 (April 13 2010), because of that commit mentioned earlier, libssh2 should send the EOF itself automatically when closing if not already sent.
There are some examples in libssh2 itself (like scp_write.c) which do the closure explicitly and it looks like this:
libssh2_channel_send_eof(channel);
libssh2_channel_wait_eof(channel);
libssh2_channel_wait_closed(channel);
libssh2_channel_free(channel);
(Of course, all of the functions above simply need to be invoked multiple times as long as they return LIBSSH2_ERROR_EAGAIN
for non-blocking sockets.)