X-Git-Url: http://git.archive.openwrt.org/?p=project%2Fprocd.git;a=blobdiff_plain;f=utils%2Futils.c;h=e239eda5110ec4e38b88880d7b7d24341389e85e;hp=c0d1cd536ae6870d1386d7ac3b8be0428b5db3a0;hb=ba0ef6bea720c6cb263c034787fdd1ebe75be2fa;hpb=6f52ef3cc9f01e952e7f32d10c7f8612e635e80c diff --git a/utils/utils.c b/utils/utils.c index c0d1cd5..e239eda 100644 --- a/utils/utils.c +++ b/utils/utils.c @@ -12,15 +12,23 @@ * GNU General Public License for more details. */ +#define _GNU_SOURCE #include #include #include "utils.h" -#include #include #include #include #include #include +#include +#include + +#include "../log.h" + +#ifndef O_PATH +#define O_PATH 010000000 +#endif void __blobmsg_list_init(struct blobmsg_list *list, int offset, int len, blobmsg_list_cmp cmp) @@ -153,3 +161,53 @@ char* get_cmdline_val(const char* name, char* out, int len) return NULL; } + +int patch_fd(const char *device, int fd, int flags) +{ + int dfd, nfd; + + if (device == NULL) + device = "/dev/null"; + + if (*device != '/') { + dfd = open("/dev", O_PATH|O_DIRECTORY); + + if (dfd < 0) + return -1; + + nfd = openat(dfd, device, flags); + + close(dfd); + } else { + nfd = open(device, flags); + } + + if (nfd < 0 && strcmp(device, "/dev/null")) + nfd = open("/dev/null", flags); + + if (nfd < 0) + return -1; + + fd = dup2(nfd, fd); + + if (nfd > STDERR_FILENO) + close(nfd); + + return (fd < 0) ? -1 : 0; +} + +int patch_stdio(const char *device) +{ + int fd, rv = 0; + const char *fdname[3] = { "stdin", "stdout", "stderr" }; + + for (fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) { + if (patch_fd(device, fd, fd ? O_WRONLY : O_RDONLY)) { + ERROR("Failed to redirect %s to %s: %d (%s)\n", + fdname[fd], device, errno, strerror(errno)); + rv = -1; + } + } + + return rv; +}