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, ": ");
123 if (level == LOG_LEVEL_ERROR) {
124 fprintf(stderr, "Aborting.\n");
129 static void log_(int level, const char *file, int line, const char *format, ...)
130 __attribute__((format(printf, 4, 5)));
131 static void log_(int level, const char *file, int line, const char *format, ...) {
134 va_start(ap, format);
135 log_helper(level, file, line, format, ap);
140 log_(LOG_LEVEL_ERROR, __FILE__, __LINE__, __VA_ARGS__)
142 log_(LOG_LEVEL_WARNING, __FILE__, __LINE__, __VA_ARGS__)
144 log_(LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__)
147 log_(LOG_LEVEL_ERROR | LOG_LEVEL_PERROR, __FILE__, __LINE__, __VA_ARGS__)
152 /* Load the function name using dlsym() if necessary and store it in pointer.
153 * Terminate program on failure. */
154 #define LOAD_FUNCTION(pointer, name) \
155 if ((pointer) == NULL) { \
157 dlerror(); /* Clear possibly existing error. */ \
159 *(void **) (&(pointer)) = dlsym(RTLD_NEXT, (name)); \
161 if ((error = dlerror()) != NULL) { \
162 ERROR("%s\n", error); \
167 /* OTHER FUNCTIONS */
169 static void *xmalloc(size_t size) {
170 void *x = malloc(size);
172 DIE("malloc(%zu)", size);
177 static struct list *find_sockfd(int sockfd) {
180 if (sockfd == socket_list.orig_sockfd) {
184 for (e = &socket_list; e != NULL; e = e->next) {
185 if (e->orig_sockfd == sockfd) {
191 static struct list *remove_sockfd(int sockfd) {
194 if (sockfd == socket_list.orig_sockfd) {
198 for (e = &socket_list, p = NULL; e != NULL; p = e, e = e->next) {
199 if (e->orig_sockfd == sockfd) {
207 static const char *get_socket_path(void) {
208 const char *path = getenv("SOCKET2UNIX_PATH");
210 ERROR("SOCKET2UNIX_PATH environment variable not defined\n");
212 if (path[0] != '/') {
213 ERROR("SOCKET2UNIX_PATH '%s' must be an absolute path\n", path);
217 static int get_log_level(void) {
218 const char *level = getenv("SOCKET2UNIX_DEBUG");
221 return LOG_LEVEL_DEBUG;
223 return LOG_LEVEL_WARNING;
226 int number = atoi(level);
227 if (number <= 0 || number > LOG_LEVEL_DEBUG) {
228 number = LOG_LEVEL_DEBUG;
232 static int get_options(void) {
233 const char *start = getenv("SOCKET2UNIX_OPTIONS");
235 return OPTION_PARSED;
238 int options = OPTION_PARSED;
240 const char *end = start + strlen(start);
241 const char *pos, *curend;
243 for (pos = start; pos < end; pos = curend + 1) {
246 curend = strchr(pos, ',');
247 if (curend == NULL) {
250 length = (size_t)(curend - pos);
252 if (!strncmp("client_only", pos, length)) {
253 options |= OPTION_CLIENT_ONLY;
254 } else if (!strncmp("server_only", pos, length)) {
255 options |= OPTION_SERVER_ONLY;
257 char option[length + 1];
258 strncpy(option, pos, length);
259 option[length] = '\0';
260 ERROR("unknown option '%s' in SOCKET2UNIX_OPTIONS\n",
265 if ((options & OPTION_CLIENT_ONLY) && (options & OPTION_SERVER_ONLY)) {
266 ERROR("conflicting options 'client_only', 'server_only' "
267 "in SOCKET2UNIX_OPTIONS\n");
273 static const char *af_to_name(int af) {
276 } else if (af == AF_LOCAL) {
278 } else if (af == AF_INET) {
280 } else if (af == AF_INET6) {
282 } else if (af == AF_IPX) {
285 } else if (af == AF_NETLINK) {
289 } else if (af == AF_X25) {
293 } else if (af == AF_AX25) {
297 } else if (af == AF_ATMPVC) {
300 } else if (af == AF_APPLETALK) {
301 return "AF_APPLETALK";
303 } else if (af == AF_PACKET) {
310 static const char *sock_to_name(int sock) {
311 if (sock & SOCK_STREAM) {
312 return "SOCK_STREAM";
313 } else if (sock & SOCK_DGRAM) {
315 } else if (sock & SOCK_SEQPACKET) {
316 return "SOCK_SEQPACKET";
317 } else if (sock & SOCK_RAW) {
319 } else if (sock & SOCK_RDM) {
322 } else if (sock & SOCK_PACKET) {
323 return "SOCK_PACKET";
326 return "SOCK_UNKNOWN";
329 /* for getsockopt()/setsockopt(). */
330 static const char *level_to_name(int level) {
331 if (level == SOL_SOCKET) {
334 } else if (level == SOL_IP) {
338 } else if (level == SOL_IPV6) {
341 } else if (level == IPPROTO_TCP) {
342 return "IPPROTO_TCP";
343 } else if (level == IPPROTO_UDP) {
344 return "IPPROTO_UDP";
346 return "SOL_UNKNOWN";
351 static int set_sockaddr_un(struct sockaddr_un *sockaddr,
352 const struct sockaddr *addr, socklen_t addrlen) {
353 /* Just in case ... */
354 if ((addr->sa_family == AF_INET
355 && addrlen < sizeof(struct sockaddr_in))
356 || (addr->sa_family == AF_INET6
357 && addrlen < sizeof(struct sockaddr_in6))) {
358 WARN("invalid addrlen from program\n");
362 const char *socket_path = get_socket_path();
364 /* The program may open multiple sockets, e.g. IPv4 and IPv6 and on
365 * multiple ports. Create unique paths. */
368 if (addr->sa_family == AF_INET) {
370 port = ntohs(((const struct sockaddr_in *)addr)->sin_port);
371 } else if (addr->sa_family == AF_INET6) {
373 port = ntohs(((const struct sockaddr_in6 *)addr)->sin6_port);
377 WARN("unknown sa_family '%s' (%d)\n",
378 af_to_name(addr->sa_family), addr->sa_family);
381 /* Initialize sockaddr_un. */
382 sockaddr->sun_family = AF_UNIX;
383 int written = snprintf(sockaddr->sun_path, sizeof(sockaddr->sun_path),
384 "%s-%s-%d", socket_path, af, port);
385 /* The maximum length is quite short, check it. */
386 if (written >= (int)sizeof(sockaddr->sun_path)) {
387 ERROR("path '%s-%s-%d' too long for UNIX socket",
388 socket_path, af, port);
394 static int replace_socket(int replaceefd, int replacerfd) {
395 static int (*real_close)(int);
396 LOAD_FUNCTION(real_close, "close");
398 /* Replace socket replaceefd with replacerfd. After dup2() both socket fds
399 * point to the same socket (replacerfd). */
400 if (dup2(replacerfd, replaceefd) < 0) {
403 /* We don't need replacerfd anymore. The program will use our replacement
404 * and we don't need it for anything else. Use real_close() to prevent
405 * unnecessary debug messages. */
406 real_close(replacerfd);
411 /* FUNCTIONS OVERWRITTEN BY LD_PRELOAD */
413 int socket(int domain, int type, int protocol) {
414 static int (*real_socket)(int, int, int);
415 LOAD_FUNCTION(real_socket, "socket");
417 /* We return the normal socket because we don't know yet if it's a client
418 * or a listen socket and therefore if we should replace it or not. This
419 * happens in listen() and connect(), see below. */
421 int sockfd = real_socket(domain, type, protocol);
424 || domain == AF_LOCAL) {
428 DBG("socket(%s, %s, %d)\n",
429 af_to_name(domain), sock_to_name(type), protocol);
431 struct list *entry = xmalloc(sizeof(*entry));
432 memset(entry, 0, sizeof(*entry));
434 entry->orig_sockfd = sockfd;
435 entry->orig_domain = domain;
436 entry->orig_type = type;
438 entry->next = socket_list.next;
439 socket_list.next = entry;
445 static int (*real_close)(int);
446 LOAD_FUNCTION(real_close, "close");
448 struct list *entry = remove_sockfd(fd);
450 DBG("close(%d): sockfd not found\n", fd);
451 return real_close(fd);
453 assert(fd == entry->orig_sockfd);
455 DBG("close(%d)\n", fd);
456 free(entry->orig_addr);
459 return real_close(fd);
462 int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
463 static int (*real_bind)(int, const struct sockaddr *, socklen_t);
464 LOAD_FUNCTION(real_bind, "bind");
466 if (addr == NULL || addrlen < sizeof(addr->sa_family)
467 || addr->sa_family == AF_UNIX
468 || addr->sa_family == AF_LOCAL) {
469 return real_bind(sockfd, addr, addrlen);
472 struct list *entry = find_sockfd(sockfd);
474 DBG("bind(%d, ..): sockfd not found\n", sockfd);
475 return real_bind(sockfd, addr, addrlen);
477 assert(sockfd == entry->orig_sockfd);
478 DBG("bind(%d, ..): %s %s\n",
480 af_to_name(entry->orig_domain), sock_to_name(entry->orig_type));
482 /* Copy struct sockaddr, we need it later in listen(). */
483 entry->orig_addr = xmalloc(addrlen);
484 memcpy(entry->orig_addr, addr, addrlen);
485 entry->orig_addrlen = addrlen;
487 return real_bind(sockfd, addr, addrlen);
490 int listen(int sockfd, int backlog) {
491 static int (*real_listen)(int, int);
492 LOAD_FUNCTION(real_listen, "listen");
494 if (!global_options) {
495 global_options = get_options();
498 if (global_options & OPTION_CLIENT_ONLY) {
499 DBG("listen(%d, %d): server hooking disabled\n", sockfd, backlog);
500 return real_listen(sockfd, backlog);
503 struct list *entry = find_sockfd(sockfd);
505 DBG("listen(%d, %d): sockfd not found\n", sockfd, backlog);
506 return real_listen(sockfd, backlog);
508 assert(sockfd == entry->orig_sockfd);
509 DBG("listen(%d, %d): %s %s\n",
511 af_to_name(entry->orig_domain), sock_to_name(entry->orig_type));
513 int unix_sockfd = socket(AF_UNIX, entry->orig_type, 0);
514 if (unix_sockfd < 0) {
515 DIE("listen(): failed to create UNIX socket");
518 struct sockaddr_un sockaddr;
519 if (set_sockaddr_un(&sockaddr, entry->orig_addr,
520 entry->orig_addrlen) != 0) {
521 ERROR("listen(%d, ..) failed\n", sockfd);
524 DBG("listen(%d, ..): using path '%s'\n", sockfd, sockaddr.sun_path);
527 while (attempts < 10) {
528 if (bind(unix_sockfd, (struct sockaddr *)&sockaddr,
529 sizeof(sockaddr)) == 0) {
532 if (errno != EADDRINUSE) {
533 DIE("listen(%d, ..): failed to bind to '%s'",
534 sockfd, sockaddr.sun_path);
537 /* File already exists, unlink it if it's a socket. This has a race
538 * condition, but the worst case is that we delete a file created by
539 * the user at the path he told us to use. Tough luck .. */
542 if (lstat(sockaddr.sun_path, &buf) != 0) {
543 /* Looks like a race, better abort. */
544 DIE("listen(%d, ..): lstat on UNIX socket '%s' failed",
545 sockfd, sockaddr.sun_path);
548 if (!S_ISSOCK(buf.st_mode)) {
549 ERROR("listen(%d, ..): path '%s' exits and is no socket\n",
550 sockfd, sockaddr.sun_path);
553 WARN("listen(%d, ..): unlinking '%s'\n", sockfd, sockaddr.sun_path);
554 if (unlink(sockaddr.sun_path) != 0) {
555 DIE("listen(%d, ..): unlink '%s' failed",
556 sockfd, sockaddr.sun_path);
562 if (attempts == 10) {
563 ERROR("listen(%d, ..): failed to create UNIX socket file\n", sockfd);
566 /* Replace the original socket of the program with our socket. */
567 if (replace_socket(entry->orig_sockfd, unix_sockfd)) {
568 DIE("listen(): failed to replace socket");
571 if (real_listen(entry->orig_sockfd, backlog) != 0) {
572 DIE("listen(): failed to listen");
578 int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
579 static int (*real_accept)(int, struct sockaddr *, socklen_t *);
580 LOAD_FUNCTION(real_accept, "accept");
582 if (!global_options) {
583 global_options = get_options();
586 if (global_options & OPTION_CLIENT_ONLY) {
587 DBG("accept(%d, ..): server hooking disabled\n", sockfd);
588 return real_accept(sockfd, addr, addrlen);
591 struct list *entry = find_sockfd(sockfd);
593 DBG("accept(%d, ..): sockfd not found\n", sockfd);
594 return real_accept(sockfd, addr, addrlen);
596 assert(sockfd == entry->orig_sockfd);
597 DBG("accept(%d, ..): %s %s\n",
599 af_to_name(entry->orig_domain), sock_to_name(entry->orig_type));
601 struct sockaddr_un sockaddr;
602 socklen_t size = sizeof(sockaddr);
603 int sock = real_accept(entry->orig_sockfd, (struct sockaddr *)&sockaddr,
606 DIE("accept(%d, ..): failed to accept", sockfd);
609 if (addr == NULL || addrlen == NULL) {
612 DBG("accept(%d, ..): caller requested sockaddr\n", sockfd);
614 if (*addrlen < size) {
615 WARN("accept(%d, ..): invalid addrlen from program", sockfd);
620 /* This is not the protocol the program asked for (AF_* vs. AF_UNIX), but
621 * it should work most of the time. */
622 memcpy(addr, &sockaddr, size);
625 /* TODO: is this enough? */
630 int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
631 static int (*real_connect)(int, const struct sockaddr *, socklen_t);
632 LOAD_FUNCTION(real_connect, "connect");
634 if (!global_options) {
635 global_options = get_options();
638 if (global_options & OPTION_SERVER_ONLY) {
639 DBG("connect(%d, ..): client hooking disabled\n", sockfd);
640 return real_connect(sockfd, addr, addrlen);
643 if (addr == NULL || addrlen < sizeof(addr->sa_family)
644 || addr->sa_family == AF_UNIX
645 || addr->sa_family == AF_LOCAL) {
646 return real_connect(sockfd, addr, addrlen);
649 struct list *entry = find_sockfd(sockfd);
651 DBG("connect(%d, ..): sockfd not found\n", sockfd);
652 return real_connect(sockfd, addr, addrlen);
654 assert(sockfd == entry->orig_sockfd);
655 DBG("connect(%d, ..): %s %s\n",
657 af_to_name(entry->orig_domain), sock_to_name(entry->orig_type));
659 int unix_sockfd = socket(AF_UNIX, entry->orig_type, 0);
660 if (unix_sockfd < 0) {
661 DIE("bind(): failed to create UNIX socket");
664 /* Replace the original socket of the program with our socket. */
665 if (replace_socket(entry->orig_sockfd, unix_sockfd)) {
666 DIE("connect(): failed to replace socket");
669 struct sockaddr_un sockaddr;
670 if (set_sockaddr_un(&sockaddr, addr, addrlen) != 0) {
671 ERROR("connect(%d, ..) failed\n", sockfd);
674 DBG("connect(%d, ..): using path '%s'\n", sockfd, sockaddr.sun_path);
676 if (real_connect(entry->orig_sockfd, (struct sockaddr *)&sockaddr,
677 sizeof(sockaddr)) != 0) {
678 DIE("connect(%d, ..): failed to connect", sockfd);
685 int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
686 static int (*real_getsockname)(int, struct sockaddr *, socklen_t *);
687 LOAD_FUNCTION(real_getsockname, "getsockname");
689 DBG("getsockname(%d, ..)\n", sockfd);
691 return real_getsockname(sockfd, addr, addrlen);
694 int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
695 static int (*real_getpeername)(int, struct sockaddr *, socklen_t *);
696 LOAD_FUNCTION(real_getpeername, "getpeername");
698 DBG("getpeername(%d, ..)\n", sockfd);
700 return real_getpeername(sockfd, addr, addrlen);
703 int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen) {
704 static int (*real_getsockopt)(int, int, int, void *, socklen_t *);
705 LOAD_FUNCTION(real_getsockopt, "getsockopt");
707 DBG("getsockopt(%d, %d %s, %d, ..)\n",
708 sockfd, level, level_to_name(level), optname);
710 return real_getsockopt(sockfd, level, optname, optval, optlen);
712 int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen) {
713 static int (*real_setsockopt)(int, int, int, const void *, socklen_t);
714 LOAD_FUNCTION(real_setsockopt, "setsockopt");
716 DBG("setsockopt(%d, %d %s, %d, ..)\n",
717 sockfd, level, level_to_name(level), optname);
719 return real_setsockopt(sockfd, level, optname, optval, optlen);