libssh2 session cleanup without blocking?

1.4k Views Asked by At

My app uses libssh2 to communicate over SSH, and generally works fine. One problem I have is when the remote host dies unexpectedly -- the remote host in this case is an embedded device that can lose power at any time, so this isn't uncommon.

When that happens, my app detects that the remote computer has stopped responding to pings, and tears down the local end of the SSH connection like this:

void SSHSession :: CleanupSession()
{
   if (_uploadFileChannel)
   {
      libssh2_channel_free(_uploadFileChannel);
      _uploadFileChannel = NULL;
   }

   if (_sendCommandsChannel)
   {
      libssh2_channel_free(_sendCommandsChannel);
      _sendCommandsChannel = NULL;
   }

   if (_session)
   {
      libssh2_session_disconnect(_session, "bye bye");
      libssh2_session_free(_session);
      _session = NULL;
   }
}

Pretty straightforward, but the problem is that the libssh2_channel_free() calls can block for a long time waiting for the remote end to respond to the "I'm going away now" message, which it will never do because it's powered off... but in the meantime, my app is frozen (blocked in the cleanup-routine), which isn't good.

Is there any way (short of hacking libssh2) to avoid this? I'd like to just tear down the local SSH data structures, and never block during this tear-down. (I suppose I could simply leak the SSH session memory, or delegate it to a different thread, but those seem like ugly hacks rather than proper solutions)

2

There are 2 best solutions below

0
On

I'm not experienced with libssh2, but perhaps we can get different behavior out of libssh2 by using libssh2_session_disconnect_ex and a different disconnect reason: SSH_DISCONNECT_CONNECTION_LOST.

libssh2_session_disconnect is equivalent to using libssh2_session_disconnect_ex with the reason SSH_DISCONNECT_BY_APPLICATION. If libssh2 knows that the connection is lost, maybe it won't try to talk to the other side.

http://libssh2.sourceforge.net/doc/#libssh2sessiondisconnectex

http://libssh2.sourceforge.net/doc/#sshdisconnectcodes

0
On

Set to non-blocking mode and take the control of reading data from the socket to your hand by setting callback function to read data from the soket using libssh2_session_callback_set with LIBSSH2_CALLBACK_RECV for cbtype

void *libssh2_session_callback_set(LIBSSH2_SESSION *session, int cbtype, void *callback);

If you can't read data from the socket due to error ENOTCONN that means remote end has closed the socket or connection failed, then return -ENOTCONN in your callback function