diff options
Diffstat (limited to 'bbot/agent.cxx')
-rw-r--r-- | bbot/agent.cxx | 77 |
1 files changed, 47 insertions, 30 deletions
diff --git a/bbot/agent.cxx b/bbot/agent.cxx index 4ade0b4..55d95ec 100644 --- a/bbot/agent.cxx +++ b/bbot/agent.cxx @@ -7,6 +7,7 @@ #include <pwd.h> // getpwuid() #include <limits.h> // PATH_MAX #include <signal.h> // signal() +#include <stdlib.h> // rand_r() #include <unistd.h> // sleep(), realink(), getuid() #include <net/if.h> // ifreq @@ -15,6 +16,7 @@ #include <sys/ioctl.h> #include <sys/socket.h> +#include <chrono> #include <iostream> #include <butl/pager> @@ -48,36 +50,6 @@ namespace bbot string hname; uid_t uid; string uname; - - // Note: Linux-specific implementation. - // - string - iface_addr (const string& i) - { - if (i.size () >= IFNAMSIZ) - throw invalid_argument ("interface nama too long"); - - auto_fd fd (socket (AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)); - - if (fd.get () == -1) - throw_system_error (errno); - - ifreq ifr; - ifr.ifr_addr.sa_family = AF_INET; - strcpy (ifr.ifr_name, i.c_str ()); - - if (ioctl (fd.get (), SIOCGIFADDR, &ifr) == -1) - throw_system_error (errno); - - char buf[3 * 4 + 3 + 1]; // IPv4 address. - if (inet_ntop (AF_INET, - &reinterpret_cast<sockaddr_in*> (&ifr.ifr_addr)->sin_addr, - buf, - sizeof (buf)) == nullptr) - throw_system_error (errno); - - return buf; - } } // The btrfs tool likes to print informational messages, like "Created @@ -1024,3 +996,48 @@ catch (const cli::exception& e) error << e; return 1; } + +namespace bbot +{ + static unsigned int rand_seed; // Seed for rand_r(); + + size_t + genrand () + { + if (rand_seed == 0) + rand_seed = static_cast<unsigned int> ( + chrono::system_clock::now ().time_since_epoch ().count ()); + + return static_cast<size_t> (rand_r (&rand_seed)); + } + + // Note: Linux-specific implementation. + // + string + iface_addr (const string& i) + { + if (i.size () >= IFNAMSIZ) + throw invalid_argument ("interface nama too long"); + + auto_fd fd (socket (AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)); + + if (fd.get () == -1) + throw_system_error (errno); + + ifreq ifr; + ifr.ifr_addr.sa_family = AF_INET; + strcpy (ifr.ifr_name, i.c_str ()); + + if (ioctl (fd.get (), SIOCGIFADDR, &ifr) == -1) + throw_system_error (errno); + + char buf[3 * 4 + 3 + 1]; // IPv4 address. + if (inet_ntop (AF_INET, + &reinterpret_cast<sockaddr_in*> (&ifr.ifr_addr)->sin_addr, + buf, + sizeof (buf)) == nullptr) + throw_system_error (errno); + + return buf; + } +} |