[LEDE-DEV] [PATCH 1/5] utils: add patch_fd() and patch_stdio() helpers

Jo-Philipp Wich jo at mein.io
Tue May 17 08:00:43 PDT 2016


Introduce two new helper functions to deal with stdio redirecation in a
uniform, reliable manner:

The patch_fd() function will attempt to redirect the given fd number to the
specified file, using the supplied flags for the open() syscall. When the
device is NULL, "/dev/null" is asumed, when the device is a relative path,
openat() is used to open it relative to the "/dev" directory. When the device
cannot be openend, a fallback to "/dev/null" is attempted.

The patch_stdio() function is essentially a wrapper around patch_fd(),
providing an easy interface to redirect stdin, stdout and stderr to the same
given device.

Both function return 0 on success and -1 on error. The errno variable will
be set accordingly.

Signed-off-by: Jo-Philipp Wich <jo at mein.io>
---
 utils/utils.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 utils/utils.h |  3 +++
 2 files changed, 57 insertions(+)

diff --git a/utils/utils.c b/utils/utils.c
index a67c004..ebf5447 100644
--- a/utils/utils.c
+++ b/utils/utils.c
@@ -20,6 +20,10 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
+#include <string.h>
+#include <errno.h>
+
+#include "../log.h"
 
 void
 __blobmsg_list_init(struct blobmsg_list *list, int offset, int len, blobmsg_list_cmp cmp)
@@ -152,3 +156,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_RDONLY);
+
+		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;
+}
diff --git a/utils/utils.h b/utils/utils.h
index 8b384fc..908c314 100644
--- a/utils/utils.h
+++ b/utils/utils.h
@@ -53,4 +53,7 @@ bool blobmsg_list_equal(struct blobmsg_list *l1, struct blobmsg_list *l2);
 void blobmsg_list_move(struct blobmsg_list *list, struct blobmsg_list *src);
 char* get_cmdline_val(const char* name, char* out, int len);
 
+int patch_fd(const char *device, int fd, int flags);
+int patch_stdio(const char *device);
+
 #endif
-- 
2.1.4




More information about the Lede-dev mailing list