[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Best way to deal with long opened sessions

Hi Stefano,

ssh_is_connected() returns session->alive which is only set to 0 when
the client or server explicitly disconnects or the handshake fails.

If your connection silently dies, you can only notice this when you send
anything to the server and it does not respond within some time frame.
If you configured a libssh timeout, most blocking functions will return
SSH_ERROR when the server does not respond to your request. You would
still have to call ssh_disconnect() yourself because a timeout does not
necessarily mean that the remote host is gone.

If you leave your connection open for longer periods of time without
interacting with the server, you will not notice a silently broken
connection until you send something to the server and wait for its
reply. If you want to detect broken connections even while idling, you
should probably enable TCP keep-alive packets by enabling SO_KEEPALIVE
on the socket:
> socket_t socket = ssh_get_fd(session);
> int yes = 1;
> if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(int)) < 0) {
>   // setting SO_KEEPALIVE failed
> }

It will cause your OS kernel to automatically send keep-alive TCP
packets every now and then (configurable on Linux via TCP_KEEPIDLE,
TCP_KEEPINTVL, TCP_KEEPCNT socket options). This is transparent to your
application. If the server does not respond for some time (Linux kernel
default: 30 minutes), the TCP socket is closed by the kernel. To notice
the latter, the socket must be polled. So, you need to regularly call
any libssh function that reads from or writes to the socket and check if
that fails.

Best regards
Tilo Eckert

Am 14.03.2019 um 07:57 schrieb Stefano Mtangoo:
> Hi,
> This library have made my life simpler and would like to thank everyone
> involded.
> I have one thing that I would like to get your advice on. I keep my
> session long open when I edit something on the server. During those long
> time network can be lost and be restored.
> Is checking for `ssh_is_connected` alone enough?
> I use SFTP module to connect to the server and edit stuffs and ssh_* for
> everything else.
> Regards,
> Stefano
> -- 
> for me to live is Christ to die is gain

Re: Best way to deal with long opened sessionsStefano Mtangoo <mwinjilisti@xxxxxxxxx>
Best way to deal with long opened sessionsStefano Mtangoo <mwinjilisti@xxxxxxxxx>
Archive administrator: postmaster@lists.cynapses.org