]> git.ipfire.org Git - thirdparty/mtr.git/commitdiff
net: use arc4random_uniform when available 627/head
authoryvs <VSYakovetsky@gmail.com>
Fri, 8 May 2026 13:26:46 +0000 (17:26 +0400)
committerDarafei Praliaskouski <me@komzpa.net>
Fri, 8 May 2026 13:26:46 +0000 (17:26 +0400)
Port the arc4random_uniform probe-randomization piece from yvs2014/mtr085. Platforms that provide arc4random_uniform use it for random packet sizes and payload patterns; other platforms keep the existing rand() fallback.

Ported-from: yvs2014/mtr085@e100fd72be37f0a98d6893db7e0baa8a5b81b72a

Original-author: yvs <VSYakovetsky@gmail.com>

configure.ac
ui/net.c

index 66a72e08580f5ac113050fc449d6b5d0fe414089..b6f7a3b1185a50e9081840327884f08b5b80c420 100644 (file)
@@ -43,6 +43,7 @@ AC_CHECK_SIZEOF([unsigned long], [4])
 # Check headers.
 AC_CHECK_HEADERS([ \
   arpa/nameser_compat.h \
+  bsd/stdlib.h \
   curses.h \
   cursesX.h \
   error.h \
@@ -67,6 +68,9 @@ AC_CHECK_FUNCS([ \
   __fpending \
   fcntl \
 ])
+AC_SEARCH_LIBS([arc4random_uniform], [bsd],
+  [AC_DEFINE([HAVE_ARC4RANDOM_UNIFORM], [1],
+    [Define to 1 if arc4random_uniform is available.])])
 
 AC_CHECK_FUNC([error], [with_error=no],
   [AC_CHECK_FUNCS([verr verrx vwarn vwarnx], [with_error=yes],
index ed71a5623ce048ee1c33fdd34964c819f7cef92b..6dc59243707971f25648150320302dfb458b5fb2 100644 (file)
--- a/ui/net.c
+++ b/ui/net.c
 #include <sys/select.h>
 #include <unistd.h>
 
+#if defined(HAVE_ARC4RANDOM_UNIFORM) && defined(HAVE_BSD_STDLIB_H)
+#include <bsd/stdlib.h>
+#endif
+
 #ifdef HAVE_ERROR_H
 #include <error.h>
 #else
 
 static int packetsize;          /* packet size used by ping */
 
+static int random_uniform(
+    int upper_bound)
+{
+#ifdef HAVE_ARC4RANDOM_UNIFORM
+    return (int) arc4random_uniform((unsigned int) upper_bound);
+#else
+    return rand() % upper_bound;
+#endif
+}
+
 struct nethost {
     ip_t addr;                  /* Latest host to respond */
     ip_t addrs[MAX_PATH];        /* For Multi paths/Path Changes: List of all hosts that have responded */
@@ -577,14 +591,14 @@ int net_send_batch(
                 packetsize = MINPACKET;
             } else {
                 packetsize =
-                    MINPACKET + rand() % (-ctl->cpacketsize - MINPACKET);
+                    MINPACKET + random_uniform(-ctl->cpacketsize - MINPACKET);
             }
         } else {
             packetsize = ctl->cpacketsize;
         }
         if (ctl->bitpattern < 0) {
             ctl->bitpattern =
-                -(int) (256 + 255 * (rand() / (RAND_MAX + 0.1)));
+                -(256 + random_uniform(256));
         }
     }