diff --git a/include/xrpl/beast/utility/temp_dir.h b/include/xrpl/beast/utility/temp_dir.h index 36d6bfe0d5..66d0193a8b 100644 --- a/include/xrpl/beast/utility/temp_dir.h +++ b/include/xrpl/beast/utility/temp_dir.h @@ -10,20 +10,25 @@ namespace beast { -/** Generate a unique, non-existing path under @p base with a random hex suffix. +/** Generate a unique, non-existing path under @p base with an optional @p prefix + and a random hex suffix. Attempts up to @p maxAttempts paths. Throws `std::runtime_error` if a unique path cannot be found or if the filesystem returns an error while checking for existence. */ inline std::filesystem::path -uniqueRandomPath(std::filesystem::path const& base, std::size_t maxAttempts = 100) +uniqueRandomPath( + std::filesystem::path const& base, + std::size_t maxAttempts = 100, + std::string const& prefix = "") { std::random_device rd; for (std::size_t attempt = 0; attempt < maxAttempts; ++attempt) { std::ostringstream oss; - oss << std::hex << std::setfill('0') << std::setw(8) << rd() << std::setw(8) << rd(); + oss << prefix << std::hex << std::setfill('0') << std::setw(8) << rd() << std::setw(8) + << rd(); auto candidate = base / oss.str(); std::error_code ec; bool const exists = std::filesystem::exists(candidate, ec); diff --git a/src/test/app/GRPCServerTLS_test.cpp b/src/test/app/GRPCServerTLS_test.cpp index b5c47d5936..b25f8ec2dc 100644 --- a/src/test/app/GRPCServerTLS_test.cpp +++ b/src/test/app/GRPCServerTLS_test.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -14,14 +15,10 @@ #include #include -#include #include #include -#include #include #include -#include -#include #include #include #include @@ -258,30 +255,8 @@ public: TemporaryTLSCertificates() { - auto tmpDir = std::filesystem::temp_directory_path(); - std::random_device rd; - constexpr std::size_t kMAX_ATTEMPTS = 100; - for (std::size_t attempt = 0; attempt < kMAX_ATTEMPTS; ++attempt) - { - std::ostringstream oss; - oss << kCERTS_DIR_PREFIX << std::hex << std::setfill('0') << std::setw(8) << rd(); - tempDir_ = tmpDir / oss.str(); - std::error_code ec; - bool const exists = std::filesystem::exists(tempDir_, ec); - if (ec) - { - throw std::runtime_error( - "Unable to check path '" + tempDir_.string() + "': " + ec.message()); - } - if (!exists) - break; - tempDir_.clear(); - } - if (tempDir_.empty()) - { - throw std::runtime_error( - "Unable to generate a unique temporary TLS certificate directory"); - } + tempDir_ = beast::uniqueRandomPath( + std::filesystem::temp_directory_path(), 100, std::string(kCERTS_DIR_PREFIX)); std::filesystem::create_directories(tempDir_); writeFile(tempDir_ / kCA_CERT_FILENAME, kCA_CERT_CONTENT);