[Dnsmasq-discuss] [PATCH 3/6] Use getentropy() if possible to reduce code duplication a bit
Leonid Evdokimov
leon at darkk.net.ru
Fri Oct 4 21:14:50 UTC 2024
It reduces binary by ~80 bytes on x86_64 :-)
---
src/config.h | 8 ++++++++
src/util.c | 25 ++++++++++++++++++-------
2 files changed, 26 insertions(+), 7 deletions(-)
diff --git src/config.h src/config.h
index e722e986..b86a53f3 100644
--- src/config.h
+++ src/config.h
@@ -144,6 +144,9 @@ HAVE_LOOP
HAVE_INOTIFY
use the Linux inotify facility to efficiently re-read configuration files.
+HAVE_GETENTROPY
+ use getentropy() call instead of RANDFILE. It is non-standard by widely available.
+
NO_ID
Don't report *.bind CHAOS info to clients, forward such requests upstream instead.
NO_TFTP
@@ -187,6 +190,7 @@ RESOLVFILE
#define HAVE_IPSET
#define HAVE_LOOP
#define HAVE_DUMPFILE
+#define HAVE_GETENTROPY
/* Build options which require external libraries.
@@ -362,6 +366,10 @@ HAVE_SOCKADDR_SA_LEN
#undef HAVE_DUMPFILE
#endif
+#ifdef NO_GETENTROPY
+#undef HAVE_GETENTROPY
+#endif
+
#if defined (HAVE_LINUX_NETWORK) && !defined(NO_INOTIFY)
#define HAVE_INOTIFY
#endif
diff --git src/util.c src/util.c
index c27d77c4..71b1dd57 100644
--- src/util.c
+++ src/util.c
@@ -34,6 +34,23 @@
#include <sys/utsname.h>
#endif
+#ifndef HAVE_GETENTROPY
+// Non-standard libc getentropy() might use getrandom() avoiding filesystem access, that's great
+// for jails and chroots. However, a fallback implemetation is required for older systems that have
+// no getentropy() in libc. Also, getentropy() might block if the kernel has not initialized random
+// pool yet. However, dnsmasq is never started that early during the OpenWRT boot process (at least).
+#define getentropy(a, b) getentropy_fallback(a, b)
+static int getentropy_fallback(void *buffer, size_t length)
+{
+ const int fd = open(RANDFILE, O_RDONLY);
+ if (fd == -1)
+ return -1;
+ const int okay = read_write(fd, buffer, length, 1);
+ close(fd);
+ return okay ? 0 : -1;
+}
+#endif // HAVE_GETENTROPY
+
/* SURF random number generator */
static u32 seed[32];
@@ -43,14 +60,8 @@ static int outleft = 0;
void rand_init()
{
- int fd = open(RANDFILE, O_RDONLY);
-
- if (fd == -1 ||
- !read_write(fd, (unsigned char *)&seed, sizeof(seed), 1) ||
- !read_write(fd, (unsigned char *)&in, sizeof(in), 1))
+ if (getentropy(&seed, sizeof(seed)) + getentropy(&in, sizeof(in)) < 0)
die(_("failed to seed the random number generator: %s"), NULL, EC_MISC);
-
- close(fd);
}
#define ROTATE(x,b) (((x) << (b)) | ((x) >> (32 - (b))))
--
2.34.1
More information about the Dnsmasq-discuss
mailing list