Routers and firewalls dropping tcp connection after a short period (eg five minutes) is a problem for applications that don't have configurable keepalive options.
Fabio Busatto's intercept library libkeepalive works by intercepting function calls to socket(2) and setting the keepalive parameters using setsockopt(2).
The actual values of (SO_KEEPALIVE, TCP_KEEPCNT, TCP_KEEPIDLE, TCP_KEEPINTVL) are passed to the process in environment variables.
Since these parameters only apply to tcp, my take on this approach was to intercept only the connect(2) and accept(2) system calls and to retrieve the parameter values from a configuration file instead of from the processes' environment. eg
# SSH to 188.8.131.52 env LD_PRELOAD=/intercept/libkeepalive.so /usr/bin/ssh firstname.lastname@example.org # Example configuration file (location is defined at compile time.) # Connect entries #C destips/mask dest-portrange keepalive idle intvl count # Accept entries #A srcpip/mask local-portrange keepalive idle intvl count C 192.168.0.0/16 * N - - - C 184.108.40.206 22 Y 240 75 8
In this example the ssh matches the second entry and the parameters are taken from the file.
Source at https://github.com/pellucida/keepalive/
Not thread aware in any way (ie not reentrant or async safe.) So only suitable for single threaded processes. Connect(2) or accept(2) shouldn't be called directly or indirectly from signal handlers.
An Mac OSX [10.4.11] version of Fabio's code http://toves.freeshell.org/interpose/old/keepalive_osx.c
Updated version that intercepts connect(2) http://toves.freeshell.org/interpose/files/
Creative Commons CC0 http://creativecommons.org/publicdomain/zero/1.0/legalcode