2 * Simple LD_PRELOAD wrapper to "convert" network sockets to UNIX sockets;
3 * works for clients and servers. See README for details.
5 * Copyright (C) 2013 Simon Ruderich
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 /* Necessary for RTLD_NEXT. */
30 #include <netinet/in.h>
35 #include <sys/socket.h>
37 #include <sys/types.h>
44 #define LOG_LEVEL_ERROR 1
45 #define LOG_LEVEL_WARNING 2
46 #define LOG_LEVEL_DEBUG 3
47 #define LOG_LEVEL_MASK LOG_LEVEL_DEBUG
49 #define LOG_LEVEL_PERROR (1 << 10)
51 #define OPTION_PARSED (1 << 1)
52 /* Don't intercept listen(), accept(). */
53 #define OPTION_CLIENT_ONLY (1 << 2)
54 /* Don't intercept connect(). */
55 #define OPTION_SERVER_ONLY (1 << 3)
58 /* GLOBAL VARIABLES */
65 /* Used by listen(). */
66 struct sockaddr *orig_addr;
67 socklen_t orig_addrlen;
72 static struct list socket_list = {
73 .orig_sockfd = -1, /* must not match a valid sockfd */
76 static int global_options;
79 /* LOG FUNCTIONS/MACROS */
81 static int get_log_level(void);
83 static void log_helper(int action, const char *file, int line, const char *format, va_list ap) {
84 int saved_errno = errno;
88 log_level = get_log_level();
91 int level = action & LOG_LEVEL_MASK;
92 if (level > log_level) {
97 if (level == LOG_LEVEL_DEBUG) {
99 } else if (level == LOG_LEVEL_WARNING) {
101 } else if (level == LOG_LEVEL_ERROR) {
107 /* Prevent other threads from interrupting the printf()s. */
110 fprintf(stderr, "socket2unix [%s] ", prefix);
111 fprintf(stderr, "[%s:%3d] ", file, line);
112 vfprintf(stderr, format, ap);
114 if ((action & ~LOG_LEVEL_MASK) == LOG_LEVEL_PERROR) {
115 fprintf(stderr, ": ");
119 /* perror writes a newline. */
121 fprintf(stderr, "\n");
126 if (level == LOG_LEVEL_ERROR) {
127 fprintf(stderr, "Aborting.\n");
132 static void log_(int level, const char *file, int line, const char *format, ...)
133 __attribute__((format(printf, 4, 5)));
134 static void log_(int level, const char *file, int line, const char *format, ...) {
137 va_start(ap, format);
138 log_helper(level, file, line, format, ap);
143 log_(LOG_LEVEL_ERROR, __FILE__, __LINE__, __VA_ARGS__)
145 log_(LOG_LEVEL_WARNING, __FILE__, __LINE__, __VA_ARGS__)
147 log_(LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__)
150 log_(LOG_LEVEL_ERROR | LOG_LEVEL_PERROR, __FILE__, __LINE__, __VA_ARGS__)
155 /* Load the function name using dlsym() if necessary and store it in pointer.
156 * Terminate program on failure. */
157 #define LOAD_FUNCTION(pointer, name) \
158 if ((pointer) == NULL) { \
160 dlerror(); /* Clear possibly existing error. */ \
162 *(void **) (&(pointer)) = dlsym(RTLD_NEXT, (name)); \
164 if ((error = dlerror()) != NULL) { \
165 ERROR("%s\n", error); \
170 /* OTHER FUNCTIONS */
172 static void *xmalloc(size_t size) {
173 void *x = malloc(size);
175 DIE("malloc(%zu)", size);
180 static struct list *find_sockfd(int sockfd) {
183 if (sockfd == socket_list.orig_sockfd) {
187 for (e = &socket_list; e != NULL; e = e->next) {
188 if (e->orig_sockfd == sockfd) {
194 static struct list *remove_sockfd(int sockfd) {
197 if (sockfd == socket_list.orig_sockfd) {
201 for (e = &socket_list, p = NULL; e != NULL; p = e, e = e->next) {
202 if (e->orig_sockfd == sockfd) {
210 static const char *get_socket_path(void) {
211 const char *path = getenv("SOCKET2UNIX_PATH");
213 ERROR("SOCKET2UNIX_PATH environment variable not defined");
215 if (path[0] != '/') {
216 ERROR("SOCKET2UNIX_PATH '%s' must be an absolute path", path);
220 static int get_log_level(void) {
221 const char *level = getenv("SOCKET2UNIX_DEBUG");
224 return LOG_LEVEL_DEBUG;
226 return LOG_LEVEL_WARNING;
229 int number = atoi(level);
230 if (number <= 0 || number > LOG_LEVEL_DEBUG) {
231 number = LOG_LEVEL_DEBUG;
235 static int get_options(void) {
236 const char *start = getenv("SOCKET2UNIX_OPTIONS");
238 return OPTION_PARSED;
241 int options = OPTION_PARSED;
243 const char *end = start + strlen(start);
244 const char *pos, *curend;
246 for (pos = start; pos < end; pos = curend + 1) {
249 curend = strchr(pos, ',');
250 if (curend == NULL) {
253 length = (size_t)(curend - pos);
255 if (!strncmp("client_only", pos, length)) {
256 options |= OPTION_CLIENT_ONLY;
257 } else if (!strncmp("server_only", pos, length)) {
258 options |= OPTION_SERVER_ONLY;
260 char option[length + 1];
261 strncpy(option, pos, length);
262 option[length] = '\0';
263 ERROR("unknown option '%s' in SOCKET2UNIX_OPTIONS", option);
267 if ((options & OPTION_CLIENT_ONLY) && (options & OPTION_SERVER_ONLY)) {
268 ERROR("conflicting options 'client_only', 'server_only' "
269 "in SOCKET2UNIX_OPTIONS");
275 static const char *af_to_name(int af) {
278 } else if (af == AF_LOCAL) {
280 } else if (af == AF_INET) {
282 } else if (af == AF_INET6) {
284 } else if (af == AF_IPX) {
287 } else if (af == AF_NETLINK) {
291 } else if (af == AF_X25) {
295 } else if (af == AF_AX25) {
299 } else if (af == AF_ATMPVC) {
302 } else if (af == AF_APPLETALK) {
303 return "AF_APPLETALK";
305 } else if (af == AF_PACKET) {
312 static const char *sock_to_name(int sock) {
313 if (sock & SOCK_STREAM) {
314 return "SOCK_STREAM";
315 } else if (sock & SOCK_DGRAM) {
317 } else if (sock & SOCK_SEQPACKET) {
318 return "SOCK_SEQPACKET";
319 } else if (sock & SOCK_RAW) {
321 } else if (sock & SOCK_RDM) {
324 } else if (sock & SOCK_PACKET) {
325 return "SOCK_PACKET";
328 return "SOCK_UNKNOWN";
331 /* for getsockopt()/setsockopt(). */
332 static const char *level_to_name(int level) {
333 if (level == SOL_SOCKET) {
336 } else if (level == SOL_IP) {
340 } else if (level == SOL_IPV6) {
343 } else if (level == IPPROTO_TCP) {
344 return "IPPROTO_TCP";
345 } else if (level == IPPROTO_UDP) {
346 return "IPPROTO_UDP";
348 return "SOL_UNKNOWN";
353 static int set_sockaddr_un(struct sockaddr_un *sockaddr,
354 const struct sockaddr *addr, socklen_t addrlen) {
355 /* Just in case ... */
356 if ((addr->sa_family == AF_INET
357 && addrlen < sizeof(struct sockaddr_in))
358 || (addr->sa_family == AF_INET6
359 && addrlen < sizeof(struct sockaddr_in6))) {
360 WARN("invalid addrlen from program");
364 const char *socket_path = get_socket_path();
366 /* The program may open multiple sockets, e.g. IPv4 and IPv6 and on
367 * multiple ports. Create unique paths. */
370 if (addr->sa_family == AF_INET) {
372 port = ntohs(((const struct sockaddr_in *)addr)->sin_port);
373 } else if (addr->sa_family == AF_INET6) {
375 port = ntohs(((const struct sockaddr_in6 *)addr)->sin6_port);
379 WARN("unknown sa_family '%s' (%d)",
380 af_to_name(addr->sa_family), addr->sa_family);
383 /* Initialize sockaddr_un. */
384 sockaddr->sun_family = AF_UNIX;
385 int written = snprintf(sockaddr->sun_path, sizeof(sockaddr->sun_path),
386 "%s-%s-%d", socket_path, af, port);
387 /* The maximum length is quite short, check it. */
388 if (written >= (int)sizeof(sockaddr->sun_path)) {
389 ERROR("path '%s-%s-%d' too long for UNIX socket",
390 socket_path, af, port);
396 static int replace_socket(int replaceefd, int replacerfd) {
397 static int (*real_close)(int);
398 LOAD_FUNCTION(real_close, "close");
400 /* Replace socket replaceefd with replacerfd. After dup2() both socket fds
401 * point to the same socket (replacerfd). */
402 if (dup2(replacerfd, replaceefd) < 0) {
405 /* We don't need replacerfd anymore. The program will use our replacement
406 * and we don't need it for anything else. Use real_close() to prevent
407 * unnecessary debug messages. */
408 real_close(replacerfd);
413 /* FUNCTIONS OVERWRITTEN BY LD_PRELOAD */
415 int socket(int domain, int type, int protocol) {
416 static int (*real_socket)(int, int, int);
417 LOAD_FUNCTION(real_socket, "socket");
419 /* We return the normal socket because we don't know yet if it's a client
420 * or a listen socket and therefore if we should replace it or not. This
421 * happens in listen() and connect(), see below. */
423 int sockfd = real_socket(domain, type, protocol);
426 || domain == AF_LOCAL) {
430 DBG("socket(%s, %s, %d)",
431 af_to_name(domain), sock_to_name(type), protocol);
433 struct list *entry = xmalloc(sizeof(*entry));
434 memset(entry, 0, sizeof(*entry));
436 entry->orig_sockfd = sockfd;
437 entry->orig_domain = domain;
438 entry->orig_type = type;
440 entry->next = socket_list.next;
441 socket_list.next = entry;
447 static int (*real_close)(int);
448 LOAD_FUNCTION(real_close, "close");
450 struct list *entry = remove_sockfd(fd);
452 DBG("close(%d): sockfd not found", fd);
453 return real_close(fd);
455 assert(fd == entry->orig_sockfd);
457 DBG("close(%d)", fd);
458 free(entry->orig_addr);
461 return real_close(fd);
464 int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
465 static int (*real_bind)(int, const struct sockaddr *, socklen_t);
466 LOAD_FUNCTION(real_bind, "bind");
468 if (addr == NULL || addrlen < sizeof(addr->sa_family)
469 || addr->sa_family == AF_UNIX
470 || addr->sa_family == AF_LOCAL) {
471 return real_bind(sockfd, addr, addrlen);
474 struct list *entry = find_sockfd(sockfd);
476 DBG("bind(%d, ..): sockfd not found", sockfd);
477 return real_bind(sockfd, addr, addrlen);
479 assert(sockfd == entry->orig_sockfd);
480 DBG("bind(%d, ..): %s %s",
482 af_to_name(entry->orig_domain), sock_to_name(entry->orig_type));
484 /* Copy struct sockaddr, we need it later in listen(). */
485 entry->orig_addr = xmalloc(addrlen);
486 memcpy(entry->orig_addr, addr, addrlen);
487 entry->orig_addrlen = addrlen;
489 return real_bind(sockfd, addr, addrlen);
492 int listen(int sockfd, int backlog) {
493 static int (*real_listen)(int, int);
494 LOAD_FUNCTION(real_listen, "listen");
496 if (!global_options) {
497 global_options = get_options();
500 if (global_options & OPTION_CLIENT_ONLY) {
501 DBG("listen(%d, %d): server hooking disabled", sockfd, backlog);
502 return real_listen(sockfd, backlog);
505 struct list *entry = find_sockfd(sockfd);
507 DBG("listen(%d, %d): sockfd not found", sockfd, backlog);
508 return real_listen(sockfd, backlog);
510 assert(sockfd == entry->orig_sockfd);
511 DBG("listen(%d, %d): %s %s",
513 af_to_name(entry->orig_domain), sock_to_name(entry->orig_type));
515 int unix_sockfd = socket(AF_UNIX, entry->orig_type, 0);
516 if (unix_sockfd < 0) {
517 DIE("listen(): failed to create UNIX socket");
520 struct sockaddr_un sockaddr;
521 if (set_sockaddr_un(&sockaddr, entry->orig_addr,
522 entry->orig_addrlen) != 0) {
523 ERROR("listen(%d, ..) failed", sockfd);
526 DBG("listen(%d, ..): using path '%s'", sockfd, sockaddr.sun_path);
529 while (attempts < 10) {
530 if (bind(unix_sockfd, (struct sockaddr *)&sockaddr,
531 sizeof(sockaddr)) == 0) {
534 if (errno != EADDRINUSE) {
535 DIE("listen(%d, ..): failed to bind to '%s'",
536 sockfd, sockaddr.sun_path);
539 /* File already exists, unlink it if it's a socket. This has a race
540 * condition, but the worst case is that we delete a file created by
541 * the user at the path he told us to use. Tough luck .. */
544 if (lstat(sockaddr.sun_path, &buf) != 0) {
545 /* Looks like a race, better abort. */
546 DIE("listen(%d, ..): lstat on UNIX socket '%s' failed",
547 sockfd, sockaddr.sun_path);
550 if (!S_ISSOCK(buf.st_mode)) {
551 ERROR("listen(%d, ..): path '%s' exits and is no socket",
552 sockfd, sockaddr.sun_path);
555 WARN("listen(%d, ..): unlinking '%s'", sockfd, sockaddr.sun_path);
556 if (unlink(sockaddr.sun_path) != 0) {
557 DIE("listen(%d, ..): unlink '%s' failed",
558 sockfd, sockaddr.sun_path);
564 if (attempts == 10) {
565 ERROR("listen(%d, ..): failed to create UNIX socket file", sockfd);
568 /* Replace the original socket of the program with our socket. */
569 if (replace_socket(entry->orig_sockfd, unix_sockfd)) {
570 DIE("listen(): failed to replace socket");
573 if (real_listen(entry->orig_sockfd, backlog) != 0) {
574 DIE("listen(): failed to listen");
580 int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
581 static int (*real_accept)(int, struct sockaddr *, socklen_t *);
582 LOAD_FUNCTION(real_accept, "accept");
584 if (!global_options) {
585 global_options = get_options();
588 if (global_options & OPTION_CLIENT_ONLY) {
589 DBG("accept(%d, ..): server hooking disabled", sockfd);
590 return real_accept(sockfd, addr, addrlen);
593 struct list *entry = find_sockfd(sockfd);
595 DBG("accept(%d, ..): sockfd not found", sockfd);
596 return real_accept(sockfd, addr, addrlen);
598 assert(sockfd == entry->orig_sockfd);
599 DBG("accept(%d, ..): %s %s",
601 af_to_name(entry->orig_domain), sock_to_name(entry->orig_type));
603 struct sockaddr_un sockaddr;
604 socklen_t size = sizeof(sockaddr);
605 int sock = real_accept(entry->orig_sockfd, (struct sockaddr *)&sockaddr,
608 DIE("accept(%d, ..): failed to accept", sockfd);
611 if (addr == NULL || addrlen == NULL) {
614 DBG("accept(%d, ..): caller requested sockaddr", sockfd);
616 if (*addrlen < size) {
617 WARN("accept(%d, ..): invalid addrlen from program", sockfd);
622 /* This is not the protocol the program asked for (AF_* vs. AF_UNIX), but
623 * it should work most of the time. */
624 memcpy(addr, &sockaddr, size);
627 /* TODO: is this enough? */
632 int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
633 static int (*real_connect)(int, const struct sockaddr *, socklen_t);
634 LOAD_FUNCTION(real_connect, "connect");
636 if (!global_options) {
637 global_options = get_options();
640 if (global_options & OPTION_SERVER_ONLY) {
641 DBG("connect(%d, ..): client hooking disabled", sockfd);
642 return real_connect(sockfd, addr, addrlen);
645 if (addr == NULL || addrlen < sizeof(addr->sa_family)
646 || addr->sa_family == AF_UNIX
647 || addr->sa_family == AF_LOCAL) {
648 return real_connect(sockfd, addr, addrlen);
651 struct list *entry = find_sockfd(sockfd);
653 DBG("connect(%d, ..): sockfd not found", sockfd);
654 return real_connect(sockfd, addr, addrlen);
656 assert(sockfd == entry->orig_sockfd);
657 DBG("connect(%d, ..): %s %s",
659 af_to_name(entry->orig_domain), sock_to_name(entry->orig_type));
661 int unix_sockfd = socket(AF_UNIX, entry->orig_type, 0);
662 if (unix_sockfd < 0) {
663 DIE("bind(): failed to create UNIX socket");
666 /* Replace the original socket of the program with our socket. */
667 if (replace_socket(entry->orig_sockfd, unix_sockfd)) {
668 DIE("connect(): failed to replace socket");
671 struct sockaddr_un sockaddr;
672 if (set_sockaddr_un(&sockaddr, addr, addrlen) != 0) {
673 ERROR("connect(%d, ..) failed", sockfd);
676 DBG("connect(%d, ..): using path '%s'", sockfd, sockaddr.sun_path);
678 if (real_connect(entry->orig_sockfd, (struct sockaddr *)&sockaddr,
679 sizeof(sockaddr)) != 0) {
680 DIE("connect(%d, ..): failed to connect", sockfd);
687 int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
688 static int (*real_getsockname)(int, struct sockaddr *, socklen_t *);
689 LOAD_FUNCTION(real_getsockname, "getsockname");
691 DBG("getsockname(%d, ..)", sockfd);
693 return real_getsockname(sockfd, addr, addrlen);
696 int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
697 static int (*real_getpeername)(int, struct sockaddr *, socklen_t *);
698 LOAD_FUNCTION(real_getpeername, "getpeername");
700 DBG("getpeername(%d, ..)", sockfd);
702 return real_getpeername(sockfd, addr, addrlen);
705 int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen) {
706 static int (*real_getsockopt)(int, int, int, void *, socklen_t *);
707 LOAD_FUNCTION(real_getsockopt, "getsockopt");
709 DBG("getsockopt(%d, %d %s, %d, ..)",
710 sockfd, level, level_to_name(level), optname);
712 return real_getsockopt(sockfd, level, optname, optval, optlen);
714 int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen) {
715 static int (*real_setsockopt)(int, int, int, const void *, socklen_t);
716 LOAD_FUNCTION(real_setsockopt, "setsockopt");
718 DBG("setsockopt(%d, %d %s, %d, ..)",
719 sockfd, level, level_to_name(level), optname);
721 return real_setsockopt(sockfd, level, optname, optval, optlen);