From 0d5b344d2ac3dd8c6964a15ff4e27c9bdaa1fc15 Mon Sep 17 00:00:00 2001 From: Jari Sundell Date: Sat, 8 Jun 2019 16:22:47 +0900 Subject: [PATCH] Switch to C++11 MRT RNG for random bytes Switching to a better RNG for generating strings will prevent the common peerID collisions the rTorrent client has been seeing for YEARS in #440 and #318. --- rak/string_manip.h | 57 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/rak/string_manip.h b/rak/string_manip.h index f8d3f590..1a09c377 100644 --- a/rak/string_manip.h +++ b/rak/string_manip.h @@ -39,9 +39,13 @@ #include #include +#include #include +#include #include #include +#include + namespace rak { @@ -312,11 +316,13 @@ transform_hex_str(const Sequence& seq) { template Sequence generate_random(size_t length) { + std::random_device rd; + std::mt19937 mt(rd()); + using bytes_randomizer = std::independent_bits_engine; + bytes_randomizer bytes(mt); Sequence s; s.reserve(length); - - std::generate_n(std::back_inserter(s), length, &::random); - + std::generate_n(std::back_inserter(s), length, std::ref(bytes)); return s; } @@ -371,6 +377,51 @@ is_all_name(const Sequence& src) { return is_all_name(src.begin(), src.end()); } +template +std::string +sanitize(Iterator first, Iterator last) { + std::string dest; + for (; first != last; ++first) { + if (std::isprint(*first) && *first != '\r' && *first != '\n' && *first != '\t') + dest += *first; + else + dest += " "; + } + + return dest; +} + +template +std::string +sanitize(const Sequence& src) { + return trim(sanitize(src.begin(), src.end())); +} + +template +std::string striptags(Iterator first, Iterator last) { + bool copychar = true; + std::string dest; + + for (; first != last; ++first) { + if (std::isprint(*first) && *first == '<') { + copychar = false; + } else if (std::isprint(*first) && *first == '>') { + copychar = true; + continue; + } + + if (copychar) + dest += *first; + } + + return dest; +} + +template +std::string striptags(const Sequence& src) { + return striptags(src.begin(), src.end()); +} + } #endif