diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/other_tools/utils/curl_url_handle.cpp | 47 | ||||
-rw-r--r-- | src/other_tools/utils/curl_url_handle.hpp | 5 |
2 files changed, 52 insertions, 0 deletions
diff --git a/src/other_tools/utils/curl_url_handle.cpp b/src/other_tools/utils/curl_url_handle.cpp index bd79b228..33390ea6 100644 --- a/src/other_tools/utils/curl_url_handle.cpp +++ b/src/other_tools/utils/curl_url_handle.cpp @@ -835,3 +835,50 @@ auto CurlURLHandle::ReplaceHostname(std::string const& url, } return std::nullopt; } + +auto CurlURLHandle::GetHostname(std::string const& url) noexcept + -> std::optional<std::string> { + try { + // Allow parsing spaces in path (we only care about hostname), and do + // not log error on failure. + if (auto parsed_url = CreatePermissive(url, + false /*use_guess_scheme*/, + false /*use_default_scheme*/, + false /*use_non_support_scheme*/, + false /*use_no_authority*/, + false /*use_path_as_is*/, + true /*use_allow_space*/, + true /*ignore_fatal*/)) { + if (*parsed_url == nullptr) { + return std::nullopt; + } + + char* buffer{nullptr}; // NOLINT + auto rc = curl_url_get( + parsed_url.value()->handle_.get(), CURLUPART_HOST, &buffer, 0U); + + std::string hostname{}; + if (buffer != nullptr) { + hostname = std::string{buffer}; + curl_free(buffer); + } + + if (rc != CURLUE_OK) { + Logger::Log(LogLevel::Debug, + "CurlURLHandle: getting hostname from URL {} " + "failed with:\n{}", + url, + curl_url_strerror(rc)); + return std::nullopt; + } + return hostname; + } + } catch (std::exception const& ex) { + Logger::Log( + LogLevel::Debug, + "CurlURLHandle: Getting hostname from URL failed unexpectedly " + "with:\n{}", + ex.what()); + } + return std::nullopt; +} diff --git a/src/other_tools/utils/curl_url_handle.hpp b/src/other_tools/utils/curl_url_handle.hpp index 5648a535..4680cb34 100644 --- a/src/other_tools/utils/curl_url_handle.hpp +++ b/src/other_tools/utils/curl_url_handle.hpp @@ -165,6 +165,11 @@ class CurlURLHandle { std::string const& url, std::string const& hostname) noexcept -> std::optional<std::string>; + /// \brief Gets the hostname from URL. + /// \returns The host name or std::nullopt if missing or on errors. + [[nodiscard]] static auto GetHostname(std::string const& url) noexcept + -> std::optional<std::string>; + private: // IMPORTANT: the CurlContext must be initialized before any curl // object! |