/* Example of using LD_PRELOAD to force TCP keep-alives on.
 * 
 * compile with
 *
 * gcc -o keep_alive.so -shared keep_alive.c -ldl
 *
 * Use with "LD_PRELOAD=/full/path/to/keep_alive.so program"
 *
 * Warning -- developed and tested with ffmpeg, but all use of such
 *            tricks I regard as dangerous. It is far better to fix
 *            the source of the orginal code. Indended as a demonstration,
 *            not for serious use. No warrenty. Etc.
 *
 * MJR 11/21
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdlib.h>

#include <errno.h>

#define __USE_GNU
#include <dlfcn.h>

int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t
             addrlen){
  static int (*connect_real)(int, const struct sockaddr*, socklen_t)=NULL;
  unsigned char *c;
  int rtn,data,old_errno;

  if (!connect_real) connect_real=dlsym(RTLD_NEXT,"connect");

  rtn=connect_real(sockfd,serv_addr,addrlen);

  if (((rtn==0)||(errno=EINPROGRESS))&&(serv_addr->sa_family==AF_INET)){
    old_errno=errno;
    data=1;
    if (!setsockopt(sockfd,SOL_SOCKET,SO_KEEPALIVE,&data,sizeof(data))){
      data=40; /* Worry after 40 seconds */
      setsockopt(sockfd,IPPROTO_TCP,TCP_KEEPIDLE,&data,sizeof(data));
      data=4; /* Send four probes */
      setsockopt(sockfd,IPPROTO_TCP,TCP_KEEPCNT,&data,sizeof(data));
      data=6; /* 6s between each probe */
      setsockopt(sockfd,IPPROTO_TCP,TCP_KEEPINTVL,&data,sizeof(data));
    }
    errno=old_errno;
  }
  
  return rtn;
}
