ports/net/socketbind/files/socketbind.c
Eugene Grosbein 03a9755147
net/socketbind: unbreak the library
The code has multiple issues making it unusable with modern FreeBSD:

* it uses long gone ascii2addr() function removed in 2007;
* it passes hardcoded "/usr/lib/libc.so" path to dlopen(),
  but now it is plain text hint file;
* this IPv4-only code neglects to check passed domain for PF_INET
  messing with sockets in other domains (like PF_INET6, PF_LOCAL).

Still, it is very useful while dealing with software like Nagios
that does not support binding to specific IPv4 address
for outgoing connections. The library solves the problem with single line
in /etc/rc.conf:

nagios_env="LD_PRELOAD=/usr/local/lib/libsocketbind.so.1 BINDTO=192.168.6.1"

This changes unbreaks the library making it usable again.
2023-10-05 20:16:51 +07:00

45 lines
1,014 B
C

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <dlfcn.h>
#include <stdlib.h>
static void *socket_p = NULL;
static struct sockaddr_in bind_addr;
static int do_bind;
int socket(int domain, int type, int protocol) {
auto int res;
if (socket_p == NULL) {
char *str;
socket_p = dlsym(RTLD_NEXT, "socket");
if (!socket_p)
return -1;
#ifdef DEBUG
printf("Loaded socket %x\n", socket_p);
#endif
if ((domain == PF_INET) && (str = getenv("BINDTO")) != NULL) {
#ifdef DEBUG
printf("Thinking about bind\n");
#endif
if (inet_aton(str, &bind_addr.sin_addr)) {
do_bind = 1;
bind_addr.sin_len = INET_ADDRSTRLEN;
bind_addr.sin_family = AF_INET;
#ifdef DEBUG
printf("WILL DO BIND %s, %x\n", str, bind_addr.sin_addr.s_addr);
#endif
}
}
}
res = ((int(*)(int a, int b, int c))socket_p)(domain, type, protocol);
if (do_bind) {
bind(res, (struct sockaddr*)&bind_addr, INET_ADDRSTRLEN);
}
return res;
};